Skip to content

Commit

Permalink
fix: another racecondition
Browse files Browse the repository at this point in the history
also bulk insert auditLogs and auditLogTargets
  • Loading branch information
Flo4604 committed Oct 8, 2024
1 parent a61f1ad commit e4ae521
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions apps/api/src/pkg/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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);
}

0 comments on commit e4ae521

Please sign in to comment.