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 |
| -------------------------- | -------- | ------------------------------------------------------------------------------- |
| `DOWNLOAD_IDLE_TIMEOUT_MS` | `300000` | Closes a download whose client has not read a byte for this long; `0` disables. |

## 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',
'DOWNLOAD_IDLE_TIMEOUT_MS': 'number.integer >= 0 = 300000',
'BENCHMARK': 'boolean = false',
'SKIP_TOKEN_VALIDATION': 'boolean = false',
'MANAGEMENT_API_KEY?': 'string',
Expand Down
27 changes: 26 additions & 1 deletion 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 Down Expand Up @@ -77,11 +78,33 @@ export default defineEventHandler(async (event) => {
// `sendStream` neither waits for `drain` nor notices client aborts; `pipeline` does both
// and destroys the source, which releases its reader lease. `_handled` is an h3 v1 internal.
event._handled = true
// 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.
let idleTimer: NodeJS.Timeout | undefined
if (env.DOWNLOAD_IDLE_TIMEOUT_MS > 0) {
const body = download.stream
idleTimer = setTimeout(() => {
body.destroy(
Object.assign(new Error(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`), {
code: 'ERR_DOWNLOAD_IDLE_TIMEOUT',
}),
)
}, env.DOWNLOAD_IDLE_TIMEOUT_MS)
idleTimer.unref()
body.on('data', () => idleTimer?.refresh())
}
try {
await pipeline(download.stream, event.node.res)
} catch (err) {
const { code } = err as NodeJS.ErrnoException
if (code === 'ERR_DOWNLOAD_IDLE_TIMEOUT') {
logger.warn(`Download /download/${locationId} closed: ${(err as Error).message}`)
return
}
// Client went away mid-body. Expected on cancelled jobs and parallel runners.
if ((err as NodeJS.ErrnoException).code === 'ERR_STREAM_PREMATURE_CLOSE') {
if (code === 'ERR_STREAM_PREMATURE_CLOSE') {
logger.debug(`Client aborted /download/${locationId}: ${(err as Error).message}`)
return
}
Expand All @@ -91,5 +114,7 @@ export default defineEventHandler(async (event) => {
return
}
throw err
} finally {
clearTimeout(idleTimer)
}
})
110 changes: 110 additions & 0 deletions tests/proxy-backpressure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { setTimeout as sleep } from 'node:timers/promises'

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

const MiB = 1024 * 1024
Expand Down Expand Up @@ -167,4 +169,112 @@ 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.each([
{ response: 'a whole entry', status: 200, range: undefined },
{ response: 'a Range', status: 206, range: { start: 0, end: ENTRY_BYTES - 1 } },
])(
'releases the storage read of a client that stopped reading $response',
async ({ status, range }) => {
// 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,
range,
})

const { port } = server.address() as AddressInfo
const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]>
const req = http.get(`http://localhost:${port}/download/${randomUUID()}`, {
headers: range ? { range: `bytes=${range.start}-${range.end}` } : {},
})
req.on('error', () => undefined)
const [res] = (await once(req, 'response')) as [IncomingMessage]
expect(res.statusCode).toBe(status)
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.toMatchObject({
code: 'ERR_DOWNLOAD_IDLE_TIMEOUT',
})
await serverClosed
expect(pulled).toBeLessThan(ENTRY_BYTES)
req.destroy()
},
20_000,
)

test('a stalled first restore is closed and its Merge still completes', async () => {
const storage = await getStorage()
const db = await getDatabase()
const reservation = {
key: `idle-unmerged-${randomUUID()}`,
version: 'v1',
scope: 'refs/heads/main',
repoId: '123',
}
const upload = await storage.createUpload(reservation)
// Far more than loopback socket buffers hold, so the stalled client really blocks the tee.
for (let i = 0; i < 4; i++)
await storage.uploadPart(upload.id, i, Readable.from([Buffer.alloc(8 * MiB, i)]))
await storage.completeUpload(reservation)
const { locationId } = await db
.selectFrom('cache_entries')
.where('key', '=', reservation.key)
.select('locationId')
.executeTakeFirstOrThrow()

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

// The pump keeps feeding the merge once the client's side of the tee is gone.
await storage.waitForOngoingMerges()
const location = await db
.selectFrom('storage_locations')
.where('id', '=', locationId)
.select('mergedAt')
.executeTakeFirstOrThrow()
expect(location.mergedAt).not.toBeNull()
await vi.waitFor(
async () => {
const leases = await db
.selectFrom('storage_reader_leases')
.where('storageLocationId', '=', locationId)
.select('id')
.execute()
expect(leases, 'reader leases left behind').toHaveLength(0)
},
{ timeout: 5000, interval: 50 },
)
}, 30_000)
})
})
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'
| 'DOWNLOAD_IDLE_TIMEOUT_MS'
| 'BENCHMARK'
| 'SKIP_TOKEN_VALIDATION'
| 'ACTIONS_TOKEN_ISSUER'
Expand Down
Loading