Add graceful shutdown which stops jamid

Change-Id: I0268077ae05f84eb8c6e7fcbbf32ce2a562c7970
diff --git a/server/src/index.ts b/server/src/index.ts
index 579e9ef..ec7067e 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -24,6 +24,7 @@
 
 import { App } from './app.js';
 import { Creds } from './creds.js';
+import { Jamid } from './jamid/jamid.js';
 import { Vault } from './vault.js';
 import { Ws } from './ws.js';
 
@@ -33,6 +34,7 @@
 
 await Container.get(Creds).build();
 await Container.get(Vault).build();
+const jamid = Container.get(Jamid);
 const app = await Container.get(App).build();
 const wss = await Container.get(Ws).build();
 
@@ -45,6 +47,10 @@
 server.on('error', onError);
 server.on('listening', onListening);
 
+process.once('SIGTERM', shutdown);
+process.once('SIGINT', shutdown);
+process.once('SIGUSR2', shutdown);
+
 function onError(error: NodeJS.ErrnoException) {
   if (error.syscall !== 'listen') {
     throw error;
@@ -71,3 +77,13 @@
   const bind = typeof address === 'string' ? `pipe ${address}` : `port ${address?.port}`;
   log.debug('Listening on ' + bind);
 }
+
+function shutdown(signal: NodeJS.Signals) {
+  log.debug(`${signal} received: shutting down server`);
+  jamid.stop();
+  server.close(() => {
+    log.debug('Server shut down');
+    // Needed in order to actually exit the process as its shutdown is blocked by something else
+    process.exit();
+  });
+}
diff --git a/server/src/jamid/jami-swig.ts b/server/src/jamid/jami-swig.ts
index 3f48fbc..63fc307 100644
--- a/server/src/jamid/jami-swig.ts
+++ b/server/src/jamid/jami-swig.ts
@@ -51,6 +51,7 @@
 
 export interface JamiSwig {
   init(args: Record<string, unknown>): void;
+  fini(): void;
 
   // IntVect(): IntVect;
   // UintVect(): UintVect;
diff --git a/server/src/jamid/jamid.ts b/server/src/jamid/jamid.ts
index 5583f5c..b2d81c4 100644
--- a/server/src/jamid/jamid.ts
+++ b/server/src/jamid/jamid.ts
@@ -92,6 +92,10 @@
     this.jamid.init(handlers);
   }
 
+  stop() {
+    this.jamid.fini();
+  }
+
   getAccountList() {
     return stringVectToArr(this.jamid.getAccountList());
   }