Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
fix(database): merge row data atomically and shape queries to indexes
spacesdriveb57df8800589
diff --git a/backend/repositories/accountRepository.ts b/backend/repositories/accountRepository.tsindex 2c70159..5af8bdc 100644--- a/backend/repositories/accountRepository.ts+++ b/backend/repositories/accountRepository.ts@@ -18,7 +18,7 @@ function toAccount(row: AccountRow): Account {// methods named ...ForUser filter by the verified user id; the others reach every user and are only for cron jobsexport interface AccountRepository {listForUser(userId: string): Promise<Account[]>;- listAll(): Promise<Account[]>;+ listByPlatform(platform: Platform): Promise<Account[]>;findForUser(id: string, userId: string): Promise<Account | null>;findById(id: string): Promise<Account | null>;create(account: NewAccount, userId: string): Promise<void>;@@ -36,29 +36,27 @@ export function createAccountRepository(db: SupabaseClient): AccountRepository {return row ? toAccount(row) : null;}- // merges into data, so fields the update does not name are kept+ // one atomic merge in the database, so two refreshes never undo each other; an undefined field keeps its stored valueasync function update(id: string, updates: Partial<Account>, userId: string | null): Promise<void> {- const current = await find(id, userId);- if (!current) throw new NotFoundError('Account not found');- const { id: _id, platform: currentPlatform, ...currentData } = current;- const { platform: newPlatform, ...dataUpdates } = updates;- await execute('accounts.update', () => {- const query = db.from('accounts').update({- platform: newPlatform || currentPlatform,- data: { ...currentData, ...dataUpdates },- }).eq('id', id);- return userId ? query.eq('user_id', userId) : query;- });+ const { id: _id, platform: _platform, ...patch } = updates;+ const { data } = await execute('accounts.update', () => db.rpc('merge_account_data', { p_id: id, p_user_id: userId, p_patch: patch }));+ if (!data) throw new NotFoundError('Account not found');}return {+ // id breaks ties between accounts added in the same instant, so the order never changes between requestsasync listForUser(userId) {- const found = await rows<AccountRow>('accounts.listForUser', () => db.from('accounts').select(COLUMNS).eq('user_id', userId));+ const found = await rows<AccountRow>('accounts.listForUser', () => db+ .from('accounts')+ .select(COLUMNS)+ .eq('user_id', userId)+ .order('created_at', { ascending: true })+ .order('id', { ascending: true }));return found.map(toAccount);},- async listAll() {- const found = await rows<AccountRow>('accounts.listAll', () => db.from('accounts').select(COLUMNS));+ async listByPlatform(platform) {+ const found = await rows<AccountRow>('accounts.listByPlatform', () => db.from('accounts').select(COLUMNS).eq('platform', platform));return found.map(toAccount);},diff --git a/backend/repositories/scheduledPostRepository.ts b/backend/repositories/scheduledPostRepository.tsindex 91fea50..e128069 100644--- a/backend/repositories/scheduledPostRepository.ts+++ b/backend/repositories/scheduledPostRepository.ts@@ -12,12 +12,6 @@ interface ScheduledPostRow {data: Partial<ScheduledPost> | null;}-interface PostColumnUpdates {- status?: PostStatus;- scheduled_at?: string;- data?: Partial<ScheduledPost>;-}-export interface DeleteAllResult {deleted: number;kept: number;@@ -52,35 +46,18 @@ export interface ScheduledPostRepository {}export function createScheduledPostRepository(db: SupabaseClient): ScheduledPostRepository {- // status and scheduledAt are columns; every other field is merged into data; claimedAt and attempts change only in claim+ // one atomic statement that merges the rest into data; claim alone sets claimedAt and attempts, and onlyStatus guards editsasync function update(id: string, updates: Partial<ScheduledPost>, userId: string | null, onlyStatus?: PostStatus): Promise<boolean> {- const { status, scheduledAt, accountId: _accountId, claimedAt: _claimedAt, attempts: _attempts, ...dataUpdates } = updates;- const columns: PostColumnUpdates = {};- if (status !== undefined) columns.status = status;- if (scheduledAt !== undefined) columns.scheduled_at = scheduledAt;-- if (Object.keys(dataUpdates).length > 0) {- const current = await rows<Pick<ScheduledPostRow, 'data'>>('scheduledPosts.readData', () => {- const query = db.from('scheduled_posts').select('data').eq('id', id);- return userId ? query.eq('user_id', userId) : query;- });- columns.data = { ...(current[0]?.data || {}), ...dataUpdates };- }-- if (!onlyStatus) {- await execute('scheduledPosts.update', () => {- const query = db.from('scheduled_posts').update(columns).eq('id', id);- return userId ? query.eq('user_id', userId) : query;- });- return true;- }-- // the status check sits in the same statement, so a scheduler claiming the post in between makes this change nothing- const changed = await rows<{ id: string }>('scheduledPosts.updateIfStatus', () => {- const query = db.from('scheduled_posts').update(columns).eq('id', id).eq('status', onlyStatus);- return (userId ? query.eq('user_id', userId) : query).select('id');- });- return changed.length > 0;+ const { status, scheduledAt, id: _id, accountId: _accountId, claimedAt: _claimedAt, attempts: _attempts, ...patch } = updates;+ const { data } = await execute('scheduledPosts.update', () => db.rpc('merge_scheduled_post', {+ p_id: id,+ p_user_id: userId,+ p_patch: patch,+ p_status: status ?? null,+ p_scheduled_at: scheduledAt ?? null,+ p_only_status: onlyStatus ?? null,+ }));+ return data === true;}return {diff --git a/backend/repositories/trackedPostRepository.ts b/backend/repositories/trackedPostRepository.tsindex 293f219..619f139 100644--- a/backend/repositories/trackedPostRepository.ts+++ b/backend/repositories/trackedPostRepository.ts@@ -22,6 +22,7 @@ export interface NewTrackedPost {label?: string;category?: string;contentType?: string;+ data?: Record<string, unknown>;}export interface TrackedPostUpdates {@@ -32,7 +33,6 @@ export interface TrackedPostUpdates {}interface TrackedPostColumnUpdates {- updated_at: string;label?: string;category?: string;account_id?: string | null;@@ -87,7 +87,7 @@ export function createTrackedPostRepository(db: SupabaseClient): TrackedPostRepo},async create(post, userId) {- const { id, accountId, url, label, category, contentType } = post;+ const { id, accountId, url, label, category, contentType, data } = post;await execute('trackedPosts.create', () => db.from('tracked_posts').insert({id,user_id: userId,@@ -96,11 +96,13 @@ export function createTrackedPostRepository(db: SupabaseClient): TrackedPostRepolabel: label || '',category: category || '',content_type: contentType || 'reddit',+ data: data ?? null,}));},+ // the database trigger keeps updated_atasync updateForUser(id, updates, userId) {- const columns: TrackedPostColumnUpdates = { updated_at: new Date().toISOString() };+ const columns: TrackedPostColumnUpdates = {};if (updates.label !== undefined) columns.label = updates.label;if (updates.category !== undefined) columns.category = updates.category;if (updates.accountId !== undefined) columns.account_id = updates.accountId || null;@@ -108,20 +110,10 @@ export function createTrackedPostRepository(db: SupabaseClient): TrackedPostRepoawait execute('trackedPosts.update', () => db.from('tracked_posts').update(columns).eq('id', id).eq('user_id', userId));},- // merges into data so manual fields and live refresh fields survive each other+ // one atomic merge, so a manual view count and a refresh that lands at the same moment both surviveasync patchDataForUser(id, patch, userId) {- const row = await maybeRow<Pick<TrackedPostRow, 'data'>>('trackedPosts.readData', () => db- .from('tracked_posts')- .select('data')- .eq('id', id)- .eq('user_id', userId)- .maybeSingle());- if (!row) throw new NotFoundError('Tracked content not found');- await execute('trackedPosts.patchData', () => db- .from('tracked_posts')- .update({ data: { ...(row.data || {}), ...patch }, updated_at: new Date().toISOString() })- .eq('id', id)- .eq('user_id', userId));+ const { data } = await execute('trackedPosts.patchData', () => db.rpc('merge_tracked_post_data', { p_id: id, p_user_id: userId, p_patch: patch }));+ if (!data) throw new NotFoundError('Tracked content not found');},async deleteForUser(id, userId) {diff --git a/backend/services/tokenRefreshService.ts b/backend/services/tokenRefreshService.tsindex ef5ed65..d31a72a 100644--- a/backend/services/tokenRefreshService.ts+++ b/backend/services/tokenRefreshService.ts@@ -42,7 +42,7 @@ export function createTokenRefreshService({ accounts, context }: TokenRefreshDepasync refreshExpiringInstagramTokens() {let listed: Account[];try {- listed = await accounts.listAll();+ listed = await accounts.listByPlatform('instagram');} catch (err) {log.error('token refresh could not load accounts', errorFields(err));return;diff --git a/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json b/backend/tests/fixtures/accountsRoutes.addInstagram.golden.jsonindex dac6cee..ba6dbda 100644--- a/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json+++ b/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json@@ -6,11 +6,11 @@},{"status": 200,- "body": "{\"success\":true,\"account\":{\"id\":\"17882640000004fzz\",\"platform\":\"instagram\",\"igUserId\":\"3000\",\"username\":\"fresh\",\"title\":\"fresh\",\"biography\":\"\",\"website\":\"\",\"profilePictureUrl\":\"\",\"followersCount\":5,\"followsCount\":0,\"mediaCount\":1,\"tokenExpiresAt\":\"2026-09-01T13:23:20.000Z\",\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":false}}"+ "body": "{\"success\":true,\"account\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"platform\":\"instagram\",\"igUserId\":\"3000\",\"username\":\"fresh\",\"title\":\"fresh\",\"biography\":\"\",\"website\":\"\",\"profilePictureUrl\":\"\",\"followersCount\":5,\"followsCount\":0,\"mediaCount\":1,\"tokenExpiresAt\":\"2026-09-01T13:23:20.000Z\",\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":false}}"},{"status": 200,- "body": "{\"success\":true,\"account\":{\"id\":\"17882640000004fzz\",\"platform\":\"instagram\",\"igUserId\":\"3001\",\"username\":\"shorty\",\"title\":\"Shorty\",\"biography\":\"\",\"website\":\"\",\"profilePictureUrl\":\"\",\"followersCount\":0,\"followsCount\":0,\"mediaCount\":0,\"tokenExpiresAt\":null,\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":false}}"+ "body": "{\"success\":true,\"account\":{\"id\":\"00000000-0000-4000-8000-000000000002\",\"platform\":\"instagram\",\"igUserId\":\"3001\",\"username\":\"shorty\",\"title\":\"Shorty\",\"biography\":\"\",\"website\":\"\",\"profilePictureUrl\":\"\",\"followersCount\":0,\"followsCount\":0,\"mediaCount\":0,\"tokenExpiresAt\":null,\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":false}}"},{"status": 409,@@ -79,7 +79,7 @@"type": "insert","table": "accounts","values": {- "id": "17882640000004fzz",+ "id": "00000000-0000-4000-8000-000000000001","user_id": "user-1","platform": "instagram","data": {@@ -115,7 +115,7 @@"type": "insert","table": "accounts","values": {- "id": "17882640000004fzz",+ "id": "00000000-0000-4000-8000-000000000002","user_id": "user-1","platform": "instagram","data": {diff --git a/backend/tests/fixtures/accountsRoutes.addReddit.golden.json b/backend/tests/fixtures/accountsRoutes.addReddit.golden.jsonindex af6a548..2353714 100644--- a/backend/tests/fixtures/accountsRoutes.addReddit.golden.json+++ b/backend/tests/fixtures/accountsRoutes.addReddit.golden.json@@ -10,7 +10,7 @@},{"status": 200,- "body": "{\"success\":true,\"account\":{\"id\":\"17882640000004fzz\",\"platform\":\"reddit\",\"username\":\"NewUser\",\"title\":\"u/NewUser\",\"totalKarma\":70,\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"createdAt\":\"2020-09-13T12:26:40.000Z\",\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":true}}"+ "body": "{\"success\":true,\"account\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"platform\":\"reddit\",\"username\":\"NewUser\",\"title\":\"u/NewUser\",\"totalKarma\":70,\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"createdAt\":\"2020-09-13T12:26:40.000Z\",\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":true}}"},{"status": 409,@@ -66,7 +66,7 @@"type": "insert","table": "accounts","values": {- "id": "17882640000004fzz",+ "id": "00000000-0000-4000-8000-000000000001","user_id": "user-1","platform": "reddit","data": {diff --git a/backend/tests/fixtures/accountsRoutes.addYouTube.golden.json b/backend/tests/fixtures/accountsRoutes.addYouTube.golden.jsonindex 9550eab..767abb2 100644--- a/backend/tests/fixtures/accountsRoutes.addYouTube.golden.json+++ b/backend/tests/fixtures/accountsRoutes.addYouTube.golden.json@@ -2,7 +2,7 @@"responses": [{"status": 200,- "body": "{\"success\":true,\"account\":{\"id\":\"17882640000004fzz\",\"channelId\":\"UCnnnnnnnnnnnnnnnnnnnnnn\",\"title\":\"Channel UCnn\",\"description\":\"Desc\",\"customUrl\":\"@chan\",\"publishedAt\":\"2020-01-01T00:00:00Z\",\"country\":\"GB\",\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"subscriberCount\":500,\"viewCount\":9000,\"videoCount\":12,\"hiddenSubscriberCount\":false,\"uploadsPlaylistId\":\"UUnnnnnnnnnnnnnnnnnnnnnn\",\"keywords\":\"k\",\"topicCategories\":[\"t\"],\"madeForKids\":false,\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\"}}"+ "body": "{\"success\":true,\"account\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"channelId\":\"UCnnnnnnnnnnnnnnnnnnnnnn\",\"title\":\"Channel UCnn\",\"description\":\"Desc\",\"customUrl\":\"@chan\",\"publishedAt\":\"2020-01-01T00:00:00Z\",\"country\":\"GB\",\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"subscriberCount\":500,\"viewCount\":9000,\"videoCount\":12,\"hiddenSubscriberCount\":false,\"uploadsPlaylistId\":\"UUnnnnnnnnnnnnnnnnnnnnnn\",\"keywords\":\"k\",\"topicCategories\":[\"t\"],\"madeForKids\":false,\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\"}}"},{"status": 409,@@ -63,7 +63,7 @@"type": "insert","table": "accounts","values": {- "id": "17882640000004fzz",+ "id": "00000000-0000-4000-8000-000000000001","user_id": "user-1","platform": "youtube","data": {diff --git a/backend/tests/fixtures/accountsRoutes.refreshAll.golden.json b/backend/tests/fixtures/accountsRoutes.refreshAll.golden.jsonindex d0900a4..157b0d8 100644--- a/backend/tests/fixtures/accountsRoutes.refreshAll.golden.json+++ b/backend/tests/fixtures/accountsRoutes.refreshAll.golden.json@@ -83,62 +83,17 @@]},{- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "yt1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "rd1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "youtube",- "data": {- "channelId": "UCaaaaaaaaaaaaaaaaaaaaaa",- "title": "Channel UCaa",- "subscriberCount": 500,+ "p_id": "yt1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "subscriberCount": 500,"viewCount": 9000,"videoCount": 12,+ "title": "Channel UCaa","thumbnails": {"default": "d","medium": "m",@@ -146,71 +101,41 @@}}},- "filters": [- [- "id",- "yt1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "instagram",- "data": {- "igUserId": "1789",- "username": "ribbon",- "accessToken": "IGTOKEN",- "tokenExpiresAt": "2026-09-05T00:00:00.000Z",- "followersCount": 2500,+ "p_id": "ig1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "followersCount": 2500,"followsCount": 10,"mediaCount": 140,"title": "Ribbon",+ "username": "ribbon","profilePictureUrl": "https://p"}},- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "reddit",- "data": {- "username": "ribbon_r",- "cookie": "COOKIE",- "totalKarma": 70,+ "p_id": "rd1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "totalKarma": 70,"postKarma": 50,"commentKarma": 20,"iconUrl": "https://i?a=1&b=2"}},- "filters": [- [- "id",- "rd1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -235,89 +160,38 @@]},{- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "rd1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "instagram",- "data": {- "igUserId": "1789",- "username": "ribbon",- "accessToken": "IGTOKEN",- "tokenExpiresAt": "2026-09-05T00:00:00.000Z",- "followersCount": 2500,+ "p_id": "ig1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "followersCount": 2500,"followsCount": 10,"mediaCount": 140,"title": "Ribbon",+ "username": "ribbon","profilePictureUrl": "https://p"}},- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "reddit",- "data": {- "username": "ribbon_r",- "cookie": "COOKIE",- "totalKarma": 70,+ "p_id": "rd1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "totalKarma": 70,"postKarma": 50,"commentKarma": 20,"iconUrl": "https://i?a=1&b=2"}},- "filters": [- [- "id",- "rd1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -342,62 +216,17 @@]},{- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "yt1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "rd1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "youtube",- "data": {- "channelId": "UCaaaaaaaaaaaaaaaaaaaaaa",- "title": "Channel UCaa",- "subscriberCount": 500,+ "p_id": "yt1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "subscriberCount": 500,"viewCount": 9000,"videoCount": 12,+ "title": "Channel UCaa","thumbnails": {"default": "d","medium": "m",@@ -405,71 +234,41 @@}}},- "filters": [- [- "id",- "yt1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "instagram",- "data": {- "igUserId": "1789",- "username": "ribbon",- "accessToken": "IGTOKEN",- "tokenExpiresAt": "2026-09-05T00:00:00.000Z",- "followersCount": 2500,+ "p_id": "ig1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "followersCount": 2500,"followsCount": 10,"mediaCount": 140,"title": "Ribbon",+ "username": "ribbon","profilePictureUrl": "https://p"}},- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "reddit",- "data": {- "username": "ribbon_r",- "cookie": "COOKIE",- "totalKarma": 70,+ "p_id": "rd1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "totalKarma": 70,"postKarma": 50,"commentKarma": 20,"iconUrl": "https://i?a=1&b=2"}},- "filters": [- [- "id",- "rd1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",diff --git a/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json b/backend/tests/fixtures/accountsRoutes.refreshOne.golden.jsonindex 8f582f5..f6b0777 100644--- a/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json+++ b/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json@@ -120,50 +120,24 @@]},{- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "instagram",- "data": {- "igUserId": "1789",- "username": "ribbon",- "accessToken": "IGTOKEN",- "tokenExpiresAt": "2026-09-05T00:00:00.000Z",- "followersCount": 2500,+ "p_id": "ig1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "followersCount": 2500,"followsCount": 10,"mediaCount": 140,"title": "Ribbon",+ "username": "ribbon","profilePictureUrl": "https://p","biography": "Bio","website": "https://r.example"}},- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -196,45 +170,20 @@]},{- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "rd1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "reddit",- "data": {- "username": "ribbon_r",- "cookie": "COOKIE",- "totalKarma": 70,+ "p_id": "rd1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "totalKarma": 70,"postKarma": 50,"commentKarma": 20,"iconUrl": "https://i?a=1&b=2"}},- "filters": [- [- "id",- "rd1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -267,32 +216,17 @@]},{- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "yt1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "youtube",- "data": {- "channelId": "UCaaaaaaaaaaaaaaaaaaaaaa",- "title": "Channel UCaa",- "subscriberCount": 500,+ "p_id": "yt1",+ "p_user_id": "user-1",+ "p_patch": {"lastUpdated": "2026-09-01T12:00:00.000Z",+ "subscriberCount": 500,"viewCount": 9000,"videoCount": 12,+ "title": "Channel UCaa","description": "Desc","thumbnails": {"default": "d",@@ -307,16 +241,7 @@]}},- "filters": [- [- "id",- "yt1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -424,50 +349,17 @@]},{- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "instagram",- "data": {- "igUserId": "1789",- "username": "ribbon",+ "p_id": "ig1",+ "p_user_id": "user-1",+ "p_patch": {"accessToken": "IGTOKEN2",- "tokenExpiresAt": "2026-09-02T12:00:00.000Z",- "followersCount": 2500,- "lastUpdated": "2026-09-01T12:00:00.000Z",- "followsCount": 10,- "mediaCount": 140,- "title": "Ribbon",- "profilePictureUrl": "https://p",- "biography": "Bio",- "website": "https://r.example"+ "tokenExpiresAt": "2026-09-02T12:00:00.000Z"}},- "filters": [- [- "id",- "ig1"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",diff --git a/backend/tests/fixtures/fakeSupabase.ts b/backend/tests/fixtures/fakeSupabase.tsindex f5222a7..cdbbd85 100644--- a/backend/tests/fixtures/fakeSupabase.ts+++ b/backend/tests/fixtures/fakeSupabase.ts@@ -6,7 +6,7 @@ export type Row = Record<string, unknown>;type Filter = [column: string, value: unknown, operator?: 'lte' | 'lt' | 'neq'];interface Action {- type: 'select' | 'update' | 'insert' | 'upsert' | 'delete';+ type: 'select' | 'update' | 'insert' | 'upsert' | 'delete' | 'rpc';table: string;columns?: string;values?: Row;@@ -57,6 +57,35 @@ function inTable(row: Row, name: string) {return row._table === undefined || row._table === name;}+// the merge functions in supabase/migrations, run on the in-memory rows: one table, a patch merged into data+const MERGE_FUNCTIONS: Record<string, { table: string; userOptional: boolean }> = {+ merge_account_data: { table: 'accounts', userOptional: true },+ merge_scheduled_post: { table: 'scheduled_posts', userOptional: true },+ merge_tracked_post_data: { table: 'tracked_posts', userOptional: false },+};++function mergeInto(table: Row[], name: string, args: Row): boolean | null {+ const fn = MERGE_FUNCTIONS[name];+ if (!fn) throw new Error(`fakeSupabase has no function ${name}`);+ const found = table.filter(candidate => inTable(candidate, fn.table)+ && candidate.id === args.p_id+ && ((fn.userOptional && args.p_user_id === null) || candidate.user_id === args.p_user_id)+ && (args.p_only_status == null || candidate.status === args.p_only_status));+ for (const row of found) {+ // JSON drops undefined keys, as the request to the database does+ row.data = { ...(row.data as Row | null ?? {}), ...JSON.parse(JSON.stringify(args.p_patch)) };+ if (args.p_status != null) row.status = args.p_status;+ if (args.p_scheduled_at != null) row.scheduled_at = args.p_scheduled_at;+ touch(row);+ }+ return found.length > 0 ? true : null;+}++// every table's updated_at trigger (supabase/migrations) sets it on each update+function touch(row: Row): void {+ row.updated_at = new Date().toISOString();+}+function queryBuilder(action: Action, run: Run): FakeQuery {const filters: Filter[] = [];const query: FakeQuery = {@@ -101,13 +130,13 @@ export function fakeSupabase(rows: Row[] = []): FakeSupabase {function run(action: Action, filters: Filter[]) {calls.push({ ...copy(action), filters: copy(filters) });const found = table.filter(row => inTable(row, action.table) && matchesFilters(row, filters));- if (action.type === 'update') found.forEach(row => Object.assign(row, copy(action.values)));- if (action.type === 'insert') table.push(copy(action.values!));+ if (action.type === 'update') found.forEach(row => touch(Object.assign(row, copy(action.values))));+ if (action.type === 'insert') table.push({ _table: action.table, ...copy(action.values!) });if (action.type === 'upsert') {const values = action.values!;const keys = (action.onConflict ?? 'id').split(',');const existing = table.find(row => inTable(row, action.table) && keys.every(key => row[key] === values[key]));- if (existing) Object.assign(existing, copy(values));+ if (existing) touch(Object.assign(existing, copy(values)));else table.push({ _table: action.table, ...copy(values) });}if (action.type === 'delete') {@@ -119,6 +148,10 @@ export function fakeSupabase(rows: Row[] = []): FakeSupabase {return {calls,table,+ rpc(name: string, args: Row) {+ calls.push({ type: 'rpc', table: name, values: copy(args), filters: [] });+ return Promise.resolve({ data: mergeInto(table, name, args), error: null });+ },from(name: string) {return {select: (columns: string) => queryBuilder({ type: 'select', table: name, columns }, run),diff --git a/backend/tests/fixtures/instagramAuth.callback.golden.json b/backend/tests/fixtures/instagramAuth.callback.golden.jsonindex 6118131..e46a2b2 100644--- a/backend/tests/fixtures/instagramAuth.callback.golden.json+++ b/backend/tests/fixtures/instagramAuth.callback.golden.json@@ -177,7 +177,7 @@"type": "insert","table": "accounts","values": {- "id": "1788264000000zk00",+ "id": "00000000-0000-4000-8000-000000000001","user_id": "user-1","platform": "instagram","data": {@@ -213,7 +213,7 @@"type": "insert","table": "accounts","values": {- "id": "1788264000000zk00",+ "id": "00000000-0000-4000-8000-000000000002","user_id": "user-1","platform": "instagram","data": {diff --git a/backend/tests/fixtures/scheduledPublisher.process.golden.json b/backend/tests/fixtures/scheduledPublisher.process.golden.jsonindex 6559f11..cd7c8e8 100644--- a/backend/tests/fixtures/scheduledPublisher.process.golden.json+++ b/backend/tests/fixtures/scheduledPublisher.process.golden.json@@ -514,66 +514,36 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-image"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "data": {- "mediaType": "IMAGE",- "mediaUrl": "https://cdn/a.jpg",- "caption": "Hello",+ "p_id": "p-image",+ "p_user_id": null,+ "p_patch": {"containerId": "c-IG1"- }+ },+ "p_status": null,+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-image"- ]- ]+ "filters": []},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-image"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "published",- "data": {- "mediaType": "IMAGE",- "mediaUrl": "https://cdn/a.jpg",- "caption": "Hello",- "containerId": "c-IG1",+ "p_id": "p-image",+ "p_user_id": null,+ "p_patch": {"publishedMediaId": "m-c-IG1","publishedAt": "2026-09-01T12:00:00.000Z","error": null- }+ },+ "p_status": "published",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-image"- ]- ]+ "filters": []},{"type": "update",@@ -610,66 +580,36 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-reel"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "data": {- "mediaType": "REELS",- "mediaUrl": "https://cdn/r.mp4",- "shareToFeed": true,+ "p_id": "p-reel",+ "p_user_id": null,+ "p_patch": {"containerId": "c-IG1"- }+ },+ "p_status": null,+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-reel"- ]- ]- },- {- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-reel"- ]- ]+ "filters": []},{- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "published",- "data": {- "mediaType": "REELS",- "mediaUrl": "https://cdn/r.mp4",- "shareToFeed": true,- "containerId": "c-IG1",+ "p_id": "p-reel",+ "p_user_id": null,+ "p_patch": {"publishedMediaId": "m-c-IG1","publishedAt": "2026-09-01T12:00:00.000Z","error": null- }+ },+ "p_status": "published",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-reel"- ]- ]+ "filters": []},{"type": "update",@@ -706,62 +646,34 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-story"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "data": {- "mediaType": "STORIES",- "mediaUrl": "https://cdn/s.mp4",+ "p_id": "p-story",+ "p_user_id": null,+ "p_patch": {"containerId": "c-ERR"- }+ },+ "p_status": null,+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-story"- ]- ]+ "filters": []},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-story"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "failed",- "data": {- "mediaType": "STORIES",- "mediaUrl": "https://cdn/s.mp4",- "containerId": "c-ERR",+ "p_id": "p-story",+ "p_user_id": null,+ "p_patch": {"error": "Processing failed: Bad video"- }+ },+ "p_status": "failed",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-story"- ]- ]+ "filters": []},{"type": "update",@@ -798,62 +710,35 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-expired"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "data": {- "mediaType": "REELS",- "mediaUrl": "https://cdn/e.mp4",+ "p_id": "p-expired",+ "p_user_id": null,+ "p_patch": {"containerId": "c-EXP"- }+ },+ "p_status": null,+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-expired"- ]- ]- },- {- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-expired"- ]- ]+ "filters": []},{- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "pending",- "data": {- "mediaType": "REELS",- "mediaUrl": "https://cdn/e.mp4",- "containerId": null,- "error": "Container expired"- }+ "p_id": "p-expired",+ "p_user_id": null,+ "p_patch": {+ "error": "Container expired",+ "containerId": null+ },+ "p_status": "pending",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-expired"- ]- ]+ "filters": []},{"type": "update",@@ -890,33 +775,19 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-missing"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "failed",- "data": {- "mediaType": "IMAGE",- "mediaUrl": "https://cdn/m.jpg",+ "p_id": "p-missing",+ "p_user_id": null,+ "p_patch": {"error": "Account not found: gone"- }+ },+ "p_status": "failed",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-missing"- ]- ]+ "filters": []},{"type": "update",@@ -953,33 +824,19 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-create"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "failed",- "data": {- "mediaType": "IMAGE",- "mediaUrl": "https://cdn/b.jpg",+ "p_id": "p-create",+ "p_user_id": null,+ "p_patch": {"error": "Invalid image"- }+ },+ "p_status": "failed",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-create"- ]- ]+ "filters": []},{"type": "update",@@ -1016,62 +873,34 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-publish"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "data": {- "mediaType": "IMAGE",- "mediaUrl": "https://cdn/p.jpg",+ "p_id": "p-publish",+ "p_user_id": null,+ "p_patch": {"containerId": "c-PUB"- }+ },+ "p_status": null,+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-publish"- ]- ]+ "filters": []},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-publish"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "failed",- "data": {- "mediaType": "IMAGE",- "mediaUrl": "https://cdn/p.jpg",- "containerId": "c-PUB",+ "p_id": "p-publish",+ "p_user_id": null,+ "p_patch": {"error": "Publish refused"- }+ },+ "p_status": "failed",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-publish"- ]- ]+ "filters": []},{"type": "update",@@ -1108,62 +937,34 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-slow"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "data": {- "mediaType": "REELS",- "mediaUrl": "https://cdn/slow.mp4",+ "p_id": "p-slow",+ "p_user_id": null,+ "p_patch": {"containerId": "c-SLOW"- }+ },+ "p_status": null,+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-slow"- ]- ]- },- {- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-slow"- ]- ]+ "filters": []},{- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "pending",- "data": {- "mediaType": "REELS",- "mediaUrl": "https://cdn/slow.mp4",- "containerId": "c-SLOW",+ "p_id": "p-slow",+ "p_user_id": null,+ "p_patch": {"error": "Instagram did not finish processing the media within 3 minutes"- }+ },+ "p_status": "pending",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-slow"- ]- ]+ "filters": []},{"type": "update",@@ -1200,64 +1001,36 @@]},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-dup"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "data": {- "mediaType": "IMAGE",- "mediaUrl": "https://cdn/d.jpg",+ "p_id": "p-dup",+ "p_user_id": null,+ "p_patch": {"containerId": "c-IG1"- }+ },+ "p_status": null,+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-dup"- ]- ]+ "filters": []},{- "type": "select",- "table": "scheduled_posts",- "columns": "data",- "filters": [- [- "id",- "p-dup"- ]- ]- },- {- "type": "update",- "table": "scheduled_posts",+ "type": "rpc",+ "table": "merge_scheduled_post","values": {- "status": "published",- "data": {- "mediaType": "IMAGE",- "mediaUrl": "https://cdn/d.jpg",- "containerId": "c-IG1",+ "p_id": "p-dup",+ "p_user_id": null,+ "p_patch": {"publishedMediaId": "m-c-IG1","publishedAt": "2026-09-01T12:00:00.000Z","error": null- }+ },+ "p_status": "published",+ "p_scheduled_at": null,+ "p_only_status": null},- "filters": [- [- "id",- "p-dup"- ]- ]+ "filters": []},{"type": "update",@@ -1361,7 +1134,8 @@"publishedMediaId": "m-c-IG1","publishedAt": "2026-09-01T12:00:00.000Z","error": null- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1380,7 +1154,8 @@"publishedMediaId": "m-c-IG1","publishedAt": "2026-09-01T12:00:00.000Z","error": null- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1396,7 +1171,8 @@"mediaUrl": "https://cdn/s.mp4","containerId": "c-ERR","error": "Processing failed: Bad video"- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1412,7 +1188,8 @@"mediaUrl": "https://cdn/e.mp4","containerId": null,"error": "Container expired"- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1427,7 +1204,8 @@"mediaType": "IMAGE","mediaUrl": "https://cdn/m.jpg","error": "Account not found: gone"- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1442,7 +1220,8 @@"mediaType": "IMAGE","mediaUrl": "https://cdn/b.jpg","error": "Invalid image"- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1458,7 +1237,8 @@"mediaUrl": "https://cdn/p.jpg","containerId": "c-PUB","error": "Publish refused"- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1474,7 +1254,8 @@"mediaUrl": "https://cdn/slow.mp4","containerId": "c-SLOW","error": "Instagram did not finish processing the media within 3 minutes"- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1492,7 +1273,8 @@"publishedMediaId": "m-c-IG1","publishedAt": "2026-09-01T12:00:00.000Z","error": null- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",@@ -1510,7 +1292,8 @@"publishedMediaId": "m-c-IG1","publishedAt": "2026-09-01T12:00:00.000Z","error": null- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"_table": "scheduled_posts",diff --git a/backend/tests/fixtures/tokenRefreshService.idle.golden.json b/backend/tests/fixtures/tokenRefreshService.idle.golden.jsonindex ba8ee4b..2e9c6d5 100644--- a/backend/tests/fixtures/tokenRefreshService.idle.golden.json+++ b/backend/tests/fixtures/tokenRefreshService.idle.golden.json@@ -11,7 +11,12 @@"type": "select","table": "accounts","columns": "id, platform, data",- "filters": []+ "filters": [+ [+ "platform",+ "instagram"+ ]+ ]}]}diff --git a/backend/tests/fixtures/tokenRefreshService.refresh.golden.json b/backend/tests/fixtures/tokenRefreshService.refresh.golden.jsonindex 2aca2eb..fdd2389 100644--- a/backend/tests/fixtures/tokenRefreshService.refresh.golden.json+++ b/backend/tests/fixtures/tokenRefreshService.refresh.golden.json@@ -28,69 +28,42 @@}],"calls": [- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": []- },{"type": "select","table": "accounts","columns": "id, platform, data","filters": [[- "id",- "a1"+ "platform",+ "instagram"]]},{- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "instagram",- "data": {- "username": "soon",+ "p_id": "a1",+ "p_user_id": null,+ "p_patch": {"accessToken": "N1","tokenExpiresAt": "2026-10-31T12:00:00.000Z"}},- "filters": [- [- "id",- "a1"- ]- ]- },- {- "type": "select",- "table": "accounts",- "columns": "id, platform, data",- "filters": [- [- "id",- "a7"- ]- ]+ "filters": []},{- "type": "update",- "table": "accounts",+ "type": "rpc",+ "table": "merge_account_data","values": {- "platform": "instagram",- "data": {- "username": "expired",+ "p_id": "a7",+ "p_user_id": null,+ "p_patch": {"accessToken": "N7","tokenExpiresAt": "2026-10-31T12:00:00.000Z"}},- "filters": [- [- "id",- "a7"- ]- ]+ "filters": []}],"table": [@@ -102,7 +75,8 @@"username": "soon","accessToken": "N1","tokenExpiresAt": "2026-10-31T12:00:00.000Z"- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"},{"id": "a2",@@ -160,7 +134,8 @@"username": "expired","accessToken": "N7","tokenExpiresAt": "2026-10-31T12:00:00.000Z"- }+ },+ "updated_at": "2026-09-01T12:00:00.000Z"}]}diff --git a/backend/tests/fixtures/trackedContentRoutes.create.golden.json b/backend/tests/fixtures/trackedContentRoutes.create.golden.jsonindex 1ea9499..465dc60 100644--- a/backend/tests/fixtures/trackedContentRoutes.create.golden.json+++ b/backend/tests/fixtures/trackedContentRoutes.create.golden.json@@ -14,7 +14,7 @@{"call": "POST /tracked-content","status": 201,- "body": "{\"id\":\"mtim7pc04i\",\"accountId\":null,\"url\":\"https://www.youtube.com/watch?v=abc\",\"label\":\"Video\",\"category\":\"Music\",\"contentType\":\"youtube\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"title\":\"Watch\",\"channelTitle\":\"Ribbon\",\"channelId\":\"UC1\",\"thumbnail\":\"m\",\"publishedAt\":\"2026-08-01T10:00:00Z\",\"viewCount\":1500,\"likeCount\":40,\"commentCount\":3,\"isShort\":false,\"permalink\":\"https://www.youtube.com/watch?v=abc\",\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"+ "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"accountId\":null,\"url\":\"https://www.youtube.com/watch?v=abc\",\"label\":\"Video\",\"category\":\"Music\",\"contentType\":\"youtube\",\"title\":\"Watch\",\"channelTitle\":\"Ribbon\",\"channelId\":\"UC1\",\"thumbnail\":\"m\",\"publishedAt\":\"2026-08-01T10:00:00Z\",\"viewCount\":1500,\"likeCount\":40,\"commentCount\":3,\"isShort\":false,\"permalink\":\"https://www.youtube.com/watch?v=abc\",\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"},{"call": "POST /tracked-content",@@ -29,12 +29,12 @@{"call": "POST /tracked-content","status": 201,- "body": "{\"id\":\"mtim7pc09\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"Mine\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-07-25T17:20:00.000Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"postId\":\"p1\",\"title\":\"Tracked\",\"subreddit\":\"webdev\",\"subredditPrefixed\":\"r/webdev\",\"author\":\"[deleted]\",\"score\":77,\"upvoteRatio\":0.93,\"numComments\":8,\"permalink\":\"https://reddit.com/r/webdev/comments/p1/tracked/\",\"isNsfw\":false,\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"+ "body": "{\"id\":\"00000000-0000-4000-8000-000000000002\",\"accountId\":\"rd1\",\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"Mine\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-07-25T17:20:00.000Z\",\"postId\":\"p1\",\"title\":\"Tracked\",\"subreddit\":\"webdev\",\"subredditPrefixed\":\"r/webdev\",\"author\":\"[deleted]\",\"score\":77,\"upvoteRatio\":0.93,\"numComments\":8,\"permalink\":\"https://reddit.com/r/webdev/comments/p1/tracked/\",\"isNsfw\":false,\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"},{"call": "POST /tracked-content","status": 201,- "body": "{\"id\":\"mtim7pc0di\",\"accountId\":null,\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-07-25T17:20:00.000Z\",\"updatedAt\":\"2026-09-01T12:00:00.000Z\",\"postId\":\"p1\",\"title\":\"Tracked\",\"subreddit\":\"webdev\",\"subredditPrefixed\":\"r/webdev\",\"author\":\"[deleted]\",\"score\":77,\"upvoteRatio\":0.93,\"numComments\":8,\"permalink\":\"https://reddit.com/r/webdev/comments/p1/tracked/\",\"isNsfw\":false,\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"+ "body": "{\"id\":\"00000000-0000-4000-8000-000000000003\",\"accountId\":null,\"url\":\"https://www.reddit.com/r/webdev/comments/p1/tracked/\",\"label\":\"\",\"category\":\"\",\"contentType\":\"reddit\",\"createdAt\":\"2026-07-25T17:20:00.000Z\",\"postId\":\"p1\",\"title\":\"Tracked\",\"subreddit\":\"webdev\",\"subredditPrefixed\":\"r/webdev\",\"author\":\"[deleted]\",\"score\":77,\"upvoteRatio\":0.93,\"numComments\":8,\"permalink\":\"https://reddit.com/r/webdev/comments/p1/tracked/\",\"isNsfw\":false,\"lastFetchedAt\":\"2026-09-01T12:00:00.000Z\"}"}],"queries": [@@ -42,21 +42,13 @@"type": "insert","table": "tracked_posts","values": {- "id": "mtim7pc04i",+ "id": "00000000-0000-4000-8000-000000000001","user_id": "user-1","account_id": null,"url": "https://www.youtube.com/watch?v=abc","label": "Video","category": "Music",- "content_type": "youtube"- },- "filters": []- },- {- "type": "update",- "table": "tracked_posts",- "values": {- "updated_at": "2026-09-01T12:00:00.000Z",+ "content_type": "youtube","data": {"contentType": "youtube","title": "Watch",@@ -72,16 +64,7 @@"lastFetchedAt": "2026-09-01T12:00:00.000Z"}},- "filters": [- [- "id",- "mtim7pc04i"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -90,7 +73,7 @@"filters": [["id",- "mtim7pc04i"+ "00000000-0000-4000-8000-000000000001"],["user_id",@@ -147,21 +130,13 @@"type": "insert","table": "tracked_posts","values": {- "id": "mtim7pc09",+ "id": "00000000-0000-4000-8000-000000000002","user_id": "user-1","account_id": "rd1","url": "https://www.reddit.com/r/webdev/comments/p1/tracked/","label": "Mine","category": "",- "content_type": "reddit"- },- "filters": []- },- {- "type": "update",- "table": "tracked_posts",- "values": {- "updated_at": "2026-09-01T12:00:00.000Z",+ "content_type": "reddit","data": {"postId": "p1","title": "Tracked",@@ -177,16 +152,7 @@"lastFetchedAt": "2026-09-01T12:00:00.000Z"}},- "filters": [- [- "id",- "mtim7pc09"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -195,7 +161,7 @@"filters": [["id",- "mtim7pc09"+ "00000000-0000-4000-8000-000000000002"],["user_id",@@ -207,21 +173,13 @@"type": "insert","table": "tracked_posts","values": {- "id": "mtim7pc0di",+ "id": "00000000-0000-4000-8000-000000000003","user_id": "user-1","account_id": null,"url": "https://www.reddit.com/r/webdev/comments/p1/tracked/","label": "","category": "",- "content_type": "reddit"- },- "filters": []- },- {- "type": "update",- "table": "tracked_posts",- "values": {- "updated_at": "2026-09-01T12:00:00.000Z",+ "content_type": "reddit","data": {"postId": "p1","title": "Tracked",@@ -237,16 +195,7 @@"lastFetchedAt": "2026-09-01T12:00:00.000Z"}},- "filters": [- [- "id",- "mtim7pc0di"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -255,7 +204,7 @@"filters": [["id",- "mtim7pc0di"+ "00000000-0000-4000-8000-000000000003"],["user_id",diff --git a/backend/tests/fixtures/trackedContentRoutes.refresh.golden.json b/backend/tests/fixtures/trackedContentRoutes.refresh.golden.jsonindex 7c757d6..ac94929 100644--- a/backend/tests/fixtures/trackedContentRoutes.refresh.golden.json+++ b/backend/tests/fixtures/trackedContentRoutes.refresh.golden.json@@ -80,28 +80,14 @@]},{- "type": "select",- "table": "tracked_posts",- "columns": "data",- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "tracked_posts",+ "type": "rpc",+ "table": "merge_tracked_post_data","values": {- "data": {- "title": "Tracked",- "manualViews": 5,+ "p_id": "t-reddit",+ "p_user_id": "user-1",+ "p_patch": {"postId": "p1",+ "title": "Tracked","subreddit": "webdev","subredditPrefixed": "r/webdev","author": "[deleted]",@@ -112,19 +98,9 @@"isNsfw": false,"createdAt": "2026-07-25T17:20:00.000Z","lastFetchedAt": "2026-09-01T12:00:00.000Z"- },- "updated_at": "2026-09-01T12:00:00.000Z"+ }},- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -172,25 +148,12 @@]},{- "type": "select",- "table": "tracked_posts",- "columns": "data",- "filters": [- [- "id",- "t-orphan"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "tracked_posts",+ "type": "rpc",+ "table": "merge_tracked_post_data","values": {- "data": {+ "p_id": "t-orphan",+ "p_user_id": "user-1",+ "p_patch": {"postId": "p1","title": "Tracked","subreddit": "webdev",@@ -203,19 +166,9 @@"isNsfw": false,"createdAt": "2026-07-25T17:20:00.000Z","lastFetchedAt": "2026-09-01T12:00:00.000Z"- },- "updated_at": "2026-09-01T12:00:00.000Z"+ }},- "filters": [- [- "id",- "t-orphan"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -248,27 +201,14 @@]},{- "type": "select",- "table": "tracked_posts",- "columns": "data",- "filters": [- [- "id",- "t-youtube"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "tracked_posts",+ "type": "rpc",+ "table": "merge_tracked_post_data","values": {- "data": {- "title": "Watch",+ "p_id": "t-youtube",+ "p_user_id": "user-1",+ "p_patch": {"contentType": "youtube",+ "title": "Watch","channelTitle": "Ribbon","channelId": "UC1","thumbnail": "m",@@ -279,19 +219,9 @@"isShort": false,"permalink": "https://www.youtube.com/watch?v=abc","lastFetchedAt": "2026-09-01T12:00:00.000Z"- },- "updated_at": "2026-09-01T12:00:00.000Z"+ }},- "filters": [- [- "id",- "t-youtube"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",diff --git a/backend/tests/fixtures/trackedContentRoutes.update.golden.json b/backend/tests/fixtures/trackedContentRoutes.update.golden.jsonindex 6270797..454cec3 100644--- a/backend/tests/fixtures/trackedContentRoutes.update.golden.json+++ b/backend/tests/fixtures/trackedContentRoutes.update.golden.json@@ -128,40 +128,16 @@]},{- "type": "select",- "table": "tracked_posts",- "columns": "data",- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "tracked_posts",+ "type": "rpc",+ "table": "merge_tracked_post_data","values": {- "data": {- "title": "Old",+ "p_id": "t-reddit",+ "p_user_id": "user-1",+ "p_patch": {"manualViews": null- },- "updated_at": "2026-09-01T12:00:00.000Z"+ }},- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -194,40 +170,16 @@]},{- "type": "select",- "table": "tracked_posts",- "columns": "data",- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "tracked_posts",+ "type": "rpc",+ "table": "merge_tracked_post_data","values": {- "data": {- "title": "Old",+ "p_id": "t-reddit",+ "p_user_id": "user-1",+ "p_patch": {"manualViews": 12- },- "updated_at": "2026-09-01T12:00:00.000Z"+ }},- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -290,41 +242,16 @@]},{- "type": "select",- "table": "tracked_posts",- "columns": "data",- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "tracked_posts",+ "type": "rpc",+ "table": "merge_tracked_post_data","values": {- "data": {- "title": "Old",- "manualViews": 12,+ "p_id": "t-reddit",+ "p_user_id": "user-1",+ "p_patch": {"imageUrl": "https://img/a%20b.png"- },- "updated_at": "2026-09-01T12:00:00.000Z"+ }},- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -357,41 +284,16 @@]},{- "type": "select",- "table": "tracked_posts",- "columns": "data",- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "tracked_posts",+ "type": "rpc",+ "table": "merge_tracked_post_data","values": {- "data": {- "title": "Old",- "manualViews": 12,+ "p_id": "t-reddit",+ "p_user_id": "user-1",+ "p_patch": {"imageUrl": null- },- "updated_at": "2026-09-01T12:00:00.000Z"+ }},- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -439,41 +341,16 @@]},{- "type": "select",- "table": "tracked_posts",- "columns": "data",- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]- },- {- "type": "update",- "table": "tracked_posts",+ "type": "rpc",+ "table": "merge_tracked_post_data","values": {- "data": {- "title": "Old",- "manualViews": 7,- "imageUrl": null- },- "updated_at": "2026-09-01T12:00:00.000Z"+ "p_id": "t-reddit",+ "p_user_id": "user-1",+ "p_patch": {+ "manualViews": 7+ }},- "filters": [- [- "id",- "t-reddit"- ],- [- "user_id",- "user-1"- ]- ]+ "filters": []},{"type": "select",@@ -494,7 +371,6 @@"type": "update","table": "tracked_posts","values": {- "updated_at": "2026-09-01T12:00:00.000Z","label": "New","category": "Cat","account_id": null@@ -544,7 +420,6 @@"type": "update","table": "tracked_posts","values": {- "updated_at": "2026-09-01T12:00:00.000Z","label": "Only label"},"filters": [diff --git a/backend/tests/repositories/accountRepository.test.ts b/backend/tests/repositories/accountRepository.test.tsindex c02a225..515a7cb 100644--- a/backend/tests/repositories/accountRepository.test.ts+++ b/backend/tests/repositories/accountRepository.test.ts@@ -14,17 +14,26 @@ describe('account repository', () => {test('user methods only see the user\'s rows; system methods see every row', async () => {const accounts = createAccountRepository(fakeSupabase(ROWS));assert.deepEqual((await accounts.listForUser('user-1')).map(account => account.id), ['a1']);- assert.deepEqual((await accounts.listAll()).map(account => account.id), ['a1', 'a2']);+ assert.deepEqual((await accounts.listByPlatform('reddit')).map(account => account.id), ['a2']);assert.equal(await accounts.findForUser('a2', 'user-1'), null);assert.deepEqual(await accounts.findById('a2'), { id: 'a2', platform: 'reddit', username: 'theirs' });});- test('an update merges into data and keeps the platform', async () => {+ test('an update is one merge in the database that keeps the platform and the fields it does not name', async () => {const db = fakeSupabase(ROWS);const accounts = createAccountRepository(db);- await accounts.updateForUser('a1', { subscriberCount: 5 }, 'user-1');+ await accounts.updateForUser('a1', { subscriberCount: 5, platform: 'reddit', title: undefined }, 'user-1');assert.deepEqual(await accounts.findForUser('a1', 'user-1'), { id: 'a1', platform: 'youtube', title: 'Mine', subscriberCount: 5 });- assert.deepEqual(db.calls.at(-2)?.filters, [['id', 'a1'], ['user_id', 'user-1']]);+ assert.deepEqual(db.calls[0], {+ type: 'rpc', table: 'merge_account_data', filters: [],+ values: { p_id: 'a1', p_user_id: 'user-1', p_patch: { subscriberCount: 5, title: undefined } },+ });+ });++ test('the cron form of an update reaches any user\'s account', async () => {+ const db = fakeSupabase(ROWS);+ await createAccountRepository(db).updateById('a2', { cookie: 'new' });+ assert.equal((await createAccountRepository(db).findById('a2'))?.cookie, 'new');});test('updating an account the user does not own is not found', async () => {diff --git a/scripts/publish-scheduled.ts b/scripts/publish-scheduled.tsindex 5adb711..f2f092e 100644--- a/scripts/publish-scheduled.ts+++ b/scripts/publish-scheduled.ts@@ -82,6 +82,17 @@ async function sbGet<T>(path: string): Promise<T> {return res.json() as Promise<T>;}+async function sbRpc(fn: string, args: Record<string, unknown>): Promise<unknown> {+ const res = await fetch(`${SUPABASE_URL}/rest/v1/rpc/${fn}`, {+ method: 'POST',+ headers: sbHeaders,+ body: JSON.stringify(args),+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ if (!res.ok) throw new Error(`Supabase RPC ${fn}: ${await res.text()}`);+ return res.json();+}+async function sbPatch<T>(path: string, body: unknown): Promise<T[]> {const res = await fetch(`${SUPABASE_URL}/rest/v1${path}`, {method: 'PATCH',@@ -121,22 +132,15 @@ async function getStalePosts(): Promise<ScheduledPost[]> {}async function getAccount(accountId: string): Promise<Account | null> {- const rows = await sbGet<AccountRow[]>(`/accounts?id=eq.${accountId}&select=id,platform,data`);+ const rows = await sbGet<AccountRow[]>(`/accounts?id=eq.${encodeURIComponent(accountId)}&select=id,platform,data`);if (!rows || rows.length === 0) return null;return { id: rows[0].id, platform: rows[0].platform, ...(rows[0].data || {}) };}+// one atomic merge in the database (supabase/migrations), the same function the Worker callsasync function updatePost(id: string, updates: Partial<ScheduledPost>): Promise<void> {- const { status, ...dataUpdates } = updates;- const patch: { status?: PostStatus; data?: Partial<ScheduledPost> } = {};- if (status) patch.status = status;-- if (Object.keys(dataUpdates).length > 0) {- const rows = await sbGet<Pick<ScheduledPostRow, 'data'>[]>(`/scheduled_posts?id=eq.${id}&select=data`);- patch.data = { ...(rows?.[0]?.data || {}), ...dataUpdates };- }-- await sbPatch(`/scheduled_posts?id=eq.${id}&select=id`, patch);+ const { status, ...patch } = updates;+ await sbRpc('merge_scheduled_post', { p_id: id, p_user_id: null, p_patch: patch, p_status: status ?? null });}// matches only the post as it was listed (pending, or the same expired claim) with the same attempts, as the Worker does@@ -146,7 +150,7 @@ async function claimPost(post: ScheduledPost): Promise<ScheduledPost | null> {? `status=eq.publishing&claimed_at=eq.${encodeURIComponent(post.claimedAt ?? '')}`: 'status=eq.pending';const rows = await sbPatch<ScheduledPostRow>(- `/scheduled_posts?id=eq.${post.id}&attempts=eq.${attempts}&${unchanged}&select=${POST_COLUMNS}`,+ `/scheduled_posts?id=eq.${encodeURIComponent(post.id)}&attempts=eq.${attempts}&${unchanged}&select=${POST_COLUMNS}`,{ status: 'publishing', claimed_at: new Date().toISOString(), attempts: attempts + 1 },);return rows[0] ? toPost(rows[0]) : null;