@coreframe/dev-supervisor 0.2.4 → 0.2.5
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/diagnostics.d.ts +1 -1
- package/dist/diagnostics.js +1 -1
- package/dist/index.d.ts +18 -3
- package/dist/index.js +1 -1
- package/dist/lazy-tcp-proxy.d.ts +28 -0
- package/dist/lazy-tcp-proxy.js +1 -0
- package/dist/project-services.js +1 -0
- package/package.json +2 -2
package/dist/diagnostics.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ declare class DevDiagnostics {
|
|
|
13
13
|
private logs;
|
|
14
14
|
private logger;
|
|
15
15
|
private closed;
|
|
16
|
-
constructor(cwd: string, component: string, onEvent?: ((event: DevDiagnosticEvent) => void) | undefined);
|
|
16
|
+
constructor(cwd: string, component: string, onEvent?: ((event: DevDiagnosticEvent) => void) | undefined, scope?: string);
|
|
17
17
|
event(event: string, properties?: Properties, level?: Level): void;
|
|
18
18
|
run<T>(properties: Properties, operation: () => T): T;
|
|
19
19
|
close(): void;
|
package/dist/diagnostics.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as e}from"node:crypto";import{readFileSync as t}from"node:fs";import n from"node:path";import{AsyncLocalStorage as r}from"node:async_hooks";import{openScopedLogs as i}from"leylines";const a=new r,o=(()=>{try{return JSON.parse(t(new URL(`../package.json`,import.meta.url),`utf8`)).version}catch{return`unknown`}})();var s=class{onEvent;instanceId=e();logs;logger;closed=!1;constructor(e,t,r){this.onEvent=r;try{this.logs=i({path:n.resolve(e,`.leylines`,`logs.sqlite`)}),this.logger=this.logs.logger({scope
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{readFileSync as t}from"node:fs";import n from"node:path";import{AsyncLocalStorage as r}from"node:async_hooks";import{openScopedLogs as i}from"leylines";const a=new r,o=(()=>{try{return JSON.parse(t(new URL(`../package.json`,import.meta.url),`utf8`)).version}catch{return`unknown`}})();var s=class{onEvent;instanceId=e();logs;logger;closed=!1;constructor(e,t,r,a=`dev.managed`){this.onEvent=r;try{this.logs=i({path:n.resolve(e,`.leylines`,`logs.sqlite`)}),this.logger=this.logs.logger({scope:a,properties:{component:t,instanceId:this.instanceId,pid:process.pid,supervisorVersion:o,nodeVersion:process.version}})}catch{}}event(e,t={},n=`info`){if(this.closed)return;let r=a.getStore(),i={...r?.diagnostics===this?r.properties:void 0,...t};try{this.onEvent?.({event:e,properties:i,level:n})}catch{}try{this.logger?.write(n,e,{properties:Object.fromEntries(Object.entries(i).filter(([,e])=>e!==void 0))})}catch{}}run(e,t){let n=a.getStore();return a.run({diagnostics:this,properties:{...n?.diagnostics===this?n.properties:void 0,...e}},t)}close(){this.closed=!0;try{this.logs?.close()}catch{}}};function c(){return a.getStore()?.properties}function l(e,t,n){a.getStore()?.diagnostics.event(e,t,n)}async function u(t,n,r={},{level:i=`info`,warnAfterMs:o=3e4}={}){let s=a.getStore();if(!s)return n();let c=performance.now(),l={phase:t,phaseId:e(),...r};s.diagnostics.event(`phase.started`,l,i);let u=setInterval(()=>s.diagnostics.event(`phase.slow`,{...s.properties,...l,durationMs:Math.round(performance.now()-c)},`warn`),o);u.unref();try{let e=await n();return s.diagnostics.event(`phase.completed`,{...l,durationMs:Math.round(performance.now()-c)},i),e}catch(e){throw s.diagnostics.event(`phase.failed`,{...l,durationMs:Math.round(performance.now()-c),...d(e)},`error`),e}finally{clearInterval(u)}}function d(e){let t=e,n=typeof t?.code==`string`&&/^[A-Z][A-Z0-9_]{0,63}$/.test(t.code)?t.code:void 0,r=typeof t?.stderr==`string`?t.stderr:``,i=/cannot lock ref|index\.lock|another git process/i.test(r)?`locked`:/authentication failed|could not read username|permission denied \(publickey\)/i.test(r)?`authentication`:/could not resolve host|unable to access|connection timed out/i.test(r)?`network`:/would be overwritten|local changes/i.test(r)?`working-tree-changed`:/CONFLICT|unmerged files|could not apply/i.test(r)?`conflict`:void 0;return{errorCode:n,exitCode:typeof t?.exitCode==`number`?t.exitCode:void 0,signal:typeof t?.signalName==`string`&&/^SIG[A-Z0-9]+$/.test(t.signalName)?t.signalName:void 0,gitFailure:i}}export{s as DevDiagnostics,c as devDiagnosticContext,d as devDiagnosticError,l as devDiagnosticEvent,u as devDiagnosticPhase};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
+
import { LazyTcpProxy, LazyTcpProxyOptions, LazyTcpProxyTarget, createLazyTcpProxy } from "./lazy-tcp-proxy.js";
|
|
1
2
|
import { DevDiagnosticEvent, DevDiagnostics, devDiagnosticContext, devDiagnosticError, devDiagnosticEvent, devDiagnosticPhase } from "./diagnostics.js";
|
|
2
3
|
import { Socket } from "node:net";
|
|
3
4
|
import { Writable } from "node:stream";
|
|
4
|
-
import { CoreframeConfig } from "@coreframe/config";
|
|
5
|
+
import { CoreframeConfig, DevConfig } from "@coreframe/config";
|
|
5
6
|
|
|
6
7
|
//#region src/index.d.ts
|
|
7
8
|
declare const protocolVersion = 1;
|
|
8
9
|
declare const devSupervisorVersion: string;
|
|
9
|
-
type DevSupervisorResource = "managed-dev" | "postgres" | "sqlite";
|
|
10
|
+
type DevSupervisorResource = "managed-dev" | "postgres" | "sqlite" | "project-services";
|
|
10
11
|
type DevSupervisorStream = "stdout" | "stderr";
|
|
11
12
|
type DevSupervisorEvent = DevSupervisorLogEvent | DevSupervisorManagedDevEvent | DevSupervisorServiceEvent | DevSupervisorGapEvent | DevSupervisorReplayCompleteEvent;
|
|
12
13
|
type DevSupervisorLogEvent = {
|
|
@@ -119,6 +120,7 @@ type DevSupervisorManagedDevSession = {
|
|
|
119
120
|
}): Promise<unknown>;
|
|
120
121
|
activate(): Promise<void>;
|
|
121
122
|
getStatus(): unknown;
|
|
123
|
+
notifyCheckoutChanged?(): void;
|
|
122
124
|
close(): Promise<void>;
|
|
123
125
|
};
|
|
124
126
|
type DevSupervisorManagedDevStarter = (options: {
|
|
@@ -186,6 +188,18 @@ declare class DevSupervisorClient {
|
|
|
186
188
|
leaseId: string;
|
|
187
189
|
state: "reused" | "started";
|
|
188
190
|
}>;
|
|
191
|
+
/** Reserve loopback endpoints for this session without starting any service processes. */
|
|
192
|
+
acquireProjectServices({
|
|
193
|
+
services,
|
|
194
|
+
env
|
|
195
|
+
}: {
|
|
196
|
+
services: NonNullable<DevConfig["services"]>;
|
|
197
|
+
env?: NodeJS.ProcessEnv;
|
|
198
|
+
}): Promise<{
|
|
199
|
+
bindings: Record<string, string>;
|
|
200
|
+
endpoints: Record<string, string>;
|
|
201
|
+
leaseId: string;
|
|
202
|
+
}>;
|
|
189
203
|
acquireManagedDev({
|
|
190
204
|
env
|
|
191
205
|
}?: {
|
|
@@ -212,6 +226,7 @@ declare class DevSupervisorClient {
|
|
|
212
226
|
managedDevStatus(): Promise<{
|
|
213
227
|
status: unknown;
|
|
214
228
|
}>;
|
|
229
|
+
notifyManagedDevCheckoutChanged(leaseId: string): Promise<void>;
|
|
215
230
|
resetIdleManagedDev(): Promise<{
|
|
216
231
|
reset: boolean;
|
|
217
232
|
}>;
|
|
@@ -245,4 +260,4 @@ declare function runDevSupervisorProcess({
|
|
|
245
260
|
implementationVersion?: string;
|
|
246
261
|
}): Promise<void>;
|
|
247
262
|
//#endregion
|
|
248
|
-
export { type DevDiagnosticEvent, DevDiagnostics, DevSupervisorClient, DevSupervisorEvent, DevSupervisorManagedDevEvent, DevSupervisorManagedDevSession, DevSupervisorManagedDevStarter, DevSupervisorPostgresSidecar, DevSupervisorPostgresStarter, DevSupervisorResource, DevSupervisorSqliteSidecar, DevSupervisorSqliteStarter, DevSupervisorState, DevSupervisorStream, connectDevSupervisor, connectExistingDevSupervisor, devDiagnosticContext, devDiagnosticError, devDiagnosticEvent, devDiagnosticPhase, devSupervisorVersion, runDevSupervisorProcess, stopDevSupervisor };
|
|
263
|
+
export { type DevDiagnosticEvent, DevDiagnostics, DevSupervisorClient, DevSupervisorEvent, DevSupervisorManagedDevEvent, DevSupervisorManagedDevSession, DevSupervisorManagedDevStarter, DevSupervisorPostgresSidecar, DevSupervisorPostgresStarter, DevSupervisorResource, DevSupervisorSqliteSidecar, DevSupervisorSqliteStarter, DevSupervisorState, DevSupervisorStream, type LazyTcpProxy, type LazyTcpProxyOptions, type LazyTcpProxyTarget, connectDevSupervisor, connectExistingDevSupervisor, createLazyTcpProxy, devDiagnosticContext, devDiagnosticError, devDiagnosticEvent, devDiagnosticPhase, devSupervisorVersion, runDevSupervisorProcess, stopDevSupervisor };
|
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 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};
|
|
1
|
+
import{DevDiagnostics as e,devDiagnosticContext as t,devDiagnosticError as n,devDiagnosticEvent as r,devDiagnosticPhase as i}from"./diagnostics.js";import{createLazyTcpProxy as a}from"./lazy-tcp-proxy.js";import{prepareProjectServices as o}from"./project-services.js";import{spawn as s}from"node:child_process";import{createHash as c,randomUUID as l}from"node:crypto";import{readFileSync as ee}from"node:fs";import{appendFile as u,mkdir as d,readFile as f,rename as te,rm as ne,stat as re,unlink as p,writeFile as m}from"node:fs/promises";import{createConnection as h,createServer as ie}from"node:net";import{tmpdir as g}from"node:os";import _ from"node:path";import v from"node:process";import{Writable as ae}from"node:stream";import{fileURLToPath as oe}from"node:url";const y=JSON.parse(ee(_.resolve(_.dirname(oe(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 E({cwd:e=v.cwd(),env:t=v.env,requiredResources:n=[],supervisorEntry:r,implementationVersion:i}={}){let a=await D({cwd:e,env:t,requiredResources:n,implementationVersion:i});if(a)return a;let o=await R(e),s=await F(e,!i);if(!s){if(o=await I(e),!B(o,n))throw Error(`The development supervisor does not provide the required resources.`);return N({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 N({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 N({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 P({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 N({cwd:e,env:t,state:o})}finally{await s()}}async function D({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 N({cwd:e,env:t,state:i})}catch{await H(e,i);return}}async function O({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 N({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 j;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 acquireProjectServices({services:e,env:t=v.env}){let n=await this.request(`acquire`,{resource:`project-services`,services:e,env:Y(t)});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 notifyManagedDevCheckoutChanged(e){await this.request(`managed-dev-checkout-changed`,{leaseId:e})}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=l();return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i}),this.socket.write(M({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(le(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,b);await d(a,{recursive:!0,mode:448}),await d(_.join(a,S),{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 se({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 se=class{diagnostics;clients=new Set;leases=new Map;resourceOperations=new Map;server;root;state;startPostgres;startSqlite;startManagedDev;postgres;sqlite;managedDev;projectServices=new Map;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 s=[`postgres`,`project-services`];i&&s.push(`sqlite`),a&&s.push(`managed-dev`),this.state={availableResources:s,cwd:e,endpoint:t,pid:v.pid,protocol:1,supervisorId:l(),token:l(),implementationVersion:o},this.server=ie(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 Promise.all([...this.projectServices.values()].map(e=>e.close())),this.projectServices.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 ce(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:l()}}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-checkout-changed`:{let t=this.leases.get(q(n.leaseId));t?.connection===e&&t.resource===`managed-dev`&&this.managedDev?.session.notifyCheckoutChanged?.();return}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));if(n===`project-services`)return this.acquireProjectServices(e,t);throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${n}.`,!1)}async acquireProjectServices(e,t){let n=await o({cwd:this.state.cwd,env:J(t.env),services:t.services,onFailure:t=>{this.publish({event:`service`,resource:`project-services`,state:`failed`,error:t},e)}});if(e.closed||this.shutdownRequested)throw await n.close(),Error(`The development session ended before its service endpoints were ready.`);let r=this.createLease(e,`project-services`);return this.projectServices.set(r.id,n),{bindings:n.bindings,endpoints:n.endpoints,leaseId:r.id}}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:l(),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===`project-services`?await this.withResourceOperation(`project-services`,async()=>{let t=this.projectServices.get(e);this.projectServices.delete(e),await t?.close()}):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 d(_.dirname(t),{recursive:!0,mode:448}),await m(t,``);let n=0;return new ae({write:(r,i,a)=>{let o=String(r),s=Buffer.from(o),c=s.subarray(Math.max(0,s.length-C)),l=n+c.length>C;(l?m(t,c):u(t,c)).then(()=>{n=l?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())}},ce=class{authenticated=!1;decoder=new j;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()}})}get closed(){return this.socket.destroyed||this.socket.readableEnded}respond(e,t){this.socket.write(M({...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=M({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=M({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()})}},j=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 M(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 N(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 P({cwd:e,env:t,entry:n}){s(v.execPath,[n,`--cwd`,e],{cwd:e,detached:!0,env:{...t,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function F(e,t=!0){let n=_.join(e,b),r=_.join(n,`start.lock`),i=Date.now()+1e4;for(await d(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 re(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 f(_.join(e,b,x),`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.projectServices===!0&&!n.includes(`project-services`)&&n.push(`project-services`),{...t,availableResources:n})}catch{return}}function z(e){return e===`managed-dev`||e===`postgres`||e===`sqlite`||e===`project-services`}function B(e,t){return t.every(t=>e.availableResources.includes(t))}async function V(e,t){let n=_.join(t,x),r=`${n}.${l()}.tmp`;await d(_.dirname(n),{recursive:!0,mode:448});try{let t={...e,availableResources:e.availableResources.filter(e=>e!==`project-services`),projectServices:e.availableResources.includes(`project-services`)};await m(r,`${JSON.stringify(t)}\n`,{flag:`wx`,mode:384}),await te(r,n)}finally{await p(r).catch(()=>void 0)}}async function H(e,t){t&&t.cwd!==_.resolve(e)||(await ne(_.join(e,b,x),{force:!0}),t&&v.platform!==`win32`&&await p(t.endpoint).catch(()=>void 0))}function U(e){if(v.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${c(`sha256`).update(_.resolve(e)).digest(`hex`).slice(0,24)}`;let t=c(`sha256`).update(_.resolve(e)).digest(`hex`).slice(0,24);return _.join(g(),`coreframe-dev-${t}-supervisor.sock`)}function W(e){return Array.isArray(e)?e.map(G):[`managed-dev`,`postgres`,`sqlite`,`project-services`]}function G(e){if(z(e))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 le(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,E as connectDevSupervisor,D as connectExistingDevSupervisor,a as createLazyTcpProxy,t as devDiagnosticContext,n as devDiagnosticError,r as devDiagnosticEvent,i as devDiagnosticPhase,y as devSupervisorVersion,A as runDevSupervisorProcess,O as stopDevSupervisor};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Socket } from "node:net";
|
|
2
|
+
|
|
3
|
+
//#region src/lazy-tcp-proxy.d.ts
|
|
4
|
+
type LazyTcpProxyTarget = {
|
|
5
|
+
host?: string;
|
|
6
|
+
port: number;
|
|
7
|
+
};
|
|
8
|
+
type LazyTcpProxy = {
|
|
9
|
+
close(): Promise<void>;
|
|
10
|
+
fail(error: unknown): void;
|
|
11
|
+
listen(): Promise<number>;
|
|
12
|
+
wait(): Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
type LazyTcpProxyOptions = {
|
|
15
|
+
host?: string;
|
|
16
|
+
port: number; /** Time to retry connecting to the target after start returns. */
|
|
17
|
+
connectTimeoutMs?: number;
|
|
18
|
+
start(): Promise<LazyTcpProxyTarget>;
|
|
19
|
+
};
|
|
20
|
+
/** Proxies TCP connections after lazily starting the target on the first connection. */
|
|
21
|
+
declare function createLazyTcpProxy({
|
|
22
|
+
host,
|
|
23
|
+
port,
|
|
24
|
+
connectTimeoutMs,
|
|
25
|
+
start
|
|
26
|
+
}: LazyTcpProxyOptions): LazyTcpProxy;
|
|
27
|
+
//#endregion
|
|
28
|
+
export { LazyTcpProxy, LazyTcpProxyOptions, LazyTcpProxyTarget, createLazyTcpProxy };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createConnection as e,createServer as t}from"node:net";import{setTimeout as n}from"node:timers/promises";function r({host:e=`127.0.0.1`,port:n,connectTimeoutMs:r=1e4,start:s}){let c=new AbortController,l=new Set,u,d,f=new Promise((e,t)=>{u=e,d=t});f.catch(()=>void 0);let p,m,h,g=t({allowHalfOpen:!0,pauseOnConnect:!0},e=>{l.add(e);let t=new AbortController;e.on(`error`,()=>e.destroy()),e.once(`close`,()=>{l.delete(e),t.abort()}),_(e,t.signal).catch(()=>e.destroy())});async function _(e,t){let n=AbortSignal.any([c.signal,t]);n.throwIfAborted(),p??=Promise.resolve().then(s).catch(e=>{throw b(e),e});let i=await o(await p,r,n);if(n.aborted){i.destroy();return}l.add(i),i.on(`error`,()=>e.destroy()),i.once(`close`,()=>{l.delete(i),(!i.readableEnded||!i.writableFinished)&&e.destroy()}),e.once(`close`,()=>{(!e.readableEnded||!e.writableFinished)&&i.destroy()}),e.pipe(i),i.pipe(e)}function v(){c.abort();for(let e of l)e.destroy()}function y(){return u(),v(),h??=(async()=>{await m?.catch(()=>void 0),await a(g)})(),h}function b(e){d(e),v()}return{close:y,fail:b,listen(){return c.signal.throwIfAborted(),m??=i(g,n,e).then(e=>(g.on(`error`,b),e)),m},wait:()=>f}}function i(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(t,n,()=>{e.off(`error`,i);let t=e.address();if(!t||typeof t==`string`){i(Error(`Could not read the bound TCP port.`));return}r(t.port)})})}function a(e){return new Promise(t=>e.close(()=>t()))}async function o({host:t=`127.0.0.1`,port:r},i,a){let o=Date.now()+i,s=AbortSignal.any([a,AbortSignal.timeout(i||1e3)]);for(;;){s.throwIfAborted();try{return await new Promise((n,i)=>{let a=e({host:t,port:r,allowHalfOpen:!0}),o=()=>a.destroy(s.reason);s.addEventListener(`abort`,o,{once:!0});let c=()=>s.removeEventListener(`abort`,o);a.on(`error`,e=>{a.destroy(),i(e)}),a.once(`close`,c),a.once(`connect`,()=>{c(),n(a)})})}catch(e){let t=o-Date.now();if(t<=0||s.aborted)throw e;await n(Math.min(50,t),void 0,{signal:s})}}}export{a as closeTcpServer,o as connectTcp,r as createLazyTcpProxy,i as listenTcpServer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DevDiagnostics as e}from"./diagnostics.js";import{closeTcpServer as t,connectTcp as n,createLazyTcpProxy as r,listenTcpServer as i}from"./lazy-tcp-proxy.js";import{spawn as a}from"node:child_process";import{createServer as o}from"node:net";import s from"node:path";import{createInterface as c}from"node:readline";import{finished as l}from"node:stream/promises";import{setTimeout as u}from"node:timers/promises";import{coreframeGeneratedWorkerVariables as d,coreframeLocalWorkerVariables as f,coreframeManagedWorkerSecrets as p}from"@coreframe/config";const m=`127.0.0.1`,h=1e4,g=process.platform===`win32`;async function _({cwd:t,env:n,services:r,onFailure:i}){let a=b(r),o=[],s={},c={},l=new e(t,`project-services`,void 0,`dev.services`),u=async()=>{try{await Promise.all(o.map(e=>e()))}finally{l.close()}};try{for(let[e,r]of a){let a=v({cwd:t,env:n,name:e,config:r,logs:l,onFailure:i});o.push(a.close);let u=await a.listen();if(c[e]=`${m}:${u}`,r.workerEnv){let{name:e,protocol:t,path:n=`/`}=r.workerEnv;s[e]=`${t}://${m}:${u}${n}`}}return{bindings:s,endpoints:c,close:u}}catch(e){throw await u(),e}}function v({cwd:e,env:l,name:u,config:d,logs:f,onFailure:p}){let _=o(e=>e.destroy()),v=new AbortController,b,x,S,C,w=()=>S??=t(_),T=r({port:0,connectTimeoutMs:0,start:O}),E=T.wait().catch(e=>{f.event(e.message,{service:u},`error`),p(e.message),k()});function D(e){T.fail(Error(`Dev service "${u}" ${e}`))}async function O(){await w();let t=v.signal;t.throwIfAborted();let r=d.readinessTimeoutMs??h,i=d.args.map(e=>e.replaceAll(`{host}`,m).replaceAll(`{port}`,String(b))),o=a(d.command,i,{cwd:e,detached:!g,env:{...l,PATH:s.resolve(e,`node_modules/.bin`)+s.delimiter+(l.PATH??l.Path??``)},stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0});x=o,o.once(`error`,e=>{t.aborted||D(e.code===`ENOENT`?`could not find executable "${d.command}". Install it or update dev.services.`:`could not launch "${d.command}" (${e.code??`spawn error`}).`)}),o.once(`exit`,(e,n)=>{t.aborted||D(`exited unexpectedly (${n??`exit code ${e}`}).`)});for(let[e,t]of[[`stdout`,`info`],[`stderr`,`error`]]){let n=c({input:o[e]});n.on(`line`,n=>f.event(n,{service:u,stream:e},t)),n.on(`error`,t=>{f.event(`Could not read service output.`,{service:u,stream:e,code:t.code},`warn`)})}try{(await n({host:m,port:b},r,t)).destroy()}catch(e){throw t.throwIfAborted(),Error(`Dev service "${u}" did not accept TCP connections on ${m}:${b} within ${r} ms. Check its loopback arguments and logs.`,{cause:e})}return{host:m,port:b}}function k(){return v.abort(),C??=(async()=>{await w(),x&&await y(x,u).catch(e=>{f.event(e.message,{service:u},`error`),p(e.message)})})(),C}return{async close(){await Promise.all([T.close(),k()]),await E},async listen(){return b=await i(_,0,m),T.listen()}}}async function y(e,t){if(e.pid===void 0)return;let n=g?e.pid:-e.pid;try{process.kill(n,`SIGTERM`);let t=Date.now()+500;for(;Date.now()<t;)await u(20),process.kill(n,0);if(e.exitCode!==null||e.signalCode!==null)process.kill(n,`SIGKILL`);else{let t=new Promise(t=>e.once(`exit`,()=>t()));process.kill(n,`SIGKILL`),await Promise.race([t,u(500,void 0,{ref:!1})])}}catch(e){if(e.code!==`ESRCH`)throw Error(`Could not stop dev service "${t}".`,{cause:e})}finally{let t=[e.stdout,e.stderr].filter(e=>e!==null);await Promise.race([Promise.allSettled(t.map(e=>l(e,{cleanup:!0}))),u(500,void 0,{ref:!1})]);for(let e of t)e.destroy()}}function b(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`dev.services must be an object keyed by service name.`);let t=Object.entries(e),n=new Set([...d,...f,...p,`DATABASE_URL`]);for(let[e,r]of t){if(!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e))throw Error(`Invalid dev service name ${JSON.stringify(e)}.`);if(!r||r.start!==`on-connect`||typeof r.command!=`string`||!r.command.trim()||r.command.includes(`\0`)||!Array.isArray(r.args)||!r.args.every(e=>typeof e==`string`&&!e.includes(`\0`))||!r.args.some(e=>e.includes(`{port}`)))throw Error(`dev.services.${e} requires start: "on-connect", a command, and args containing {port}.`);let t=r.readinessTimeoutMs??h;if(!Number.isInteger(t)||t<1||t>12e4)throw Error(`dev.services.${e}.readinessTimeoutMs must be an integer from 1 through 120000.`);let i=r.workerEnv;if(i!==void 0){if(!i||typeof i.name!=`string`||!/^[A-Z][A-Z0-9_]*$/.test(i.name)||![`tcp`,`http`,`https`,`ws`,`wss`].includes(i.protocol)||i.path!==void 0&&(typeof i.path!=`string`||!i.path.startsWith(`/`)))throw Error(`Invalid dev.services.${e}.workerEnv. Specify an uppercase name, a supported protocol, and optionally a path starting with /.`);if(n.has(i.name))throw Error(`dev.services.${e}.workerEnv name "${i.name}" is already in use by development.`);n.add(i.name)}}return t}export{_ as prepareProjectServices};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coreframe/dev-supervisor",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "Process supervision utilities for Coreframe development workflows",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"leylines": "^0.3.8",
|
|
22
|
-
"@coreframe/config": "^0.3.
|
|
22
|
+
"@coreframe/config": "^0.3.2"
|
|
23
23
|
},
|
|
24
24
|
"devDependencies": {
|
|
25
25
|
"@types/node": "^26.1.0",
|