From 3eb405de83c66d71b057d9a9bb45b2cbf1ad51e0 Mon Sep 17 00:00:00 2001 From: Guido Doumen Date: Mon, 9 Nov 2026 11:53:40 +0100 Subject: [PATCH 1/3] fix: a cancelled or abandoned wait for a WiFi device no longer hangs forever DirectConnectInterface.waitForPeripheral()'s internal wait only ever settled on success: cancelling it (pauseBackgroundActivity, or a caller giving up) and its own 5-minute lifetime both just cleaned up internal state without resolving or rejecting the promise the caller was awaiting. Any caller awaiting that promise - directly or indirectly, such as BleAdapter.stop() awaiting a still in-flight start() via its underlying promise - was stuck for as long as the wait happened to keep running, in practice indefinitely whenever the device stayed unreachable. - waitForPeripheral()'s wait now rejects on cancel and on its own lifetime being reached, instead of only ever resolving. - a new cancelWait() lets a specific device's pending wait be settled without canceling every other interface's in-flight wait. - BleAdapter.start()'s task now calls cancelWait() via the existing onCancel hook when the start is stopped or times out, so a still-pending wait is interrupted immediately rather than left to its own, much longer, timeout. IBleInterface.cancelWait() is optional - an interface with no comparable internal wait doesn't need one. - runStop()'s wait on the previous start's underlying promise is now also bounded as a backstop, so stop() still returns even if some other promise in the chain genuinely never settles. --- src/ble/base/adapter.ts | 34 +++++++++++-- src/ble/fm/adapter.unit.test.ts | 48 +++++++++++++++++++ src/ble/types.ts | 5 ++ src/direct-connect/base/interface.ts | 29 +++++++++-- .../base/interface.unit.test.ts | 30 +++++++++++- 5 files changed, 136 insertions(+), 10 deletions(-) diff --git a/src/ble/base/adapter.ts b/src/ble/base/adapter.ts index d8a9120..489b52d 100644 --- a/src/ble/base/adapter.ts +++ b/src/ble/base/adapter.ts @@ -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 extends IncyclistDevice { +export default class BleAdapter extends IncyclistDevice { + + // 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 @@ -346,7 +353,12 @@ export default class BleAdapter{ ble.cancelWait?.(this.settings) } }) this.startPromise = this.runStartTask(ble) @@ -650,7 +662,21 @@ export default class BleAdapter{}) + // + // 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) { + 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 diff --git a/src/ble/fm/adapter.unit.test.ts b/src/ble/fm/adapter.unit.test.ts index 70ed4e6..481c663 100644 --- a/src/ble/fm/adapter.unit.test.ts +++ b/src/ble/fm/adapter.unit.test.ts @@ -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(()=>{}) + }) + }) }) \ No newline at end of file diff --git a/src/ble/types.ts b/src/ble/types.ts index c92e82a..7661111 100644 --- a/src/ble/types.ts +++ b/src/ble/types.ts @@ -219,6 +219,11 @@ export interface IBleInterface extends Incycli createPeripheralFromSettings(settings:DeviceSettings):IBlePeripheral createDeviceSetting(announcement: T):DeviceSettings waitForPeripheral(settings:DeviceSettings): Promise + // 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 resumeDiscovery?():Promise diff --git a/src/direct-connect/base/interface.ts b/src/direct-connect/base/interface.ts index bcbdd80..e7d9ae2 100644 --- a/src/direct-connect/base/interface.ts +++ b/src/direct-connect/base/interface.ts @@ -456,14 +456,24 @@ export default class DirectConnectInterface extends EventEmitter implements IB if (pending) return pending.promise let cancel: ()=>void = ()=>{} - const promise = new Promise( (resolve)=> { - cancel = this.runWait(key, settings, resolve) + const promise = new Promise( (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 @@ -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) @@ -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) @@ -524,7 +543,7 @@ export default class DirectConnectInterface extends EventEmitter implements IB this.on('device', onDevice) void attempt('start') - return cleanup + return ()=>fail('cancelled') } /** diff --git a/src/direct-connect/base/interface.unit.test.ts b/src/direct-connect/base/interface.unit.test.ts index a079a03..1044bc8 100644 --- a/src/direct-connect/base/interface.unit.test.ts +++ b/src/direct-connect/base/interface.unit.test.ts @@ -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 @@ -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', () => { From fd02f86535969d2e59737420ebe8491b233a428e Mon Sep 17 00:00:00 2001 From: Guido Doumen Date: Mon, 9 Nov 2026 13:14:58 +0100 Subject: [PATCH 2/3] remove error log in BLE device start failure --- src/ble/base/adapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ble/base/adapter.ts b/src/ble/base/adapter.ts index 489b52d..2a9bd41 100644 --- a/src/ble/base/adapter.ts +++ b/src/ble/base/adapter.ts @@ -530,7 +530,7 @@ export default class BleAdapter Date: Mon, 9 Nov 2026 13:18:06 +0100 Subject: [PATCH 3/3] chore: make an existence check on a promise explicit Checking a Promise-or-undefined field directly in a boolean conditional reads like an accidentally-skipped await. Made the intent (is it set at all, not whether it resolved truthy) explicit. --- src/ble/base/adapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ble/base/adapter.ts b/src/ble/base/adapter.ts index 2a9bd41..805c809 100644 --- a/src/ble/base/adapter.ts +++ b/src/ble/base/adapter.ts @@ -669,7 +669,7 @@ export default class BleAdaptertrue).catch(()=>true), sleep(this.getStopWaitBound()).then(()=>false),