Skip to content

Commit

Permalink
Retry server binding if it fails.
Browse files Browse the repository at this point in the history
  • Loading branch information
saul-jb committed Apr 12, 2024
1 parent 93fc8f2 commit 72a5d14
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion packages/rpc/src/rpc-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,28 @@ interface Client {
controllers: Map<number | string, AbortController>
}

export interface RPCServerOptions {
retryDelay?: number
retryCount?: number
}

export class RPCServer {
readonly events = createEventTarget()
readonly rpc = new JSONRPCServer<AbortOptions & { id: number }>()
private readonly path: string
private readonly clients = new Map<number, Client>()
private readonly server = net.createServer(socket => { this.handleClient(socket) })
private readonly genId: () => number
private readonly options: Required<RPCServerOptions>

constructor (path: string) {
constructor (path: string, options: RPCServerOptions = {}) {
this.path = path

this.options = {
retryCount: options.retryCount ?? 3,
retryDelay: options.retryDelay ?? 1000
}

this.genId = ((): () => number => {
let id = 0

Expand All @@ -36,6 +47,24 @@ export class RPCServer {
}

async start (): Promise<void> {
let retryCount = 0

this.server.on('error', (e: Error & { code?: string }) => {
if (e.code === 'EADDRINUSE') {
if (retryCount > this.options.retryCount) {
throw e
}

this.events.dispatchEvent(new RPCEvent(e.code))

setTimeout(() => {
retryCount++
this.server.close()
this.server.listen(this.path)
}, this.options.retryDelay)
}
})

await new Promise<void>(resolve => this.server.listen(this.path, resolve))

this.rpc.addMethod('rpc-abort', (raw, { id }) => {
Expand Down

0 comments on commit 72a5d14

Please sign in to comment.