From 8beec515146fc8cc323d9de722a405372801e1df Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Wed, 10 Apr 2024 11:33:01 +0200 Subject: fly: stop running in secondary regions if no meaningful requests --- bun.lockb | Bin 32114 -> 32114 bytes fly.toml | 4 ++-- src/app.ts | 18 ++++++++++++++++-- src/sleep.ts | 8 ++++++++ 4 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 src/sleep.ts diff --git a/bun.lockb b/bun.lockb index 3fd980c..1b07b2e 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/fly.toml b/fly.toml index 77017b1..d04e736 100644 --- a/fly.toml +++ b/fly.toml @@ -15,9 +15,9 @@ primary_region = "ams" [http_service] internal_port = 3000 force_https = true - auto_stop_machines = false + auto_stop_machines = true auto_start_machines = true - min_machines_running = 3 + min_machines_running = 1 processes = ["app"] [http_service.http_options.response.headers] Strict-Transport-Security = "max-age=31536000; includeSubdomains; preload" diff --git a/src/app.ts b/src/app.ts index 6cc6520..a656ca5 100644 --- a/src/app.ts +++ b/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"; @@ -25,6 +26,10 @@ const defaultHeaders = { 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; handle: BunFile; @@ -283,8 +288,10 @@ export const server = { 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 @@ export const server = { pathname, newpath ? newpath : "", ); + if (autoSleep && pathname !== "/health") { + keepAwake(); + } } }, } satisfies Serve; +if (autoSleep) { + keepAwake(); +} + export default server; diff --git a/src/sleep.ts b/src/sleep.ts new file mode 100644 index 0000000..94d7547 --- /dev/null +++ b/src/sleep.ts @@ -0,0 +1,8 @@ +let sleepTimeout: Timer; + +export function keepAwake() { + if (sleepTimeout) clearTimeout(sleepTimeout); + sleepTimeout = setTimeout(function () { + process.exit(0); + }, 60_000); +} -- cgit 1.4.1