-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.ts
More file actions
130 lines (107 loc) · 3.54 KB
/
Copy pathmain.ts
File metadata and controls
130 lines (107 loc) · 3.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import { logger } from "@discordeno/utils";
import "./events/interactionCreate.ts";
import { client } from "./bot.ts";
import { loadCommands } from "./commands/index.ts";
import { commands } from "./commands/mod.ts";
const MAX_RETRY_DELAY_MS = 30_000;
const STARTUP_ATTEMPTS = 5;
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function withRetry<T>(
label: string,
operation: () => Promise<T>,
maxAttempts = STARTUP_ATTEMPTS,
): Promise<T> {
let attempt = 1;
while (true) {
try {
return await operation();
} catch (error) {
if (attempt >= maxAttempts) {
throw error;
}
const retryDelay = Math.min(
1_000 * 2 ** (attempt - 1),
MAX_RETRY_DELAY_MS,
);
logger.warn(
`${label} failed (attempt ${attempt}/${maxAttempts}); retrying in ${retryDelay}ms`,
error,
);
await delay(retryDelay);
attempt += 1;
}
}
}
async function syncApplicationCommands(): Promise<void> {
await withRetry(
"Application command sync",
() => client.helpers.upsertGlobalApplicationCommands(commands.array()),
);
logger.info(`Synced ${commands.size} application commands.`);
}
async function main(): Promise<void> {
const loadResult = await loadCommands();
logger.info(`Loaded ${loadResult.loaded.length} command modules.`);
if (loadResult.failed.length > 0) {
logger.warn(
`Bot will continue without ${loadResult.failed.length} command modules: ${
loadResult.failed.join(", ")
}`,
);
}
if (commands.size === 0) {
throw new Error("No application commands loaded successfully");
}
logger.info("Starting bot...");
await withRetry("Discord gateway startup", () => client.start());
logger.info("Bot started!");
// Command registration is useful but not required to keep the gateway alive.
// Own this promise so a transient Discord REST failure cannot stop the bot.
void syncApplicationCommands().catch((error) => {
logger.error("Application command sync failed after all retries", error);
});
}
process.on("unhandledRejection", (reason) => {
// This is a last-resort boundary for third-party callbacks. Application code
// should still catch failures at the task/event that owns the promise.
logger.error("Unhandled promise rejection escaped its owner", reason);
});
process.on("uncaughtExceptionMonitor", (error, origin) => {
// Do not suppress an uncaught exception: the process may be corrupted and
// should be restarted by its service manager. This preserves the root cause.
logger.fatal(`Uncaught exception (${origin})`, error);
});
let shuttingDown = false;
async function shutdown(signal: NodeJS.Signals): Promise<void> {
if (shuttingDown) {
return;
}
shuttingDown = true;
logger.info(`Received ${signal}; shutting down Discord gateway...`);
const forcedExit = setTimeout(() => {
logger.fatal("Graceful shutdown timed out");
process.exit(1);
}, 10_000);
forcedExit.unref();
try {
await client.shutdown();
clearTimeout(forcedExit);
process.exit(0);
} catch (error) {
logger.error("Graceful shutdown failed", error);
process.exit(1);
}
}
process.once("SIGINT", () => void shutdown("SIGINT"));
process.once("SIGTERM", () => void shutdown("SIGTERM"));
void main().catch(async (error) => {
logger.fatal("Bot failed to start", error);
try {
await client.shutdown();
} catch (shutdownError) {
logger.error("Failed to clean up after startup error", shutdownError);
}
process.exitCode = 1;
});