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.

fix(accounts): answer a racing duplicate add with the usual conflict

spacesdrived5896810c762
diff --git a/backend/lib/errors.ts b/backend/lib/errors.ts
index bc0432e..c51d324 100644
--- a/backend/lib/errors.ts
+++ b/backend/lib/errors.ts
@@ -90,6 +90,11 @@ export class DatabaseError extends AppError {
}
}
+// Postgres error 23505: the write broke a unique index, so the row already exists
+export function isUniqueViolation(err: unknown): boolean {
+ return err instanceof DatabaseError && (err.cause as { code?: string } | undefined)?.code === '23505';
+}
+
export function isAbortError(err: unknown): boolean {
const name = (err as Error | undefined)?.name;
return name === 'AbortError' || name === 'TimeoutError';
diff --git a/backend/services/accountService.ts b/backend/services/accountService.ts
index 638f92d..f70724d 100644
--- a/backend/services/accountService.ts
+++ b/backend/services/accountService.ts
@@ -3,7 +3,7 @@ import { fetchRedditProfile } from './reddit/redditApi.ts';
import { fetchInstagramProfile } from './instagram/instagramApi.ts';
import { exchangeForLongLivedToken, refreshLongLivedToken } from './instagram/instagramTokens.ts';
import { buildYouTubeAccount, buildRedditAccount, buildInstagramAccount } from './accountFactory.ts';
-import { ConflictError, NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';
+import { ConflictError, NotConfiguredError, NotFoundError, ValidationError, isUniqueViolation } from '../lib/errors.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
import type { AuditRepository } from '../repositories/auditRepository.ts';
@@ -93,6 +93,10 @@ function youtubeUpdates(channelData: YouTubeChannelData, full: boolean): Partial
};
}
+const CHANNEL_ADDED = 'This channel is already added';
+const REDDIT_ADDED = 'This Reddit account is already added';
+const INSTAGRAM_ADDED = 'This Instagram account is already added';
+
export function createAccountService({ accounts, cache, audit, config, context }: AccountServiceDeps): AccountService {
const { signal, log } = context;
@@ -101,6 +105,16 @@ export function createAccountService({ accounts, cache, audit, config, context }
return config.youtubeApiKey;
}
+ // the list check misses an add made at the same moment; the unique index catches it, with the same answer
+ async function createUnlessAdded(account: NewAccount, userId: string, alreadyAdded: string): Promise<void> {
+ try {
+ await accounts.create(account, userId);
+ } catch (err) {
+ if (isUniqueViolation(err)) throw new ConflictError(alreadyAdded);
+ throw err;
+ }
+ }
+
async function findOwned(userId: string, accountId: string): Promise<Account> {
const account = await accounts.findForUser(accountId, userId);
if (!account) throw new NotFoundError('Account not found');
@@ -155,10 +169,10 @@ export function createAccountService({ accounts, cache, audit, config, context }
fetchChannelData(channelId, apiKey, signal),
accounts.listForUser(userId),
]);
- if (existing.find(account => account.channelId === channelId)) throw new ConflictError('This channel is already added');
+ if (existing.find(account => account.channelId === channelId)) throw new ConflictError(CHANNEL_ADDED);
const account = buildYouTubeAccount(channelData);
- await accounts.create(account, userId);
+ await createUnlessAdded(account, userId, CHANNEL_ADDED);
return account;
},
@@ -166,11 +180,11 @@ export function createAccountService({ accounts, cache, audit, config, context }
const profile = await fetchRedditProfile(username.replace(/^u\//i, '').trim(), cookie, signal);
const existing = await accounts.listForUser(userId);
if (existing.find(account => account.platform === 'reddit' && account.username === profile.username)) {
- throw new ConflictError('This Reddit account is already added');
+ throw new ConflictError(REDDIT_ADDED);
}
const account = buildRedditAccount(profile, cookie);
- await accounts.create(account, userId);
+ await createUnlessAdded(account, userId, REDDIT_ADDED);
return account;
},
@@ -182,11 +196,11 @@ export function createAccountService({ accounts, cache, audit, config, context }
}
const existing = await accounts.listForUser(userId);
if (existing.find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId)) {
- throw new ConflictError('This Instagram account is already added');
+ throw new ConflictError(INSTAGRAM_ADDED);
}
const account = buildInstagramAccount(profile, token, expiresIn);
- await accounts.create(account, userId);
+ await createUnlessAdded(account, userId, INSTAGRAM_ADDED);
return account;
},
diff --git a/backend/services/instagramConnectService.ts b/backend/services/instagramConnectService.ts
index 9c89ddf..8a9344c 100644
--- a/backend/services/instagramConnectService.ts
+++ b/backend/services/instagramConnectService.ts
@@ -2,12 +2,13 @@ import { buildAuthorizationUrl, exchangeCodeForToken, isOAuthConfigured, upgrade
import { fetchInstagramProfile } from './instagram/instagramApi.ts';
import { buildInstagramAccount, tokenExpiryIso } from './accountFactory.ts';
import { verifyOAuthState } from '../lib/oauthState.ts';
-import { NotConfiguredError, ValidationError } from '../lib/errors.ts';
+import { NotConfiguredError, ValidationError, isUniqueViolation } from '../lib/errors.ts';
import type { ConfiguredInstagramOAuth } from './instagram/instagramOAuth.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { AuditRepository } from '../repositories/auditRepository.ts';
import type { AppConfig } from '../lib/config.ts';
import type { RequestContext } from '../types/context.ts';
+import type { Account } from '../../shared/types/domain.ts';
export interface InstagramConnectDeps {
accounts: AccountRepository;
@@ -52,17 +53,27 @@ export function createInstagramConnectService({ accounts, audit, config, context
const profile = await fetchInstagramProfile(null, token, signal);
if (!profile.igUserId) throw new ValidationError('Could not get Instagram User ID. Account must be a Business or Creator account.');
+ const findConnected = async () => (await accounts.listForUser(userId)).find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId);
// connecting an account again renews its token in place, which keeps its rules and history
- const existing = (await accounts.listForUser(userId)).find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId);
- if (existing) {
+ const renew = async (existing: Account): Promise<InstagramConnectOutcome> => {
const now = new Date().toISOString();
await accounts.updateForUser(existing.id, { accessToken: token, tokenExpiresAt: tokenExpiryIso(expiresIn), lastUpdated: now }, userId);
await audit.recordForUser(userId, { action: 'account.reconnected', subjectType: 'account', subjectId: existing.id, details: { platform: 'instagram' } });
return 'reconnected';
- }
+ };
+
+ const existing = await findConnected();
+ if (existing) return renew(existing);
const account = buildInstagramAccount(profile, token, expiresIn);
- await accounts.create(account, userId);
+ try {
+ await accounts.create(account, userId);
+ } catch (err) {
+ // a second connect at the same moment stored the account first, so this one renews its token instead
+ const stored = isUniqueViolation(err) ? await findConnected() : undefined;
+ if (!stored) throw err;
+ return renew(stored);
+ }
await audit.recordForUser(userId, { action: 'account.connected', subjectType: 'account', subjectId: account.id, details: { platform: 'instagram' } });
return 'connected';
},
diff --git a/backend/tests/services/accountService.test.ts b/backend/tests/services/accountService.test.ts
new file mode 100644
index 0000000..e010b18
--- /dev/null
+++ b/backend/tests/services/accountService.test.ts
@@ -0,0 +1,49 @@
+import { test, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAccountService } from '../../services/accountService.ts';
+import { ConflictError, DatabaseError } from '../../lib/errors.ts';
+import { readConfig } from '../../lib/config.ts';
+import { createLogger } from '../../lib/logger.ts';
+import type { AccountRepository } from '../../repositories/accountRepository.ts';
+import type { AnalyticsCacheRepository } from '../../repositories/analyticsCacheRepository.ts';
+import type { AuditRepository } from '../../repositories/auditRepository.ts';
+import type { Env } from '../../types/env.ts';
+
+// an account list that is still empty and an insert that fails the way Postgres does
+function accountsFailingWith(cause: unknown): AccountRepository {
+ return {
+ listForUser: async () => [],
+ create: async () => { throw new DatabaseError('accounts.create', cause); },
+ } as unknown as AccountRepository;
+}
+
+function service(accounts: AccountRepository) {
+ return createAccountService({
+ accounts,
+ cache: {} as AnalyticsCacheRepository,
+ audit: {} as AuditRepository,
+ config: readConfig({} as Env),
+ context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },
+ });
+}
+
+function redditAnswers(t: { after(fn: () => void): void }) {
+ const fetch = mock.method(globalThis, 'fetch', async () => Response.json({ data: { name: 'ribbon_r', total_karma: 3 } }));
+ t.after(() => fetch.mock.restore());
+}
+
+test('an add that loses a race to the same account gets the usual already added answer, not a database error', async t => {
+ redditAnswers(t);
+ const accounts = accountsFailingWith({ code: '23505', message: 'duplicate key value violates unique constraint "accounts_identity_key"' });
+ await assert.rejects(service(accounts).addReddit('user-1', { username: 'ribbon_r', cookie: '' }), (err: Error) => {
+ assert.ok(err instanceof ConflictError);
+ assert.equal(err.message, 'This Reddit account is already added');
+ return true;
+ });
+});
+
+test('any other failed insert stays a database error', async t => {
+ redditAnswers(t);
+ const accounts = accountsFailingWith({ code: '08006', message: 'connection failure' });
+ await assert.rejects(service(accounts).addReddit('user-1', { username: 'ribbon_r', cookie: '' }), DatabaseError);
+});
diff --git a/backend/tests/services/instagramConnectService.test.ts b/backend/tests/services/instagramConnectService.test.ts
new file mode 100644
index 0000000..03cfa3b
--- /dev/null
+++ b/backend/tests/services/instagramConnectService.test.ts
@@ -0,0 +1,46 @@
+import { test, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { createInstagramConnectService } from '../../services/instagramConnectService.ts';
+import { DatabaseError } from '../../lib/errors.ts';
+import { readConfig } from '../../lib/config.ts';
+import { createLogger } from '../../lib/logger.ts';
+import type { AccountRepository } from '../../repositories/accountRepository.ts';
+import type { AuditEvent, AuditRepository } from '../../repositories/auditRepository.ts';
+import type { Account } from '../../../shared/types/domain.ts';
+import type { Env } from '../../types/env.ts';
+
+const ENV = { INSTAGRAM_APP_ID: 'APPID', INSTAGRAM_APP_SECRET: 'APPSECRET' } as Env;
+
+test('a connect that loses a race to a second connect of the same account renews the stored token instead of failing', async t => {
+ // the code exchange, the long-lived upgrade and the profile, by url
+ const fetch = mock.method(globalThis, 'fetch', async (input: string | URL) => {
+ const url = String(input);
+ if (url.includes('oauth/access_token')) return Response.json({ access_token: 'SHORT' });
+ if (url.includes('/access_token')) return Response.json({ access_token: 'LONG', expires_in: 5184000 });
+ return Response.json({ user_id: '1789', username: 'ribbon' });
+ });
+ t.after(() => fetch.mock.restore());
+
+ // the first lookup sees nothing; by the time the insert fails the other connect has stored the account
+ const stored: Account = { id: 'ig-1', platform: 'instagram', igUserId: '1789' } as Account;
+ let lookups = 0;
+ const updates: Array<[string, Partial<Account>]> = [];
+ const accounts = {
+ listForUser: async () => (lookups++ === 0 ? [] : [stored]),
+ create: async () => { throw new DatabaseError('accounts.create', { code: '23505' }); },
+ updateForUser: async (id: string, values: Partial<Account>) => { updates.push([id, values]); },
+ } as unknown as AccountRepository;
+ const events: AuditEvent[] = [];
+ const audit = { recordForUser: async (_userId: string, event: AuditEvent) => { events.push(event); } } as unknown as AuditRepository;
+
+ const connect = createInstagramConnectService({
+ accounts,
+ audit,
+ config: readConfig(ENV),
+ context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },
+ });
+
+ assert.equal(await connect.connect('user-1', 'CODE'), 'reconnected');
+ assert.deepEqual(updates.map(([id, values]) => [id, values.accessToken]), [['ig-1', 'LONG']]);
+ assert.deepEqual(events.map(event => event.action), ['account.reconnected']);
+});