From 7fa5c84188b80c9b04a1e65dd5d15f44824ee6d8 Mon Sep 17 00:00:00 2001 From: deptyped Date: Thu, 6 Jun 2024 02:23:01 +0300 Subject: [PATCH] Refactor server startup and shutdown --- src/main.ts | 32 +++++++------------------------- src/server/index.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/src/main.ts b/src/main.ts index 939cc2ab..7b677b46 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,12 +1,10 @@ #!/usr/bin/env tsx import process from 'node:process' -import type { AddressInfo } from 'node:net' -import { serve } from '@hono/node-server' import { createBot } from '#root/bot/index.js' import { config } from '#root/config.js' import { logger } from '#root/logger.js' -import { createServer } from '#root/server/index.js' +import { createServer, createServerManager } from '#root/server/index.js' function onShutdown(cleanUp: () => Promise) { let isShuttingDown = false @@ -43,37 +41,21 @@ async function startPolling() { async function startWebhook() { const bot = createBot(config.BOT_TOKEN) const server = createServer(bot) - - let serverHandle: undefined | ReturnType - const startServer = () => - new Promise((resolve) => { - serverHandle = serve( - { - fetch: server.fetch, - hostname: config.BOT_SERVER_HOST, - port: config.BOT_SERVER_PORT, - }, - info => resolve(info), - ) - }) - const stopServer = async () => - new Promise((resolve) => { - if (serverHandle) - serverHandle.close(() => resolve()) - else - resolve() - }) + const serverManager = createServerManager(server) // graceful shutdown onShutdown(async () => { - await stopServer() + await serverManager.stop() }) // to prevent receiving updates before the bot is ready await bot.init() // start server - const info = await startServer() + const info = await serverManager.start( + config.BOT_SERVER_HOST, + config.BOT_SERVER_PORT, + ) logger.info({ msg: 'Server started', url: diff --git a/src/server/index.ts b/src/server/index.ts index 9e0b4d65..4fadd096 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,5 +1,7 @@ +import type { AddressInfo } from 'node:net' import { Hono } from 'hono' import { HTTPException } from 'hono/http-exception' +import { serve } from '@hono/node-server' import { webhookCallback } from 'grammy' import { getPath } from 'hono/utils/url' import { requestId } from './middlewares/request-id.js' @@ -55,3 +57,27 @@ export function createServer(bot: Bot) { } export type Server = Awaited> + +export function createServerManager(server: Server) { + let handle: undefined | ReturnType + return { + start: (host: string, port: number) => + new Promise((resolve) => { + handle = serve( + { + fetch: server.fetch, + hostname: host, + port, + }, + info => resolve(info), + ) + }), + stop: () => + new Promise((resolve) => { + if (handle) + handle.close(() => resolve()) + else + resolve() + }), + } +}