diff --git a/src/AltSocket.test.ts b/src/AltSocket.test.ts index d490f6a..e304fb1 100644 --- a/src/AltSocket.test.ts +++ b/src/AltSocket.test.ts @@ -315,3 +315,61 @@ describe('AltSocket notifications and close', () => { socket.close(); }); }); + +describe('AltSocket heartbeat', () => { + const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); + + /** getServerVersion answers during startup, then goes silent. */ + function silentAfterStartup(server: FakeAltServer): void { + let answered = 0; + server.on('getServerVersion', () => (answered++ === 0 ? [{ data: '2.3.3' }] : 'silent')); + } + + it('a silent ping holds the slot only for heartbeatTimeoutMs, so a user command still gets through', async () => { + const server = new FakeAltServer(); + silentAfterStartup(server); + server.on('getAllComponents', () => [{ data: [] }]); + const socket = await AltSocket.connect(opts(server, { heartbeatMs: 20, heartbeatTimeoutMs: 15, commandTimeoutMs: 5_000 })); + await wait(25); // first ping is on the wire and silent + const started = Date.now(); + await socket.send({ commandName: 'getAllComponents' }); + expect(Date.now() - started).toBeLessThan(200); + socket.close(); + }); + + it('closes as unresponsive after three missed pings in a row', async () => { + const server = new FakeAltServer(); + silentAfterStartup(server); + const socket = await AltSocket.connect(opts(server, { heartbeatMs: 10, heartbeatTimeoutMs: 5 })); + const closes: string[] = []; + socket.onClose((i) => closes.push(i.kind)); + await wait(150); + expect(closes).toEqual(['unresponsive']); + expect(server.commandsNamed('getServerVersion').length).toBeGreaterThanOrEqual(3); + }); + + it('a ping that answers resets the miss count', async () => { + const server = new FakeAltServer(); + let n = 0; + // startup answer, then silent, silent, answer, silent, silent, answer, ...: never three misses in a row + server.on('getServerVersion', () => (n++ % 3 === 0 ? [{ data: '2.3.3' }] : 'silent')); + const socket = await AltSocket.connect(opts(server, { heartbeatMs: 10, heartbeatTimeoutMs: 5 })); + const closes: string[] = []; + socket.onClose((i) => closes.push(i.kind)); + await wait(200); + expect(closes).toEqual([]); + socket.close(); + }); + + it('does not ping while the app is paused', async () => { + const server = new FakeAltServer(); + silentAfterStartup(server); + const socket = await AltSocket.connect(opts(server, { heartbeatMs: 10, heartbeatTimeoutMs: 5 })); + server.last().notify('applicationPausedNotification', true); + const before = server.commandsNamed('getServerVersion').length; + await wait(80); + expect(server.commandsNamed('getServerVersion').length).toBe(before); + expect(socket.paused).toBe(true); + socket.close(); + }); +}); diff --git a/src/AltSocket.ts b/src/AltSocket.ts index cacedea..5c2634a 100644 --- a/src/AltSocket.ts +++ b/src/AltSocket.ts @@ -3,7 +3,7 @@ // (AltDriverController.cs): one command in flight, FIFO, consecutive duplicate reads collapse, // 60 s timeout, reads retried up to twice on timeout, inputs never retried. -import { closedByClient, connectFailed, describeClose, type CloseInfo } from './closeCodes'; +import { appStoppedAnswering, closedByClient, connectFailed, describeClose, type CloseInfo } from './closeCodes'; import { AltTimeoutError, createAltError, createConnectionError } from './errors'; import { buildConnectionUrl, type AppSelector, type ServerAddress } from './connectionUrl'; import { defaultWebSocket, WS_OPEN, type WebSocketCtor, type WebSocketLike } from './socketTypes'; @@ -19,6 +19,11 @@ export interface ConnectOptions extends ServerAddress, AppSelector { maxRetries?: number; /** Interval for a liveness `getServerVersion` while idle; 0 disables (default). */ heartbeatMs?: number; + /** + * How long one liveness ping may hold the command slot (default 5 s, capped at `heartbeatMs`). + * After 3 missed pings in a row the socket closes with kind 'unresponsive'. + */ + heartbeatTimeoutMs?: number; /** NotificationType values activated after registration (default [0, 1, 3], as Desktop does). */ startupNotifications?: readonly number[]; /** Merge a read into an identical read still waiting in the queue (default true). */ @@ -50,6 +55,9 @@ export type NotificationName = /** NotificationType values for activateNotification (LOADSCENE, UNLOADSCENE, APPLICATION_PAUSED). */ const STARTUP_NOTIFICATIONS = [0, 1, 3]; +/** Missed liveness pings in a row before the socket gives up on the app. */ +const HEARTBEAT_MAX_MISSES = 3; + // Moved to errors.ts; re-exported here for existing imports. export { AltConnectionError, AltError, AltTimeoutError } from './errors'; @@ -116,7 +124,10 @@ export class AltSocket { private constructor( private readonly ws: WebSocketLike, private readonly options: Required< - Pick + Pick< + ConnectOptions, + 'commandTimeoutMs' | 'maxRetries' | 'startupNotifications' | 'collapseReads' | 'delayAfterCommandMs' | 'heartbeatTimeoutMs' + > >, ) {} @@ -127,6 +138,7 @@ export class AltSocket { const ws = new Impl(url); const socket = new AltSocket(ws, { commandTimeoutMs: opts.commandTimeoutMs ?? 60_000, + heartbeatTimeoutMs: opts.heartbeatTimeoutMs ?? 5_000, maxRetries: opts.maxRetries ?? 2, startupNotifications: opts.startupNotifications ?? STARTUP_NOTIFICATIONS, collapseReads: opts.collapseReads ?? true, @@ -208,8 +220,12 @@ export class AltSocket { } close(): void { + this.closeWith(closedByClient()); + } + + private closeWith(info: CloseInfo): void { if (this.closeInfo) return; - this.handleClose(closedByClient()); + this.handleClose(info); try { this.ws.close(1000); } catch { @@ -303,9 +319,24 @@ export class AltSocket { } private startHeartbeat(ms: number): void { + const timeoutMs = Math.min(this.options.heartbeatTimeoutMs, ms); + let misses = 0; + let pinging = false; this.heartbeat = setInterval(() => { - if (this.inFlight || this.queue.length) return; - this.send({ commandName: 'getServerVersion', kind: 'input' }).catch(() => undefined); + if (pinging || this.inFlight || this.queue.length || this._paused) return; + pinging = true; + this.send({ commandName: 'getServerVersion', kind: 'input', timeoutMs }).then( + () => { + pinging = false; + misses = 0; + }, + (e) => { + pinging = false; + if (!(e instanceof AltTimeoutError)) return; // closed, or an error reply: the app is alive + misses += 1; + if (misses >= HEARTBEAT_MAX_MISSES) this.closeWith(appStoppedAnswering()); + }, + ); }, ms); } diff --git a/src/LiveUpdateSocket.test.ts b/src/LiveUpdateSocket.test.ts index e9c210c..6194cf7 100644 --- a/src/LiveUpdateSocket.test.ts +++ b/src/LiveUpdateSocket.test.ts @@ -3,7 +3,7 @@ import { FakeAltServer, flush } from '../test/fakeAltServer'; import type { CloseInfo } from './closeCodes'; import { FrameUrls, LiveUpdateSocket } from './LiveUpdateSocket'; -function setup(server = new FakeAltServer()) { +function setup(server = new FakeAltServer(), extra: { openTimeoutMs?: number } = {}) { const frames: ArrayBuffer[] = []; const closes: CloseInfo[] = []; const live = new LiveUpdateSocket({ @@ -14,11 +14,33 @@ function setup(server = new FakeAltServer()) { WebSocketImpl: server.WebSocket, onFrame: (f) => frames.push(f), onClose: (i) => closes.push(i), + ...extra, }); return { server, live, frames, closes }; } describe('LiveUpdateSocket', () => { + it('reports unreachable when the socket never opens within openTimeoutMs', async () => { + const { closes } = setup(new FakeAltServer({ scheme: 'wss', stallWrongScheme: true }), { openTimeoutMs: 20 }); + await new Promise((r) => setTimeout(r, 40)); + expect(closes.map((c) => c.kind)).toEqual(['unreachable']); + }); + + it('reports notRegistered when the socket opens but the server never registers it', async () => { + const { server, closes } = setup(new FakeAltServer({ register: false }), { openTimeoutMs: 20 }); + await new Promise((r) => setTimeout(r, 40)); + expect(closes.map((c) => c.kind)).toEqual(['notRegistered']); + expect(server.last('/altws/live-update').sent).toEqual([]); + }); + + it('does not time out once the stream has started', async () => { + const { live, closes } = setup(new FakeAltServer(), { openTimeoutMs: 20 }); + await new Promise((r) => setTimeout(r, 40)); + expect(live.isStarted).toBe(true); + expect(closes).toEqual([]); + live.stop(); + }); + it('sends Quality:25, FrameRate:10, Start in that order after driverRegistered, with the app params', async () => { const { server, live } = setup(); await flush(5); diff --git a/src/LiveUpdateSocket.ts b/src/LiveUpdateSocket.ts index 9efb7c0..edcdffe 100644 --- a/src/LiveUpdateSocket.ts +++ b/src/LiveUpdateSocket.ts @@ -15,6 +15,11 @@ export interface LiveUpdateOptions extends ServerAddress, AppSelector { /** Called with each frame's JPEG bytes. */ onFrame: (jpeg: ArrayBuffer) => void; onClose?: (info: CloseInfo) => void; + /** + * How long to wait for the socket to open and the server to register this driver (default 5 s). + * A host that drops packets, or a wss:// connect to a plain ws server, otherwise never ends. + */ + openTimeoutMs?: number; } export class LiveUpdateSocket { @@ -22,10 +27,12 @@ export class LiveUpdateSocket { private started = false; private opened = false; private closed = false; + private openTimer: ReturnType | null = null; constructor(private readonly opts: LiveUpdateOptions) { const Impl = opts.WebSocketImpl ?? defaultWebSocket(); this.ws = new Impl(buildConnectionUrl(opts, '/altws/live-update', opts, opts.driverType)); + this.openTimer = setTimeout(() => this.openTimedOut(), opts.openTimeoutMs ?? 5_000); this.ws.binaryType = 'arraybuffer'; this.ws.onopen = () => { this.opened = true; @@ -56,6 +63,7 @@ export class LiveUpdateSocket { /** Stops the stream (only if this client started it) and closes the socket. */ stop(): void { + this.clearOpenTimer(); if (this.closed) return; if (this.started) this.sendText('Stop'); this.started = false; @@ -68,6 +76,7 @@ export class LiveUpdateSocket { } private begin(): void { + this.clearOpenTimer(); this.sendText(`Quality:${Math.round(this.opts.quality ?? 25)}`); this.sendText(`FrameRate:${Math.round(this.opts.frameRate ?? 10)}`); this.sendText('Start'); @@ -83,7 +92,35 @@ export class LiveUpdateSocket { } } + private openTimedOut(): void { + this.openTimer = null; + if (this.closed || this.started) return; + const info: CloseInfo = this.opened + ? { + code: 0, + kind: 'notRegistered', + message: 'The server is reachable but did not register the live view in time.', + serverReason: '', + } + : connectFailed(); + this.ws.onopen = null; + this.ws.onerror = null; + this.ws.onclose = null; + try { + this.ws.close(); + } catch { + // never opened + } + this.finish(info); + } + + private clearOpenTimer(): void { + if (this.openTimer) clearTimeout(this.openTimer); + this.openTimer = null; + } + private finish(info: CloseInfo): void { + this.clearOpenTimer(); if (this.closed) return; this.closed = true; this.started = false; diff --git a/src/binding/AltDriver.ts b/src/binding/AltDriver.ts index f41b9a8..98b486c 100644 --- a/src/binding/AltDriver.ts +++ b/src/binding/AltDriver.ts @@ -411,7 +411,9 @@ export class AltDriver { width = 1, quality = 100, ): Promise { + // Never retried: the app cycles through stacked hits at a point, so a repeat selects the next one. const frames = await this._sendFrames('hightlightObjectFromCoordinatesScreenshot', { coordinates, color, width, size: { x: 0, y: 0 }, quality }, { + input: true, responses: 3, expect: [undefined, 'Ok'], }); diff --git a/src/closeCodes.ts b/src/closeCodes.ts index dcbdd8f..0bfa2cf 100644 --- a/src/closeCodes.ts +++ b/src/closeCodes.ts @@ -119,3 +119,11 @@ export const serverStoppedAnswering = (): CloseInfo => ({ message: 'The server stopped answering. Check that AltTesterĀ® Server is still running, then connect again.', serverReason: '', }); + +/** The driver socket is open but the app stopped answering the liveness pings. */ +export const appStoppedAnswering = (): CloseInfo => ({ + code: 0, + kind: 'unresponsive', + message: 'The app stopped answering. Check that it is still running, then connect again.', + serverReason: '', +}); diff --git a/src/commands.test.ts b/src/commands.test.ts index 50ea353..ac31906 100644 --- a/src/commands.test.ts +++ b/src/commands.test.ts @@ -320,6 +320,32 @@ describe('AltDriver retries', () => { socket.close(); }); + it('a timed-out select-from-screen is not retried, so it cannot cycle to the next stacked object', async () => { + const { server, socket, driver } = await setup('unity', 30); + server.on('hightlightObjectFromCoordinatesScreenshot', () => 'silent'); + const err = await driver.hightlightObjectFromCoordinatesScreenshot({ x: 1, y: 1 }).catch((e) => e); + expect(err).toBeInstanceOf(AltTimeoutError); + expect(server.commandsNamed('hightlightObjectFromCoordinatesScreenshot')).toHaveLength(1); + socket.close(); + }); + + it('two select-from-screen clicks at one point are both sent, not collapsed', async () => { + const { server, socket, driver } = await setup(); + let n = 0; + server.on('hightlightObjectFromCoordinatesScreenshot', () => [ + { data: { name: `Hit${++n}`, id: n } }, + { data: 'Ok' }, + { data: { textureSize: { x: 1, y: 1 }, compressedImage: '' } }, + ]); + const [a, b, c] = await Promise.all([ + driver.hightlightObjectFromCoordinatesScreenshot({ x: 1, y: 1 }), + driver.hightlightObjectFromCoordinatesScreenshot({ x: 1, y: 1 }), + driver.hightlightObjectFromCoordinatesScreenshot({ x: 1, y: 1 }), + ]); + expect([a.object?.name, b.object?.name, c.object?.name]).toEqual(['Hit1', 'Hit2', 'Hit3']); + socket.close(); + }); + it('a timed-out getAllComponents is retried twice', async () => { const { server, socket, driver } = await setup('unity', 30); server.on('getAllComponents', () => 'silent'); diff --git a/src/commands.ts b/src/commands.ts index bce8811..0954fe9 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -87,7 +87,10 @@ export class AltDriver { return this.send('hightlightObjectScreenshot', { altObjectId, color, width, size: SIZE_IGNORED, quality }, { responses: 2 }); } - /** Repeated calls at the same point cycle through stacked hits (app-side state). */ + /** + * Repeated calls at the same point cycle through stacked hits (app-side state). So this is sent as an + * input command: a retry, or two clicks collapsed into one, would land on the wrong stacked object. + */ hightlightObjectFromCoordinatesScreenshot( coordinates: AltVector2, color: AltColor = HIGHLIGHT_COLOR, @@ -98,6 +101,7 @@ export class AltDriver { 'hightlightObjectFromCoordinatesScreenshot', { coordinates, color, width, size: SIZE_IGNORED, quality }, { + kind: 'input', responses: 3, select: (frames) => { const hit = frames[0] as AltObject | null;