Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions lib/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export const uploadSchema = z.object({
startedPartUploadCount: z.number(),
finishedPartUploadCount: z.number(),
folderName: z.string(),
reservationHash: z.string().nullable(),
})
type Upload = z.infer<typeof uploadSchema>

Expand All @@ -90,9 +91,16 @@ const RETRYABLE_LOCK_ERRORS = new Set([
'40P01',
])

function isRetryableLockError(err: unknown) {
// sqlite, postgres `unique_violation` and mysql
const UNIQUE_VIOLATION_ERRORS = new Set(['SQLITE_CONSTRAINT_UNIQUE', '23505', 'ER_DUP_ENTRY'])

function hasErrorCode(err: unknown, codes: Set<string>) {
const code = (err as { code?: unknown } | null)?.code
return typeof code === 'string' && RETRYABLE_LOCK_ERRORS.has(code)
return typeof code === 'string' && codes.has(code)
}

export function isUniqueViolation(err: unknown) {
return hasErrorCode(err, UNIQUE_VIOLATION_ERRORS)
}

/**
Expand All @@ -106,7 +114,7 @@ export async function retryOnLockConflict<T>(run: () => Promise<T>, attempts = 3
try {
return await run()
} catch (err) {
if (attempt >= attempts || !isRetryableLockError(err)) throw err
if (attempt >= attempts || !hasErrorCode(err, RETRYABLE_LOCK_ERRORS)) throw err
dbLogger.warn(`Retrying transaction after lock conflict (attempt ${attempt})`, { error: err })
}
}
Expand Down
15 changes: 15 additions & 0 deletions lib/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
import { createHash } from 'node:crypto'
import { customAlphabet } from 'nanoid'

const generate = customAlphabet('0123456789', 10)

export function generateNumberId() {
return Number.parseInt(generate())
}

/** The key, version, scope and repo that at most one Upload may hold at a time. */
export interface Reservation {
key: string
version: string
scope: string
repoId: string
}

export function reservationHash({ key, version, scope, repoId }: Reservation) {
return createHash('sha256')
.update(JSON.stringify([key, version, scope, repoId]))
.digest('hex')
}
41 changes: 41 additions & 0 deletions lib/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Hookable } from 'hookable'
import type { Kysely } from 'kysely'
import type { Migration } from 'kysely/migration'
import type { Env } from './schemas'
import { reservationHash } from './helpers'
import { Storage } from './storage'

export function migrations(
Expand Down Expand Up @@ -220,5 +221,45 @@ export function migrations(
await dropIndex(db, 'idx_cache_entries_locationId', 'cache_entries')
},
},
$7_uploads_reservationHash: {
async up(db) {
// A unique index over (key, version, scope, repoId) exceeds MySQL's
// 3072-byte key limit, so it covers a fixed-width hash of the tuple.
// Nullable so replicas still on the previous version can insert during a rollout.
await db.schema.alterTable('uploads').addColumn('reservationHash', 'char(64)').execute()

const uploads = await db
.selectFrom('uploads')
.select(['id', 'key', 'version', 'scope', 'repoId'])
.orderBy('createdAt', 'desc')
.execute()
const seen = new Set<string>()
for (const { id, ...reservation } of uploads) {
const hash = reservationHash(reservation)
// keep the newest upload per reservation, cleanup:orphaned-storage reclaims the rest's parts
if (seen.has(hash)) {
await db.deleteFrom('uploads').where('id', '=', id).execute()
continue
}
seen.add(hash)
await db
.updateTable('uploads')
.set({ reservationHash: hash })
.where('id', '=', id)
.execute()
}

await db.schema
.createIndex('idx_uploads_reservationHash')
.unique()
.on('uploads')
.column('reservationHash')
.execute()
},
async down(db) {
await dropIndex(db, 'idx_uploads_reservationHash', 'uploads')
await db.schema.alterTable('uploads').dropColumn('reservationHash').execute()
},
},
} satisfies Record<string, Migration>
}
79 changes: 26 additions & 53 deletions lib/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import type { ContainerClient } from '@azure/storage-blob'
import type { Kysely } from 'kysely'
import type { Database, StorageLocation } from './db'
import type { Reservation } from './helpers'
import type { Env } from './schemas'
import { randomUUID } from 'node:crypto'
import { once } from 'node:events'
Expand Down Expand Up @@ -38,9 +39,9 @@ import { NodeHttpHandler } from '@smithy/node-http-handler'
import { sql } from 'kysely'
import { chunk } from 'remeda'
import { match } from 'ts-pattern'
import { getDatabase, retryOnLockConflict } from './db'
import { getDatabase, isUniqueViolation, retryOnLockConflict } from './db'
import { env } from './env'
import { generateNumberId } from './helpers'
import { generateNumberId, reservationHash } from './helpers'
import { logger } from './logger'
import {
acquireMergeLease,
Expand Down Expand Up @@ -404,23 +405,12 @@ export class Storage {
.execute()
}

async completeUpload({
key,
version,
scope,
repoId,
}: {
key: string
version: string
scope: string
repoId: string
}) {
async completeUpload(reservation: Reservation) {
const { key, version, scope, repoId } = reservation
// the hash matches exactly, a `key` comparison would be case-insensitive on MySQL
const upload = await this.db
.selectFrom('uploads')
.where('key', '=', key)
.where('version', '=', version)
.where('scope', '=', scope)
.where('repoId', '=', repoId)
.where('reservationHash', '=', reservationHash(reservation))
.selectAll()
.executeTakeFirst()
if (!upload) return
Expand Down Expand Up @@ -640,43 +630,26 @@ export class Storage {
}
}

async createUpload({
key,
version,
scope,
repoId,
}: {
key: string
version: string
scope: string
repoId: string
}) {
const existingUpload = await this.db
.selectFrom('uploads')
.where('key', '=', key)
.where('version', '=', version)
.where('scope', '=', scope)
.where('repoId', '=', repoId)
.select('id')
.executeTakeFirst()
if (existingUpload) throw new AlreadyExistsError(key)

async createUpload(reservation: Reservation) {
const uploadId = generateNumberId()
await this.db
.insertInto('uploads')
.values({
id: uploadId,
folderName: uploadId.toString(),
createdAt: Date.now(),
key,
version,
scope,
repoId,
lastPartUploadedAt: null,
finishedPartUploadCount: 0,
startedPartUploadCount: 0,
})
.execute()
try {
await this.db
.insertInto('uploads')
.values({
...reservation,
id: uploadId,
folderName: uploadId.toString(),
createdAt: Date.now(),
reservationHash: reservationHash(reservation),
lastPartUploadedAt: null,
finishedPartUploadCount: 0,
startedPartUploadCount: 0,
})
.execute()
} catch (err) {
if (isUniqueViolation(err)) throw new AlreadyExistsError(reservation.key)
throw err
}

return { id: uploadId }
}
Expand Down
39 changes: 39 additions & 0 deletions tests/create-upload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { randomUUID } from 'node:crypto'
import { Readable } from 'node:stream'

import { expect, test } from 'vitest'
import { getDatabase } from '~/lib/db'
import { AlreadyExistsError, getStorage } from '~/lib/storage'

test('concurrent duplicate reservations create exactly one upload', async () => {
const storage = await getStorage()
const reservation = { key: randomUUID(), version: 'v1', scope: 'refs/heads/main', repoId: '123' }

const results = await Promise.allSettled(
Array.from({ length: 10 }, () => storage.createUpload(reservation)),
)

expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1)
expect(results.flatMap((r) => (r.status === 'rejected' ? [r.reason] : []))).toEqual(
Array.from({ length: 9 }, () => expect.any(AlreadyExistsError)),
)
})

test('completing an upload leaves a reservation differing only in key case alone', async () => {
const storage = await getStorage()
const db = await getDatabase()
const base = { version: 'v1', scope: 'refs/heads/main', repoId: '123' }
const key = `Key-${randomUUID()}`

const upper = await storage.createUpload({ ...base, key })
const lower = await storage.createUpload({ ...base, key: key.toLowerCase() })
await storage.uploadPart(lower.id, 0, Readable.from('payload'))
await storage.completeUpload({ ...base, key: key.toLowerCase() })

const remaining = await db
.selectFrom('uploads')
.where('id', 'in', [upper.id, lower.id])
.select('id')
.execute()
expect(remaining).toEqual([{ id: upper.id }])
})
1 change: 1 addition & 0 deletions tests/storage-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ describe('storage lifecycle reconciliation', () => {
createdAt: Date.now(),
lastPartUploadedAt: null,
folderName: authorizedFolder,
reservationHash: randomUUID(),
startedPartUploadCount: 0,
finishedPartUploadCount: 0,
})
Expand Down
Loading