feat: Graceful termination of task runner (no-changelog) (#11009)

This commit is contained in:
Tomi Turtiainen
2024-10-07 12:23:14 +03:00
committed by GitHub
parent 6a2f9e7295
commit 4434668135
2 changed files with 62 additions and 1 deletions

View File

@@ -359,4 +359,36 @@ export abstract class TaskRunner {
}
return rpcObject;
}
/** Close the connection gracefully and wait until has been closed */
async stop() {
this.stopTaskOffers();
await this.waitUntilAllTasksAreDone();
await this.closeConnection();
}
private async closeConnection() {
// 1000 is the standard close code
// https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5
this.ws.close(1000, 'Shutting down');
await new Promise((resolve) => {
this.ws.once('close', resolve);
});
}
private async waitUntilAllTasksAreDone(maxWaitTimeInMs = 30_000) {
// TODO: Make maxWaitTimeInMs configurable
const start = Date.now();
while (this.runningTasks.size > 0) {
if (Date.now() - start > maxWaitTimeInMs) {
throw new ApplicationError('Timeout while waiting for tasks to finish');
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
}