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(api): pause calls to a platform that keeps failing

spacesdrivece567f61f83e
diff --git a/backend/lib/circuitBreaker.ts b/backend/lib/circuitBreaker.ts
new file mode 100644
index 0000000..bb1f433
--- /dev/null
+++ b/backend/lib/circuitBreaker.ts
@@ -0,0 +1,60 @@
+import { UpstreamError, UpstreamTimeoutError } from './errors.ts';
+
+// five failures in a row is an outage, not one unlucky request
+const FAILURE_THRESHOLD = 5;
+// long enough for a platform blip to pass, short enough that a person trying again a minute later gets through
+const OPEN_MS = 30_000;
+
+export interface CircuitOptions {
+ // false when the error's status is not an http status, as with Instagram's Graph error codes such as 506
+ httpStatus?: boolean;
+ now?: () => number;
+}
+
+export interface CircuitBreaker {
+ run<T>(call: () => Promise<T>, signal?: AbortSignal): Promise<T>;
+}
+
+// a timeout, an unreachable host or a 5xx says the platform is down; a 4xx is about the request, and a call the caller
+// cancelled says nothing about the platform
+export function isOutage(err: unknown, signal?: AbortSignal, httpStatus = true): boolean {
+ if (signal?.aborted) return false;
+ if (err instanceof UpstreamTimeoutError) return true;
+ if (!(err instanceof UpstreamError)) return false;
+ return err.reason === 'unreachable' || (httpStatus && (err.upstreamStatus ?? 0) >= 500);
+}
+
+// one per platform and Worker isolate: while open, calls fail at once instead of waiting on a platform that is down,
+// then one trial call decides whether it is back
+export function createCircuitBreaker(platform: string, { httpStatus = true, now = Date.now }: CircuitOptions = {}): CircuitBreaker {
+ let failures = 0;
+ let openUntil = 0;
+ let trialRunning = false;
+
+ return {
+ async run(call, signal) {
+ const open = failures >= FAILURE_THRESHOLD;
+ if (open && (now() < openUntil || trialRunning)) {
+ // 'unreachable' marks it temporary, so a scheduled post that meets it is tried again later
+ throw new UpstreamError(`${platform} is not answering, so calls to it are paused for a moment. Try again in a minute.`, { reason: 'unreachable' });
+ }
+ if (open) trialRunning = true;
+ try {
+ const result = await call();
+ failures = 0;
+ return result;
+ } catch (err) {
+ if (isOutage(err, signal, httpStatus)) {
+ failures += 1;
+ if (failures >= FAILURE_THRESHOLD) openUntil = now() + OPEN_MS;
+ } else if (!signal?.aborted) {
+ // the platform answered, even if with an error, so it is up
+ failures = 0;
+ }
+ throw err;
+ } finally {
+ if (open) trialRunning = false;
+ }
+ },
+ };
+}
diff --git a/backend/services/instagram/instagramApi.ts b/backend/services/instagram/instagramApi.ts
index 9b01288..4a50073 100644
--- a/backend/services/instagram/instagramApi.ts
+++ b/backend/services/instagram/instagramApi.ts
@@ -1,3 +1,4 @@
+import { createCircuitBreaker } from '../../lib/circuitBreaker.ts';
import { UpstreamError, UpstreamTimeoutError } from '../../lib/errors.ts';
import type { InstagramContainerStatusCode, InstagramProfile } from '../../../shared/types/instagram.ts';
@@ -74,8 +75,14 @@ function unreachable(err: unknown): Error {
return new UpstreamError(`Instagram API unreachable (${(err as Error).message})`, { reason: 'unreachable', cause: err });
}
+export const instagramCircuit = createCircuitBreaker('Instagram', { httpStatus: false });
+
+export function igFetch<T = unknown>(endpoint: string, params: GraphParams = {}, retries = 1, signal?: AbortSignal): Promise<T> {
+ return instagramCircuit.run(() => graphGet<T>(endpoint, params, retries, signal), signal);
+}
+
// GET with a 15 second timeout and one retry on a network blip; a cancelled request is never retried
-export async function igFetch<T = unknown>(endpoint: string, params: GraphParams = {}, retries = 1, signal?: AbortSignal): Promise<T> {
+async function graphGet<T>(endpoint: string, params: GraphParams, retries: number, signal?: AbortSignal): Promise<T> {
const url = buildGraphUrl(endpoint, params);
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
@@ -86,7 +93,7 @@ export async function igFetch<T = unknown>(endpoint: string, params: GraphParams
if (signal?.aborted) throw new UpstreamTimeoutError('Instagram', err);
if (isTransientError(err as Error) && retries > 0) {
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
- return igFetch<T>(endpoint, params, retries - 1, signal);
+ return graphGet<T>(endpoint, params, retries - 1, signal);
}
if ((err as Error).name === 'AbortError' || (err as Error).name === 'TimeoutError') throw new UpstreamTimeoutError('Instagram', err);
throw unreachable(err);
@@ -95,8 +102,12 @@ export async function igFetch<T = unknown>(endpoint: string, params: GraphParams
return readGraphResponse(await response.json() as T & InstagramApiErrorBody);
}
+export function igPost<T = unknown>(endpoint: string, params: GraphParams, signal?: AbortSignal): Promise<T> {
+ return instagramCircuit.run(() => graphPost<T>(endpoint, params, signal), signal);
+}
+
// POST is never retried: a repeated media_publish could publish the post twice
-export async function igPost<T = unknown>(endpoint: string, params: GraphParams, signal?: AbortSignal): Promise<T> {
+async function graphPost<T>(endpoint: string, params: GraphParams, signal?: AbortSignal): Promise<T> {
const url = buildGraphUrl(endpoint, params);
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
let response: Response;
diff --git a/backend/services/reddit/redditApi.ts b/backend/services/reddit/redditApi.ts
index 2c5230a..bce941f 100644
--- a/backend/services/reddit/redditApi.ts
+++ b/backend/services/reddit/redditApi.ts
@@ -1,4 +1,5 @@
import type { RedditMediaType, RedditPost, RedditProfile, RedditTrackedPostData } from '../../../shared/types/reddit.ts';
+import { createCircuitBreaker } from '../../lib/circuitBreaker.ts';
import { NotFoundError, UpstreamError, UpstreamTimeoutError, ValidationError, isAbortError } from '../../lib/errors.ts';
export { computeRedditAnalytics } from './redditAnalytics.ts';
@@ -63,7 +64,13 @@ interface RedditListing<T> {
type RedditCookie = string | null | undefined;
-async function redditFetch<T>(path: string, cookie: RedditCookie, signal?: AbortSignal): Promise<T> {
+export const redditCircuit = createCircuitBreaker('Reddit');
+
+function redditFetch<T>(path: string, cookie: RedditCookie, signal?: AbortSignal): Promise<T> {
+ return redditCircuit.run(() => requestReddit<T>(path, cookie, signal), signal);
+}
+
+async function requestReddit<T>(path: string, cookie: RedditCookie, signal?: AbortSignal): Promise<T> {
const headers: Record<string, string> = { 'User-Agent': USER_AGENT, 'Accept': 'application/json' };
if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;
let res: Response;
@@ -71,7 +78,7 @@ async function redditFetch<T>(path: string, cookie: RedditCookie, signal?: Abort
res = await fetch(`${REDDIT_BASE}${path}`, { headers, signal });
} catch (err) {
if (isAbortError(err)) throw new UpstreamTimeoutError('Reddit', err);
- throw new UpstreamError(`Reddit could not be reached (${(err as Error).message})`, { cause: err });
+ throw new UpstreamError(`Reddit could not be reached (${(err as Error).message})`, { reason: 'unreachable', cause: err });
}
if (res.status === 404) throw new NotFoundError('Reddit user not found - check the username');
diff --git a/backend/services/youtube/youtubeApi.ts b/backend/services/youtube/youtubeApi.ts
index 8e2d750..5c3cf54 100644
--- a/backend/services/youtube/youtubeApi.ts
+++ b/backend/services/youtube/youtubeApi.ts
@@ -1,3 +1,4 @@
+import { createCircuitBreaker } from '../../lib/circuitBreaker.ts';
import { UpstreamError, UpstreamTimeoutError, isAbortError } from '../../lib/errors.ts';
export type YouTubeApiParams = Record<string, string>;
@@ -87,8 +88,14 @@ export interface YouTubeApiVideo {
status?: { privacyStatus?: string; embeddable?: boolean; madeForKids?: boolean };
}
+export const youtubeCircuit = createCircuitBreaker('YouTube');
+
// adds the key to the caller's params object, as callers always pass a fresh one
-export async function ytFetch<T>(endpoint: string, params: YouTubeApiParams, apiKey: string, signal?: AbortSignal): Promise<T> {
+export function ytFetch<T>(endpoint: string, params: YouTubeApiParams, apiKey: string, signal?: AbortSignal): Promise<T> {
+ return youtubeCircuit.run(() => requestYouTube<T>(endpoint, params, apiKey, signal), signal);
+}
+
+async function requestYouTube<T>(endpoint: string, params: YouTubeApiParams, apiKey: string, signal?: AbortSignal): Promise<T> {
const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);
params.key = apiKey;
Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
@@ -97,7 +104,7 @@ export async function ytFetch<T>(endpoint: string, params: YouTubeApiParams, api
response = await fetch(url.toString(), { signal });
} catch (err) {
if (isAbortError(err)) throw new UpstreamTimeoutError('YouTube', err);
- throw new UpstreamError(`YouTube could not be reached (${(err as Error).message})`, { cause: err });
+ throw new UpstreamError(`YouTube could not be reached (${(err as Error).message})`, { reason: 'unreachable', cause: err });
}
const data = await response.json() as T & YouTubeApiErrorBody;
if (data.error) {
diff --git a/backend/tests/lib/circuitBreaker.test.ts b/backend/tests/lib/circuitBreaker.test.ts
new file mode 100644
index 0000000..fe85ffa
--- /dev/null
+++ b/backend/tests/lib/circuitBreaker.test.ts
@@ -0,0 +1,102 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createCircuitBreaker, isOutage } from '../../lib/circuitBreaker.ts';
+import { NotFoundError, UpstreamError, UpstreamTimeoutError } from '../../lib/errors.ts';
+
+function clock(start = 0) {
+ let time = start;
+ return { now: () => time, advance: (ms: number) => { time += ms; } };
+}
+
+const down = () => Promise.reject(new UpstreamError('YouTube could not be reached (fetch failed)', { reason: 'unreachable' }));
+const up = () => Promise.resolve('ok');
+
+async function failTimes(breaker: ReturnType<typeof createCircuitBreaker>, times: number) {
+ for (let i = 0; i < times; i++) await assert.rejects(breaker.run(down));
+}
+
+test('four outage failures in a row still let the next call through', async () => {
+ const breaker = createCircuitBreaker('YouTube', { now: clock().now });
+ await failTimes(breaker, 4);
+ assert.equal(await breaker.run(up), 'ok');
+});
+
+test('the fifth failure in a row pauses calls, which then fail at once with a temporary error that says to wait', async () => {
+ const breaker = createCircuitBreaker('YouTube', { now: clock().now });
+ await failTimes(breaker, 5);
+ let called = false;
+ await assert.rejects(breaker.run(() => { called = true; return up(); }), (err: UpstreamError) => {
+ assert.equal(err.reason, 'unreachable');
+ assert.equal(err.message, 'YouTube is not answering, so calls to it are paused for a moment. Try again in a minute.');
+ return true;
+ });
+ assert.equal(called, false);
+});
+
+test('after 30 seconds one trial call goes through, and an answer closes the breaker', async () => {
+ const time = clock();
+ const breaker = createCircuitBreaker('YouTube', { now: time.now });
+ await failTimes(breaker, 5);
+ time.advance(29_999);
+ await assert.rejects(breaker.run(up), /paused/);
+ time.advance(1);
+ assert.equal(await breaker.run(up), 'ok');
+ assert.equal(await breaker.run(up), 'ok');
+});
+
+test('a failed trial pauses calls for another 30 seconds', async () => {
+ const time = clock();
+ const breaker = createCircuitBreaker('YouTube', { now: time.now });
+ await failTimes(breaker, 5);
+ time.advance(30_000);
+ await assert.rejects(breaker.run(down), /could not be reached/);
+ time.advance(29_000);
+ await assert.rejects(breaker.run(up), /paused/);
+});
+
+test('while the trial call runs, other calls keep failing at once', async () => {
+ const time = clock();
+ const breaker = createCircuitBreaker('YouTube', { now: time.now });
+ await failTimes(breaker, 5);
+ time.advance(30_000);
+ let answer: (value: string) => void = () => {};
+ const trial = breaker.run(() => new Promise<string>(resolve => { answer = resolve; }));
+ await assert.rejects(breaker.run(up), /paused/);
+ answer('ok');
+ assert.equal(await trial, 'ok');
+ assert.equal(await breaker.run(up), 'ok');
+});
+
+test('errors about the request, such as a missing channel or a bad token, never open the breaker and reset the count', async () => {
+ const breaker = createCircuitBreaker('YouTube', { now: clock().now });
+ await failTimes(breaker, 4);
+ await assert.rejects(breaker.run(() => Promise.reject(new UpstreamError('Invalid token', { status: 401 }))));
+ await failTimes(breaker, 4);
+ assert.equal(await breaker.run(up), 'ok');
+});
+
+test('a call the caller cancelled says nothing about the platform', async () => {
+ const breaker = createCircuitBreaker('YouTube', { now: clock().now });
+ const cancelled = AbortSignal.abort();
+ for (let i = 0; i < 6; i++) {
+ await assert.rejects(breaker.run(() => Promise.reject(new UpstreamTimeoutError('YouTube')), cancelled));
+ }
+ assert.equal(await breaker.run(up), 'ok');
+});
+
+test('timeouts, unreachable hosts and server errors are outages; client errors and other failures are not', () => {
+ assert.equal(isOutage(new UpstreamTimeoutError('Reddit')), true);
+ assert.equal(isOutage(new UpstreamError('down', { reason: 'unreachable' })), true);
+ assert.equal(isOutage(new UpstreamError('Reddit API 503: Service Unavailable', { status: 503 })), true);
+ assert.equal(isOutage(new UpstreamError('Reddit rate limit hit', { status: 429 })), false);
+ assert.equal(isOutage(new UpstreamError('Invalid OAuth access token', { status: 190 })), false);
+ assert.equal(isOutage(new NotFoundError('Reddit user not found')), false);
+ assert.equal(isOutage(new UpstreamTimeoutError('Reddit'), AbortSignal.abort()), false);
+});
+
+test('for Instagram a Graph error code above 500, such as 506 for a duplicate post, is not mistaken for a server error', async () => {
+ assert.equal(isOutage(new UpstreamError('Duplicate posting', { status: 506 }), undefined, false), false);
+ const breaker = createCircuitBreaker('Instagram', { httpStatus: false, now: clock().now });
+ for (let i = 0; i < 6; i++) await assert.rejects(breaker.run(() => Promise.reject(new UpstreamError('Duplicate posting', { status: 506 }))));
+ assert.equal(await breaker.run(up), 'ok');
+});