Skip to content

Commit

Permalink
Improve graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
deptyped committed May 16, 2024
1 parent 223c9c5 commit bef94e5
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 65 deletions.
31 changes: 11 additions & 20 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@
"grammy-guard": "0.5.0",
"hono": "4.3.7",
"iso-639-1": "3.1.2",
"node-graceful-shutdown": "1.1.5",
"pino": "8.20.0",
"pino-pretty": "10.3.1",
"tsx": "4.10.2",
"tsx": "4.10.3",
"znv": "0.4.0",
"zod": "3.23.8"
},
Expand All @@ -61,6 +60,6 @@
"npm": ">=8.0.0"
},
"lint-staged": {
"*.ts": "npm run lint"
"*.ts": "eslint"
}
}
121 changes: 79 additions & 42 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,65 +1,102 @@
#!/usr/bin/env tsx

import { serve } from "@hono/node-server";
import { onShutdown } from "node-graceful-shutdown";
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 { AddressInfo } from "node:net";

try {
function onShutdown(cleanUp: () => Promise<void>) {
let isShuttingDown = false;
const handleShutdown = async () => {
if (isShuttingDown) return;
isShuttingDown = true;
logger.info("Shutdown");
await cleanUp();
};
process.on("SIGINT", handleShutdown);
process.on("SIGTERM", handleShutdown);
}

async function startPolling() {
const bot = createBot(config.BOT_TOKEN);
const server = await createServer(bot);

// graceful shutdown
onShutdown(async () => {
logger.info("Shutdown");

await bot.stop();
});

if (config.BOT_MODE === "webhook") {
// to prevent receiving updates before the bot is ready
await bot.init();

// start server
serve(
{
fetch: server.fetch,
hostname: config.BOT_SERVER_HOST,
port: config.BOT_SERVER_PORT,
},
(info) => {
const url =
info.family === "IPv6"
? `http://[${info.address}]:${info.port}`
: `http://${info.address}:${info.port}`;
// start bot
await bot.start({
allowed_updates: config.BOT_ALLOWED_UPDATES,
onStart: ({ username }) =>
logger.info({
msg: "Bot running...",
username,
}),
});
}

logger.info({
msg: "Server started",
url,
});
},
);
async function startWebhook() {
const bot = createBot(config.BOT_TOKEN);
const server = await createServer(bot);

// set webhook
await bot.api.setWebhook(config.BOT_WEBHOOK, {
allowed_updates: config.BOT_ALLOWED_UPDATES,
secret_token: config.BOT_WEBHOOK_SECRET,
let serverHandle: undefined | ReturnType<typeof serve>;
const startServer = () =>
new Promise<AddressInfo>((resolve) => {
serverHandle = serve(
{
fetch: server.fetch,
hostname: config.BOT_SERVER_HOST,
port: config.BOT_SERVER_PORT,
},
(info) => resolve(info),
);
});
logger.info({
msg: "Webhook was set",
url: config.BOT_WEBHOOK,
const stopServer = async () =>
new Promise<void>((resolve) => {
if (serverHandle) {
serverHandle.close(() => resolve());
} else {
resolve();
}
});

// graceful shutdown
onShutdown(async () => {
await stopServer();
});

// to prevent receiving updates before the bot is ready
await bot.init();

// start server
const info = await startServer();
logger.info({
msg: "Server started",
url:
info.family === "IPv6"
? `http://[${info.address}]:${info.port}`
: `http://${info.address}:${info.port}`,
});

// set webhook
await bot.api.setWebhook(config.BOT_WEBHOOK, {
allowed_updates: config.BOT_ALLOWED_UPDATES,
secret_token: config.BOT_WEBHOOK_SECRET,
});
logger.info({
msg: "Webhook was set",
url: config.BOT_WEBHOOK,
});
}

try {
if (config.BOT_MODE === "webhook") {
await startWebhook();
} else if (config.BOT_MODE === "polling") {
await bot.start({
allowed_updates: config.BOT_ALLOWED_UPDATES,
onStart: ({ username }) =>
logger.info({
msg: "Bot running...",
username,
}),
});
await startPolling();
}
} catch (error) {
logger.error(error);
Expand Down

0 comments on commit bef94e5

Please sign in to comment.