Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 31 additions & 5 deletions src/ble/base/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,17 @@ import ICyclingMode from "../../modes/types.js";
import { BleMultiTransportInterfaceFactory } from "../factories/interface-factory.js";
import { InteruptableTask, TaskState } from "../../utils/task.js";
import { TBleSensor } from "./sensor.js";
import { resolveNextTick } from "../../utils/utils.js";
import { resolveNextTick, sleep } from "../../utils/utils.js";


export default class BleAdapter<TDeviceData extends BleDeviceData, TDevice extends TBleSensor> extends IncyclistDevice<BleDeviceProperties> {
export default class BleAdapter<TDeviceData extends BleDeviceData, TDevice extends TBleSensor> extends IncyclistDevice<BleDeviceProperties> {

// backstop bound for runStop()'s wait on a previous start's underlying promise - see runStop()
protected static readonly STOP_WAIT_BOUND_MS = 10000

protected getStopWaitBound():number {
return BleAdapter.STOP_WAIT_BOUND_MS
}

protected deviceData: TDeviceData
protected dataMsgCount: number
Expand Down Expand Up @@ -346,7 +353,12 @@ export default class BleAdapter<TDeviceData extends BleDeviceData, TDevice exten
timeout: startProps?.timeout ?? this.getDefaultStartupTimeout(),
name:'start',
errorOnTimeout: false,
log: this.logEvent.bind(this)
log: this.logEvent.bind(this),
// this task being stopped/timed out doesn't by itself interrupt a still-running
// waitForPeripheral() underneath (startSensor() has no way to see it) - without this,
// stop() can be left awaiting that wait's own, much longer, timeout (interfaces that
// support it settle this immediately; others are unaffected, same as pauseDiscovery())
onCancel: ()=>{ ble.cancelWait?.(this.settings) }
})

this.startPromise = this.runStartTask(ble)
Expand Down Expand Up @@ -518,7 +530,7 @@ export default class BleAdapter<TDeviceData extends BleDeviceData, TDevice exten
return true;
}
catch(err:any) {
this.logEvent({message: 'start result: error', error: err.message,stack:err.stack,device:this.getName(),interface:this.getInterface(), protocol:this.getProtocolName()})
this.logEvent({message: 'start result: error', error: err.message,device:this.getName(),interface:this.getInterface(), protocol:this.getProtocolName()})
this.started = false;
this.stopped = true;
const ble = this.getBle()
Expand Down Expand Up @@ -650,7 +662,21 @@ export default class BleAdapter<TDeviceData extends BleDeviceData, TDevice exten
// prior run has genuinely settled (completed, errored, or hit its own timeout). Without
// this, a subsequent start() could begin while the previous run's GATT operations were
// still physically in flight, colliding with them.
await task.getUnderlyingPromise()?.catch(()=>{})
//
// Bounded as a backstop: the task's onCancel hook above (cancelWait()) is what actually
// interrupts a still-pending wait underneath, promptly, for the interfaces that support
// it. This bound only matters if that didn't happen - an interface with no cancelWait(),
// or some other promise in the chain that genuinely never settles - so stop() still
// returns instead of leaving the caller (and whatever it's waiting to do next) stuck.
const underlying = task.getUnderlyingPromise()
if (underlying !== undefined) {
const settled = await Promise.race([
underlying.then(()=>true).catch(()=>true),
sleep(this.getStopWaitBound()).then(()=>false),
])
if (!settled)
this.logEvent({message:'stop(): the previous start is still running past its bound, proceeding anyway', device:this.getName(),interface:this.getInterface()})
}
}

// make sure that we restart upon next start() call, even if the stop fails
Expand Down
48 changes: 48 additions & 0 deletions src/ble/fm/adapter.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -708,5 +708,53 @@ describe('BleFmAdapter',()=>{
expect(sensor.reset).toHaveBeenCalledTimes(1)
})

test('stop() interrupts a still-pending waitForPeripheral() instead of being stuck behind its own, much longer, timeout',async ()=>{
setupMocks(adapter)
emitDataContinuously()
sensor.hasPeripheral = jest.fn().mockReturnValue(false)

// the interface's own wait never settles on its own (e.g. the device isn't reachable
// yet) - only cancelWait() (called via the task's onCancel hook) can unstick it, the
// same way the real DirectConnectInterface's cancelWait() settles its own pending wait
let rejectWait: (err:Error)=>void
ble.waitForPeripheral = jest.fn().mockReturnValue(new Promise( (_,reject) => { rejectWait = reject }))
ble.cancelWait = jest.fn( ()=> rejectWait(new Error('cancelled')))

const p1 = adapter.start({timeout:5000})
await sleep(20)
expect(ble.waitForPeripheral).toHaveBeenCalled()

const stopPromise = adapter.stop()
await sleep(20)

expect(ble.cancelWait).toHaveBeenCalledWith(adapter['settings'])

// stop() must not actually be waiting on the real 5+ minute lifetime of that wait -
// this only passes because something settles the underlying promise; with no cancelWait
// wired up, this would still be pending and the test would time out
await stopPromise
await p1.catch(()=>{})
})

test('stop() does not wait forever if a pending wait cannot be interrupted at all',async ()=>{
setupMocks(adapter)
emitDataContinuously()
sensor.hasPeripheral = jest.fn().mockReturnValue(false)
adapter['getStopWaitBound'] = jest.fn().mockReturnValue(50)

// no cancelWait on this interface (e.g. plain BLE, which has no comparable internal
// wait today) and the wait itself never settles - runStop()'s bound is the only thing
// that can still unstick stop() here
ble.waitForPeripheral = jest.fn().mockReturnValue(new Promise(()=>{}))

const p1 = adapter.start({timeout:5000})
await sleep(20)
expect(ble.waitForPeripheral).toHaveBeenCalled()

await adapter.stop() // must return (bound by getStopWaitBound()), not hang

p1.catch(()=>{})
})

})
})
5 changes: 5 additions & 0 deletions src/ble/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,11 @@ export interface IBleInterface<T extends PeripheralAnnouncement> extends Incycli
createPeripheralFromSettings(settings:DeviceSettings):IBlePeripheral
createDeviceSetting(announcement: T):DeviceSettings
waitForPeripheral(settings:DeviceSettings): Promise<IBlePeripheral>
// settles (rejects) a specific device's still-pending waitForPeripheral(), if any - lets a
// cancelled/timed-out start interrupt that wait immediately instead of leaving it to its own,
// much longer, internal timeout. Optional: an interface whose waitForPeripheral() has no
// comparable internal wait (or settles quickly on its own) doesn't need one.
cancelWait?(settings:DeviceSettings): void
pauseDiscovery?():Promise<void>
resumeDiscovery?():Promise<void>

Expand Down
29 changes: 24 additions & 5 deletions src/direct-connect/base/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -456,14 +456,24 @@ export default class DirectConnectInterface extends EventEmitter implements IB
if (pending) return pending.promise

let cancel: ()=>void = ()=>{}
const promise = new Promise<IBlePeripheral>( (resolve)=> {
cancel = this.runWait(key, settings, resolve)
const promise = new Promise<IBlePeripheral>( (resolve,reject)=> {
cancel = this.runWait(key, settings, resolve, reject)
})
this.pendingWaits.set(key, {promise, cancel})
return promise
}

protected runWait(key:string, settings:DeviceSettings, resolve:(p:IBlePeripheral)=>void): ()=>void {
/**
* Settles a specific device's pending wait (if any) without the caller having to know whether
* one is even running - used when a start attempt for this device is itself being cancelled
* (BleAdapter.stop()/timeout), so the wait doesn't keep that cancellation hanging behind it.
*/
cancelWait(settings:DeviceSettings): void {
const key = `${settings.name}|${(settings as BleDeviceSettings).address??''}`
this.pendingWaits.get(key)?.cancel()
}

protected runWait(key:string, settings:DeviceSettings, resolve:(p:IBlePeripheral)=>void, reject:(err:Error)=>void): ()=>void {
const start = Date.now()
let probes = 0
let lastResult: string|undefined
Expand All @@ -484,6 +494,15 @@ export default class DirectConnectInterface extends EventEmitter implements IB
resolve(peripheral)
}

// settles the promise instead of leaving it pending - a cancelled/abandoned wait is still
// an outcome a caller is genuinely waiting on (e.g. BleAdapter.stop() awaits this via
// startAdapter()'s underlying promise), not something that can be silently dropped
const fail = (reason:'cancelled'|'abandoned')=> {
if (finished) return
cleanup()
reject(new Error(`wifi device wait ${reason}`))
}

const onDevice = (device:BleDeviceSettings)=> {
if (finished || device.name!==settings.name) return
const peripheral = this.createPeripheralFromSettings(settings)
Expand Down Expand Up @@ -515,7 +534,7 @@ export default class DirectConnectInterface extends EventEmitter implements IB

if (Date.now()-start >= DC_WAIT_LIFETIME) {
this.logEvent({message:'wifi device wait abandoned', device:settings.name, address:(settings as BleDeviceSettings).address??'', waitedMs:Date.now()-start, probes})
cleanup()
fail('abandoned')
return
}
timer = setTimeout( ()=>{ void attempt('reprobe') }, DC_REPROBE_INTERVAL)
Expand All @@ -524,7 +543,7 @@ export default class DirectConnectInterface extends EventEmitter implements IB
this.on('device', onDevice)
void attempt('start')

return cleanup
return ()=>fail('cancelled')
}

/**
Expand Down
30 changes: 29 additions & 1 deletion src/direct-connect/base/interface.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,8 @@ describe('DirectConnectInterface', () => {
iface.addKnownDevice(settings)
dc.probePort = jest.fn().mockResolvedValue('closed')

iface.waitForPeripheral(settings)
const p = iface.waitForPeripheral(settings)
p.catch(()=>{}) // settling (rejecting) it is covered by its own test below
await jest.advanceTimersByTimeAsync(100)
const calls = dc.probePort.mock.calls.length

Expand All @@ -252,6 +253,33 @@ describe('DirectConnectInterface', () => {
expect(dc.probePort.mock.calls.length).toBe(calls)
expect(iface.listenerCount('device')).toBe(0)
})

// a caller (e.g. BleAdapter.stop()) awaits this promise to know a cancelled/abandoned wait
// has genuinely finished - it must always settle, never hang forever
test('settles (rejects) once cancelled, instead of leaving the caller waiting forever', async () => {
iface.addKnownDevice(settings)
dc.probePort = jest.fn().mockResolvedValue('closed')

const p = iface.waitForPeripheral(settings)
const outcome = p.then(()=>'resolved').catch(()=>'rejected')

await jest.advanceTimersByTimeAsync(100)
dc.cancelWaits()

await expect(outcome).resolves.toBe('rejected')
})

test('settles (rejects) once its lifetime is abandoned, instead of leaving the caller waiting forever', async () => {
iface.addKnownDevice(settings)
dc.probePort = jest.fn().mockResolvedValue('closed')

const p = iface.waitForPeripheral(settings)
const outcome = p.then(()=>'resolved').catch(()=>'rejected')

await jest.advanceTimersByTimeAsync(5*60*1000 + 1000)

await expect(outcome).resolves.toBe('rejected')
})
})

describe('probePort', () => {
Expand Down
Loading