import { createServer, type Server } from 'node:http'; import { once } from 'node:events'; import type { AddressInfo } from 'node:net'; import { WebSocketServer } from 'ws'; import { createInstanceClient, type InstanceClient } from '../src/instance-client'; describe('Android performance captures', () => { let server: Server; let signaling: WebSocketServer; let client: InstanceClient; let requests: Array>; let commandError: { code: string; message: string } | undefined; beforeEach(async () => { requests = []; commandError = undefined; server = createServer((_req, res) => res.writeHead(404).end()); signaling = new WebSocketServer({ server, path: '/android/api/ws' }); signaling.on('connection', (socket) => { socket.on('message', (data) => { const message = JSON.parse(data.toString()); if (!message.type.includes('PerformanceCapture')) return; requests.push(message); socket.send( JSON.stringify({ type: `${message.type}Result`, id: message.id, ...(commandError ? { error: { ...commandError, retriable: false } } : message.type === 'startPerformanceCapture' ? { payload: { captureId: 'perf-1' } } : { payload: {} }), }), ); }); }); server.listen(0, '127.0.0.1'); await once(server, 'listening'); const apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/android/api`; client = await createInstanceClient({ apiUrl, token: 'instance-token', logLevel: 'none' }); }); afterEach(async () => { client.disconnect(); for (const socket of signaling.clients) socket.terminate(); await new Promise((resolve) => signaling.close(() => resolve())); await new Promise((resolve) => server.close(() => resolve())); }); test('starts with a TTL and stops with no fields, as on iOS', async () => { await client.startPerformanceCapture({ ttlSeconds: 3600 }); await client.stopPerformanceCapture(); await client.startPerformanceCapture(); expect(requests.map((r) => r['type'])).toEqual([ 'startPerformanceCapture', 'stopPerformanceCapture', 'startPerformanceCapture', ]); expect(requests[0]).toMatchObject({ ttlSeconds: 3600, payload: { ttlSeconds: 3600 } }); // A performance capture always persists, so neither message carries persist. expect(requests[0]).not.toHaveProperty('persist'); expect(Object.keys(requests[1]!).sort()).toEqual(['id', 'type']); expect(Object.keys(requests[2]!).sort()).toEqual(['id', 'type']); }); test('rejects a TTL that is not a positive integer before sending', async () => { await expect(client.startPerformanceCapture({ ttlSeconds: 0 })).rejects.toThrow(); expect(requests).toEqual([]); }); test('surfaces the runtime refusing a second capture', async () => { commandError = { code: 'capture_already_active', message: 'A performance capture is already active' }; await expect(client.startPerformanceCapture()).rejects.toThrow(/already active/); }); });