fly: stop running in secondary regions if no meaningful requests
1 file changed, 16 insertions(+), 2 deletions(-)
changed files
M src/app.ts → src/app.ts
@@ -5,6 +5,7 @@ import type { BunFile, Serve } from "bun"; import * as Sentry from "@sentry/node"; import prom from "bun-prometheus-client"; import log from "loglevel"; +import { keepAwake } from "./sleep.ts"; import config from "./config";@@ -24,6 +25,10 @@ const defaultHeaders = { ...config.extra.headers, vary: "Accept-Encoding", }; + +const autoSleep = + import.meta.env.NODE_ENV === "production" && + import.meta.env["FLY_REGION"] !== import.meta.env["PRIMARY_REGION"]; type File = { filename: string;@@ -283,8 +288,10 @@ Sentry.captureException(error); log.error("Error", error); return new Response("Something went wrong", { status: status }); } finally { - const seconds = endTimer(); - metrics.requestDuration.observe(seconds); + if (status === 200) { + const seconds = endTimer(); + metrics.requestDuration.observe(seconds); + } transaction.finish(); log.info( request.method,@@ -293,8 +300,15 @@ hostname, pathname, newpath ? newpath : "", ); + if (autoSleep && pathname !== "/health") { + keepAwake(); + } } }, } satisfies Serve; + +if (autoSleep) { + keepAwake(); +} export default server;