trasherdk / uWebSockets.js

μWebSockets for Node.js back-ends :metal:
Apache License 2.0
0 stars 0 forks source link

Snippet: Graceful shutdown example #7

Open trasherdk opened 1 year ago

trasherdk commented 1 year ago
import { App, us_listen_socket_close } from 'uWebSockets.js';

const wsMap = new Map();
let id = 0;

const port = 8002;
let listenSocket;

const app = App()
   .get('/', res => res.end('123'))
   .ws('/', {
      open: ws => {
         ws.id = ++id;
         wsMap.set(ws.id, ws);
         console.log('open', ws.id);
      },
      close: (ws, code) => {
         wsMap.delete(ws.id);
         console.log('close', ws.id, code);
      }  
   })
   .listen(port, s => {
      listenSocket = s;
      if (s) console.log('listening on', port);
      else console.log('failed to listen on', port);
   });

const shutdown = () => {
   if (listenSocket) us_listen_socket_close(listenSocket); // close listen socket for new http and ws connections
   listenSocket = null;
   wsMap.forEach(ws => ws.close()); // immediate close all websockets
   // ws.end(code) - potentially takes 4 to 16 seconds to graceful close websocket (depends on idletimeout)
};

Other than websockets, Http connection can keep app open for up to 10 seconds (http timeout) and if you have response.onData() set it is extended 10 seconds every onData event.

If you want to close requests, you can track open requests and close like, websockets:

 openRequests = new Set();
 openRequests.forEach(r => r.close())

Or process.exit() also works. app.close() could be shortcut to close all sockets.

Source: https://github.com/uNetworking/uWebSockets.js/issues/794#issuecomment-1226685328