Skip to content
Open
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
58 changes: 58 additions & 0 deletions src/AltSocket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
41 changes: 36 additions & 5 deletions src/AltSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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). */
Expand Down Expand Up @@ -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';

Expand Down Expand Up @@ -116,7 +124,10 @@ export class AltSocket {
private constructor(
private readonly ws: WebSocketLike,
private readonly options: Required<
Pick<ConnectOptions, 'commandTimeoutMs' | 'maxRetries' | 'startupNotifications' | 'collapseReads' | 'delayAfterCommandMs'>
Pick<
ConnectOptions,
'commandTimeoutMs' | 'maxRetries' | 'startupNotifications' | 'collapseReads' | 'delayAfterCommandMs' | 'heartbeatTimeoutMs'
>
>,
) {}

Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
}

Expand Down
24 changes: 23 additions & 1 deletion src/LiveUpdateSocket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand All @@ -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);
Expand Down
37 changes: 37 additions & 0 deletions src/LiveUpdateSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,24 @@ 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 {
private readonly ws: WebSocketLike;
private started = false;
private opened = false;
private closed = false;
private openTimer: ReturnType<typeof setTimeout> | 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;
Expand Down Expand Up @@ -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;
Expand All @@ -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');
Expand All @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions src/binding/AltDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,9 @@ export class AltDriver {
width = 1,
quality = 100,
): Promise<HighlightedScreenshotAt> {
// 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'],
});
Expand Down
8 changes: 8 additions & 0 deletions src/closeCodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '',
});
26 changes: 26 additions & 0 deletions src/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
6 changes: 5 additions & 1 deletion src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;
Expand Down
Loading