Skip to content

Commit

Permalink
Graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
ledyba committed May 10, 2022
1 parent f385976 commit 0649912
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
13 changes: 12 additions & 1 deletion server/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ class Server {
private readonly asset: Asset;
private readonly shelf: Shelf;
private readonly http: FastifyInstance;
private readonly onClose: Promise<void>;

/* **************************************************************************
* constructors
Expand All @@ -58,6 +59,11 @@ class Server {
bodyLimit: 256*1024*1024,
maxParamLength: 1024*1024,
});
this.onClose = new Promise<void>((resolve, reject) => {
this.http.addHook('onClose', async(_instance) => {
resolve();
});
});
}

static async create(asset: Asset, shelf: Shelf): Promise<Server> {
Expand Down Expand Up @@ -221,10 +227,15 @@ class Server {
* start/exit
* **************************************************************************/

async start() {
async listen() {

await this.http.ready();
console.log(this.http.printRoutes());
await this.http.listen(8888, '::', 512);
await this.onClose;
}
async exit() {
await this.http.close();
}

/* **************************************************************************
Expand Down
13 changes: 11 additions & 2 deletions server/src/cmd/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,24 @@ async function main() {
const shelf = new Shelf(repo);
try {
const server = await Server.create(asset, shelf);
await server.start();
process.on('exit', () => {
server.exit()
.then(() => {
console.log('Server exited.');
})
.catch((err) => {
console.log(`Failed to exit server: ${err}`);
});
});
await server.listen();
} finally {
console.log('Closing repo...');
await repo.close();
}
}

main()
.then(() => {})
.catch((err) => {
console.error(err);
throw err;
});

0 comments on commit 0649912

Please sign in to comment.