about summary refs log tree commit diff stats
path: root/src
diff options
context:
space:
mode:
authorAlan Pearce2024-04-10 11:33:01 +0200
committerAlan Pearce2024-04-10 11:33:01 +0200
commit8beec515146fc8cc323d9de722a405372801e1df (patch)
tree9af1125471e312f4d3ae0e1026fd2018d7edabc8 /src
parent8de5eac6f52beba26d3ce6b5406dcf4ac35da641 (diff)
downloadwebsite-8beec515146fc8cc323d9de722a405372801e1df.tar.lz
website-8beec515146fc8cc323d9de722a405372801e1df.tar.zst
website-8beec515146fc8cc323d9de722a405372801e1df.zip
fly: stop running in secondary regions if no meaningful requests
Diffstat (limited to 'src')
-rw-r--r--src/app.ts18
-rw-r--r--src/sleep.ts8
2 files changed, 24 insertions, 2 deletions
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);
+}