Skip to content

Commit

Permalink
fix: latest: true version disappear on parallel writes
Browse files Browse the repository at this point in the history
  • Loading branch information
r1tsuu authored and DanRibbens committed Nov 4, 2024
1 parent e390835 commit 7f5689c
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/db-mongodb/src/createVersion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ export const createVersion: CreateVersion = async function createVersion(
$eq: true,
},
},
{
createdAt: {
$lt: new Date(doc.createdAt),
},
},
],
},
{ $unset: { latest: 1 } },
Expand Down
1 change: 1 addition & 0 deletions packages/drizzle/src/createVersion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export async function createVersion<T extends TypeWithID>(
SET latest = false
WHERE ${table.id} != ${result.id}
AND ${table.parent} = ${parent}
AND ${table.createdAt} < ${result.createdAt}
`,
})
}
Expand Down
55 changes: 55 additions & 0 deletions test/versions/int.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,61 @@ describe('Versions', () => {
expect(docs.totalDocs).toStrictEqual(2)
})
})

describe('Race conditions', () => {
it('should keep latest true with parallel writes', async () => {
const doc = await payload.create({
collection: 'draft-posts',
data: {
description: 'A',
title: 'A',
},
})

for (let i = 0; i < 200; i++) {
const writeAmount = 2

const promises = Array.from({ length: writeAmount }, async (_, i) => {
return new Promise((resolve) => {
// Add latency so updates aren't immediate after each other but still in parallel
setTimeout(() => {
payload
.update({
id: doc.id,
collection: 'draft-posts',
data: {},
draft: true,
})
.then(resolve)
.catch(resolve)
}, i * 10)
})
})

await Promise.all(promises)

const { docs } = await payload.findVersions({
collection: 'draft-posts',
where: {
and: [
{
parent: {
equals: doc.id,
},
},
{
latest: {
equals: true,
},
},
],
},
})

expect(docs[0]).toBeDefined()
}
})
})
})

describe('Querying', () => {
Expand Down

0 comments on commit 7f5689c

Please sign in to comment.