1+ import { Colors } from "./_utils.cli.ts" ;
12import type { ServerPlugin } from "./types.ts" ;
23
34export const errorPlugin : ServerPlugin = ( server ) => {
@@ -14,3 +15,61 @@ export const errorPlugin: ServerPlugin = (server) => {
1415 }
1516 } ) ;
1617} ;
18+
19+ export const gracefulShutdownPlugin : ServerPlugin = ( server ) => {
20+ const config = server . options ?. gracefulShutdown ;
21+ if (
22+ ! globalThis . process ?. on ||
23+ config === false ||
24+ ( config === undefined && ( process . env . CI || process . env . TEST ) )
25+ ) {
26+ return ;
27+ }
28+ const gracefulShutdown =
29+ config === true || ! config ?. gracefulTimeout ? 3 : config . gracefulTimeout ;
30+ const forceShutdown =
31+ config === true || ! config ?. forceTimeout ? 3 : config . forceTimeout ;
32+ let isShuttingDown = false ;
33+ const shutdown = async ( ) => {
34+ if ( isShuttingDown ) return ;
35+ isShuttingDown = true ;
36+ console . log (
37+ Colors . gray (
38+ `\nShutting down server... (timeout in ${ gracefulShutdown } +${ forceShutdown } s)` ,
39+ ) ,
40+ ) ;
41+ let timeout : any ;
42+ await Promise . race ( [
43+ // Graceful shutdown
44+ server . close ( ) . finally ( ( ) => {
45+ clearTimeout ( timeout ) ;
46+ console . log ( Colors . green ( "Server closed all connections." ) ) ;
47+ } ) ,
48+ new Promise < void > ( ( resolve ) => {
49+ timeout = setTimeout ( ( ) => {
50+ // Graceful shutdown timeout
51+ console . warn (
52+ Colors . yellow (
53+ `Forcing closing connections to exit... (timeout in ${ forceShutdown } s)` ,
54+ ) ,
55+ ) ;
56+ timeout = setTimeout ( ( ) => {
57+ // Force shutdown timeout
58+ console . error (
59+ Colors . red ( "Could not close connections in time, force exiting." ) ,
60+ ) ;
61+ resolve ( ) ;
62+ } , 1000 ) ;
63+ return server . close ( true ) . finally ( ( ) => {
64+ clearTimeout ( timeout ) ;
65+ resolve ( ) ;
66+ } ) ;
67+ } , 1000 ) ;
68+ } ) ,
69+ ] ) ;
70+ globalThis . process . exit ( 0 ) ;
71+ } ;
72+ for ( const sig of [ "SIGINT" , "SIGTERM" ] as const ) {
73+ globalThis . process . on ( sig , shutdown ) ;
74+ }
75+ } ;
0 commit comments