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.

refactor(overview): move cache summary and warm tasks into a service

spacesdriveac4554f7de29
diff --git a/backend/routes/overview.js b/backend/routes/overview.js
index d470af4..9f43f34 100644
--- a/backend/routes/overview.js
+++ b/backend/routes/overview.js
@@ -1,9 +1,6 @@
import { Hono } from 'hono';
import { getAccounts, getTrackedPosts } from '../lib/db.js';
-import { getVideosCache, setVideosCache, getIGCache, setIGCache, getRedditCache, setRedditCache } from '../lib/cache.js';
-import { fetchAllVideos } from '../services/youtube.js';
-import { fetchInstagramMedia, summarizeContentTypes } from '../services/instagram.js';
-import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from '../services/reddit.js';
+import { summarizeAccountCaches } from '../services/overviewSummary.js';
const router = new Hono();
@@ -25,87 +22,12 @@ router.get('/overview', async (c) => {
const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^/, '').trim();
try {
- const [rawAccounts, tracked] = await Promise.all([
+ const [accounts, tracked] = await Promise.all([
getAccounts(supabase, userId),
getTrackedPosts(supabase, userId),
]);
-
- const warmTasks = [];
- // syncing is true only when a fetch started, so the client never waits on an unfetchable account
- const warm = (id, task) => {
- if (!redis || !task) return { id, cacheWarmed: false, syncing: false };
- warmTasks.push(task().catch(() => {}));
- return { id, cacheWarmed: false, syncing: true };
- };
-
- const cacheResults = await Promise.allSettled(
- rawAccounts.map(async (a) => {
- if (a.platform === 'reddit') {
- const cached = await getRedditCache(redis, userId, a.id);
- if (!cached?.analytics) {
- return warm(a.id, a.username && a.cookie && (async () => {
- const [profile, posts] = await Promise.all([
- fetchRedditProfile(a.username, a.cookie),
- fetchRedditPosts(a.username, a.cookie, 100),
- ]);
- await setRedditCache(redis, userId, a.id, { profile, analytics: computeRedditAnalytics(profile, posts), posts });
- }));
- }
- return {
- id: a.id,
- cacheWarmed: true,
- fetchedPosts: cached.analytics.fetchedPosts ?? 0,
- totalScore: cached.analytics.totalScore ?? 0,
- totalComments: cached.analytics.totalComments ?? 0,
- };
- }
-
- if (a.platform === 'instagram') {
- const cached = await getIGCache(redis, userId, a.id);
- if (!cached?.media) {
- return warm(a.id, a.igUserId && a.accessToken && (() =>
- fetchInstagramMedia(a.igUserId, a.accessToken, 500)
- .then(m => setIGCache(redis, userId, a.id, { media: m, fetchedAt: new Date().toISOString() }))));
- }
- const media = cached.media;
- const contentTypes = summarizeContentTypes(media);
- const types = Object.values(contentTypes);
- return {
- id: a.id,
- cacheWarmed: true,
- totalLikes: types.reduce((s, t) => s + t.likes, 0),
- totalComments: types.reduce((s, t) => s + t.comments, 0),
- totalViews: types.reduce((s, t) => s + t.views, 0),
- contentTypes,
- };
- }
-
- // YouTube
- const cached = await getVideosCache(redis, userId, a.id);
- if (!cached?.videos) {
- return warm(a.id, apiKey && a.uploadsPlaylistId && (() =>
- fetchAllVideos(a.uploadsPlaylistId, apiKey, 10)
- .then(v => setVideosCache(redis, userId, a.id, { videos: v, fetchedAt: new Date().toISOString() }))));
- }
- const videos = cached.videos;
- return {
- id: a.id,
- cacheWarmed: true,
- totalLikes: videos.reduce((s, v) => s + (v.likeCount ?? 0), 0),
- totalComments: videos.reduce((s, v) => s + (v.commentCount ?? 0), 0),
- };
- })
- );
-
+ const { analyticsCache, warmTasks } = await summarizeAccountCaches(accounts, { redis, userId, apiKey });
runInBackground(c, warmTasks);
-
- const analyticsCache = {};
- cacheResults.forEach(r => {
- if (r.status === 'fulfilled' && r.value?.id) {
- analyticsCache[r.value.id] = r.value;
- }
- });
-
return c.json({ tracked, analyticsCache });
} catch (err) {
console.error('GET /overview:', err.message);
diff --git a/backend/services/overviewSummary.js b/backend/services/overviewSummary.js
new file mode 100644
index 0000000..6808a2f
--- /dev/null
+++ b/backend/services/overviewSummary.js
@@ -0,0 +1,105 @@
+import { getVideosCache, setVideosCache, getIGCache, setIGCache, getRedditCache, setRedditCache } from '../lib/cache.js';
+import { fetchAllVideos } from './youtube.js';
+import { fetchInstagramMedia, summarizeContentTypes } from './instagram.js';
+import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from './reddit.js';
+
+function sumBy(items, pick) {
+ return items.reduce((total, item) => total + pick(item), 0);
+}
+
+// syncing is true only when a fetch started, so the client never waits on an unfetchable account
+function startWarm(context, accountId, task) {
+ if (!context.redis || !task) return { id: accountId, cacheWarmed: false, syncing: false };
+ // a failed warm leaves the cache empty, so the next overview load starts it again
+ context.warmTasks.push(task().catch(() => undefined));
+ return { id: accountId, cacheWarmed: false, syncing: true };
+}
+
+function redditWarmTask(context, account) {
+ if (!account.username || !account.cookie) return null;
+ return async () => {
+ const [profile, posts] = await Promise.all([
+ fetchRedditProfile(account.username, account.cookie),
+ fetchRedditPosts(account.username, account.cookie, 100),
+ ]);
+ await setRedditCache(context.redis, context.userId, account.id, { profile, analytics: computeRedditAnalytics(profile, posts), posts });
+ };
+}
+
+function instagramWarmTask(context, account) {
+ if (!account.igUserId || !account.accessToken) return null;
+ return async () => {
+ const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);
+ await setIGCache(context.redis, context.userId, account.id, { media, fetchedAt: new Date().toISOString() });
+ };
+}
+
+function youtubeWarmTask(context, account) {
+ if (!context.apiKey || !account.uploadsPlaylistId) return null;
+ return async () => {
+ const videos = await fetchAllVideos(account.uploadsPlaylistId, context.apiKey, 10);
+ await setVideosCache(context.redis, context.userId, account.id, { videos, fetchedAt: new Date().toISOString() });
+ };
+}
+
+async function summarizeReddit(context, account) {
+ const cached = await getRedditCache(context.redis, context.userId, account.id);
+ if (!cached?.analytics) return startWarm(context, account.id, redditWarmTask(context, account));
+ return {
+ id: account.id,
+ cacheWarmed: true,
+ fetchedPosts: cached.analytics.fetchedPosts ?? 0,
+ totalScore: cached.analytics.totalScore ?? 0,
+ totalComments: cached.analytics.totalComments ?? 0,
+ };
+}
+
+async function summarizeInstagram(context, account) {
+ const cached = await getIGCache(context.redis, context.userId, account.id);
+ if (!cached?.media) return startWarm(context, account.id, instagramWarmTask(context, account));
+ const contentTypes = summarizeContentTypes(cached.media);
+ const types = Object.values(contentTypes);
+ return {
+ id: account.id,
+ cacheWarmed: true,
+ totalLikes: sumBy(types, type => type.likes),
+ totalComments: sumBy(types, type => type.comments),
+ totalViews: sumBy(types, type => type.views),
+ contentTypes,
+ };
+}
+
+async function summarizeYouTube(context, account) {
+ const cached = await getVideosCache(context.redis, context.userId, account.id);
+ if (!cached?.videos) return startWarm(context, account.id, youtubeWarmTask(context, account));
+ return {
+ id: account.id,
+ cacheWarmed: true,
+ totalLikes: sumBy(cached.videos, video => video.likeCount ?? 0),
+ totalComments: sumBy(cached.videos, video => video.commentCount ?? 0),
+ };
+}
+
+async function summarizeAccount(context, account) {
+ if (account.platform === 'reddit') return summarizeReddit(context, account);
+ if (account.platform === 'instagram') return summarizeInstagram(context, account);
+ return summarizeYouTube(context, account);
+}
+
+// an account whose cache read failed is left out instead of failing the whole overview
+function collectSummaries(results) {
+ const analyticsCache = {};
+ results.forEach(result => {
+ if (result.status === 'fulfilled' && result.value?.id) {
+ analyticsCache[result.value.id] = result.value;
+ }
+ });
+ return analyticsCache;
+}
+
+// warmTasks are already running; the caller decides how long the runtime keeps them alive
+export async function summarizeAccountCaches(accounts, { redis, userId, apiKey }) {
+ const context = { redis, userId, apiKey, warmTasks: [] };
+ const results = await Promise.allSettled(accounts.map(account => summarizeAccount(context, account)));
+ return { analyticsCache: collectSummaries(results), warmTasks: context.warmTasks };
+}
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 6f00425..f26f7a7 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -4,7 +4,7 @@ Services in `backend/services/` contain all logic for communicating with externa
## Shared analytics math (`backend/services/analyticsMath.js`)
-Pure helpers whose formulas are identical in the Instagram and Reddit analytics: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest` and `monthKey` (local time). YouTube keeps its own recency (strict `<`) and weekly consistency formulas and only shares `monthKey`.
+Pure helpers whose formulas are identical in the Instagram and Reddit analytics: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest` and `monthKey` (local time). YouTube keeps its own recency (strict `<`) and weekly consistency formulas: `youtubeAnalytics.js` imports `DAY_MS`, `sumOf`, `roundedAverage` and `medianOf`, and `youtubeTrends.js` imports `DAY_NAMES`, `DAY_MS` and `monthKey`.
---
@@ -163,6 +163,12 @@ Pure rules for `routes/trackedContent.js`: `detectContentType(url)` (`reddit`, `
---
+## Overview summary (`overviewSummary.js`)
+
+Used by `routes/overview.js`. `summarizeAccountCaches(accounts, { redis, userId, apiKey })` reads each account's Redis cache in parallel (`Promise.allSettled`) and returns `{ analyticsCache, warmTasks }`. A warm account gets its totals (`cacheWarmed: true`); an account with no cache gets `cacheWarmed: false`, and when Redis and the account's credentials are present its background fetch starts at once and `syncing` is `true`. An account whose cache read fails is left out of `analyticsCache`. The route passes `warmTasks` to `waitUntil` so the response never waits for them.
+
+---
+
## Instagram OAuth (`instagramOAuth.js`)
Used by `routes/instagramAuth.js`. `readInstagramOAuthConfig(env)` strips a leading byte order mark and whitespace from the app id, secret and URLs, drops a trailing slash from `BACKEND_URL`, and falls back to `http://localhost:8787` and `http://localhost:5173`. `buildAuthorizationUrl` signs the state with the app secret. `connectInstagramFromOAuth` exchanges the code (stripping a trailing `#_`), upgrades to a long-lived token when Instagram allows it (otherwise keeps the short-lived token with no expiry), fetches the profile and returns `'already_added'` or `'connected'`. The route turns those into the `ig_error` and `ig_connected` redirects.