diff --git a/plugins/motrix.scraper-hook/src/index.test.ts b/plugins/motrix.scraper-hook/src/index.test.ts new file mode 100644 index 0000000..56f18bc --- /dev/null +++ b/plugins/motrix.scraper-hook/src/index.test.ts @@ -0,0 +1,82 @@ +import type { BeforeCreateHttpContext } from 'motrix:plugin-api' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const api = vi.hoisted(() => ({ + config: { get: vi.fn() }, + hooks: { beforeCreate: vi.fn() }, + http: { request: vi.fn() }, + lifecycle: { onDeactivate: vi.fn() }, + log: { info: vi.fn(), warn: vi.fn() }, +})) +vi.mock('motrix:plugin-api', () => api) + +describe('optional scraper budget', () => { + let run: (ctx: BeforeCreateHttpContext) => Promise + let ctx: BeforeCreateHttpContext + beforeEach(async () => { + vi.resetModules() + vi.resetAllMocks() + vi.useFakeTimers() + vi.setSystemTime(0) + api.config.get.mockResolvedValue(undefined) + await import('./index') + run = api.hooks.beforeCreate.mock.calls[0]![0] + ctx = { + type: 'http', + uris: ['https://example.test/page'], + headers: [{ name: 'Referer', value: 'https://example.test/' }], + update: vi.fn(), + } as unknown as BeforeCreateHttpContext + }) + afterEach(() => vi.useRealTimers()) + + it('shares one three-second deadline across HEAD and GET', async () => { + api.http.request + .mockImplementationOnce(async () => { + vi.setSystemTime(2400) + return { headers: [{ name: 'Content-Type', value: 'text/html' }] } + }) + .mockResolvedValueOnce({ body: '', headers: [] }) + expect(await run(ctx)).toBe(ctx) + expect( + api.http.request.mock.calls.map(([request]) => request.timeoutMs) + ).toEqual([3000, 600]) + expect(api.http.request.mock.calls[1]![0]).toMatchObject({ + maxBodyBytes: 524288, + headers: ctx.headers, + }) + }) + + it('does not start GET when HEAD has consumed the budget', async () => { + api.http.request.mockImplementationOnce(async () => { + vi.setSystemTime(3001) + return { headers: [{ name: 'Content-Type', value: 'text/html' }] } + }) + expect(await run(ctx)).toBe(ctx) + expect(api.http.request).toHaveBeenCalledOnce() + }) + + it.each([ + 'plugin.http.timeout', + 'plugin.http.network', + 'plugin.http.response_too_large', + ])('falls back for %s without a partial update', async (code) => { + api.http.request.mockRejectedValue( + Object.assign(new Error('unavailable'), { code }) + ) + expect(await run(ctx)).toBe(ctx) + expect(ctx.update).not.toHaveBeenCalled() + }) + + it.each([ + 'plugin.http.aborted', + 'plugin.http.host_not_permitted', + 'plugin.http.redirect_not_allowed', + 'unknown', + ])('propagates critical failure %s', async (code) => { + const error = Object.assign(new Error('denied'), { code }) + api.http.request.mockRejectedValue(error) + await expect(run(ctx)).rejects.toBe(error) + expect(ctx.update).not.toHaveBeenCalled() + }) +}) diff --git a/plugins/motrix.scraper-hook/src/index.ts b/plugins/motrix.scraper-hook/src/index.ts index c917315..151493c 100644 --- a/plugins/motrix.scraper-hook/src/index.ts +++ b/plugins/motrix.scraper-hook/src/index.ts @@ -9,6 +9,13 @@ import { import { findArchiveLink } from './scrapers' const DEFAULT_MAX_BODY = 524288 +const DISCOVERY_BUDGET_MS = 3_000 +const OPTIONAL_NETWORK_ERRORS = new Set([ + 'plugin.http.timeout', + 'plugin.http.network', + 'plugin.http.response_too_large', + 'plugin.http.too_many_redirects', +]) async function isEnabled(): Promise { const v = await config.get('enabled') @@ -26,33 +33,44 @@ hooks.beforeCreate( if (!(await isEnabled())) return ctx const url = ctx.uris[0] if (!url) return ctx + const deadline = Date.now() + DISCOVERY_BUDGET_MS + const maxBody = await readMaxBody() + const remaining = () => Math.max(0, deadline - Date.now()) try { + const headBudget = remaining() + if (!headBudget) return ctx const head = await http.request({ method: 'HEAD', url, responseType: 'text', - timeoutMs: 5_000, + headers: ctx.headers, + timeoutMs: headBudget, }) const ctHeader = head.headers.find( (h) => h.name.toLowerCase() === 'content-type' ) const ct = ctHeader?.value ?? '' if (!ct.includes('text/html')) return ctx - const maxBody = await readMaxBody() + const getBudget = remaining() + if (!getBudget) return ctx const res = await http.request({ method: 'GET', url, responseType: 'text', - timeoutMs: 10_000, + headers: ctx.headers, + timeoutMs: getBudget, maxBodyBytes: maxBody, }) const archiveUrl = findArchiveLink(res.body as string, url) if (archiveUrl) { - log.info('scraper rewrote URL', { from: url, to: archiveUrl }) + log.info('scraper discovered a download target') ctx.update({ uris: [archiveUrl] }) } } catch (e) { - log.warn('scraper failed', { err: String(e) }) + const code = + typeof e === 'object' && e !== null && 'code' in e ? String(e.code) : '' + if (!OPTIONAL_NETWORK_ERRORS.has(code)) throw e + log.warn('optional discovery unavailable', { code }) } return ctx }