Skip to content
Closed
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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ volumes:
cache-data:
```

## Resource limits

All optional.

| Variable | Default | Effect |
| ----------------------- | ------- | -------------------------------------------------------------------------------------------------- |
| `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once. Beyond it, restores stream the parts and a later download merges. |

## Documentation

👉 <https://gha-cache-server.falcondev.io/getting-started> 👈
1 change: 1 addition & 0 deletions lib/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export const envBaseSchema = type({
'DEBUG?': 'unknown',
'ENABLE_DIRECT_DOWNLOADS': 'boolean = false',
'EAGER_MERGE': 'boolean = false',
'MAX_CONCURRENT_MERGES': 'number.integer >= 1 = 16',
'BENCHMARK': 'boolean = false',
'SKIP_TOKEN_VALIDATION': 'boolean = false',
'MANAGEMENT_API_KEY?': 'string',
Expand Down
40 changes: 29 additions & 11 deletions lib/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export class Storage {

private db
private mergeStreamPromises = new Set<Promise<void>>()
private activeMerges = 0
adapter

private constructor({ db, adapter }: { adapter: StorageAdapter; db: Kysely<Database> }) {
Expand Down Expand Up @@ -281,19 +282,35 @@ export class Storage {
/**
* Runs a Merge under a Merge Lease. `write` produces `${folderName}/merged`;
* a lease-fenced transaction then marks the Merge complete. Returns false
* when another worker holds the lease. Writing straight to the final object
* is safe (ADR-0004). The returned promise never rejects: failures are logged
* and the merge state rolled back.
* when another worker holds the lease or this process already runs
* MAX_CONCURRENT_MERGES Merges; a skipped Merge is retried by a later
* download. Writing straight to the final object is safe (ADR-0004). The
* returned promise never rejects: failures are logged and the merge state
* rolled back.
*/
private async startMerge(location: StorageLocation, write: () => Promise<void>) {
const mergeToken = await acquireMergeLease(this.db, location.id)
if (!mergeToken) return false

await this.db
.updateTable('storage_locations')
.set({ mergeStartedAt: Date.now() })
.where('id', '=', location.id)
.execute()
// Each Merge holds storage connections and buffers for its whole duration;
// unbounded, a burst of first restores or finalizes exhausts them.
if (this.activeMerges >= env.MAX_CONCURRENT_MERGES) return false
// Reserve the slot before the first await so concurrent callers cannot overshoot it.
this.activeMerges++
let mergeToken: string | undefined
try {
mergeToken = await acquireMergeLease(this.db, location.id)
if (mergeToken)
await this.db
.updateTable('storage_locations')
.set({ mergeStartedAt: Date.now() })
.where('id', '=', location.id)
.execute()
} catch (err) {
this.activeMerges--
throw err
}
if (!mergeToken) {
this.activeMerges--
return false
}

const renewalTimer = setInterval(() => {
void renewMergeLease(this.db, location.id, mergeToken)
Expand Down Expand Up @@ -341,6 +358,7 @@ export class Storage {
})
.finally(async () => {
clearInterval(renewalTimer)
this.activeMerges--
await releaseMergeLease(this.db, location.id, mergeToken)
})
this.mergeStreamPromises.add(mergePromise)
Expand Down
111 changes: 111 additions & 0 deletions tests/merge-concurrency.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { createHash, randomUUID } from 'node:crypto'
import { Readable } from 'node:stream'

import { afterEach, describe, expect, test } from 'vitest'
import { getDatabase } from '~/lib/db'
import { env } from '~/lib/env'
import { Storage } from '~/lib/storage'

const scope = { version: 'v1', scope: 'refs/heads/main', repoId: '123' }
const parts = [Buffer.alloc(256 * 1024, 'a'), Buffer.alloc(256 * 1024, 'b')]
const expected = createHash('sha256').update(Buffer.concat(parts)).digest('hex')

async function uploadEntry(storage: Storage) {
const key = `merge-cap-${randomUUID()}`
const upload = await storage.createUpload({ key, ...scope })
for (const [index, part] of parts.entries())
await storage.uploadPart(upload.id, index, Readable.from(part))
await storage.completeUpload({ key, ...scope })
const db = await getDatabase()
return db
.selectFrom('cache_entries')
.innerJoin('storage_locations', 'storage_locations.id', 'cache_entries.locationId')
.where('cache_entries.key', '=', key)
.select(['storage_locations.id as locationId', 'folderName'])
.executeTakeFirstOrThrow()
}

async function download(storage: Storage, locationId: string) {
const result = await storage.download(locationId)
if (!result) throw new Error(`location ${locationId} not found`)
return result.stream
}

async function sha256(stream: Readable) {
const hash = createHash('sha256')
for await (const chunk of stream) hash.update(chunk)
return hash.digest('hex')
}

async function mergeState(locationId: string) {
const db = await getDatabase()
return db
.selectFrom('storage_locations')
.where('id', '=', locationId)
.select(['mergedAt', 'mergeStartedAt'])
.executeTakeFirstOrThrow()
}

describe('merge concurrency limit', () => {
const originalMaxMerges = env.MAX_CONCURRENT_MERGES
const originalEagerMerge = env.EAGER_MERGE
afterEach(() => {
env.MAX_CONCURRENT_MERGES = originalMaxMerges
env.EAGER_MERGE = originalEagerMerge
})

test('a first restore beyond the limit is served from parts without merging', async () => {
env.EAGER_MERGE = false
env.MAX_CONCURRENT_MERGES = 1
const storage = await Storage.fromEnv()
const first = await uploadEntry(storage)
const second = await uploadEntry(storage)

try {
// The first restore's Merge is paced by its unread stream, so it still
// holds the only slot when the second restore starts.
const firstStream = await download(storage, first.locationId)
const secondStream = await download(storage, second.locationId)
expect(await sha256(secondStream)).toBe(expected)
expect(await sha256(firstStream)).toBe(expected)
await storage.waitForOngoingMerges()

expect(await mergeState(first.locationId)).not.toMatchObject({ mergedAt: null })
expect(await mergeState(second.locationId)).toMatchObject({ mergedAt: null })

// With the slot free again, the next restore merges the skipped entry.
expect(await sha256(await download(storage, second.locationId))).toBe(expected)
await storage.waitForOngoingMerges()
expect(await mergeState(second.locationId)).not.toMatchObject({ mergedAt: null })
} finally {
await storage.adapter.deleteFolder(first.folderName)
await storage.adapter.deleteFolder(second.folderName)
}
})

test('an eager merge beyond the limit leaves the entry to a later download', async () => {
env.EAGER_MERGE = false
env.MAX_CONCURRENT_MERGES = 1
const storage = await Storage.fromEnv()
const busy = await uploadEntry(storage)
// An unread first restore keeps its Merge, and the only slot, busy.
const busyStream = await download(storage, busy.locationId)

env.EAGER_MERGE = true
const eager = await uploadEntry(storage)
try {
// Upload completion awaits the Merge Lease, so a started Merge would have
// stamped mergeStartedAt by now.
expect(await mergeState(eager.locationId)).toEqual({ mergedAt: null, mergeStartedAt: null })

expect(await sha256(busyStream)).toBe(expected)
await storage.waitForOngoingMerges()
expect(await sha256(await download(storage, eager.locationId))).toBe(expected)
await storage.waitForOngoingMerges()
expect(await mergeState(eager.locationId)).not.toMatchObject({ mergedAt: null })
} finally {
await storage.adapter.deleteFolder(busy.folderName)
await storage.adapter.deleteFolder(eager.folderName)
}
})
})
1 change: 1 addition & 0 deletions tests/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const TESTING_ENV_BASE = {
| 'ORPHANED_STORAGE_GRACE_PERIOD_HOURS'
| 'ENABLE_DIRECT_DOWNLOADS'
| 'EAGER_MERGE'
| 'MAX_CONCURRENT_MERGES'
| 'BENCHMARK'
| 'SKIP_TOKEN_VALIDATION'
| 'ACTIONS_TOKEN_ISSUER'
Expand Down
Loading