From dfd21e8a2e38d320c845c9812a61d6914d1a84f7 Mon Sep 17 00:00:00 2001 From: saul Date: Fri, 12 Apr 2024 13:11:02 +1200 Subject: [PATCH] Wait for server listen retries. --- packages/rpc/src/rpc-server.ts | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/packages/rpc/src/rpc-server.ts b/packages/rpc/src/rpc-server.ts index 8b2c4d0..49c4b63 100644 --- a/packages/rpc/src/rpc-server.ts +++ b/packages/rpc/src/rpc-server.ts @@ -47,25 +47,29 @@ export class RPCServer { } async start (): Promise { - let retryCount = 0 + for (let i = 0; i <= this.options.retryCount; i++) { + try { + await new Promise(resolve => this.server.listen(this.path, resolve)) + break + } catch (e) { + const code = (e as { code?: string }).code + + if (code === 'EADDRINUSE') { + if (i >= this.options.retryCount) { + throw e + } - this.server.on('error', (e: Error & { code?: string }) => { - if (e.code === 'EADDRINUSE') { - if (retryCount > this.options.retryCount) { - throw e - } + this.events.dispatchEvent(new RPCEvent(code)) - this.events.dispatchEvent(new RPCEvent(e.code)) + await new Promise(resolve => setTimeout(resolve, this.options.retryDelay)) - setTimeout(() => { - retryCount++ this.server.close() this.server.listen(this.path) - }, this.options.retryDelay) + } else { + throw e + } } - }) - - await new Promise(resolve => this.server.listen(this.path, resolve)) + } this.rpc.addMethod('rpc-abort', (raw, { id }) => { const params = z.object({ id: z.number() }).parse(raw)