From 04018015c57939b0874940867a60fb8c2677454e Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 24 May 2024 20:11:22 -0500 Subject: [PATCH] stats: fix race conditions (on Postgres) --- src/utils/stats.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/utils/stats.ts b/src/utils/stats.ts index 61d5e9a..0b0eb7e 100644 --- a/src/utils/stats.ts +++ b/src/utils/stats.ts @@ -6,6 +6,7 @@ import { SetRequired } from 'type-fest'; import { DittoTables } from '@/db/DittoTables.ts'; import { getTagSet } from '@/utils/tags.ts'; +import { Conf } from '@/config.ts'; interface UpdateStatsOpts { kysely: Kysely; @@ -153,8 +154,16 @@ export async function updateAuthorStats( notes_count: 0, }; - const prev = await getAuthorStats(kysely, pubkey); + let query = kysely + .selectFrom('author_stats') + .selectAll() + .where('pubkey', '=', pubkey); + if (Conf.db.dialect === 'postgres') { + query = query.forUpdate(); + } + + const prev = await query.executeTakeFirst(); const stats = fn(prev ?? empty); if (prev) { @@ -195,8 +204,16 @@ export async function updateEventStats( reactions: '{}', }; - const prev = await getEventStats(kysely, eventId); + let query = kysely + .selectFrom('event_stats') + .selectAll() + .where('event_id', '=', eventId); + if (Conf.db.dialect === 'postgres') { + query = query.forUpdate(); + } + + const prev = await query.executeTakeFirst(); const stats = fn(prev ?? empty); if (prev) {