11import * as WebSocket from 'ws'
22import * as vscode from 'vscode'
33import * as child_process from 'child_process'
4+ import * as http from 'http'
45import * as path from 'path'
56import * as net from 'net'
67import {
@@ -49,21 +50,16 @@ export class WebSocketManager {
4950 resolve ( true )
5051 } )
5152 . once ( 'listening' , ( ) => {
52- tester . close ( )
53- resolve ( false )
53+ tester . close ( ( ) => {
54+ resolve ( false )
55+ } )
5456 } )
5557 . listen ( port )
5658 } )
5759 }
5860
5961 private async _initialize_server ( ) {
6062 try {
61- const port_in_use = await this . _is_port_in_use ( this . port )
62-
63- if ( ! port_in_use ) {
64- await this . _start_server_process ( )
65- }
66-
6763 this . _connect_as_client ( )
6864 } catch ( error ) {
6965 Logger . error ( {
@@ -85,21 +81,22 @@ export class WebSocketManager {
8581 )
8682
8783 try {
88- const process = child_process . fork ( server_script_path , [ ] , {
84+ const spawned = child_process . spawn ( process . execPath , [ server_script_path ] , {
8985 detached : true ,
90- stdio : 'ignore'
86+ stdio : 'ignore' ,
87+ env : { ...process . env , ELECTRON_RUN_AS_NODE : '1' }
9188 } )
9289
93- if ( process . pid ) {
94- process . unref ( )
90+ if ( spawned . pid ) {
91+ spawned . unref ( )
9592 }
9693
9794 Logger . info ( {
9895 function_name : '_start_server_process' ,
99- message : `Started WebSocket server process with PID: ${ process . pid } `
96+ message : `Started WebSocket server process with PID: ${ spawned . pid } `
10097 } )
10198
102- return new Promise < void > ( ( resolve ) => setTimeout ( resolve , 1000 ) )
99+ return this . _wait_for_server_ready ( )
103100 } catch ( error ) {
104101 Logger . error ( {
105102 function_name : '_start_server_process' ,
@@ -110,6 +107,41 @@ export class WebSocketManager {
110107 }
111108 }
112109
110+ private _wait_for_server_ready (
111+ retries = 20 ,
112+ interval_ms = 250
113+ ) : Promise < void > {
114+ return new Promise ( ( resolve , reject ) => {
115+ let attempts = 0
116+
117+ const check = ( ) => {
118+ const req = http . get (
119+ `http://localhost:${ this . port } /health` ,
120+ ( res ) => {
121+ if ( res . statusCode === 200 ) {
122+ resolve ( )
123+ } else {
124+ retry ( )
125+ }
126+ }
127+ )
128+ req . on ( 'error' , retry )
129+ req . end ( )
130+ }
131+
132+ const retry = ( ) => {
133+ attempts ++
134+ if ( attempts >= retries ) {
135+ reject ( new Error ( `WebSocket server did not become ready after ${ retries } attempts` ) )
136+ } else {
137+ setTimeout ( check , interval_ms )
138+ }
139+ }
140+
141+ check ( )
142+ } )
143+ }
144+
113145 private async _connect_as_client ( ) {
114146 if ( this . client ) {
115147 this . client . close ( )
0 commit comments