From e4ae521cba6d10892b5be4613bb6ba2f7ffc3a93 Mon Sep 17 00:00:00 2001 From: Flo <53355483+Flo4604@users.noreply.github.com> Date: Tue, 8 Oct 2024 17:31:51 +0200 Subject: [PATCH] fix: another racecondition also bulk insert auditLogs and auditLogTargets --- apps/api/src/pkg/audit.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/apps/api/src/pkg/audit.ts b/apps/api/src/pkg/audit.ts index ae6329853..512dc541e 100644 --- a/apps/api/src/pkg/audit.ts +++ b/apps/api/src/pkg/audit.ts @@ -41,6 +41,9 @@ export async function insertGenericAuditLogs( const { cache, logger, db } = c.get("services"); + const auditLogsInserts = []; + const auditLogTargetInserts = []; + for (const log of arr) { const cacheKey = [log.workspaceId, log.bucket].join(":"); let { val: bucket, err } = await cache.auditLogBucketByWorkspaceIdAndName.swr( @@ -73,7 +76,9 @@ export async function insertGenericAuditLogs( if (!bucket) { const bucketId = newId("auditLogBucket"); - await (tx ?? db.primary).insert(schema.auditLogBucket).values({ + // do not use the transaction here, otherwise we may run into race conditions + // https://github.com/unkeyed/unkey/pull/2278 + await db.primary.insert(schema.auditLogBucket).values({ id: bucketId, workspaceId: log.workspaceId, name: log.bucket, @@ -84,7 +89,7 @@ export async function insertGenericAuditLogs( } const auditLogId = newId("auditLog"); - await (tx ?? db.primary).insert(schema.auditLog).values({ + auditLogsInserts.push({ id: auditLogId, workspaceId: log.workspaceId, bucketId: bucket.id, @@ -102,8 +107,8 @@ export async function insertGenericAuditLogs( actorMeta: log.actor.meta, }); - await (tx ?? db.primary).insert(schema.auditLogTarget).values( - log.resources.map((r) => ({ + auditLogTargetInserts.push( + ...log.resources.map((r) => ({ workspaceId: log.workspaceId, bucketId: bucket.id, auditLogId, @@ -115,4 +120,8 @@ export async function insertGenericAuditLogs( })), ); } + + await (tx ?? db.primary).insert(schema.auditLog).values(auditLogsInserts); + + await (tx ?? db.primary).insert(schema.auditLogTarget).values(auditLogTargetInserts); }