refactor: share tbank-sync claim and generation lock (WealthLedger/backend#166) (#188)
Backend verify / commits (push) Skipped
Backend verify / security (push) Successful in 1m9s
Backend verify / verify (push) Failing after 7m40s

This commit was merged in pull request #188.
This commit is contained in:
2026-11-04 20:47:50 +03:00
parent c5ccfeadea
commit 5d31b3e6dd
8 changed files with 167 additions and 206 deletions
@@ -6,6 +6,7 @@ import type { TbankSyncAttempt } from '../../../integrations/tbank/tbank.api';
import type { InvestmentAttemptDto } from '../investment-resource.dto';
import type { InvestmentScreenDto } from './tbank-sync.dto';
import { claimSyncWork, lockConnectionGeneration } from '../../../integrations/tbank/tbank-sync-claim';
import { PrismaService } from '../../../prisma/prisma.service';
export type ScreenIntent = { now: string; scope: InvestmentScreenDto };
@@ -88,11 +89,8 @@ export class TbankSyncRepository {
runId: string,
) {
return this.prisma.$transaction(async (tx) => {
const valid = await tx.tbankConnection.updateMany({
where: { userId, revision, invalidToken: false },
data: { membershipRevision: { increment: 0 } },
});
if (!valid.count) return null;
const valid = await lockConnectionGeneration(tx, { userId, revision });
if (!valid) return null;
const scopeKey = `screen:${JSON.stringify(scope)}`;
const key = { userId, revision, scopeKey };
const previous = await tx.tbankSyncWork.findUnique({
@@ -176,17 +174,11 @@ export class TbankSyncRepository {
...Object.fromEntries(rows.map((row) => [row.id, row.attemptId])),
...old.attempts,
};
return tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: false },
},
data: {
progress: { children: [...new Set(children)], attempts, dispatched },
...(errorCode ? { state: 'failed', errorCode } : {}),
},
const claimed = await claimSyncWork(tx, attempt, {
progress: { children: [...new Set(children)], attempts, dispatched },
...(errorCode ? { state: 'failed', errorCode } : {}),
});
return { count: claimed };
});
}
@@ -364,20 +356,17 @@ export class TbankSyncRepository {
where: { userId: attempt.userId, id: child.id },
select: { attemptId: true },
});
const updated = await tx.tbankSyncWork.updateMany({
where: { ...attempt, state: 'running' },
data: {
progress: {
attempts: {
...progress.attempts,
...(row ? { [child.id]: row.attemptId } : {}),
},
children: [...(progress.children ?? []), child],
sections: progress.sections ?? [],
const updated = await claimSyncWork(tx, attempt, {
progress: {
attempts: {
...progress.attempts,
...(row ? { [child.id]: row.attemptId } : {}),
},
children: [...(progress.children ?? []), child],
sections: progress.sections ?? [],
},
});
return Boolean(updated.count);
}, { withoutConnectionFence: true });
return Boolean(updated);
});
}