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
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,13 @@ volumes:

All optional.

| Variable | Default | Effect |
| ------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `STORAGE_S3_MAX_SOCKETS` | `50` | Sockets per S3 data pool, for `http://` and `https://` endpoints alike. Reads (GetObject) and writes (uploads, Merges) each get a pool this size. |
| `STORAGE_S3_CONTROL_MAX_SOCKETS` | `16` | Sockets for HEAD, LIST and DELETE requests (cache lookups, cleanup), kept apart from bulk transfers. |
| `STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS` | `5000` | How long each attempt of a control request waits for a socket and connection; `0` waits forever. |
| Variable | Default | Effect |
| ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `STORAGE_S3_MAX_SOCKETS` | `50` | Sockets per S3 data pool, for `http://` and `https://` endpoints alike. Reads (GetObject) and writes (uploads, Merges) each get a pool this size. |
| `STORAGE_S3_CONTROL_MAX_SOCKETS` | `16` | Sockets for HEAD, LIST and DELETE requests (cache lookups, cleanup), kept apart from bulk transfers. |
| `STORAGE_S3_CONTROL_QUEUE_TIMEOUT_MS` | `5000` | How long each attempt of a control request waits for a socket and connection; `0` waits forever. |
| `MAX_CONCURRENT_MERGES` | `16` | Merges one process runs at once, eager or lazy. Beyond it, restores stream the parts and a later download merges. |
| `DOWNLOAD_IDLE_TIMEOUT_MS` | `300000` | Closes a download whose storage read has not moved for this long (client stopped reading); `0` disables. |

## Documentation

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Direct downloads need a merged object, and the Merge runs lazily on first download, so the first Cache Hit of every entry is proxied through the server even with `ENABLE_DIRECT_DOWNLOADS`. `EAGER_MERGE=true` runs the Merge right after upload completion instead. It stays off by default because lazy merging never pays merge traffic for entries that are never downloaded.

Both paths share one merge runner. Merge Lease, renewal, lease-fenced completion, and rollback are identical, so eager and lazy merges race safely against each other and against `cleanup:merges`. Upload completion picks the strategy up front from the Part sizes it already lists to record `sizeBytes`. When the adapter offers `composeParts` and every Part satisfies its limits, the Merge is a Server-side Merge with no bytes passing through the server. On S3 that is `CreateMultipartUpload`, one `UploadPartCopy` per Part, `CompleteMultipartUpload`; the limits are every Part but the last at least 5 MiB, none above 5 GiB, at most 10,000 Parts. On GCS it is `compose`, folding 32 sources at a time into a top-level temp object and composing `merged` in one final call; there is no minimum Part size. Otherwise the existing streaming merge runs immediately. Buildx uploads 1 MiB blocks, so its entries always take the streaming path. A backend that rejects the copy call fails the Merge like any other merge failure; the entry then merges lazily on first download.
Both paths share one merge runner. Merge Lease, renewal, lease-fenced completion, and rollback are identical, so eager and lazy merges race safely against each other and against `cleanup:merges`. Upload completion picks the strategy up front from the Part sizes it already lists to record `sizeBytes`. When the adapter offers `composeParts` and every Part satisfies its limits, the Merge is a Server-side Merge with no bytes passing through the server. On S3 that is `CreateMultipartUpload`, one `UploadPartCopy` per Part, `CompleteMultipartUpload`; the limits are every Part but the last at least 5 MiB, none above 5 GiB, at most 10,000 Parts. On GCS it is `compose`, folding 32 sources at a time into a top-level temp object and composing `merged` in one final call; there is no minimum Part size. Otherwise the existing streaming merge runs immediately. Buildx uploads 1 MiB blocks, so its entries always take the streaming path. A backend that rejects the copy call fails the Merge like any other merge failure; the entry then merges lazily on first download. Eager and lazy Merges share the per-process `MAX_CONCURRENT_MERGES` cap; an Eager Merge past it is skipped the same way, and the entry merges lazily on first download.

This does not reopen ADR-0004. The 5 GiB cap it cites applies to `CopyObject` used as a promote step. `UploadPartCopy` writes `merged` directly under the same lease fence, and Parts are immutable, so a merger that lost its lease can only write identical bytes.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ Generate environment variables from config values.
value: {{ .Values.config.enableDirectDownloads | quote }}
- name: EAGER_MERGE
value: {{ .Values.config.eagerMerge | quote }}
- name: MAX_CONCURRENT_MERGES
value: {{ .Values.config.maxConcurrentMerges | quote }}
- name: DOWNLOAD_IDLE_TIMEOUT_MS
value: {{ .Values.config.downloadIdleTimeoutMs | quote }}
- name: CACHE_CLEANUP_OLDER_THAN_DAYS
value: {{ .Values.config.cacheCleanupOlderThanDays | quote }}
{{- if .Values.config.cacheMaxSizeBytes }}
Expand Down
6 changes: 6 additions & 0 deletions install/kubernetes/github-actions-cache-server/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ config:
# bucket. Doubles storage per entry until the parts cleanup job runs.
eagerMerge: false

# -- Merges one process runs at once, eager or lazy. Beyond it, restores stream the parts and a later download merges.
maxConcurrentMerges: 16

# -- Closes a download whose storage read has not moved for this long (client stopped reading). Set to 0 to disable.
downloadIdleTimeoutMs: 300000

# -- Number of days to keep stale cache data before deleting it. Set to 0 to disable.
cacheCleanupOlderThanDays: 90

Expand Down
2 changes: 2 additions & 0 deletions lib/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ export const envBaseSchema = type({
'DEBUG?': 'unknown',
'ENABLE_DIRECT_DOWNLOADS': 'boolean = false',
'EAGER_MERGE': 'boolean = false',
'MAX_CONCURRENT_MERGES': 'number.integer >= 1 = 16',
'DOWNLOAD_IDLE_TIMEOUT_MS': '0 <= number.integer <= 2147483647 = 300000',
'BENCHMARK': 'boolean = false',
'SKIP_TOKEN_VALIDATION': 'boolean = false',
'MANAGEMENT_API_KEY?': 'string',
Expand Down
36 changes: 26 additions & 10 deletions lib/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,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 @@ -297,20 +298,34 @@ 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)
// 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 {
const token = await acquireMergeLease(this.db, location.id)
if (token) {
await this.db
.updateTable('storage_locations')
.set({ mergeStartedAt: Date.now() })
.where('id', '=', location.id)
.execute()
mergeToken = token
}
} finally {
if (!mergeToken) this.activeMerges--
}
if (!mergeToken) return false

await this.db
.updateTable('storage_locations')
.set({ mergeStartedAt: Date.now() })
.where('id', '=', location.id)
.execute()

const renewalTimer = setInterval(() => {
void renewMergeLease(this.db, location.id, mergeToken)
}, LEASE_RENEWAL_MS)
Expand Down Expand Up @@ -357,6 +372,7 @@ export class Storage {
})
.finally(async () => {
clearInterval(renewalTimer)
this.activeMerges--
await releaseMergeLease(this.db, location.id, mergeToken)
})
this.mergeStreamPromises.add(mergePromise)
Expand Down
24 changes: 24 additions & 0 deletions routes/download/[locationId].ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { RangeRequest } from '~/lib/storage'
import { pipeline } from 'node:stream/promises'
import { z } from 'zod'
import { env } from '~/lib/env'
import { logger } from '~/lib/logger'
import { getStorage, RangeNotSatisfiableError } from '~/lib/storage'

Expand All @@ -23,6 +24,12 @@ function parseRange(header: string | undefined): RangeRequest | undefined {
return { start, end }
}

class DownloadIdleTimeoutError extends Error {
constructor() {
super(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`)
}
}

export default defineEventHandler(async (event) => {
const parsedPathParams = pathParamsSchema.safeParse(event.context.params)
if (!parsedPathParams.success)
Expand Down Expand Up @@ -78,6 +85,17 @@ export default defineEventHandler(async (event) => {
// and destroys the source, which releases its reader lease. `_handled` is an h3 v1 internal.
event._handled = true
const { res } = event.node
// The HTTP server has no idle timeout, so a client that stops reading but keeps
// the connection open would hold the backend read, its reader lease and, on a
// first restore, the Merge it paces forever. Bytes moving at any rate keep the
// download alive.
const idleTimer =
env.DOWNLOAD_IDLE_TIMEOUT_MS > 0
? setTimeout(() => {
download.stream.destroy(new DownloadIdleTimeoutError())
}, env.DOWNLOAD_IDLE_TIMEOUT_MS)
: undefined
if (idleTimer) download.stream.on('data', () => idleTimer.refresh())
try {
await pipeline(download.stream, res)
} catch (err) {
Expand All @@ -86,6 +104,10 @@ export default defineEventHandler(async (event) => {
// read waited for a socket) without taking ownership of the source.
download.stream.destroy()
const { code, message } = err as NodeJS.ErrnoException
if (err instanceof DownloadIdleTimeoutError) {
logger.warn(`Download /download/${locationId} closed: ${message}`)
return
}
// Client went away. Expected on cancelled jobs and parallel runners.
if (code === 'ERR_STREAM_PREMATURE_CLOSE' || code === 'ERR_STREAM_UNABLE_TO_PIPE') {
logger.debug(`Client aborted /download/${locationId}: ${message}`)
Expand All @@ -97,5 +119,7 @@ export default defineEventHandler(async (event) => {
return
}
throw err
} finally {
clearTimeout(idleTimer)
}
})
86 changes: 86 additions & 0 deletions tests/merge-concurrency.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
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 mergedAt(locationId: string) {
const db = await getDatabase()
const location = await db
.selectFrom('storage_locations')
.where('id', '=', locationId)
.select('mergedAt')
.executeTakeFirstOrThrow()
return location.mergedAt
}

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 mergedAt(first.locationId)).not.toBeNull()
expect(await mergedAt(second.locationId)).toBeNull()

// 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 mergedAt(second.locationId)).not.toBeNull()
} finally {
await storage.adapter.deleteFolder(first.folderName)
await storage.adapter.deleteFolder(second.folderName)
}
})
})
68 changes: 68 additions & 0 deletions tests/proxy-backpressure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { setTimeout as sleep } from 'node:timers/promises'

import * as h3 from 'h3'
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { env } from '~/lib/env'
import { getStorage } from '~/lib/storage'

const MiB = 1024 * 1024
Expand Down Expand Up @@ -167,4 +168,71 @@ describe('proxy routes apply backpressure', () => {

await vi.waitFor(() => expect(source.destroyed).toBe(true), { timeout: 5000, interval: 50 })
}, 20_000)

describe('download idle timeout', () => {
const originalIdleTimeout = env.DOWNLOAD_IDLE_TIMEOUT_MS
beforeAll(() => {
env.DOWNLOAD_IDLE_TIMEOUT_MS = 500
})
afterAll(() => {
env.DOWNLOAD_IDLE_TIMEOUT_MS = originalIdleTimeout
})

test('keeps a download open while bytes keep moving', async () => {
const chunks = 8
// Slower in total than the idle timeout, but never idle for that long.
const source = Readable.from(
(async function* () {
for (let i = 0; i < chunks; i++) {
await sleep(200)
yield Buffer.alloc(CHUNK_BYTES)
}
})(),
)
const storage = await getStorage()
vi.spyOn(storage, 'download').mockResolvedValue({
stream: source,
size: chunks * CHUNK_BYTES,
})

const { port } = server.address() as AddressInfo
const res = await fetch(`http://localhost:${port}/download/${randomUUID()}`)
const body = await res.arrayBuffer()
expect(body.byteLength).toBe(chunks * CHUNK_BYTES)
}, 20_000)

test('releases the storage read of a client that stopped reading', async () => {
// Real timers and sockets on purpose: the stall comes from TCP flow control,
// which fake timers cannot drive.
let pulled = 0
function* entry() {
while (pulled < ENTRY_BYTES) {
pulled += CHUNK_BYTES
yield Buffer.alloc(CHUNK_BYTES)
}
}
const source = Readable.from(entry(), { objectMode: false, highWaterMark: CHUNK_BYTES })
const storage = await getStorage()
vi.spyOn(storage, 'download').mockResolvedValue({
stream: source,
size: ENTRY_BYTES,
})

const { port } = server.address() as AddressInfo
const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]>
const req = http.get(`http://localhost:${port}/download/${randomUUID()}`)
req.on('error', () => undefined)
const [res] = (await once(req, 'response')) as [IncomingMessage]
expect(res.statusCode).toBe(200)
res.once('data', () => res.pause()) // stops reading, keeps the connection open
const [, serverRes] = await serverSide
const serverClosed = once(serverRes, 'close')

// Without an idle timeout neither ever happens: the pipe just stays parked.
await expect(once(source, 'close')).rejects.toThrow('No bytes sent')
await serverClosed
expect(pulled).toBeLessThan(ENTRY_BYTES)
req.destroy()
}, 20_000)
})
})
2 changes: 2 additions & 0 deletions tests/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ const TESTING_ENV_BASE = {
| 'ORPHANED_STORAGE_GRACE_PERIOD_HOURS'
| 'ENABLE_DIRECT_DOWNLOADS'
| 'EAGER_MERGE'
| 'MAX_CONCURRENT_MERGES'
| 'DOWNLOAD_IDLE_TIMEOUT_MS'
| 'BENCHMARK'
| 'SKIP_TOKEN_VALIDATION'
| 'ACTIONS_TOKEN_ISSUER'
Expand Down
Loading