Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: address review (claude) playlist resilience

[._.]/ Adam Eivy617ead6f82a9
diff --git a/server/services/spotifyPlaylists.js b/server/services/spotifyPlaylists.js
index b0a476fbdd..8774cbc8f9 100644
--- a/server/services/spotifyPlaylists.js
+++ b/server/services/spotifyPlaylists.js
@@ -6,7 +6,7 @@
* URLs, and service links) under data/spotify/; raw API responses never leave
* the request and this snapshot is not part of federation.
*/
-import { dataPath, ensureDir, atomicWrite, readJSONFile } from '../lib/fileUtils.js';
+import { dataPath, ensureDir, atomicWrite, readJSONFile, sleep } from '../lib/fileUtils.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { getAccessToken } from './spotifyAuth.js';
@@ -14,6 +14,7 @@ const API_BASE = 'https://api.spotify.com/v1';
const REQUEST_TIMEOUT_MS = 15000;
const PAGE_LIMIT = 50;
const PLAYLIST_BATCH_SIZE = 5;
+const MAX_RATE_LIMIT_RETRIES = 2;
const PLAYLISTS_FILE = dataPath('spotify', 'playlists.json');
const SNAPSHOT_VERSION = 1;
@@ -79,14 +80,21 @@ export function playlistSnapshotSummary(snapshot) {
}
async function fetchJson(url, accessToken) {
- const response = await fetchWithTimeout(url, {
- headers: { Authorization: `Bearer ${accessToken}` },
- }, REQUEST_TIMEOUT_MS);
- const payload = await response.json().catch(() => ({}));
- if (!response.ok) {
- throw new Error(`Spotify API returned ${response.status}${payload?.error?.message ? `: ${payload.error.message}` : ''}`);
+ for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt += 1) {
+ const response = await fetchWithTimeout(url, {
+ headers: { Authorization: `Bearer ${accessToken}` },
+ }, REQUEST_TIMEOUT_MS);
+ if (!response.ok && response.status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {
+ const retryAfter = Number(response.headers?.get?.('retry-after'));
+ await sleep(Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter * 1000 : 1000);
+ continue;
+ }
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ throw new Error(`Spotify API returned ${response.status}${payload?.error?.message ? `: ${payload.error.message}` : ''}`);
+ }
+ return payload;
}
- return payload;
}
async function fetchPages(path, accessToken) {
diff --git a/server/services/spotifyPlaylists.test.js b/server/services/spotifyPlaylists.test.js
index 9ca6423efd..22177b055d 100644
--- a/server/services/spotifyPlaylists.test.js
+++ b/server/services/spotifyPlaylists.test.js
@@ -1,14 +1,14 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
- getAccessToken: vi.fn(), fetchWithTimeout: vi.fn(), readJSONFile: vi.fn(), ensureDir: vi.fn(), atomicWrite: vi.fn(),
+ getAccessToken: vi.fn(), fetchWithTimeout: vi.fn(), readJSONFile: vi.fn(), ensureDir: vi.fn(), atomicWrite: vi.fn(), sleep: vi.fn(),
}));
vi.mock('./spotifyAuth.js', () => ({ getAccessToken: (...args) => mocks.getAccessToken(...args) }));
vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: (...args) => mocks.fetchWithTimeout(...args) }));
vi.mock('../lib/fileUtils.js', () => ({
dataPath: (...parts) => `/tmp/${parts.join('/')}`, readJSONFile: (...args) => mocks.readJSONFile(...args),
- ensureDir: (...args) => mocks.ensureDir(...args), atomicWrite: (...args) => mocks.atomicWrite(...args),
+ ensureDir: (...args) => mocks.ensureDir(...args), atomicWrite: (...args) => mocks.atomicWrite(...args), sleep: (...args) => mocks.sleep(...args),
}));
import { normalizeSpotifyPlaylist, normalizeSpotifyTrack, playlistSnapshotSummary, syncSpotifyPlaylists } from './spotifyPlaylists.js';
@@ -103,4 +103,18 @@ describe('syncSpotifyPlaylists', () => {
expect(result).toMatchObject({ ok: true, playlistCount: 1, trackCount: 1, scanned: 1 });
expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(2);
});
+
+ it('retries rate-limited playlist item requests before recording a failure', async () => {
+ mocks.fetchWithTimeout
+ .mockReset()
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ total: 1, items: [playlist] }) })
+ .mockResolvedValueOnce({ ok: false, status: 429, headers: { get: () => '0' }, json: async () => ({}) })
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ total: 1, items: [trackItem] }) });
+
+ const result = await syncSpotifyPlaylists();
+
+ expect(result).toMatchObject({ ok: true, playlistCount: 1, trackCount: 1 });
+ expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(3);
+ expect(mocks.sleep).toHaveBeenCalledWith(0);
+ });
});
diff --git a/server/services/youtubePlaylists.js b/server/services/youtubePlaylists.js
index f08fe90630..b2aba0a9e4 100644
--- a/server/services/youtubePlaylists.js
+++ b/server/services/youtubePlaylists.js
@@ -16,6 +16,7 @@ const SNAPSHOT_VERSION = 1;
const MAX_PLAYLISTS = 100;
const MAX_VIDEOS_PER_PLAYLIST = 200;
const NAV_SETTLE_MS = 2500;
+const MAX_SYNC_MS = 2 * 60 * 1000;
export function normalizeYoutubeVideo(raw) {
if (!raw?.id || !raw?.title) return null;
@@ -133,8 +134,9 @@ async function loadPage(url) {
let page = await findOrOpenPage(url).catch(() => null);
if (!page || isAuthPage(page)) return { page: null, status: page ? 'auth-required' : 'no-browser' };
if (!/\/feed\/playlists/.test(page.url || '')) {
- const navigated = await evaluateOnPage(page, `location.assign(${JSON.stringify(url)}); true`).catch(() => false);
- if (!navigated) return { page: null, status: 'navigation-failed' };
+ // A navigation can tear down the CDP execution context after location.assign
+ // runs, which makes evaluateOnPage resolve null even though the page moved.
+ await evaluateOnPage(page, `location.assign(${JSON.stringify(url)}); true`).catch(() => null);
await sleep(NAV_SETTLE_MS);
const refreshed = (await listCdpPages().catch(() => [])).find((candidate) => candidate.id === page.id);
if (refreshed) page = refreshed;
@@ -185,15 +187,23 @@ async function doSyncYoutubePlaylists() {
failed: 0,
};
}
- for (const rawPlaylist of sourcePlaylists) {
- const navigated = await evaluateOnPage(loaded.page, `location.assign(${JSON.stringify(`${PLAYLIST_URL}${encodeURIComponent(rawPlaylist.id)}`)}); true`).catch(() => false);
- if (!navigated) {
- warnings.push(`${rawPlaylist.name || 'Playlist'}: could not open playlist`);
- const stale = previous?.playlists?.find((playlist) => playlist.id === rawPlaylist.id);
- if (stale) playlists.push(stale);
- continue;
+ const deadline = Date.now() + MAX_SYNC_MS;
+ for (let index = 0; index < sourcePlaylists.length; index += 1) {
+ const rawPlaylist = sourcePlaylists[index];
+ if (Date.now() >= deadline) {
+ warnings.push(`Sync stopped after ${Math.round(MAX_SYNC_MS / 60000)} minutes; remaining playlists were not refreshed`);
+ sourcePlaylists.slice(index).forEach((remaining) => {
+ const stale = previous?.playlists?.find((playlist) => playlist.id === remaining.id);
+ if (stale) playlists.push(stale);
+ });
+ break;
}
+ // Do not use the evaluate result as the navigation verdict: CDP can report
+ // a context error while the requested navigation is already in progress.
+ await evaluateOnPage(loaded.page, `location.assign(${JSON.stringify(`${PLAYLIST_URL}${encodeURIComponent(rawPlaylist.id)}`)}); true`).catch(() => null);
await sleep(NAV_SETTLE_MS);
+ const refreshed = (await listCdpPages().catch(() => [])).find((candidate) => candidate.id === loaded.page.id);
+ if (refreshed) loaded.page = refreshed;
const detail = await evaluateOnPage(loaded.page, buildPlaylistVideosExtractionScript()).catch(() => null);
if (!detail || !Array.isArray(detail.videos) || detail.signedOut) {
warnings.push(`${rawPlaylist.name || 'Playlist'}: could not read videos`);
@@ -201,13 +211,24 @@ async function doSyncYoutubePlaylists() {
if (stale) playlists.push(stale);
continue;
}
- if (!detail.videos.length && Number.isFinite(rawPlaylist.videoCount) && rawPlaylist.videoCount > 0) {
+ const normalizedVideos = detail.videos.map(normalizeYoutubeVideo).filter(Boolean);
+ if (!normalizedVideos.length && Number.isFinite(rawPlaylist.videoCount) && rawPlaylist.videoCount > 0) {
warnings.push(`${rawPlaylist.name || 'Playlist'}: no videos read`);
const stale = previous?.playlists?.find((playlist) => playlist.id === rawPlaylist.id);
if (stale) playlists.push(stale);
continue;
}
- const normalizedVideos = detail.videos.map(normalizeYoutubeVideo).filter(Boolean);
+ const expectedVideoCount = Number.isFinite(rawPlaylist.videoCount)
+ ? Math.min(rawPlaylist.videoCount, MAX_VIDEOS_PER_PLAYLIST)
+ : 0;
+ if (expectedVideoCount > 0 && normalizedVideos.length < expectedVideoCount * 0.5) {
+ warnings.push(`${rawPlaylist.name || 'Playlist'}: only read ${normalizedVideos.length} of ${expectedVideoCount} video(s)`);
+ const stale = previous?.playlists?.find((playlist) => playlist.id === rawPlaylist.id);
+ if (stale) {
+ playlists.push(stale);
+ continue;
+ }
+ }
const playlist = normalizeYoutubePlaylist(rawPlaylist, normalizedVideos);
if (playlist) playlists.push(playlist);
}
diff --git a/server/services/youtubePlaylists.test.js b/server/services/youtubePlaylists.test.js
index e10b112c7e..a2b4886bed 100644
--- a/server/services/youtubePlaylists.test.js
+++ b/server/services/youtubePlaylists.test.js
@@ -77,17 +77,19 @@ describe('syncYoutubePlaylists', () => {
expect(mocks.atomicWrite).not.toHaveBeenCalled();
});
- it('retains a stale playlist when navigation fails', async () => {
+ it('retains a stale playlist when navigation closes the CDP context', async () => {
const stale = { id: 'PL-example', name: 'Example playlist', videoCount: 1, videos: [{ id: 'video-1' }] };
mocks.readJSONFile.mockResolvedValue({ playlists: [stale] });
mocks.evaluateOnPage
.mockReset()
.mockResolvedValueOnce({ signedOut: false, playlists: [{ id: stale.id, name: stale.name, videoCount: 1 }] })
- .mockResolvedValueOnce(false);
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(null);
const result = await syncYoutubePlaylists();
expect(result).toMatchObject({ ok: false, playlistCount: 1, videoCount: 1, failed: 1 });
+ expect(result.warnings).toEqual(['Example playlist: could not read videos']);
expect(mocks.atomicWrite).toHaveBeenCalledWith('/tmp/youtube/playlists.json', expect.objectContaining({ playlists: [stale] }));
});
@@ -105,4 +107,23 @@ describe('syncYoutubePlaylists', () => {
expect(result).toMatchObject({ ok: false, playlistCount: 1, videoCount: 1, failed: 1 });
expect(result.warnings).toEqual(['Example playlist: no videos read']);
});
+
+ it('retains a complete prior snapshot when the page only hydrates a small fraction', async () => {
+ const stale = {
+ id: 'PL-example', name: 'Example playlist', videoCount: 90,
+ videos: Array.from({ length: 90 }, (_, index) => ({ id: `video-${index}` })),
+ };
+ mocks.readJSONFile.mockResolvedValue({ playlists: [stale] });
+ mocks.evaluateOnPage
+ .mockReset()
+ .mockResolvedValueOnce({ signedOut: false, playlists: [{ id: stale.id, name: stale.name, videoCount: 90 }] })
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce({ signedOut: false, videos: [{ id: 'video-1', title: 'Example video' }] });
+
+ const result = await syncYoutubePlaylists();
+
+ expect(result).toMatchObject({ ok: false, playlistCount: 1, videoCount: 90, failed: 1 });
+ expect(result.warnings).toEqual(['Example playlist: only read 1 of 90 video(s)']);
+ expect(mocks.atomicWrite).toHaveBeenCalledWith('/tmp/youtube/playlists.json', expect.objectContaining({ playlists: [stale] }));
+ });
});