Skip to content

Commit 5700ca0

Browse files
Merge pull request #192 from corbitsdev/cl-12159-stop-the-hub-when-it-is-signalled-during-startup
fix(hub): stop the hub when it is signalled during startup
2 parents e4f84c3 + b33b61a commit 5700ca0

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

‎apps/hub/src/server.ts‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ if (import.meta.main) {
1414
const log = getLogger(["corbits-builder", "hub"]);
1515
let close = async () => {};
1616
let stopping: Promise<void> | undefined;
17+
let stopRequested = false;
18+
let startupDone = false;
1719
const shutDown = async () => {
1820
for (const step of [close, dispose]) {
1921
try {
@@ -28,6 +30,7 @@ if (import.meta.main) {
2830
const exitOnFatal = (message: string) => async (error: unknown) => {
2931
try {
3032
log.error(message, errorMetadata(error));
33+
// Unlike a signal, this does not wait for startup: a startup stuck on the failure would keep the hub up instead of letting its supervisor restart it.
3134
await stop();
3235
} finally {
3336
// Handles a failed shutdown left open would keep a broken hub alive instead of letting its supervisor restart it.
@@ -39,14 +42,18 @@ if (import.meta.main) {
3942
exitOnFatal("Hub hit an unhandled rejection"),
4043
);
4144
process.on("uncaughtException", exitOnFatal("Hub hit an uncaught exception"));
42-
process.once("SIGTERM", () => {
43-
void stop();
44-
});
45-
process.once("SIGINT", () => {
46-
void stop();
47-
});
48-
try {
45+
// Startup takes seconds; a stop meanwhile is recorded and acted on when startup finishes, so it closes what startup opened.
46+
const requestStop = () => {
47+
stopRequested = true;
48+
if (startupDone) void stop();
49+
};
50+
process.once("SIGTERM", requestStop);
51+
process.once("SIGINT", requestStop);
52+
const start = async () => {
4953
const runtime = await createHubRuntime();
54+
close = () => runtime.close();
55+
// A stop requested meanwhile must not open the port; the stop after startup closes the runtime.
56+
if (stopRequested) return;
5057
const server = Bun.serve({
5158
hostname: runtime.hostname,
5259
port: runtime.port,
@@ -63,6 +70,9 @@ if (import.meta.main) {
6370
log.info(
6471
"Hub ready: Postgres connected; local Interchange sidecar provisioner",
6572
);
73+
};
74+
try {
75+
await start();
6676
} catch (error) {
6777
log.error(
6878
"Hub startup failed; check environment and database readiness",
@@ -71,4 +81,6 @@ if (import.meta.main) {
7181
process.exitCode = 1;
7282
await stop();
7383
}
84+
startupDone = true;
85+
if (stopRequested) await stop();
7486
}

0 commit comments

Comments
 (0)