Skip to content

Commit

Permalink
wrap httpServer.listen() in pRetry instead of creating new server to …
Browse files Browse the repository at this point in the history
…test port.
  • Loading branch information
busma13 committed Dec 12, 2024
1 parent ceb179a commit fe14cf4
Showing 1 changed file with 8 additions and 36 deletions.
44 changes: 8 additions & 36 deletions packages/teraslice-messaging/src/messenger/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,34 +93,16 @@ export class Server extends Core {
}

async listen(): Promise<void> {
// Check if port is available before using it
const testPort = async function (port: number) {
return new Promise((resolve) => {
const portTestServer = http.createServer();

portTestServer.unref();

portTestServer.once('error', () => {
portTestServer.close(() => {
return resolve(false);
});
});

portTestServer.once('listening', () => {
portTestServer.close(() => {
return resolve(true);
});
await pRetry(async () => {
await new Promise<void>((resolve, reject) => {
this.httpServer.listen(this.port, (err?: Error) => {
if (err) {
reject(err);
} else {
resolve();
}
});

portTestServer.listen(port);
});
};

await pRetry(async () => {
const portAvailable = await testPort(this.port);
if (!portAvailable) {
throw new Error(`Port ${this.port} is already in-use`);
}
}, {
retries: isTest ? 1 : 5,
endWithFatal: true,
Expand All @@ -129,16 +111,6 @@ export class Server extends Core {
}
});

await new Promise<void>((resolve, reject) => {
this.httpServer.listen(this.port, (err?: Error) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});

this.server.attach(this.httpServer);

this.server.use((socket, next) => {
Expand Down

0 comments on commit fe14cf4

Please sign in to comment.