diff --git a/README.md b/README.md index 1d6a0a2..8ba4b42 100644 --- a/README.md +++ b/README.md @@ -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 | @@ -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 diff --git a/docs/design-notes.md b/docs/design-notes.md index 4ebb9be..62fa0e0 100644 --- a/docs/design-notes.md +++ b/docs/design-notes.md @@ -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 @@ -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 diff --git a/package-lock.json b/package-lock.json index bc64d9e..07b5d7e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sleevenote", - "version": "0.1.0", + "version": "0.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sleevenote", - "version": "0.1.0", + "version": "0.4.1", "license": "MIT", "dependencies": { "@prometheus-io/client": "^0.16.1", diff --git a/package.json b/package.json index cb8aba8..804ffdd 100644 --- a/package.json +++ b/package.json @@ -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" diff --git a/src/browser.ts b/src/browser.ts index 73516c7..c353a33 100644 --- a/src/browser.ts +++ b/src/browser.ts @@ -3,9 +3,21 @@ import type { Config } from './config.js' export type Lease = { page: Page; release: () => Promise } +export type PoolStats = { free: number; leased: number; waiting: number } + export interface Pool { - acquire(): Promise + /** + * 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 liveContexts(): number + stats(): PoolStats close(): Promise } @@ -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, ms: number): Promise { + 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 @@ -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 @@ -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 { allRecords.delete(record) - await record.context.close().catch(() => {}) + let close = (): Promise => record.context.close() + if (closeHangsRemaining > 0) { + closeHangsRemaining-- + close = () => new Promise(() => {}) // injected: a close that never finishes + } + await closeWithin(close, cfg.contextCloseTimeoutMs) try { return await createContext() } catch (err) { @@ -98,7 +134,7 @@ export async function createPool(cfg: Config, testHooks?: TestFaultHooks): Promi } } - async function releaseRecord(record: ContextRecord): Promise { + async function releaseRecord(record: ContextRecord, revoked = false): Promise { // `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 @@ -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 @@ -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 { + async acquire(deadline?: AbortSignal): Promise { 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((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 @@ -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 { closed = true // Nothing will ever release into a closing pool. diff --git a/src/config.ts b/src/config.ts index d697a0a..4d9f106 100644 --- a/src/config.ts +++ b/src/config.ts @@ -3,6 +3,7 @@ export type Config = { redisUrl: string poolSize: number contextMaxUses: number + contextCloseTimeoutMs: number navTimeoutMs: number produceBudgetMs: number failureRelayTtl: number @@ -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 diff --git a/src/extract.ts b/src/extract.ts index 25f4e35..047fc4a 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -184,6 +184,25 @@ function sleep(ms: number): Promise { }) } +/** + * Wait for the body reads provoked so far, but not past `ms`. Resolves `true` + * when every one finished, `false` when it gave up. + * + * A response whose headers arrived and whose body never does leaves its read + * pending for as long as the page lives. An unbounded wait here held its + * lease with it: that is the hang behind the pool starvation of 2026-09-19. + * Whatever did arrive is already in `recorded`; the stragglers are abandoned. + */ +async function settleBodies(bodies: Promise[], ms: number): Promise { + return Promise.race([Promise.all(bodies).then(() => true), sleep(ms).then(() => false)]) +} + +function warnStragglers(kind: string, id: string, ms: number): void { + console.warn( + `[extract] ${kind} ${id}: response bodies still arriving after ${ms}ms -- continuing with what arrived`, + ) +} + // Only reached when the harvested query carried no usable `limit` of its own, // which no observed query has done -- `isWindowedQuery` already demands an // `offset`, and every windowed query measured so far carried both. It stays a @@ -325,7 +344,7 @@ export async function recordResponses( // right here. Reading the declared total off it without this wait finds // null, pages nothing, and produces the short listing this task exists // to eliminate, wearing pagination's clothes. - await Promise.all(bodies) + if (!(await settleBodies(bodies, entityDataTimeoutMs))) warnStragglers(kind, id, entityDataTimeoutMs) const total = declaredTotalFrom(kind, recorded, id) // Nothing declared a total, so `pageOffsets` asks for nothing and the @@ -348,16 +367,23 @@ export async function recordResponses( for (const [i, offset] of offsets.entries()) { const next = withOffset(template, offset, limit) try { - await page.evaluate(async (req) => { - const res = await fetch(req.url, { - method: 'POST', - headers: req.headers, - body: JSON.stringify(req.body), - }) - // Drain it in the page: Playwright can only hand us a body the - // browser actually finished receiving. - await res.text() - }, next) + await page.evaluate( + async ({ req, timeoutMs }) => { + const res = await fetch(req.url, { + method: 'POST', + headers: req.headers, + body: JSON.stringify(req.body), + // Nothing else bounds this: Playwright's evaluate has no + // timeout, and a window Spotify never answers would hold it, + // and the lease, forever. The signal also covers the body. + signal: AbortSignal.timeout(timeoutMs), + }) + // Drain it in the page: Playwright can only hand us a body the + // browser actually finished receiving. + await res.text() + }, + { req: next, timeoutMs: entityDataTimeoutMs }, + ) } catch (err) { // A window we could not fetch is a short listing, not a failed // extraction -- holding that distinction is the whole of Phase 1. @@ -393,7 +419,7 @@ export async function recordResponses( // The final window's body is still crossing the wire when its // `page.evaluate` resolves. Dropping it would silently lose the last // page of every listing. - await Promise.all(bodies) + if (!(await settleBodies(bodies, entityDataTimeoutMs))) warnStragglers(kind, id, entityDataTimeoutMs) } else { // No query to repeat: fall back to provoking the page into fetching more // by scrolling. This is the degraded path -- undirected, and with no way @@ -468,8 +494,9 @@ async function runExtraction( id: string, pool: Pool, cfg: Config, + deadline: AbortSignal, ): Promise { - const lease = await pool.acquire() + const lease = await pool.acquire(deadline) try { const capture = await recordResponses( lease.page, @@ -518,33 +545,39 @@ async function runExtraction( // is not a partial listing, it is extraction that stopped matching. return result } finally { - // The pool cannot enforce this, so every path out -- including a throw - // above -- must release. A second release() is a documented no-op. + // Every path out -- including a throw above -- must release. The + // deadline covers the path that never gets out: by then the pool has + // revoked the lease, and this release() is a documented no-op. await lease.release() } } /** - * Race `work` against `budgetMs`. On timeout the caller sees a rejection but - * `work` is NOT cancelled -- Playwright offers no way to abort an in-flight - * evaluate. It runs to completion in the background, including its own - * `lease.release()`, so the lease still returns to the pool. + * Settle with `work`, or with ExtractionTimeoutError the moment `deadline` + * fires, whichever is first. + * + * This only answers the caller. Stopping the work is the pool's job: the same + * `deadline` revokes the lease, and closing its context is what fails the + * work's pending Playwright calls. Before that, this rejected on time and + * trusted the work to finish and release on its own -- and on 2026-09-19 two + * never did, which left a pool of two empty until a restart. * * A backstop against anomalies, not an everyday path: the constituent steps * are already bounded and sum to well under the default budget. */ -function withBudget(work: Promise, budgetMs: number): Promise { +function withBudget(work: Promise, deadline: AbortSignal, budgetMs: number): Promise { return new Promise((resolve, reject) => { - const timer = setTimeout(() => { + const expire = (): void => { reject(new ExtractionTimeoutError(`extraction exceeded produceBudgetMs (${budgetMs}ms)`)) - }, budgetMs) + } + deadline.addEventListener('abort', expire, { once: true }) work.then( (value) => { - clearTimeout(timer) + deadline.removeEventListener('abort', expire) resolve(value) }, (err: unknown) => { - clearTimeout(timer) + deadline.removeEventListener('abort', expire) reject(err instanceof Error ? err : new Error(String(err))) }, ) @@ -554,9 +587,9 @@ function withBudget(work: Promise, budgetMs: number): Promise { /** * Resolve one Spotify entity to normalized metadata. * - * `cfg.produceBudgetMs` bounds the whole call -- navigate, scroll and settle - * together, not just navigation (`navTimeoutMs` is the narrower bound for - * that). The cache's single-flight lock derives its TTL from the same number, + * `cfg.produceBudgetMs` bounds the whole call -- waiting for a context, + * navigate, scroll and settle together, not just navigation (`navTimeoutMs` is + * the narrower bound for that). The cache's single-flight lock derives its TTL from the same number, * so this enforces it as a real ceiling rather than trusting the steps to add * up. */ @@ -566,5 +599,8 @@ export async function extract( pool: Pool, cfg: Config, ): Promise { - return withBudget(runExtraction(kind, id, pool, cfg), cfg.produceBudgetMs) + // One deadline, three jobs: it bounds the wait for a context, it ends the + // lease, and it answers the caller. + const deadline = AbortSignal.timeout(cfg.produceBudgetMs) + return withBudget(runExtraction(kind, id, pool, cfg, deadline), deadline, cfg.produceBudgetMs) } diff --git a/src/metrics.ts b/src/metrics.ts index abf5a2e..f4549aa 100644 --- a/src/metrics.ts +++ b/src/metrics.ts @@ -54,6 +54,23 @@ export const partialListings = new Counter({ * running instance can be asked. `build_info` is the Prometheus convention: a * gauge fixed at 1 whose labels carry the payload. */ +// Set from `pool.stats()` at scrape time, never tracked incrementally, so +// they cannot drift from the pool. `leased` at POOL_SIZE with `waiting` above +// zero is a starved pool: on 2026-09-19 that state lasted over an hour while +// /health answered "ok". +export const poolContexts = new Gauge({ + name: 'sleevenote_pool_contexts', + help: 'Browser contexts by state (free/leased), read from the pool at scrape time.', + labelNames: ['state'] as const, + registers: [registry], +}) + +export const poolWaiting = new Gauge({ + name: 'sleevenote_pool_waiting', + help: 'Callers queued for a browser context, read from the pool at scrape time.', + registers: [registry], +}) + export const buildInfo = new Gauge({ name: 'sleevenote_build_info', help: 'Build metadata for the running instance. Always 1; read the labels.', diff --git a/src/server.ts b/src/server.ts index 56633b4..f46c363 100644 --- a/src/server.ts +++ b/src/server.ts @@ -19,7 +19,16 @@ import { ExtractionIncompleteError, ExtractionTimeoutError, } from './extract.js' -import { cacheHits, scrapeDuration, scrapeFailures, extractionEmpty, partialListings, registry } from './metrics.js' +import { + cacheHits, + scrapeDuration, + scrapeFailures, + extractionEmpty, + partialListings, + poolContexts, + poolWaiting, + registry, +} from './metrics.js' export type ExtractFn = ( kind: 'track' | 'album' | 'playlist', @@ -385,6 +394,10 @@ export function buildServer(deps: ServerDeps): FastifyInstance { }) fastify.get('/metrics', async (_req, reply) => { + const { free, leased, waiting } = pool.stats() + poolContexts.set({ state: 'free' }, free) + poolContexts.set({ state: 'leased' }, leased) + poolWaiting.set(waiting) reply.header('Content-Type', registry.contentType) return registry.metrics() }) diff --git a/tests/browser.test.ts b/tests/browser.test.ts index aa9b80f..7b7119c 100644 --- a/tests/browser.test.ts +++ b/tests/browser.test.ts @@ -155,3 +155,130 @@ describe('createPool: a crashed page is recycled and stops counting as live imme } }) }) + +const TIMED_OUT = Symbol('timed out') + +/** `p`'s value if it settles within `ms`, else TIMED_OUT. Never rejects on `p`'s behalf. */ +async function settlesWithin(p: Promise, ms: number): Promise { + let timer: NodeJS.Timeout | undefined + const timeout = new Promise((r) => { timer = setTimeout(() => r(TIMED_OUT), ms) }) + try { + return await Promise.race([p, timeout]) + } finally { + clearTimeout(timer) + } +} + +// Production, 2026-09-19. A lookup that overran produceBudgetMs was answered +// 504, but it kept its lease: the budget rejected the CALLER without stopping +// the WORK, and the work never finished. Two of those, days apart, emptied a +// pool of two, and every later request of every kind waited out the budget +// and failed -- until a restart. /health said "ok" throughout. The holder +// cannot be trusted to give a context back; the pool has to take it. +describe('createPool: a lease past its deadline', () => { + it('takes the context back from a holder that never releases it, and stops the stuck work', async () => { + const dCfg = loadConfig({ POOL_SIZE: '1' }) + const dPool = await createPool(dCfg) + try { + const lease = await dPool.acquire(AbortSignal.timeout(300)) + // Stuck on the page forever -- the shape of the production hang. + const stuck = lease.page.evaluate(() => new Promise(() => {})).then( + () => 'resolved' as const, + () => 'rejected' as const, + ) + + // Pool of one: only a slot the pool took back itself can serve this. + const next = await settlesWithin(dPool.acquire(), 5_000) + expect(next).not.toBe(TIMED_OUT) + if (next === TIMED_OUT) return + // The stuck work was stopped, not left running against a context the + // pool has already handed to someone else. + expect(await settlesWithin(stuck, 2_000)).toBe('rejected') + expect(dPool.liveContexts()).toBe(1) + await next.page.setContent('

fresh

') + expect(await next.page.textContent('h1')).toBe('fresh') + + // The revoked holder releasing late must not free the slot a second time. + await lease.release() + const whileHeld = await settlesWithin(dPool.acquire(), 300) + expect(whileHeld).toBe(TIMED_OUT) + await next.release() + } finally { + await dPool.close() + } + }, 20_000) + + it('drops a queued caller whose deadline passes, so the next free context goes to a live one', async () => { + const qCfg = loadConfig({ POOL_SIZE: '1' }) + const qPool = await createPool(qCfg) + try { + const held = await qPool.acquire() + const expired = await settlesWithin(qPool.acquire(AbortSignal.timeout(200)).then(() => 'served', (e: unknown) => e), 2_000) + expect(expired).toBeInstanceOf(Error) + expect(qPool.stats().waiting).toBe(0) + + const live = qPool.acquire() + await held.release() + // FIFO would hand the context to the expired caller ahead of this one, + // and nothing would ever release it. + const got = await settlesWithin(live, 2_000) + expect(got).not.toBe(TIMED_OUT) + if (got !== TIMED_OUT) await got.release() + } finally { + await qPool.close() + } + }, 20_000) + + it('leaves alone a lease released before its deadline, even after that deadline passes', async () => { + const rCfg = loadConfig({ POOL_SIZE: '1' }) + const rPool = await createPool(rCfg) + try { + const early = await rPool.acquire(AbortSignal.timeout(300)) + await early.release() + // Pool of one: this is the same context, now someone else's. + const later = await rPool.acquire() + await new Promise((r) => setTimeout(r, 600)) + expect(later.page.isClosed()).toBe(false) + await later.release() + } finally { + await rPool.close() + } + }, 20_000) + + it('reports free, leased and waiting counts', async () => { + const sCfg = loadConfig({ POOL_SIZE: '2' }) + const sPool = await createPool(sCfg) + try { + expect(sPool.stats()).toEqual({ free: 2, leased: 0, waiting: 0 }) + const a = await sPool.acquire() + const b = await sPool.acquire() + const c = sPool.acquire() + expect(sPool.stats()).toEqual({ free: 0, leased: 2, waiting: 1 }) + await a.release() + await (await c).release() + await b.release() + expect(sPool.stats()).toEqual({ free: 2, leased: 0, waiting: 0 }) + } finally { + await sPool.close() + } + }, 20_000) +}) + +describe('createPool: a context close that never finishes', () => { + it('abandons the close after CONTEXT_CLOSE_TIMEOUT_MS and refills the slot', async () => { + const hCfg = loadConfig({ POOL_SIZE: '1', CONTEXT_MAX_USES: '1', CONTEXT_CLOSE_TIMEOUT_MS: '300' }) + const hPool = await createPool(hCfg, { hangNextContextCloses: 1 }) + try { + const lease = await hPool.acquire() // uses becomes 1 -- at budget, so release recycles + // Every close happens on a release path: an unbounded one would hold + // this release, and the slot, forever. + expect(await settlesWithin(lease.release(), 3_000)).not.toBe(TIMED_OUT) + expect(hPool.liveContexts()).toBe(1) + const next = await settlesWithin(hPool.acquire(), 2_000) + expect(next).not.toBe(TIMED_OUT) + if (next !== TIMED_OUT) await next.release() + } finally { + await hPool.close() + } + }, 20_000) +}) diff --git a/tests/extract.test.ts b/tests/extract.test.ts index de48ff5..d1d4345 100644 --- a/tests/extract.test.ts +++ b/tests/extract.test.ts @@ -1,5 +1,7 @@ import { describe, it, expect, afterAll, vi } from 'vitest' import { readFile } from 'node:fs/promises' +import { createServer, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' import type { Page, Request } from 'playwright' import { createPool } from '../src/browser.js' import { loadConfig } from '../src/config.js' @@ -14,6 +16,7 @@ import { NotFoundError, ExtractionEmptyError, ExtractionSilentError, + ExtractionTimeoutError, } from '../src/extract.js' import { PATHFINDER_URL, @@ -1438,3 +1441,140 @@ describe('declaredTotalFrom', () => { expect(declaredTotalFrom('playlist', [], 'plId')).toBeNull() }) }) + +const TIMED_OUT = Symbol('timed out') + +/** `p`'s value if it settles within `ms`, else TIMED_OUT. Never rejects on `p`'s behalf. */ +async function settlesWithin(p: Promise, ms: number): Promise { + let timer: NodeJS.Timeout | undefined + const timeout = new Promise((r) => { timer = setTimeout(() => r(TIMED_OUT), ms) }) + try { + return await Promise.race([p, timeout]) + } finally { + clearTimeout(timer) + } +} + +// Production, 2026-09-19: see tests/browser.test.ts's "a lease past its +// deadline". These are the extraction half -- the budget has to reach the +// pool, and the two waits that had no bound of their own get one, so a stall +// costs seconds instead of the whole budget. +describe('extract: a stuck extraction', () => { + it('gives the context back when the budget runs out, not when the stuck work finishes', async () => { + // The page never issues the entity query, so the extraction sits in its + // entity-data wait for 8s. The budget is 1s. + const bCfg = loadConfig({ POOL_SIZE: '1', PRODUCE_BUDGET_MS: '1000', ENTITY_DATA_TIMEOUT_MS: '8000' }) + const bPool = await createPool(bCfg) + try { + const page = await routedPage(bPool) + await page.route('https://open.spotify.com/**', (route) => + route.fulfill({ status: 200, contentType: 'text/html', body: 'nothing yet' }), + ) + await expect(extract('track', 'stuckId', bPool, bCfg)).rejects.toThrow(ExtractionTimeoutError) + + // Pool of one. Before the fix this waited out the rest of the 8s. + const next = await settlesWithin(bPool.acquire(), 2_000) + expect(next).not.toBe(TIMED_OUT) + if (next !== TIMED_OUT) await next.release() + } finally { + await bPool.close() + } + }, 30_000) + + it('stops waiting on a JSON response whose body never finishes arriving', async () => { + // A real server: page.route can only fulfil a whole body, and the hang + // needs headers that arrive and a body that does not. + const server: Server = createServer((req, res) => { + if (req.url === '/page') { + res.writeHead(200, { 'content-type': 'text/html' }) + // Both fetches start well after the page has gone network-idle, which + // is where production stalled: past `goto`, inside the body wait. + res.end(``) + return + } + if (req.url === '/stall.json') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.write('{"never":') // ...and never another byte + return + } + res.writeHead(404).end() + }) + await new Promise((r) => server.listen(0, '127.0.0.1', r)) + const port = (server.address() as AddressInfo).port + + const sCfg = loadConfig({ POOL_SIZE: '1' }) + const sPool = await createPool(sCfg) + try { + const lease = await sPool.acquire() + await routePathfinder(lease.page, (vars) => + playlistPageResponse('stallId', { offset: vars.offset, limit: 25, itemCount: 25, totalCount: 25, entity: true }).body, + ) + const capture = await settlesWithin( + // The entity wait has to outlast the 1.8s pathfinder fetch, or the + // capture never reaches the body wait at all and takes the scroll path. + recordResponses(lease.page, `http://127.0.0.1:${port}/page`, 'playlist', 'stallId', 10_000, 2_500), + 10_000, + ) + expect(capture).not.toBe(TIMED_OUT) + // What did arrive is kept: the stall costs a bounded wait, not the listing. + if (capture !== TIMED_OUT) expect(capture.responses.some((r) => r.url.startsWith(PATHFINDER_URL))).toBe(true) + await lease.release() + } finally { + await sPool.close() + server.closeAllConnections() + await new Promise((r) => server.close(r)) + } + }, 30_000) + + it('gives up on a pagination window that never answers, and serves the short listing', async () => { + const id = 'silentWindowId' + const wCfg = loadConfig({ POOL_SIZE: '1', ENTITY_DATA_TIMEOUT_MS: '500' }) + const wPool = await createPool(wCfg) + try { + const page = await routedPage(wPool) + await page.route('https://open.spotify.com/**', (route) => + route.fulfill({ status: 200, contentType: 'text/html', body: windowedQueryPage(id, 25) }), + ) + await page.route(PATHFINDER_URL, (route) => { + const req = route.request() + if (req.method() === 'OPTIONS') { + return route.fulfill({ + status: 204, + headers: { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'POST, OPTIONS', + 'access-control-allow-headers': req.headers()['access-control-request-headers'] ?? '*', + }, + }) + } + const { offset } = (req.postDataJSON() as { variables: { offset: number } }).variables + // The second window is never answered -- not refused, not failed. + if (offset > 0) return + return route.fulfill({ + status: 200, + headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*' }, + body: JSON.stringify(playlistPageResponse(id, { offset: 0, limit: 25, itemCount: 25, totalCount: 50, entity: true }).body), + }) + }) + + const result = await settlesWithin(extract('playlist', id, wPool, wCfg), 15_000) + expect(result).not.toBe(TIMED_OUT) + if (result !== TIMED_OUT && result.type === 'playlist') { + expect(result.tracks).toHaveLength(25) + expect(result.complete).toBe(false) + } + } finally { + await wPool.close() + } + }, 30_000) +}) diff --git a/tests/server.test.ts b/tests/server.test.ts index e772146..e04115a 100644 --- a/tests/server.test.ts +++ b/tests/server.test.ts @@ -37,7 +37,12 @@ async function counterTotal(counter: CounterLike): Promise { // Silent: buildServer now builds a real pino unless a logger is injected, // and an `info`-level suite floods stdout with a line per request. const cfg = loadConfig({ LOG_LEVEL: 'silent' }) -const fakePool = { acquire: async () => { throw new Error('unused') }, liveContexts: () => 1, close: async () => {} } +const fakePool = { + acquire: async () => { throw new Error('unused') }, + liveContexts: () => 1, + stats: () => ({ free: 0, leased: 2, waiting: 3 }), + close: async () => {}, +} function server(extract: any, store = new MemoryStore()) { return buildServer({ cfg, store, pool: fakePool as any, extract }) @@ -185,6 +190,17 @@ describe('GET /metrics', () => { expect(res.statusCode).toBe(200) expect(res.body).toContain('sleevenote_extraction_empty_total') }) + + // A starved pool -- every context leased, callers queueing -- looked + // exactly like a healthy one from outside on 2026-09-19. These are read + // from the pool at scrape time, so they cannot drift from it. + it("exposes the pool's state as it is at scrape time", async () => { + const app = server(async () => TRACK) + const res = await app.inject({ method: 'GET', url: '/metrics' }) + expect(res.body).toMatch(/sleevenote_pool_contexts\{state="free"\} 0/) + expect(res.body).toMatch(/sleevenote_pool_contexts\{state="leased"\} 2/) + expect(res.body).toMatch(/sleevenote_pool_waiting 3/) + }) }) describe('ExtractionTimeoutError', () => {