Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(database): give every Supabase call a 15 second timeout

spacesdrive52c0c02bd9bd
diff --git a/backend/database/supabase.ts b/backend/database/supabase.ts
index 23b8e3f..430d63c 100644
--- a/backend/database/supabase.ts
+++ b/backend/database/supabase.ts
@@ -12,7 +12,10 @@ function workerFetch(url: RequestInfo | URL, options: RequestInit = {}): Promise
return fetch(url, rest);
}
-const CLIENT_OPTS = { auth: { persistSession: false }, global: { fetch: workerFetch } };
+// well under the 30 second request deadline, so a hung query fails as a database error and the request still answers
+export const DB_TIMEOUT_MS = 15_000;
+
+const CLIENT_OPTS = { auth: { persistSession: false }, global: { fetch: workerFetch }, db: { timeout: DB_TIMEOUT_MS } };
// Returns a service-role client that bypasses RLS - used for all DB operations.
export function getSupabase(env: Env): SupabaseClient {
diff --git a/backend/tests/database/supabase.test.ts b/backend/tests/database/supabase.test.ts
new file mode 100644
index 0000000..954732f
--- /dev/null
+++ b/backend/tests/database/supabase.test.ts
@@ -0,0 +1,29 @@
+import { test, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { DB_TIMEOUT_MS, getSupabase } from '../../database/supabase.ts';
+import type { Env } from '../../types/env.ts';
+
+const ENV = { SUPABASE_URL: 'https://project.supabase.co', SUPABASE_SERVICE_KEY: 'service', SUPABASE_ANON_KEY: 'anon' } as Env;
+
+test('a database call that never answers is cut off at the timeout and comes back as an error', async t => {
+ mock.timers.enable({ apis: ['setTimeout'] });
+ t.after(() => mock.timers.reset());
+ // a database that accepts the request and never answers, until the request is aborted
+ const hanging = mock.method(globalThis, 'fetch', (_url: unknown, init: RequestInit = {}) => new Promise((_resolve, reject) => {
+ init.signal?.addEventListener('abort', () => reject(new DOMException('The operation was aborted.', 'AbortError')));
+ }));
+ t.after(() => hanging.mock.restore());
+
+ let settled = false;
+ const query = Promise.resolve(getSupabase(ENV).from('accounts').select('id').limit(1)).finally(() => { settled = true; });
+ // the client reads its auth header first, and the timeout starts when the request goes out
+ while (hanging.mock.callCount() === 0) await new Promise(resolve => setImmediate(resolve));
+ mock.timers.tick(DB_TIMEOUT_MS - 1);
+ await Promise.resolve();
+ assert.equal(settled, false);
+
+ mock.timers.tick(1);
+ const result = await query;
+ assert.ok(result.error, 'the query reports an error instead of hanging');
+ assert.equal(hanging.mock.callCount(), 1);
+});