about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rwxr-xr-xbun.lockbbin32114 -> 32114 bytes
-rw-r--r--fly.toml4
-rw-r--r--src/app.ts18
-rw-r--r--src/sleep.ts8
4 files changed, 26 insertions, 4 deletions
diff --git a/bun.lockb b/bun.lockb
index 3fd980c..1b07b2e 100755
--- a/bun.lockb
+++ b/bun.lockb
Binary files differdiff --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);
+}