@coreframe/dev-supervisor 0.2.3 → 0.2.4
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/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DevDiagnostics as e,devDiagnosticContext as t,devDiagnosticError as n,devDiagnosticEvent as r,devDiagnosticPhase as i}from"./diagnostics.js";import{spawn as a}from"node:child_process";import{createHash as o,randomUUID as s}from"node:crypto";import{readFileSync as c}from"node:fs";import{appendFile as l,mkdir as u,readFile as d,rename as ee,rm as te,stat as f,unlink as p,writeFile as m}from"node:fs/promises";import{createConnection as h,createServer as g}from"node:net";import{tmpdir as ne}from"node:os";import _ from"node:path";import v from"node:process";import{Writable as y}from"node:stream";const b=JSON.parse(c(new URL(`../package.json`,import.meta.url),`utf8`)).version,x=`.coreframe/dev-supervisor`,S=`supervisor.json`,C=`logs`,w=1*1024*1024,T=4*1024*1024,E=45e3;async function D({cwd:e=v.cwd(),env:t=v.env,requiredResources:n=[],supervisorEntry:r,implementationVersion:i}={}){let a=await O({cwd:e,env:t,requiredResources:n,implementationVersion:i});if(a)return a;let o=await R(e),s=await ae(e,!i);if(!s){if(o=await I(e),!B(o,n))throw Error(`The development supervisor does not provide the required resources.`);return F({cwd:e,env:t,state:o})}try{if(o=await R(e),o&&o.cwd===_.resolve(e)&&Z(o.pid)&&i&&o.implementationVersion!==i){let n=await F({cwd:e,env:t,state:o});try{await n.retireIfIdle()}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`INVALID_REQUEST`;throw Error(t?`The existing development supervisor predates automatic handoff. Stop its dev servers and supervisor, then retry.`:`The existing development supervisor uses a different version and cannot hand off while it is active. Stop its dev servers and supervisor, then retry.`,{cause:e})}finally{n.close()}await L(e,o.supervisorId),o=void 0}if(o&&o.cwd===_.resolve(e)&&Z(o.pid)){if(!B(o,n))throw Error(`The development supervisor does not provide the required resources.`);return await F({cwd:e,env:t,state:o})}if(o&&await H(e,o),!r)throw Error(`A development supervisor process entry is required to start the supervisor.`);if(await ie({cwd:e,env:t,entry:r}),o=await I(e),i&&o.implementationVersion!==i)throw Error(`The started development supervisor has an unexpected implementation version.`);if(!B(o,n))throw Error(`The development supervisor does not provide the required resources.`);return F({cwd:e,env:t,state:o})}finally{await s()}}async function O({cwd:e=v.cwd(),env:t=v.env,requiredResources:n=[],implementationVersion:r}={}){let i=await R(e);if(!(!i||i.cwd!==_.resolve(e)||!Z(i.pid)||!B(i,n)||r!==void 0&&i.implementationVersion!==r))try{return await F({cwd:e,env:t,state:i})}catch{await H(e,i);return}}async function re({cwd:e=v.cwd()}={}){let t=await R(e);if(!t||t.cwd!==_.resolve(e)||!Z(t.pid))return await H(e,t),!1;let n=await F({cwd:e,env:v.env,state:t});try{await n.shutdown()}finally{n.close()}return await L(e,t.supervisorId),!0}var k=class e{state;socket;pending=new Map;listeners=new Set;closeListeners=new Set;leases=new Set;decoder=new N;closed=!1;closeError;renewalTimer;constructor(e){this.state=e.state,this.socket=e.socket,this.socket.on(`data`,e=>{for(let t of this.decoder.push(e))this.handleFrame(t)}),this.socket.on(`close`,()=>this.handleClose(Error(`Development supervisor disconnected.`))),this.socket.on(`error`,e=>this.handleClose(e)),this.renewalTimer=setInterval(()=>void this.renewLeases(),E/3),this.renewalTimer.unref()}static async create(t){let n=new e(t);return await n.request(`hello`,{protocol:1,token:t.state.token}),n}async acquirePostgres({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`postgres`,config:e,env:Y(t??v.env)});return this.leases.add(n.leaseId),n}async acquireSqlite({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`sqlite`,config:e,env:Y(t??v.env)});return this.leases.add(n.leaseId),n}async acquireManagedDev({env:e}={}){let t=await this.request(`acquire`,{resource:`managed-dev`,env:Y(e??v.env)});return this.leases.add(t.leaseId),t}async managedDevAction({action:e,requestId:t,operationId:n,requestKey:r}){return this.request(`managed-dev-action`,{action:e,requestId:t,operationId:n,requestKey:r})}async managedDevStatus(){return this.request(`managed-dev-status`)}async resetIdleManagedDev(){return this.request(`managed-dev-reset-idle`)}async release(e){this.leases.delete(e),await this.request(`release`,{leaseId:e})}async subscribe(e){return this.request(`subscribe`,{resources:e})}async status(){return this.request(`status`)}async shutdown(){await this.request(`shutdown`)}async retireIfIdle(){await this.request(`retire-if-idle`)}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onClose(e){return this.closed?(e(this.closeError??Error(`Development supervisor client is closed.`)),()=>!1):(this.closeListeners.add(e),()=>this.closeListeners.delete(e))}waitForServiceExit(e){return this.closed?Promise.resolve():new Promise(t=>{let n=()=>{r(),this.closeListeners.delete(n),t()},r=this.onEvent(t=>{!(`resource`in t)||t.resource!==e||t.event!==`service`||(t.state===`failed`||t.state===`stopped`)&&n()});this.closeListeners.add(n)})}close(){this.closed||(this.socket.end(),this.handleClose(Error(`Development supervisor client closed.`)))}request(e,t){if(this.closed)return Promise.reject(Error(`Development supervisor client is closed.`));let n=s();return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i}),this.socket.write(P({id:n,method:e,params:t,type:`request`}))})}async renewLeases(){for(let e of this.leases)if(await this.request(`renew`,{leaseId:e}).catch(t=>{this.leases.delete(e),this.handleClose(t instanceof Error?t:Error(String(t))),this.socket.destroy()}),this.closed)return}handleFrame(e){if(e.type===`event`){for(let t of this.listeners)t(e.event);return}if(e.type!==`response`)return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.result):t.reject(oe(e.error)))}handleClose(e){if(!this.closed){this.closed=!0,this.closeError=e,clearInterval(this.renewalTimer);for(let t of this.pending.values())t.reject(e);this.pending.clear();for(let t of this.closeListeners)t(e);this.closeListeners.clear()}}};async function A({cwd:e=v.cwd(),startPostgres:t,startSqlite:n,startManagedDev:r,implementationVersion:i}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let a=_.resolve(e,x);await u(a,{recursive:!0,mode:448}),await u(_.join(a,C),{recursive:!0,mode:448});let o=await R(e);if(o&&o.pid!==v.pid&&Z(o.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let s=U(e);v.platform!==`win32`&&await p(s).catch(()=>void 0);let c=new j({cwd:_.resolve(e),endpoint:s,root:a,startPostgres:t,startSqlite:n,startManagedDev:r,implementationVersion:i});await c.listen();let l=()=>{c.shutdown()};v.once(`SIGINT`,l),v.once(`SIGTERM`,l);try{await c.waitForShutdown()}finally{v.off(`SIGINT`,l),v.off(`SIGTERM`,l)}}var j=class{diagnostics;clients=new Set;leases=new Map;resourceOperations=new Map;server;root;state;startPostgres;startSqlite;startManagedDev;postgres;sqlite;managedDev;sequence=0;shutdownPromise;shutdownRequested=!1;idleTimer;leaseTimer;lastLeaseSweepAt=Date.now();postgresStopTimer;sqliteStopTimer;managedDevStopTimer;constructor({cwd:e,endpoint:t,root:n,startPostgres:r,startSqlite:i,startManagedDev:a,implementationVersion:o}){this.root=n,this.startPostgres=r,this.startSqlite=i,this.startManagedDev=a;let c=[`postgres`];i&&c.push(`sqlite`),a&&c.push(`managed-dev`),this.state={availableResources:c,cwd:e,endpoint:t,pid:v.pid,protocol:1,supervisorId:s(),token:s(),implementationVersion:o},this.server=g(e=>this.accept(e)),this.leaseTimer=setInterval(()=>this.expireLeases(),5e3),this.leaseTimer.unref()}async listen(){await new Promise((e,t)=>{this.server.once(`error`,t),this.server.listen(this.state.endpoint,()=>{this.server.off(`error`,t),e()})}),await V(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!0,stopSqlite:t=!0}={}){return this.shutdownPromise||=(async()=>{this.shutdownRequested=!0,this.idleTimer&&clearTimeout(this.idleTimer),clearInterval(this.leaseTimer),await Promise.all(this.resourceOperations.values()),this.leases.clear(),await this.stopManagedDev(),e?await this.stopPostgres():(this.cancelPostgresStop(),this.postgres=void 0),t?await this.stopSqlite():(this.cancelSqliteStop(),this.sqlite=void 0);for(let e of this.clients)e.close();await new Promise(e=>this.server.close(()=>e())),await p(this.state.endpoint).catch(()=>void 0),await p(_.join(this.root,S)).catch(()=>void 0),this.diagnostics?.event(`supervisor.stopped`,{supervisorId:this.state.supervisorId}),this.diagnostics?.close(),this.resolveShutdown?.()})(),this.shutdownPromise}resolveShutdown;accept(e){let t=new M(this,e);this.clients.add(t),e.once(`close`,()=>{this.clients.delete(t);for(let e of this.leases.values())e.connection===t&&this.releaseLease(e.id);this.maybeScheduleIdleShutdown()})}async handleRequest(e,t){try{let n=await this.dispatch(e,t.method,t.params??{});e.respond(t.id,{ok:!0,result:n})}catch(n){e.respond(t.id,{ok:!1,error:$(n)})}}publish(e,t){let n={...e,sequence:++this.sequence,timestamp:new Date().toISOString()};if(t)t.publish(n);else for(let e of this.clients)e.publish(n);return n}async addSubscription(e,t){return e.subscribe(t),e.publish({event:`replay-complete`,sequence:this.sequence,timestamp:new Date().toISOString()}),{subscriptionId:s()}}async dispatch(e,t,n){if(this.shutdownRequested&&t!==`shutdown`)throw Q(`SUPERVISOR_STOPPING`,`Development supervisor is stopping.`,!0);switch(t){case`hello`:return this.hello(e,n);case`status`:return this.status();case`managed-dev-status`:return this.managedDevStatus();case`managed-dev-reset-idle`:return this.withResourceOperation(`managed-dev`,async()=>!this.managedDev||this.managedDev.leases.size>0?{reset:!1}:(await this.stopManagedDev(),{reset:!0}));case`managed-dev-action`:return this.managedDevAction(e,n);case`subscribe`:return this.addSubscription(e,W(n.resources));case`acquire`:return this.withResourceOperation(G(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(q(n.leaseId));return;case`renew`:return this.renewLease(q(n.leaseId));case`shutdown`:this.shutdownRequested=!0,setImmediate(()=>void this.shutdown({stopPostgres:!1}));return;case`retire-if-idle`:if(this.leases.size>0||this.resourceOperations.size>0)throw Q(`SUPERVISOR_BUSY`,`Development supervisor still owns active work.`,!0);this.shutdownRequested=!0,setImmediate(()=>void this.shutdown());return;default:throw Q(`INVALID_REQUEST`,`Unknown supervisor method: ${t}.`,!1)}}async withResourceOperation(e,t){let n=this.resourceOperations.get(e),r,i=new Promise(e=>{r=e});this.resourceOperations.set(e,i),n&&await n;try{return await t()}finally{r(),this.resourceOperations.get(e)===i&&this.resourceOperations.delete(e)}}hello(e,t){if(t.protocol!==1||t.token!==this.state.token)throw e.close(),Q(`AUTH_FAILED`,`Invalid supervisor protocol or token.`,!1);return e.authenticated=!0,{cwd:this.state.cwd,protocol:1,supervisorId:this.state.supervisorId}}status(){return{managedDev:this.managedDev?{leases:this.managedDev.leases.size,state:`running`}:void 0,postgres:this.postgres?{leases:this.postgres.leases.size,state:`running`}:void 0,sqlite:this.sqlite?{leases:this.sqlite.leases.size,state:`running`}:void 0}}async acquire(e,t){let n=G(t.resource);if(n===`managed-dev`)return this.acquireManagedDev(e,K(t));if(n===`postgres`)return this.acquirePostgres(e,K(t));if(n===`sqlite`)return this.acquireSqlite(e,K(t));throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${n}.`,!1)}async acquireManagedDev(t,n){if(!this.startManagedDev)throw Error(`A managed development starter is required to run managed development.`);if(this.diagnostics??=new e(this.state.cwd,`supervisor`),this.diagnostics.event(`supervisor.attached`,{supervisorId:this.state.supervisorId,reused:!!this.managedDev}),this.managedDev){this.cancelManagedDevStop();let e=this.createLease(t,`managed-dev`);return this.managedDev.leases.add(e.id),{leaseId:e.id,state:`reused`,status:this.managedDev.session.getStatus()}}let r=J(n.env),i=await this.startManagedDev({cwd:this.state.cwd,env:Y(r),onRestart:()=>{this.diagnostics?.event(`restart.requested`,{supervisorId:this.state.supervisorId}),this.publish({event:`managed-dev`,kind:`restart`,resource:`managed-dev`})},onStatusChange:e=>{this.publish({event:`managed-dev`,kind:`status`,resource:`managed-dev`,status:e})}}),a={leases:new Set,session:i};this.managedDev=a;try{await i.activate()}catch(e){throw this.managedDev=void 0,await i.close(),e}let o=this.createLease(t,`managed-dev`);return a.leases.add(o.id),{leaseId:o.id,state:`started`,status:i.getStatus()}}managedDevStatus(){if(!this.managedDev)throw Error(`Managed development is not active.`);return{status:this.managedDev.session.getStatus()}}async managedDevAction(e,t){if(!this.managedDev)throw Error(`Managed development is not active.`);let n=q(t.requestId);if(!n)throw Q(`INVALID_REQUEST`,`A managed development action request ID is required.`,!1);try{let r=q(t.operationId)||n;return await this.diagnostics.run({operationId:r,supervisorId:this.state.supervisorId,supervisorRequestId:n},()=>i(`supervisor.action`,()=>this.managedDev.session.action(t.action,{operationId:r,requestKey:q(t.requestKey)||void 0,onCodexEvent:t=>{this.publish({codex:t,event:`managed-dev`,kind:`codex`,requestId:n,resource:`managed-dev`},e)}})))}catch(e){return{error:e instanceof Error?e.message:String(e),status:this.managedDev.session.getStatus()}}}async acquirePostgres(e,t){let n=this.postgres===void 0;if(this.postgres)this.cancelPostgresStop();else{let e=await this.createLogStream(`postgres`),n=J(t.env),r=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:Y(n),failIfRunning:!1,postgresOutput:e});this.postgres={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:Y(this.postgres.env),leaseId:r.id,state:n?`started`:`reused`}}async acquireSqlite(e,t){if(!this.startSqlite)throw Error(`A SQLite starter is required to run the development supervisor.`);let n=this.sqlite===void 0;if(this.sqlite)this.cancelSqliteStop();else{let e=await this.createLogStream(`sqlite`),n=J(t.env),r=await this.startSqlite({config:t.config,cwd:this.state.cwd,env:Y(n),tursoOutput:e});this.sqlite={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`sqlite`,state:`running`})}let r=this.createLease(e,`sqlite`);return this.sqlite.leases.add(r.id),{env:Y(this.sqlite.env),leaseId:r.id,state:n?`started`:`reused`}}createLease(e,t){let n={connection:e,expiresAt:Date.now()+E,id:s(),resource:t};return this.leases.set(n.id,n),t===`managed-dev`&&this.diagnostics?.event(`lease.acquired`,{leaseId:n.id,supervisorId:this.state.supervisorId}),n}renewLease(e){let t=this.leases.get(e);if(!t)throw this.diagnostics?.event(`lease.renewal-rejected`,{leaseId:e},`warn`),Q(`LEASE_EXPIRED`,`The supervisor lease is no longer active.`,!0);return t.expiresAt=Date.now()+E,{expiresAt:t.expiresAt}}expireLeases(){let e=Date.now(),t=e-this.lastLeaseSweepAt;if(this.lastLeaseSweepAt=e,t>=1e4){this.diagnostics?.event(`supervisor.resumed`,{sweepDelayMs:t});for(let t of this.leases.values())t.expiresAt=Math.max(t.expiresAt,e+E);return}for(let t of this.leases.values())t.expiresAt<=e&&(t.resource===`managed-dev`&&this.diagnostics?.event(`lease.expired`,{leaseId:t.id,overdueMs:e-t.expiresAt},`warn`),this.releaseLease(t.id))}async releaseLease(e){let t=this.leases.get(e);t&&(this.leases.delete(e),t.resource===`postgres`?(this.postgres?.leases.delete(e),this.postgres?.leases.size===0&&this.schedulePostgresStop()):t.resource===`sqlite`?(this.sqlite?.leases.delete(e),this.sqlite?.leases.size===0&&this.scheduleSqliteStop()):t.resource===`managed-dev`&&(this.managedDev?.leases.delete(e),this.diagnostics?.event(`lease.released`,{leaseId:e,remainingLeases:this.managedDev?.leases.size}),this.managedDev?.leases.size===0&&this.scheduleManagedDevStop()),this.maybeScheduleIdleShutdown())}async stopPostgres(){if(this.cancelPostgresStop(),!this.postgres)return;let e=this.postgres;this.postgres=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`postgres`,state:`stopped`})}schedulePostgresStop(){this.postgresStopTimer||(this.postgresStopTimer=setTimeout(()=>{this.postgresStopTimer=void 0,this.withResourceOperation(`postgres`,async()=>{this.postgres?.leases.size===0&&await this.stopPostgres()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.postgresStopTimer.unref())}async stopSqlite(){if(this.cancelSqliteStop(),!this.sqlite)return;let e=this.sqlite;this.sqlite=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`sqlite`,state:`stopped`})}async stopManagedDev(){if(this.cancelManagedDevStop(),!this.managedDev)return;let e=this.managedDev;this.diagnostics?.event(`session.stopping`,{supervisorId:this.state.supervisorId}),await e.session.close(),this.managedDev=void 0}scheduleSqliteStop(){this.sqliteStopTimer||(this.sqliteStopTimer=setTimeout(()=>{this.sqliteStopTimer=void 0,this.withResourceOperation(`sqlite`,async()=>{this.sqlite?.leases.size===0&&await this.stopSqlite()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.sqliteStopTimer.unref())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),void 0)}cancelSqliteStop(){this.sqliteStopTimer&&=(clearTimeout(this.sqliteStopTimer),void 0)}scheduleManagedDevStop(){this.managedDevStopTimer||(this.managedDevStopTimer=setTimeout(()=>{this.managedDevStopTimer=void 0,this.withResourceOperation(`managed-dev`,async()=>{this.managedDev?.leases.size===0&&await this.stopManagedDev()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e4),this.managedDevStopTimer.unref())}cancelManagedDevStop(){this.managedDevStopTimer&&=(clearTimeout(this.managedDevStopTimer),void 0)}async createLogStream(e){let t=_.join(this.root,C,`${e.replaceAll(`:`,`-`)}.log`);await u(_.dirname(t),{recursive:!0,mode:448}),await m(t,``);let n=0;return new y({write:(r,i,a)=>{let o=String(r),s=Buffer.from(o),c=s.subarray(Math.max(0,s.length-w)),u=n+c.length>w;(u?m(t,c):l(t,c)).then(()=>{n=u?c.length:n+c.length,a()},a),this.publish({event:`log`,resource:e,stream:`stdout`,data:o})}})}maybeScheduleIdleShutdown(){this.leases.size>0||this.postgres||this.sqlite||this.managedDev||this.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&!this.postgres&&!this.sqlite&&!this.managedDev&&this.shutdown()},3e4),this.idleTimer.unref())}},M=class{authenticated=!1;decoder=new N;subscriptions=new Set;eventQueue=[];queuedEventBytes=0;writingEvent=!1;droppedEventRange;server;socket;constructor(e,t){this.server=e,this.socket=t,t.on(`error`,()=>this.close()),t.on(`data`,t=>{try{for(let n of this.decoder.push(t))n.type===`request`&&(!this.authenticated&&n.method!==`hello`?this.respond(n.id,{ok:!1,error:$(Q(`AUTH_FAILED`,`Send hello first.`,!1))}):e.handleRequest(this,n))}catch{this.close()}})}respond(e,t){this.socket.write(P({...t,id:e,type:`response`}))}publish(e){let t=[...this.subscriptions];t.length!==0&&(e.event!==`replay-complete`&&e.event!==`gap`&&(e.resource===void 0||!t.some(t=>t.has(e.resource)))||this.enqueueEvent(e))}subscribe(e){this.subscriptions.add(new Set(e))}close(){this.eventQueue.length=0,this.queuedEventBytes=0,this.socket.destroy()}enqueueEvent(e){let t=P({event:e,type:`event`});if(t.length>T){this.noteDropped(e);return}for(;;){let n=this.droppedEventRange?{event:{event:`gap`,from:this.droppedEventRange.from,reason:`buffer-overflow`,to:this.droppedEventRange.to,sequence:e.sequence,timestamp:new Date().toISOString()},frame:Buffer.alloc(0)}:void 0;n&&(n.frame=P({event:n.event,type:`event`}));let r=t.length+(n?.frame.length??0),i=!1;for(;this.queuedEventBytes+r>T;){let e=this.eventQueue.shift();if(!e)break;i=!0,this.queuedEventBytes-=e.frame.length,this.noteDropped(e.event)}if(!i){if(this.queuedEventBytes+r<=T){n&&(this.eventQueue.push(n),this.queuedEventBytes+=n.frame.length,this.droppedEventRange=void 0),this.eventQueue.push({event:e,frame:t}),this.queuedEventBytes+=t.length,this.pumpEvents();return}if(this.eventQueue.length===0){this.noteDropped(e);return}}}}noteDropped(e){let t=e.sequence;if(!this.droppedEventRange){this.droppedEventRange={from:t,to:t};return}this.droppedEventRange.from=Math.min(this.droppedEventRange.from,t),this.droppedEventRange.to=Math.max(this.droppedEventRange.to,t)}pumpEvents(){if(this.writingEvent||this.eventQueue.length===0||this.socket.destroyed)return;let e=this.eventQueue.shift();this.queuedEventBytes-=e.frame.length,this.writingEvent=!0,this.socket.write(e.frame,()=>{this.writingEvent=!1,this.pumpEvents()})}},N=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,Buffer.from(e)]);let t=[];for(;this.buffer.length>=4;){let e=this.buffer.readUInt32BE(0);if(e>16777216)throw Error(`Development supervisor protocol frame is too large.`);if(this.buffer.length<e+4)break;let n=this.buffer.subarray(4,e+4).toString(`utf8`);this.buffer=this.buffer.subarray(e+4),t.push(JSON.parse(n))}return t}};function P(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.allocUnsafe(t.length+4);return n.writeUInt32BE(t.length,0),t.copy(n,4),n}async function F(e){let t=await new Promise((t,n)=>{let r=h(e.state.endpoint);r.once(`connect`,()=>t(r)),r.once(`error`,n)});return k.create({...e,socket:t})}async function ie({cwd:e,env:t,entry:n}){a(v.execPath,[n,`--cwd`,e],{cwd:e,detached:!0,env:{...t,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function ae(e,t=!0){let n=_.join(e,x),r=_.join(n,`start.lock`),i=Date.now()+1e4;for(await u(n,{recursive:!0,mode:448});Date.now()<i;)try{return await m(r,`${v.pid}\n`,{flag:`wx`,mode:384}),async()=>{await p(r).catch(()=>void 0)}}catch(n){if(!(n instanceof Error&&n.code===`EEXIST`))throw n;let i=await R(e);if(t&&i&&Z(i.pid))return;try{let e=await f(r);if(Date.now()-e.mtimeMs>1e4){await p(r).catch(()=>void 0);continue}}catch{continue}await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor startup is already in progress.`)}async function I(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await R(e);if(t&&Z(t.pid))return t;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not start within 10 seconds.`)}async function L(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await R(e);if(!n||n.supervisorId!==t)return;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not stop within 10 seconds.`)}async function R(e){try{let t=JSON.parse(await d(_.join(e,x,S),`utf8`)),n=t.availableResources===void 0?[`postgres`]:Array.isArray(t.availableResources)&&t.availableResources.every(z)?t.availableResources:void 0;return!n||t.protocol!==1||typeof t.cwd!=`string`||typeof t.endpoint!=`string`||typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.supervisorId!=`string`||t.implementationVersion!==void 0&&typeof t.implementationVersion!=`string`||typeof t.token!=`string`?void 0:{...t,availableResources:n}}catch{return}}function z(e){return e===`managed-dev`||e===`postgres`||e===`sqlite`}function B(e,t){return t.every(t=>e.availableResources.includes(t))}async function V(e,t){let n=_.join(t,S),r=`${n}.${s()}.tmp`;await u(_.dirname(n),{recursive:!0,mode:448});try{await m(r,`${JSON.stringify(e)}\n`,{flag:`wx`,mode:384}),await ee(r,n)}finally{await p(r).catch(()=>void 0)}}async function H(e,t){t&&t.cwd!==_.resolve(e)||(await te(_.join(e,x,S),{force:!0}),t&&v.platform!==`win32`&&await p(t.endpoint).catch(()=>void 0))}function U(e){if(v.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${o(`sha256`).update(_.resolve(e)).digest(`hex`).slice(0,24)}`;let t=o(`sha256`).update(_.resolve(e)).digest(`hex`).slice(0,24);return _.join(ne(),`coreframe-dev-${t}-supervisor.sock`)}function W(e){return Array.isArray(e)?e.map(G):[`managed-dev`,`postgres`,`sqlite`]}function G(e){if(e===`managed-dev`||e===`postgres`||e===`sqlite`)return e;throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function K(e){return e&&typeof e==`object`?e:{}}function q(e){return typeof e==`string`?e:String(e??``)}function J(e){let t=K(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function Y(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function X(e,t){return Object.fromEntries(Object.entries(t).filter(t=>{let[n,r]=t;return r!==void 0&&e[n]!==r}))}function Z(e){try{return v.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Q(e,t,n,r){return Object.assign(Error(t),{code:e,details:r,retryable:n})}function $(e){if(e&&typeof e==`object`){let t=e;return{code:t.code??`SUPERVISOR_ERROR`,details:t.details,message:t.message??String(e),retryable:t.retryable??!1}}return{code:`SUPERVISOR_ERROR`,message:String(e),retryable:!1}}function oe(e){let t=Error(e?.message??`Development supervisor request failed.`);return t.code=e?.code,t.details=e?.details,t.retryable=e?.retryable,t}export{e as DevDiagnostics,k as DevSupervisorClient,D as connectDevSupervisor,O as connectExistingDevSupervisor,t as devDiagnosticContext,n as devDiagnosticError,r as devDiagnosticEvent,i as devDiagnosticPhase,b as devSupervisorVersion,A as runDevSupervisorProcess,re as stopDevSupervisor};
|
|
1
|
+
import{DevDiagnostics as e,devDiagnosticContext as t,devDiagnosticError as n,devDiagnosticEvent as r,devDiagnosticPhase as i}from"./diagnostics.js";import{spawn as a}from"node:child_process";import{createHash as o,randomUUID as s}from"node:crypto";import{readFileSync as c}from"node:fs";import{appendFile as l,mkdir as u,readFile as ee,rename as te,rm as d,stat as f,unlink as p,writeFile as m}from"node:fs/promises";import{createConnection as ne,createServer as h}from"node:net";import{tmpdir as g}from"node:os";import _ from"node:path";import v from"node:process";import{Writable as y}from"node:stream";import{fileURLToPath as re}from"node:url";const ie=JSON.parse(c(_.resolve(_.dirname(re(import.meta.url)),`../package.json`),`utf8`)).version,b=`.coreframe/dev-supervisor`,x=`supervisor.json`,S=`logs`,C=1*1024*1024,w=4*1024*1024,T=45e3;async function ae({cwd:e=v.cwd(),env:t=v.env,requiredResources:n=[],supervisorEntry:r,implementationVersion:i}={}){let a=await E({cwd:e,env:t,requiredResources:n,implementationVersion:i});if(a)return a;let o=await z(e),s=await I(e,!i);if(!s){if(o=await L(e),!V(o,n))throw Error(`The development supervisor does not provide the required resources.`);return P({cwd:e,env:t,state:o})}try{if(o=await z(e),o&&o.cwd===_.resolve(e)&&Z(o.pid)&&i&&o.implementationVersion!==i){let n=await P({cwd:e,env:t,state:o});try{await n.retireIfIdle()}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`INVALID_REQUEST`;throw Error(t?`The existing development supervisor predates automatic handoff. Stop its dev servers and supervisor, then retry.`:`The existing development supervisor uses a different version and cannot hand off while it is active. Stop its dev servers and supervisor, then retry.`,{cause:e})}finally{n.close()}await R(e,o.supervisorId),o=void 0}if(o&&o.cwd===_.resolve(e)&&Z(o.pid)){if(!V(o,n))throw Error(`The development supervisor does not provide the required resources.`);return await P({cwd:e,env:t,state:o})}if(o&&await U(e,o),!r)throw Error(`A development supervisor process entry is required to start the supervisor.`);if(await F({cwd:e,env:t,entry:r}),o=await L(e),i&&o.implementationVersion!==i)throw Error(`The started development supervisor has an unexpected implementation version.`);if(!V(o,n))throw Error(`The development supervisor does not provide the required resources.`);return P({cwd:e,env:t,state:o})}finally{await s()}}async function E({cwd:e=v.cwd(),env:t=v.env,requiredResources:n=[],implementationVersion:r}={}){let i=await z(e);if(!(!i||i.cwd!==_.resolve(e)||!Z(i.pid)||!V(i,n)||r!==void 0&&i.implementationVersion!==r))try{return await P({cwd:e,env:t,state:i})}catch{await U(e,i);return}}async function D({cwd:e=v.cwd()}={}){let t=await z(e);if(!t||t.cwd!==_.resolve(e)||!Z(t.pid))return await U(e,t),!1;let n=await P({cwd:e,env:v.env,state:t});try{await n.shutdown()}finally{n.close()}return await R(e,t.supervisorId),!0}var O=class e{state;socket;pending=new Map;listeners=new Set;closeListeners=new Set;leases=new Set;decoder=new M;closed=!1;closeError;renewalTimer;constructor(e){this.state=e.state,this.socket=e.socket,this.socket.on(`data`,e=>{for(let t of this.decoder.push(e))this.handleFrame(t)}),this.socket.on(`close`,()=>this.handleClose(Error(`Development supervisor disconnected.`))),this.socket.on(`error`,e=>this.handleClose(e)),this.renewalTimer=setInterval(()=>void this.renewLeases(),T/3),this.renewalTimer.unref()}static async create(t){let n=new e(t);return await n.request(`hello`,{protocol:1,token:t.state.token}),n}async acquirePostgres({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`postgres`,config:e,env:Y(t??v.env)});return this.leases.add(n.leaseId),n}async acquireSqlite({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`sqlite`,config:e,env:Y(t??v.env)});return this.leases.add(n.leaseId),n}async acquireManagedDev({env:e}={}){let t=await this.request(`acquire`,{resource:`managed-dev`,env:Y(e??v.env)});return this.leases.add(t.leaseId),t}async managedDevAction({action:e,requestId:t,operationId:n,requestKey:r}){return this.request(`managed-dev-action`,{action:e,requestId:t,operationId:n,requestKey:r})}async managedDevStatus(){return this.request(`managed-dev-status`)}async resetIdleManagedDev(){return this.request(`managed-dev-reset-idle`)}async release(e){this.leases.delete(e),await this.request(`release`,{leaseId:e})}async subscribe(e){return this.request(`subscribe`,{resources:e})}async status(){return this.request(`status`)}async shutdown(){await this.request(`shutdown`)}async retireIfIdle(){await this.request(`retire-if-idle`)}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onClose(e){return this.closed?(e(this.closeError??Error(`Development supervisor client is closed.`)),()=>!1):(this.closeListeners.add(e),()=>this.closeListeners.delete(e))}waitForServiceExit(e){return this.closed?Promise.resolve():new Promise(t=>{let n=()=>{r(),this.closeListeners.delete(n),t()},r=this.onEvent(t=>{!(`resource`in t)||t.resource!==e||t.event!==`service`||(t.state===`failed`||t.state===`stopped`)&&n()});this.closeListeners.add(n)})}close(){this.closed||(this.socket.end(),this.handleClose(Error(`Development supervisor client closed.`)))}request(e,t){if(this.closed)return Promise.reject(Error(`Development supervisor client is closed.`));let n=s();return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i}),this.socket.write(N({id:n,method:e,params:t,type:`request`}))})}async renewLeases(){for(let e of this.leases)if(await this.request(`renew`,{leaseId:e}).catch(t=>{this.leases.delete(e),this.handleClose(t instanceof Error?t:Error(String(t))),this.socket.destroy()}),this.closed)return}handleFrame(e){if(e.type===`event`){for(let t of this.listeners)t(e.event);return}if(e.type!==`response`)return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.result):t.reject(se(e.error)))}handleClose(e){if(!this.closed){this.closed=!0,this.closeError=e,clearInterval(this.renewalTimer);for(let t of this.pending.values())t.reject(e);this.pending.clear();for(let t of this.closeListeners)t(e);this.closeListeners.clear()}}};async function k({cwd:e=v.cwd(),startPostgres:t,startSqlite:n,startManagedDev:r,implementationVersion:i}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let a=_.resolve(e,b);await u(a,{recursive:!0,mode:448}),await u(_.join(a,S),{recursive:!0,mode:448});let o=await z(e);if(o&&o.pid!==v.pid&&Z(o.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let s=W(e);v.platform!==`win32`&&await p(s).catch(()=>void 0);let c=new A({cwd:_.resolve(e),endpoint:s,root:a,startPostgres:t,startSqlite:n,startManagedDev:r,implementationVersion:i});await c.listen();let l=()=>{c.shutdown()};v.once(`SIGINT`,l),v.once(`SIGTERM`,l);try{await c.waitForShutdown()}finally{v.off(`SIGINT`,l),v.off(`SIGTERM`,l)}}var A=class{diagnostics;clients=new Set;leases=new Map;resourceOperations=new Map;server;root;state;startPostgres;startSqlite;startManagedDev;postgres;sqlite;managedDev;sequence=0;shutdownPromise;shutdownRequested=!1;idleTimer;leaseTimer;lastLeaseSweepAt=Date.now();postgresStopTimer;sqliteStopTimer;managedDevStopTimer;constructor({cwd:e,endpoint:t,root:n,startPostgres:r,startSqlite:i,startManagedDev:a,implementationVersion:o}){this.root=n,this.startPostgres=r,this.startSqlite=i,this.startManagedDev=a;let c=[`postgres`];i&&c.push(`sqlite`),a&&c.push(`managed-dev`),this.state={availableResources:c,cwd:e,endpoint:t,pid:v.pid,protocol:1,supervisorId:s(),token:s(),implementationVersion:o},this.server=h(e=>this.accept(e)),this.leaseTimer=setInterval(()=>this.expireLeases(),5e3),this.leaseTimer.unref()}async listen(){await new Promise((e,t)=>{this.server.once(`error`,t),this.server.listen(this.state.endpoint,()=>{this.server.off(`error`,t),e()})}),await H(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!0,stopSqlite:t=!0}={}){return this.shutdownPromise||=(async()=>{this.shutdownRequested=!0,this.idleTimer&&clearTimeout(this.idleTimer),clearInterval(this.leaseTimer),await Promise.all(this.resourceOperations.values()),this.leases.clear(),await this.stopManagedDev(),e?await this.stopPostgres():(this.cancelPostgresStop(),this.postgres=void 0),t?await this.stopSqlite():(this.cancelSqliteStop(),this.sqlite=void 0);for(let e of this.clients)e.close();await new Promise(e=>this.server.close(()=>e())),await p(this.state.endpoint).catch(()=>void 0),await p(_.join(this.root,x)).catch(()=>void 0),this.diagnostics?.event(`supervisor.stopped`,{supervisorId:this.state.supervisorId}),this.diagnostics?.close(),this.resolveShutdown?.()})(),this.shutdownPromise}resolveShutdown;accept(e){let t=new j(this,e);this.clients.add(t),e.once(`close`,()=>{this.clients.delete(t);for(let e of this.leases.values())e.connection===t&&this.releaseLease(e.id);this.maybeScheduleIdleShutdown()})}async handleRequest(e,t){try{let n=await this.dispatch(e,t.method,t.params??{});e.respond(t.id,{ok:!0,result:n})}catch(n){e.respond(t.id,{ok:!1,error:$(n)})}}publish(e,t){let n={...e,sequence:++this.sequence,timestamp:new Date().toISOString()};if(t)t.publish(n);else for(let e of this.clients)e.publish(n);return n}async addSubscription(e,t){return e.subscribe(t),e.publish({event:`replay-complete`,sequence:this.sequence,timestamp:new Date().toISOString()}),{subscriptionId:s()}}async dispatch(e,t,n){if(this.shutdownRequested&&t!==`shutdown`)throw Q(`SUPERVISOR_STOPPING`,`Development supervisor is stopping.`,!0);switch(t){case`hello`:return this.hello(e,n);case`status`:return this.status();case`managed-dev-status`:return this.managedDevStatus();case`managed-dev-reset-idle`:return this.withResourceOperation(`managed-dev`,async()=>!this.managedDev||this.managedDev.leases.size>0?{reset:!1}:(await this.stopManagedDev(),{reset:!0}));case`managed-dev-action`:return this.managedDevAction(e,n);case`subscribe`:return this.addSubscription(e,oe(n.resources));case`acquire`:return this.withResourceOperation(G(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(q(n.leaseId));return;case`renew`:return this.renewLease(q(n.leaseId));case`shutdown`:this.shutdownRequested=!0,setImmediate(()=>void this.shutdown({stopPostgres:!1}));return;case`retire-if-idle`:if(this.leases.size>0||this.resourceOperations.size>0)throw Q(`SUPERVISOR_BUSY`,`Development supervisor still owns active work.`,!0);this.shutdownRequested=!0,setImmediate(()=>void this.shutdown());return;default:throw Q(`INVALID_REQUEST`,`Unknown supervisor method: ${t}.`,!1)}}async withResourceOperation(e,t){let n=this.resourceOperations.get(e),r,i=new Promise(e=>{r=e});this.resourceOperations.set(e,i),n&&await n;try{return await t()}finally{r(),this.resourceOperations.get(e)===i&&this.resourceOperations.delete(e)}}hello(e,t){if(t.protocol!==1||t.token!==this.state.token)throw e.close(),Q(`AUTH_FAILED`,`Invalid supervisor protocol or token.`,!1);return e.authenticated=!0,{cwd:this.state.cwd,protocol:1,supervisorId:this.state.supervisorId}}status(){return{managedDev:this.managedDev?{leases:this.managedDev.leases.size,state:`running`}:void 0,postgres:this.postgres?{leases:this.postgres.leases.size,state:`running`}:void 0,sqlite:this.sqlite?{leases:this.sqlite.leases.size,state:`running`}:void 0}}async acquire(e,t){let n=G(t.resource);if(n===`managed-dev`)return this.acquireManagedDev(e,K(t));if(n===`postgres`)return this.acquirePostgres(e,K(t));if(n===`sqlite`)return this.acquireSqlite(e,K(t));throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${n}.`,!1)}async acquireManagedDev(t,n){if(!this.startManagedDev)throw Error(`A managed development starter is required to run managed development.`);if(this.diagnostics??=new e(this.state.cwd,`supervisor`),this.diagnostics.event(`supervisor.attached`,{supervisorId:this.state.supervisorId,reused:!!this.managedDev}),this.managedDev){this.cancelManagedDevStop();let e=this.createLease(t,`managed-dev`);return this.managedDev.leases.add(e.id),{leaseId:e.id,state:`reused`,status:this.managedDev.session.getStatus()}}let r=J(n.env),i=await this.startManagedDev({cwd:this.state.cwd,env:Y(r),onRestart:()=>{this.diagnostics?.event(`restart.requested`,{supervisorId:this.state.supervisorId}),this.publish({event:`managed-dev`,kind:`restart`,resource:`managed-dev`})},onStatusChange:e=>{this.publish({event:`managed-dev`,kind:`status`,resource:`managed-dev`,status:e})}}),a={leases:new Set,session:i};this.managedDev=a;try{await i.activate()}catch(e){throw this.managedDev=void 0,await i.close(),e}let o=this.createLease(t,`managed-dev`);return a.leases.add(o.id),{leaseId:o.id,state:`started`,status:i.getStatus()}}managedDevStatus(){if(!this.managedDev)throw Error(`Managed development is not active.`);return{status:this.managedDev.session.getStatus()}}async managedDevAction(e,t){if(!this.managedDev)throw Error(`Managed development is not active.`);let n=q(t.requestId);if(!n)throw Q(`INVALID_REQUEST`,`A managed development action request ID is required.`,!1);try{let r=q(t.operationId)||n;return await this.diagnostics.run({operationId:r,supervisorId:this.state.supervisorId,supervisorRequestId:n},()=>i(`supervisor.action`,()=>this.managedDev.session.action(t.action,{operationId:r,requestKey:q(t.requestKey)||void 0,onCodexEvent:t=>{this.publish({codex:t,event:`managed-dev`,kind:`codex`,requestId:n,resource:`managed-dev`},e)}})))}catch(e){return{error:e instanceof Error?e.message:String(e),status:this.managedDev.session.getStatus()}}}async acquirePostgres(e,t){let n=this.postgres===void 0;if(this.postgres)this.cancelPostgresStop();else{let e=await this.createLogStream(`postgres`),n=J(t.env),r=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:Y(n),failIfRunning:!1,postgresOutput:e});this.postgres={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:Y(this.postgres.env),leaseId:r.id,state:n?`started`:`reused`}}async acquireSqlite(e,t){if(!this.startSqlite)throw Error(`A SQLite starter is required to run the development supervisor.`);let n=this.sqlite===void 0;if(this.sqlite)this.cancelSqliteStop();else{let e=await this.createLogStream(`sqlite`),n=J(t.env),r=await this.startSqlite({config:t.config,cwd:this.state.cwd,env:Y(n),tursoOutput:e});this.sqlite={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`sqlite`,state:`running`})}let r=this.createLease(e,`sqlite`);return this.sqlite.leases.add(r.id),{env:Y(this.sqlite.env),leaseId:r.id,state:n?`started`:`reused`}}createLease(e,t){let n={connection:e,expiresAt:Date.now()+T,id:s(),resource:t};return this.leases.set(n.id,n),t===`managed-dev`&&this.diagnostics?.event(`lease.acquired`,{leaseId:n.id,supervisorId:this.state.supervisorId}),n}renewLease(e){let t=this.leases.get(e);if(!t)throw this.diagnostics?.event(`lease.renewal-rejected`,{leaseId:e},`warn`),Q(`LEASE_EXPIRED`,`The supervisor lease is no longer active.`,!0);return t.expiresAt=Date.now()+T,{expiresAt:t.expiresAt}}expireLeases(){let e=Date.now(),t=e-this.lastLeaseSweepAt;if(this.lastLeaseSweepAt=e,t>=1e4){this.diagnostics?.event(`supervisor.resumed`,{sweepDelayMs:t});for(let t of this.leases.values())t.expiresAt=Math.max(t.expiresAt,e+T);return}for(let t of this.leases.values())t.expiresAt<=e&&(t.resource===`managed-dev`&&this.diagnostics?.event(`lease.expired`,{leaseId:t.id,overdueMs:e-t.expiresAt},`warn`),this.releaseLease(t.id))}async releaseLease(e){let t=this.leases.get(e);t&&(this.leases.delete(e),t.resource===`postgres`?(this.postgres?.leases.delete(e),this.postgres?.leases.size===0&&this.schedulePostgresStop()):t.resource===`sqlite`?(this.sqlite?.leases.delete(e),this.sqlite?.leases.size===0&&this.scheduleSqliteStop()):t.resource===`managed-dev`&&(this.managedDev?.leases.delete(e),this.diagnostics?.event(`lease.released`,{leaseId:e,remainingLeases:this.managedDev?.leases.size}),this.managedDev?.leases.size===0&&this.scheduleManagedDevStop()),this.maybeScheduleIdleShutdown())}async stopPostgres(){if(this.cancelPostgresStop(),!this.postgres)return;let e=this.postgres;this.postgres=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`postgres`,state:`stopped`})}schedulePostgresStop(){this.postgresStopTimer||(this.postgresStopTimer=setTimeout(()=>{this.postgresStopTimer=void 0,this.withResourceOperation(`postgres`,async()=>{this.postgres?.leases.size===0&&await this.stopPostgres()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.postgresStopTimer.unref())}async stopSqlite(){if(this.cancelSqliteStop(),!this.sqlite)return;let e=this.sqlite;this.sqlite=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`sqlite`,state:`stopped`})}async stopManagedDev(){if(this.cancelManagedDevStop(),!this.managedDev)return;let e=this.managedDev;this.diagnostics?.event(`session.stopping`,{supervisorId:this.state.supervisorId}),await e.session.close(),this.managedDev=void 0}scheduleSqliteStop(){this.sqliteStopTimer||(this.sqliteStopTimer=setTimeout(()=>{this.sqliteStopTimer=void 0,this.withResourceOperation(`sqlite`,async()=>{this.sqlite?.leases.size===0&&await this.stopSqlite()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.sqliteStopTimer.unref())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),void 0)}cancelSqliteStop(){this.sqliteStopTimer&&=(clearTimeout(this.sqliteStopTimer),void 0)}scheduleManagedDevStop(){this.managedDevStopTimer||(this.managedDevStopTimer=setTimeout(()=>{this.managedDevStopTimer=void 0,this.withResourceOperation(`managed-dev`,async()=>{this.managedDev?.leases.size===0&&await this.stopManagedDev()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e4),this.managedDevStopTimer.unref())}cancelManagedDevStop(){this.managedDevStopTimer&&=(clearTimeout(this.managedDevStopTimer),void 0)}async createLogStream(e){let t=_.join(this.root,S,`${e.replaceAll(`:`,`-`)}.log`);await u(_.dirname(t),{recursive:!0,mode:448}),await m(t,``);let n=0;return new y({write:(r,i,a)=>{let o=String(r),s=Buffer.from(o),c=s.subarray(Math.max(0,s.length-C)),u=n+c.length>C;(u?m(t,c):l(t,c)).then(()=>{n=u?c.length:n+c.length,a()},a),this.publish({event:`log`,resource:e,stream:`stdout`,data:o})}})}maybeScheduleIdleShutdown(){this.leases.size>0||this.postgres||this.sqlite||this.managedDev||this.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&!this.postgres&&!this.sqlite&&!this.managedDev&&this.shutdown()},3e4),this.idleTimer.unref())}},j=class{authenticated=!1;decoder=new M;subscriptions=new Set;eventQueue=[];queuedEventBytes=0;writingEvent=!1;droppedEventRange;server;socket;constructor(e,t){this.server=e,this.socket=t,t.on(`error`,()=>this.close()),t.on(`data`,t=>{try{for(let n of this.decoder.push(t))n.type===`request`&&(!this.authenticated&&n.method!==`hello`?this.respond(n.id,{ok:!1,error:$(Q(`AUTH_FAILED`,`Send hello first.`,!1))}):e.handleRequest(this,n))}catch{this.close()}})}respond(e,t){this.socket.write(N({...t,id:e,type:`response`}))}publish(e){let t=[...this.subscriptions];t.length!==0&&(e.event!==`replay-complete`&&e.event!==`gap`&&(e.resource===void 0||!t.some(t=>t.has(e.resource)))||this.enqueueEvent(e))}subscribe(e){this.subscriptions.add(new Set(e))}close(){this.eventQueue.length=0,this.queuedEventBytes=0,this.socket.destroy()}enqueueEvent(e){let t=N({event:e,type:`event`});if(t.length>w){this.noteDropped(e);return}for(;;){let n=this.droppedEventRange?{event:{event:`gap`,from:this.droppedEventRange.from,reason:`buffer-overflow`,to:this.droppedEventRange.to,sequence:e.sequence,timestamp:new Date().toISOString()},frame:Buffer.alloc(0)}:void 0;n&&(n.frame=N({event:n.event,type:`event`}));let r=t.length+(n?.frame.length??0),i=!1;for(;this.queuedEventBytes+r>w;){let e=this.eventQueue.shift();if(!e)break;i=!0,this.queuedEventBytes-=e.frame.length,this.noteDropped(e.event)}if(!i){if(this.queuedEventBytes+r<=w){n&&(this.eventQueue.push(n),this.queuedEventBytes+=n.frame.length,this.droppedEventRange=void 0),this.eventQueue.push({event:e,frame:t}),this.queuedEventBytes+=t.length,this.pumpEvents();return}if(this.eventQueue.length===0){this.noteDropped(e);return}}}}noteDropped(e){let t=e.sequence;if(!this.droppedEventRange){this.droppedEventRange={from:t,to:t};return}this.droppedEventRange.from=Math.min(this.droppedEventRange.from,t),this.droppedEventRange.to=Math.max(this.droppedEventRange.to,t)}pumpEvents(){if(this.writingEvent||this.eventQueue.length===0||this.socket.destroyed)return;let e=this.eventQueue.shift();this.queuedEventBytes-=e.frame.length,this.writingEvent=!0,this.socket.write(e.frame,()=>{this.writingEvent=!1,this.pumpEvents()})}},M=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,Buffer.from(e)]);let t=[];for(;this.buffer.length>=4;){let e=this.buffer.readUInt32BE(0);if(e>16777216)throw Error(`Development supervisor protocol frame is too large.`);if(this.buffer.length<e+4)break;let n=this.buffer.subarray(4,e+4).toString(`utf8`);this.buffer=this.buffer.subarray(e+4),t.push(JSON.parse(n))}return t}};function N(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.allocUnsafe(t.length+4);return n.writeUInt32BE(t.length,0),t.copy(n,4),n}async function P(e){let t=await new Promise((t,n)=>{let r=ne(e.state.endpoint);r.once(`connect`,()=>t(r)),r.once(`error`,n)});return O.create({...e,socket:t})}async function F({cwd:e,env:t,entry:n}){a(v.execPath,[n,`--cwd`,e],{cwd:e,detached:!0,env:{...t,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function I(e,t=!0){let n=_.join(e,b),r=_.join(n,`start.lock`),i=Date.now()+1e4;for(await u(n,{recursive:!0,mode:448});Date.now()<i;)try{return await m(r,`${v.pid}\n`,{flag:`wx`,mode:384}),async()=>{await p(r).catch(()=>void 0)}}catch(n){if(!(n instanceof Error&&n.code===`EEXIST`))throw n;let i=await z(e);if(t&&i&&Z(i.pid))return;try{let e=await f(r);if(Date.now()-e.mtimeMs>1e4){await p(r).catch(()=>void 0);continue}}catch{continue}await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor startup is already in progress.`)}async function L(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await z(e);if(t&&Z(t.pid))return t;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not start within 10 seconds.`)}async function R(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await z(e);if(!n||n.supervisorId!==t)return;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not stop within 10 seconds.`)}async function z(e){try{let t=JSON.parse(await ee(_.join(e,b,x),`utf8`)),n=t.availableResources===void 0?[`postgres`]:Array.isArray(t.availableResources)&&t.availableResources.every(B)?t.availableResources:void 0;return!n||t.protocol!==1||typeof t.cwd!=`string`||typeof t.endpoint!=`string`||typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.supervisorId!=`string`||t.implementationVersion!==void 0&&typeof t.implementationVersion!=`string`||typeof t.token!=`string`?void 0:{...t,availableResources:n}}catch{return}}function B(e){return e===`managed-dev`||e===`postgres`||e===`sqlite`}function V(e,t){return t.every(t=>e.availableResources.includes(t))}async function H(e,t){let n=_.join(t,x),r=`${n}.${s()}.tmp`;await u(_.dirname(n),{recursive:!0,mode:448});try{await m(r,`${JSON.stringify(e)}\n`,{flag:`wx`,mode:384}),await te(r,n)}finally{await p(r).catch(()=>void 0)}}async function U(e,t){t&&t.cwd!==_.resolve(e)||(await d(_.join(e,b,x),{force:!0}),t&&v.platform!==`win32`&&await p(t.endpoint).catch(()=>void 0))}function W(e){if(v.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${o(`sha256`).update(_.resolve(e)).digest(`hex`).slice(0,24)}`;let t=o(`sha256`).update(_.resolve(e)).digest(`hex`).slice(0,24);return _.join(g(),`coreframe-dev-${t}-supervisor.sock`)}function oe(e){return Array.isArray(e)?e.map(G):[`managed-dev`,`postgres`,`sqlite`]}function G(e){if(e===`managed-dev`||e===`postgres`||e===`sqlite`)return e;throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function K(e){return e&&typeof e==`object`?e:{}}function q(e){return typeof e==`string`?e:String(e??``)}function J(e){let t=K(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function Y(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function X(e,t){return Object.fromEntries(Object.entries(t).filter(t=>{let[n,r]=t;return r!==void 0&&e[n]!==r}))}function Z(e){try{return v.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Q(e,t,n,r){return Object.assign(Error(t),{code:e,details:r,retryable:n})}function $(e){if(e&&typeof e==`object`){let t=e;return{code:t.code??`SUPERVISOR_ERROR`,details:t.details,message:t.message??String(e),retryable:t.retryable??!1}}return{code:`SUPERVISOR_ERROR`,message:String(e),retryable:!1}}function se(e){let t=Error(e?.message??`Development supervisor request failed.`);return t.code=e?.code,t.details=e?.details,t.retryable=e?.retryable,t}export{e as DevDiagnostics,O as DevSupervisorClient,ae as connectDevSupervisor,E as connectExistingDevSupervisor,t as devDiagnosticContext,n as devDiagnosticError,r as devDiagnosticEvent,i as devDiagnosticPhase,ie as devSupervisorVersion,k as runDevSupervisorProcess,D as stopDevSupervisor};
|