import { packageStorage } from 'kody:runtime'
export type WaitReason = 'login-failed' | 'reconnect-needed' | 'unauthorized' | 'timeouts'
export type Backoff = { failures: number; nextAllowedAt: number; reason: WaitReason | null; lastSuccessAt: string | null; timeoutPending: boolean; identity: string | null; generation: number; version: number; disconnected: boolean }
const COLUMNS = 'failures, next_allowed_at, reason, last_success_at, timeout_pending, identity, generation, version, disconnected'
const WAIT_MS_BY_PRIOR_FAILURES = 'CASE failures WHEN 0 THEN 1800000 WHEN 1 THEN 3600000 WHEN 2 THEN 7200000 WHEN 3 THEN 14400000 ELSE 21600000 END'
async function initialize(store: ReturnType<typeof packageStorage>) {
noRows(await store.sql(`CREATE TABLE IF NOT EXISTS audible_login_backoff (
id INTEGER PRIMARY KEY CHECK (id = 1),
identity TEXT,
generation INTEGER NOT NULL DEFAULT 0,
version INTEGER NOT NULL DEFAULT 0,
disconnected INTEGER NOT NULL DEFAULT 0 CHECK (disconnected IN (0, 1)),
failures INTEGER NOT NULL DEFAULT 0,
next_allowed_at INTEGER NOT NULL DEFAULT 0,
reason TEXT,
last_success_at TEXT,
timeout_pending INTEGER NOT NULL DEFAULT 0 CHECK (timeout_pending IN (0, 1))
)`))
noRows(await store.sql('INSERT OR IGNORE INTO audible_login_backoff (id) VALUES (1)'))
}
let setup: Promise<void> | undefined
function prepare(store: ReturnType<typeof packageStorage>): Promise<void> {
if (!setup) {
const pending = initialize(store)
setup = pending
pending.catch(() => { if (setup === pending) setup = undefined })
}
return setup
}
const UNAVAILABLE = 'Audible login state unavailable.'
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function rowsOf(result: unknown): Array<Record<string, unknown>> {
if (!isRecord(result) || !Array.isArray(result.rows) || !result.rows.every(isRecord)) throw new Error(UNAVAILABLE)
return result.rows
}
function noRows(result: unknown): void {
if (rowsOf(result).length !== 0) throw new Error(UNAVAILABLE)
}
function returnedGeneration(rows: Array<Record<string, unknown>>): number | null {
if (rows.length === 0) return null
const generation = rows[0].generation
if (rows.length !== 1 || typeof generation !== 'number') throw new Error(UNAVAILABLE)
return generation
}
async function sql(query: string, params: Array<string | number | null> = []): Promise<unknown> {
const store = packageStorage()
await prepare(store)
const initialized = setup
try { return await store.sql(query, params) }
catch (error) {
if (!(error instanceof Error) || !/no such table:\s*audible_login_backoff/i.test(error.message)) throw error
if (setup === initialized) setup = undefined
await prepare(store)
return await store.sql(query, params)
}
}
async function run(query: string, params: Array<string | number | null> = []): Promise<void> {
noRows(await sql(query, params))
}
export async function readBackoff(): Promise<Backoff> {
const rows = rowsOf(await sql(`SELECT ${COLUMNS} FROM audible_login_backoff WHERE id = 1`))
const row = rows[0]
if (rows.length !== 1 || !row || typeof row.failures !== 'number' || typeof row.next_allowed_at !== 'number'
|| (row.reason !== null && row.reason !== 'login-failed' && row.reason !== 'reconnect-needed' && row.reason !== 'unauthorized' && row.reason !== 'timeouts')
|| typeof row.generation !== 'number' || typeof row.version !== 'number' || (row.identity !== null && typeof row.identity !== 'string')
|| (row.disconnected !== 0 && row.disconnected !== 1)
|| (row.last_success_at !== null && typeof row.last_success_at !== 'string') || (row.timeout_pending !== 0 && row.timeout_pending !== 1)) {
throw new Error(UNAVAILABLE)
}
return { failures: row.failures, nextAllowedAt: row.next_allowed_at, reason: row.reason, lastSuccessAt: row.last_success_at, timeoutPending: row.timeout_pending === 1, identity: row.identity, generation: row.generation, version: row.version, disconnected: row.disconnected === 1 }
}
export async function resetBackoff(success: boolean, generation: number, version: number): Promise<void> {
await run(`UPDATE audible_login_backoff SET version = version + 1, failures = 0, next_allowed_at = 0, reason = NULL,
last_success_at = ?, timeout_pending = 0 WHERE id = 1 AND generation = ? AND version = ?
AND (failures <> 0 OR next_allowed_at <> 0 OR reason IS NOT NULL OR timeout_pending <> 0 OR last_success_at IS NULL)`, [success ? new Date().toISOString() : null, generation, version])
}
export async function checkBackoff(generation: number, bypassWait = false): Promise<Backoff> {
const state = await readBackoff()
if (state.generation !== generation) throw new Error('Audible login changed. Try again with the current setup.')
if (!bypassWait && Date.now() < state.nextAllowedAt) throw new Error(`Audible login wait until ${new Date(state.nextAllowedAt).toISOString()} (${state.reason}).`)
return state
}
export async function recordFailure(reason: WaitReason | 'timeout' | null, generation: number, version: number): Promise<void> {
if (reason === 'timeout') {
await run(`UPDATE audible_login_backoff SET version = version + 1,
failures = failures + timeout_pending,
next_allowed_at = CASE WHEN timeout_pending = 1 THEN ? + ${WAIT_MS_BY_PRIOR_FAILURES} ELSE next_allowed_at END,
reason = CASE WHEN timeout_pending = 1 THEN 'timeouts' ELSE reason END,
timeout_pending = 1 - timeout_pending WHERE id = 1 AND generation = ? AND version = ?`, [Date.now(), generation, version])
} else if (reason === null) {
await run('UPDATE audible_login_backoff SET version = version + 1, timeout_pending = 0 WHERE id = 1 AND generation = ? AND version = ? AND timeout_pending <> 0', [generation, version])
} else {
await run(`UPDATE audible_login_backoff SET version = version + 1, failures = failures + 1,
next_allowed_at = ? + ${WAIT_MS_BY_PRIOR_FAILURES}, reason = ?, timeout_pending = 0 WHERE id = 1 AND generation = ? AND version = ?`, [Date.now(), reason, generation, version])
}
}
export async function adoptLogin(identity: string, previousIdentity: string | null): Promise<number> {
const rows = rowsOf(await sql(`UPDATE audible_login_backoff SET identity = ?, generation = generation + 1, version = version + 1,
disconnected = 0, failures = 0, next_allowed_at = 0, reason = NULL, last_success_at = NULL, timeout_pending = 0
WHERE id = 1 AND (identity = ? OR (identity IS NULL AND ? IS NULL))
AND identity IS NOT ? RETURNING generation`, [identity, previousIdentity, previousIdentity, identity]))
const generation = returnedGeneration(rows)
if (generation !== null) return generation
const state = await readBackoff()
if (state.identity !== identity) throw new Error('Audible login changed. Try again with the current setup.')
return state.generation
}
export async function disconnectBackoff(generation: number, disconnected: boolean): Promise<void> {
const rows = rowsOf(await sql(`UPDATE audible_login_backoff SET generation = generation + 1, version = version + 1,
disconnected = ?, failures = 0, next_allowed_at = 0, reason = NULL, last_success_at = NULL, timeout_pending = 0
WHERE id = 1 AND generation = ? RETURNING generation`, [disconnected ? 1 : 0, generation]))
if (returnedGeneration(rows) === null) throw new Error('Audible login changed during Disconnect. Check setup before deleting a login.')
}