Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@danj/audible-auth

Locked Audible gateway using one owner-provisioned Kody login.

FollowFork

Files

deadline.ts

91 lines · 2.9 KB · TypeScript
/**
 * No AbortSignal: Kody's package-app bridge refuses a Request that carries
 * one (DataCloneError), so the package bounds its own wait. Kody's
 * gateway still ends the upstream request at its own 300 s bound.
 */

export class DeadlineError extends Error {}
export class ResponseTimeoutError extends DeadlineError {}

export const CALL_MS = 20_000
// About 19 times a measured 100-row Library page.
export const MAX_SUCCESS_BODY_BYTES = 16 * 1024 * 1024

export type Deadline = {
	run<T>(work: () => Promise<T>, drop?: (late: T) => void): Promise<T>
	end(): void
}

export function startDeadline(ms: number, late: () => Error): Deadline {
	// The cutoff decides; the timer only wakes a wait that nothing else ends. A
	// continuation can run past the cutoff before the timer callback gets its turn.
	const cutoff = Date.now() + ms
	let fired = false
	const over = () => fired || Date.now() >= cutoff
	let expire = () => {}
	const spent = new Promise<undefined>((resolve) => {
		expire = () => resolve(undefined)
	})
	const timer = setTimeout(() => {
		fired = true
		expire()
	}, ms)
	return {
		async run<T>(work: () => Promise<T>, drop?: (late: T) => void): Promise<T> {
			if (over()) throw late()
			const pending = work()
			const first = await Promise.race([pending.then((value) => ({ value })), spent])
			if (first && !over()) return first.value
			if (first) drop?.(first.value)
			else pending.then(drop, () => {})
			throw late()
		},
		end: () => clearTimeout(timer),
	}
}

export const dropAnswer = (response: Response) => {
	response.body?.cancel().catch(() => {})
}

export async function waitForResponse(deadline: Deadline, send: () => Promise<Response>): Promise<Response> {
	let dispatched = false
	try {
		return await deadline.run(() => { dispatched = true; return send() }, dropAnswer)
	} catch (error) {
		if (dispatched && error instanceof DeadlineError) throw new ResponseTimeoutError(error.message)
		throw error
	}
}

async function readPrefix(reader: ReadableStreamDefaultReader<Uint8Array>, bytes: number) {
	const decoder = new TextDecoder()
	let text = ''
	let size = 0
	while (size < bytes) {
		const { done, value } = await reader.read()
		if (done) {
			text += decoder.decode()
			break
		}
		const chunk = value.subarray(0, bytes - size)
		size += chunk.byteLength
		text += decoder.decode(chunk, { stream: true })
	}
	return { text, size }
}

export async function readBounded(response: Response, bytes: number, deadline: Deadline, ms?: number) {
	const reader = response.body?.getReader()
	if (!reader) return { text: '', size: 0 }
	let timer: ReturnType<typeof setTimeout> | undefined
	const slow = new Promise<undefined>((resolve) => {
		if (ms !== undefined) timer = setTimeout(resolve, ms)
	})
	try {
		return await deadline.run(() => Promise.race([readPrefix(reader, bytes), slow]).catch(() => undefined))
	} finally {
		clearTimeout(timer)
		reader.cancel().catch(() => {})
	}
}