import assert from 'node:assert/strict'
import { beforeEach, test } from 'node:test'
import { fixture as f, reset } from './helpers/runtime.ts'
const request=(await import('../request.ts')).default
const {readBackoff}=await import('../backoff.ts')
const {disconnect}=await import('../disconnect.ts')
const status=(await import('../status.ts')).default
const call=()=>request({path:'/1.0/library'})
beforeEach(reset)
test('login_failed counts; only fixed exchange HTTP 400/401 says reconnect needed',async()=>{
for(const [message,reconnect] of [['The login exchange did not return a session (HTTP 400).',true],['The login exchange did not return a session (HTTP 401).',true],['The login exchange did not return a session (HTTP 500).',false],['The login exchange did not complete.',false]] as const){
reset();f.provider=async()=>{throw Object.assign(new Error(message),{code:'login_failed'})}
await assert.rejects(call(),error=>!String(error).includes(message))
assert.equal((await readBackoff()).failures,1);assert.equal((await status()).reconnectNeeded,reconnect)
await assert.rejects(call(),/Audible login wait until/);assert.equal(f.fetches,1)
}
})
test('returned 401 counts for bodyless calls and calls with a body; never package replayed',async()=>{
for(const input of [{path:'/1.0/library'},{path:'/1.0/wishlist',method:'POST',body:{asin:'B000000001'}}]){
reset();f.provider=async()=>new Response(null,{status:401})
await assert.rejects(request(input));assert.equal(f.fetches,1);assert.equal((await readBackoff()).reason,'unauthorized')
}
})
test('404, 403, 500, transport, redirects and unreadable bodies do not count as credential failures',async()=>{
for(const code of [404,403,500,302]){f.provider=async()=>new Response(null,{status:code});await assert.rejects(call());assert.equal((await readBackoff()).failures,0)}
f.provider=async()=>{throw new Error('remote diagnostic')};await assert.rejects(call(),/→ no answer$/)
f.provider=async()=>new Response(new ReadableStream({start(c){c.error(new Error('remote diagnostic'))}}));await assert.rejects(call(),/unreadable/)
assert.equal((await readBackoff()).failures,0)
})
test('wait schedule is 30m, 1h, 2h, 4h, then 6h forever; wait sends nothing',async(t)=>{
t.mock.timers.enable({apis:['Date'],now:1000})
f.provider=async()=>new Response(null,{status:401})
for(const minutes of [30,60,120,240,360,360,360]){
await assert.rejects(call());const state=await readBackoff()
assert.equal(state.nextAllowedAt-Date.now(),minutes*60_000)
const sent=f.fetches;await assert.rejects(call(),/login wait/);assert.equal(f.fetches,sent)
t.mock.timers.setTime(state.nextAllowedAt)
}
})
test('one 20s timeout does not count; two consecutive timeouts count once',async(t)=>{
t.mock.timers.enable({apis:['Date','setTimeout'],now:0})
f.provider=()=>new Promise(()=>{})
const timeout=async()=>{const p=call();const handled=assert.rejects(p,/no answer within 20 s/);for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));t.mock.timers.tick(20_000);await handled}
await timeout();assert.equal((await readBackoff()).failures,0)
await timeout();assert.equal((await readBackoff()).failures,1);assert.equal((await readBackoff()).reason,'timeouts')
})
test('a different failure breaks the consecutive timeout streak',async(t)=>{
t.mock.timers.enable({apis:['Date','setTimeout'],now:0})
const timeout=async()=>{f.provider=()=>new Promise(()=>{});const p=assert.rejects(call());for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));t.mock.timers.tick(20_000);await p}
await timeout();f.provider=async()=>new Response(null,{status:404});await assert.rejects(call());await timeout()
assert.equal((await readBackoff()).failures,0)
})
test('success, Disconnect and saving a replacement login reset the backoff',async(t)=>{
t.mock.timers.enable({apis:['Date'],now:0})
f.provider=async()=>new Response(null,{status:401});await assert.rejects(call())
t.mock.timers.setTime((await readBackoff()).nextAllowedAt)
f.provider=async()=>Response.json({});await call();assert.equal((await readBackoff()).failures,0);assert.ok((await readBackoff()).lastSuccessAt)
await disconnect();assert.equal((await status()).deleteLoginOnWebsite,true)
f.description=JSON.stringify({registration:'00000000-0000-4000-8000-000000000002'});await call();assert.equal((await status()).ready,true)
f.provider=async()=>new Response(null,{status:401});await assert.rejects(call())
f.description=JSON.stringify({registration:'00000000-0000-4000-8000-000000000003'});f.provider=async()=>Response.json({});await call();assert.equal((await readBackoff()).failures,0)
})
test('healthy Library and Wishlist calls both dispatch without an admission lock',async()=>{
let release=()=>{};const gate=new Promise<void>(r=>{release=r})
f.provider=async()=>{await gate;return Response.json({})}
const a=request({path:'/1.0/library'}),b=request({path:'/1.0/wishlist'})
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r))
assert.equal(f.fetches,2);release();await Promise.all([a,b])
})
test('successful collection substep does not reset an unsuccessful remove',async()=>{
f.provider=async url=>url.includes('/items')?new Response(null,{status:401}):Response.json({state_token:'test-state'})
await assert.rejects(request({method:'DELETE',path:'/1.0/collections/__WISHLIST/items',query:{asins:'B000000001'}}))
assert.equal((await readBackoff()).failures,1);assert.equal((await readBackoff()).lastSuccessAt,null)
})
test('confirmed Disconnect resets existing failures',async(t)=>{
t.mock.timers.enable({apis:['Date'],now:0})
f.provider=async()=>new Response(null,{status:401});await assert.rejects(call())
t.mock.timers.setTime((await readBackoff()).nextAllowedAt)
f.provider=async()=>Response.json({});await disconnect();assert.equal((await readBackoff()).failures,0)
})
test('one in-flight timeout preserves an already counted failure reason and wait',async(t)=>{
t.mock.timers.enable({apis:['Date','setTimeout'],now:0})
let entered=()=>{};const started=new Promise<void>(r=>{entered=r})
f.provider=async url=>{if(url.includes('wishlist')){entered();return new Promise(()=>{})}throw Object.assign(new Error('The login exchange did not return a session (HTTP 401).'),{code:'login_failed'})}
const timeout=assert.rejects(request({path:'/1.0/wishlist'}),/within 20 s/)
await started;await assert.rejects(call());const wait=await readBackoff()
t.mock.timers.tick(20_000);await timeout
assert.equal((await readBackoff()).reason,'reconnect-needed');assert.equal((await readBackoff()).nextAllowedAt,wait.nextAllowedAt)
})
test('login_needs_reconnect counts as reconnect needed',async()=>{
f.provider=async()=>{throw Object.assign(new Error('remote diagnostic'),{code:'login_needs_reconnect'})}
await assert.rejects(call(),error=>!String(error).includes('remote diagnostic'))
const state=await readBackoff();assert.equal(state.failures,1);assert.equal(state.reason,'reconnect-needed')
assert.equal((await status()).reconnectNeeded,true)
})
test('login_retry_later names when to try again and counts nothing',async(t)=>{
t.mock.timers.enable({apis:['Date'],now:0})
for(const [retryAfterSeconds,when] of [[90,'after 1970-01-01T00:01:30.000Z'],[undefined,'later'],[-1,'later'],[1e20,'later'],[Infinity,'later'],[Number.NaN,'later'],['90','later']] as const){
f.provider=async()=>{throw Object.assign(new Error('remote diagnostic'),{code:'login_retry_later',retryAfterSeconds})}
await assert.rejects(call(),error=>error instanceof Error&&error.message.endsWith(`try again ${when}`)&&!/no answer|remote diagnostic/.test(error.message))
const state=await readBackoff();assert.equal(state.failures,0);assert.equal(state.nextAllowedAt,0);assert.equal(state.reason,null)
}
})
test('login_retry_later keeps a pending timeout pair',async(t)=>{
const {recordFailure}=await import('../backoff.ts')
await call();const before=await readBackoff();await recordFailure('timeout',before.generation,before.version)
assert.equal((await readBackoff()).timeoutPending,true)
f.provider=async()=>{throw Object.assign(new Error('remote diagnostic'),{code:'login_retry_later',retryAfterSeconds:1e20})}
await assert.rejects(call(),error=>error instanceof Error&&error.name==='AudibleLoginRetryLater'&&error.message.endsWith('try again later'))
const state=await readBackoff();assert.equal(state.timeoutPending,true);assert.equal(state.failures,0);assert.equal(state.nextAllowedAt,0)
})