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
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,10 @@ copy-pasteable version with fuller comments:
| `REDIS_URL` | `redis://127.0.0.1:6379` | the only state this stateless service depends on |
| `POOL_SIZE` | `2` | browser contexts kept warm; excess requests queue, they don't fail |
| `CONTEXT_MAX_USES` | `50` | extractions served before a context is recycled |
| `CONTEXT_CLOSE_TIMEOUT_MS` | `5000` | how long a context close may take before it is abandoned and the slot refilled. Every close is on a release path, so an unbounded one holds the slot |
| `NAV_TIMEOUT_MS` | `45000` | cap on a single page navigation |
| `ENTITY_DATA_TIMEOUT_MS` | `15000` | how long to wait for Spotify's entity query after the page looks settled. Deliberately far below `NAV_TIMEOUT_MS`: it covers the gap between "went idle" and "data arrived", so reusing the nav timeout would make every genuinely silent extraction cost 45s before it could say so |
| `PRODUCE_BUDGET_MS` | `150000` | cap on one whole extraction; also sets the cache's single-flight lock TTL (see `src/config.ts`) |
| `ENTITY_DATA_TIMEOUT_MS` | `15000` | how long to wait for Spotify's entity query after the page looks settled. Deliberately far below `NAV_TIMEOUT_MS`: it covers the gap between "went idle" and "data arrived", so reusing the nav timeout would make every genuinely silent extraction cost 45s before it could say so. Also bounds waiting for response bodies to finish arriving, and each pagination window |
| `PRODUCE_BUDGET_MS` | `150000` | cap on one whole extraction, including the wait for a context; also sets the cache's single-flight lock TTL (see `src/config.ts`). Enforced by the pool: a lease still held when it runs out is revoked and its context replaced |
| `TTL_TRACK` | `2592000` (30d) | track cache TTL, in seconds |
| `TTL_ALBUM` | `2592000` (30d) | album cache TTL, in seconds |
| `TTL_PLAYLIST` | `14400` (4h) | playlist cache TTL — playlists genuinely change |
Expand Down Expand Up @@ -131,6 +132,10 @@ release gate, in [docs/releasing.md](docs/releasing.md).
A running instance reports its own build as
`sleevenote_build_info{version="..."}` on `GET /metrics`.

The browser pool's state is `sleevenote_pool_contexts{state="free"|"leased"}`
and `sleevenote_pool_waiting`, read at scrape time. Every context leased with
callers waiting is a starved pool.

## Testing

```bash
Expand Down
54 changes: 53 additions & 1 deletion docs/design-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ cost.

`acquire()` queues FIFO rather than rejecting when everything is busy: a third
concurrent caller against a pool of two should wait its turn, not become a
500.
500. It waits only until its deadline, though (below).

Contexts are recycled at release time, at `contextMaxUses` **or** when the
page has closed. The use budget alone was not enough — a context whose
Expand All @@ -351,6 +351,58 @@ Contexts block `image`, `font` and `media`. The fixture corpus was recorded
with exactly those blocked, so a pool serving unblocked pages would show
production a different page than the normalizer was built against.

### The pool owns the deadline, not the holder

Until 0.4.1, `produceBudgetMs` only answered the caller. `withBudget` rejected
on time, and its comment said the work "runs to completion in the background,
including its own `lease.release()`, so the lease still returns to the pool."
That assumed every step of an extraction ends eventually. One did not.
`await Promise.all(bodies)` waited for every JSON body the page had started,
and a body whose headers arrive but whose stream stalls leaves Playwright's
`response.json()` pending for as long as the page lives.

**Production, 2026-09-19.** Each such hang lost one context for good. The
first was on 09-15; the service kept working on the other one. The second, at
11:59, emptied the pool of two. From then on every request of every kind, a
single track included, sat in `acquire()` until the budget ran out, and came
back 504 after exactly 150 seconds. The container idled at about 1% CPU, and
`/health` answered "ok" throughout, because a context held by a hung lease is
still live. A restart fixed it at once. Across the container's lifetime the
number of `ExtractionTimeoutError`s was exactly the number of contexts lost.

Off-the-shelf pools were checked first. generic-pool and tarn bound acquire
and destroy, but their evictors only touch *idle* resources, so neither can
take one back from a borrower that hangs. Crawlee's browser-pool bounds its
own operations; the per-request timeout lives in its crawler, not its pool.
puppeteer-cluster has the right idea, closing the job's context when its
timeout fires, but it is Puppeteer-only and makes a fresh context per job. So
the pattern was adopted here rather than the dependency.

**The pattern is cancellation by destroying what the work holds.** Playwright
cannot abort an in-flight call, but closing a context rejects every call
pending on it ("Target page, context or browser has been closed"). So
`extract()` makes one `AbortSignal` from the budget and passes it to
`acquire()`, and the pool uses it three ways:

- **A queued caller whose deadline passes leaves the queue.** Left in it, it
would be handed the next free context after it had stopped listening, ahead
of a caller still waiting.
- **A lease still held at the deadline is revoked.** The pool closes its
context and a fresh one takes the slot, *without waiting for the holder*.
The holder's pending calls reject, and its eventual `release()` is a no-op.
Revocation does not rely on the holder unwinding, because a holder can also
be waiting on a plain timer, which closing a page does not interrupt.
- **A close gets `CONTEXT_CLOSE_TIMEOUT_MS`.** Every close is on a release
path, so a wedged renderer holding `close()` open would hold the slot the
same way. Past the limit, the context is abandoned and replaced.

The budget remains a backstop. The steps that had no bound now have one: the
body wait and each pagination window's in-page `fetch` both take
`ENTITY_DATA_TIMEOUT_MS`. A stalled body now costs seconds and leaves the
listing it did get, rather than costing the whole budget and the lease.
`sleevenote_pool_contexts` and `sleevenote_pool_waiting` make a starved pool
visible from outside.

## Redis client tuning

ioredis's defaults leave a command queued through up to 20 retries — roughly
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "sleevenote",
"version": "0.4.0",
"version": "0.4.1",
"description": "Resolve a music-entity URL to normalized metadata. No provider API key.",
"directories": {
"doc": "docs"
Expand Down
117 changes: 103 additions & 14 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,21 @@ import type { Config } from './config.js'

export type Lease = { page: Page; release: () => Promise<void> }

export type PoolStats = { free: number; leased: number; waiting: number }

export interface Pool {
acquire(): Promise<Lease>
/**
* A free context, or a place in the queue for one.
*
* With `deadline`, the pool -- not the holder -- owns when the lease ends. A
* caller still queued when it fires is rejected and leaves the queue. A
* lease still held when it fires is revoked: its context is closed, which
* fails every Playwright call still pending on it, and a fresh context
* takes its slot. The holder's own `release()` is then a no-op.
*/
acquire(deadline?: AbortSignal): Promise<Lease>
liveContexts(): number
stats(): PoolStats
close(): Promise<void>
}

Expand All @@ -25,7 +37,25 @@ class PoolClosedError extends Error {
// Test-only fault injection, not part of the Pool contract: `createPool(cfg)`
// alone is the real signature. Lets tests reach the recycle-failure path
// without exhausting real system resources.
type TestFaultHooks = { failNextContextCreations?: number }
type TestFaultHooks = { failNextContextCreations?: number; hangNextContextCloses?: number }

/**
* Close `context`, but stop waiting after `ms`. A context whose renderer has
* wedged can hold `close()` open indefinitely, and the caller here is always a
* release: waiting on it would hold the slot exactly as a stuck holder did.
* The context is abandoned rather than awaited, and the pool replaces it.
*/
async function closeWithin(close: () => Promise<void>, ms: number): Promise<void> {
let timer: NodeJS.Timeout | undefined
const gaveUp = new Promise<'gave up'>((resolve) => {
timer = setTimeout(() => resolve('gave up'), ms)
})
const outcome = await Promise.race([close().then(() => 'closed' as const, () => 'closed' as const), gaveUp])
clearTimeout(timer)
if (outcome === 'gave up') {
console.warn(`[pool] a context did not close within ${ms}ms -- abandoning it and creating a replacement`)
}
}

/**
* One browser backing `cfg.poolSize` reused contexts. `acquire()` hands out a
Expand Down Expand Up @@ -75,6 +105,7 @@ export async function createPool(cfg: Config, testHooks?: TestFaultHooks): Promi
free.push(await createContext())
}
failuresRemaining = testHooks?.failNextContextCreations ?? 0
let closeHangsRemaining = testHooks?.hangNextContextCloses ?? 0

// Recycling at release time bounds what a long-lived page accumulates.
// `record` leaves `allRecords` up front because the old context is closed
Expand All @@ -83,7 +114,12 @@ export async function createPool(cfg: Config, testHooks?: TestFaultHooks): Promi
// costing the pool a permanent slot.
async function recycle(record: ContextRecord): Promise<ContextRecord> {
allRecords.delete(record)
await record.context.close().catch(() => {})
let close = (): Promise<void> => record.context.close()
if (closeHangsRemaining > 0) {
closeHangsRemaining--
close = () => new Promise<void>(() => {}) // injected: a close that never finishes
}
await closeWithin(close, cfg.contextCloseTimeoutMs)
try {
return await createContext()
} catch (err) {
Expand All @@ -98,7 +134,7 @@ export async function createPool(cfg: Config, testHooks?: TestFaultHooks): Promi
}
}

async function releaseRecord(record: ContextRecord): Promise<void> {
async function releaseRecord(record: ContextRecord, revoked = false): Promise<void> {
// `closed` is createPool's own flag, declared above and closed over here
// rather than passed in. True on entry means the pool shut down *before*
// this release: browser.close() has already torn this context down, so
Expand All @@ -111,7 +147,11 @@ export async function createPool(cfg: Config, testHooks?: TestFaultHooks): Promi
// Recycle on a crashed page as well as at the use budget: a dead
// renderer would otherwise sit in `free` being handed out until it
// happened to also reach `contextMaxUses`.
returned = record.uses >= cfg.contextMaxUses || record.page.isClosed() ? await recycle(record) : record
//
// And always on a revoked lease: its holder may still be running against
// this page, so the page must not go back out.
returned =
revoked || record.uses >= cfg.contextMaxUses || record.page.isClosed() ? await recycle(record) : record
} catch (err) {
if (closed) {
// close() won a race with an in-flight recycle. It already rejected
Expand Down Expand Up @@ -143,29 +183,71 @@ export async function createPool(cfg: Config, testHooks?: TestFaultHooks): Promi
}
}

function makeLease(record: ContextRecord): Lease {
function makeLease(record: ContextRecord, deadline?: AbortSignal): Lease {
record.uses++
// A double release must not free the record twice or resolve two waiters.
let released = false
// Whichever comes first, the holder's release() or the deadline, ends the
// lease; the other is a no-op. A double release must not free the record
// twice or resolve two waiters.
let ended = false
const revoke = (): void => {
if (ended) return
ended = true
// The holder is stuck or slow, and cannot be trusted to hand this back:
// on 2026-09-19 two holders never did, and a pool of two stayed empty
// until a restart. Take it. Closing the context is also what stops the
// holder -- every Playwright call it has pending rejects.
console.warn('[pool] a lease outlived its deadline -- closing its context and replacing it')
releaseRecord(record, true).catch((err: unknown) => {
console.warn(`[pool] replacing a revoked context failed: ${String(err)}`)
})
}
deadline?.addEventListener('abort', revoke, { once: true })
return {
page: record.page,
release: async () => {
if (released) return
released = true
deadline?.removeEventListener('abort', revoke)
if (ended) return
ended = true
await releaseRecord(record)
},
}
}

return {
async acquire(): Promise<Lease> {
async acquire(deadline?: AbortSignal): Promise<Lease> {
if (closed) throw new Error('browser pool is closed')
deadline?.throwIfAborted()
const record = free.shift()
if (record) return makeLease(record)
if (record) return makeLease(record, deadline)
const queued = await new Promise<ContextRecord>((resolve, reject) => {
waiters.push({ resolve, reject })
// A caller whose deadline passes leaves the queue. Left in it, it
// would be handed the next free context after it had stopped
// listening, ahead of a caller that is still waiting.
const leave = (): void => {
const i = waiters.indexOf(waiter)
if (i !== -1) waiters.splice(i, 1)
reject(deadline?.reason)
}
const waiter = {
resolve: (r: ContextRecord) => {
deadline?.removeEventListener('abort', leave)
resolve(r)
},
reject: (err: Error) => {
deadline?.removeEventListener('abort', leave)
reject(err)
},
}
deadline?.addEventListener('abort', leave, { once: true })
waiters.push(waiter)
})
return makeLease(queued)
if (deadline?.aborted) {
// Handed a context in the same tick the deadline fired. Nothing has
// touched it, so pass it on rather than revoking a good context.
await releaseRecord(queued)
throw deadline.reason
}
return makeLease(queued, deadline)
},

// Filtered by the same predicate `releaseRecord` recycles on. An unfiltered
Expand All @@ -179,6 +261,13 @@ export async function createPool(cfg: Config, testHooks?: TestFaultHooks): Promi
return live
},

// Read at scrape time by /metrics. `leased` includes a record in transit
// to a waiter; a pool with every context leased and callers waiting is
// starved, which is what this exists to make visible.
stats(): PoolStats {
return { free: free.length, leased: allRecords.size - free.length, waiting: waiters.length }
},

async close(): Promise<void> {
closed = true
// Nothing will ever release into a closing pool.
Expand Down
5 changes: 5 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export type Config = {
redisUrl: string
poolSize: number
contextMaxUses: number
contextCloseTimeoutMs: number
navTimeoutMs: number
produceBudgetMs: number
failureRelayTtl: number
Expand Down Expand Up @@ -47,6 +48,10 @@ export function loadConfig(env: NodeJS.ProcessEnv): Config {
redisUrl: env.REDIS_URL ?? 'redis://127.0.0.1:6379',
poolSize: num(env.POOL_SIZE, 2),
contextMaxUses: num(env.CONTEXT_MAX_USES, 50),
// A context close that has not finished by then is abandoned and the slot
// refilled. Every close happens on a release path, so an unbounded one
// holds the slot exactly as a stuck holder does.
contextCloseTimeoutMs: num(env.CONTEXT_CLOSE_TIMEOUT_MS, 5_000),
navTimeoutMs: num(env.NAV_TIMEOUT_MS, 45_000),
produceBudgetMs: num(env.PRODUCE_BUDGET_MS, DEFAULT_PRODUCE_BUDGET_MS),
// Seconds, not minutes: a handoff to the cohort already waiting, not a
Expand Down
Loading
Loading