Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

chore: refactor httpServer ws transport (#40181)

Simon Knott07dd357e77bb
diff --git a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
index 019fefffcd..a7d1f70ee5 100644
--- a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
+++ b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
@@ -231,23 +231,25 @@ class StdinServer implements Transport {
onconnect() {
}
- async dispatch(method: string, params: any) {
+ onmessage(message: string) {
+ const { id, method } = JSON.parse(message);
if (method === 'initialize') {
if (this._traceUrl)
this._loadTrace(this._traceUrl);
}
+ this.sendMessage?.(JSON.stringify({ id }));
}
onclose() {
}
- sendEvent?: (method: string, params: any) => void;
+ sendMessage?: (message: string) => void;
close?: () => void;
private _loadTrace(traceUrl: string) {
this._traceUrl = traceUrl;
clearTimeout(this._pollTimer);
- this.sendEvent?.('loadTraceRequested', { traceUrl });
+ this.sendMessage?.(JSON.stringify({ method: 'loadTraceRequested', params: { traceUrl } }));
}
private _pollLoadTrace(url: string) {
diff --git a/packages/playwright-core/src/tools/dashboard/dashboardController.ts b/packages/playwright-core/src/tools/dashboard/dashboardController.ts
index 9fb79198cc..3f61d74e50 100644
--- a/packages/playwright-core/src/tools/dashboard/dashboardController.ts
+++ b/packages/playwright-core/src/tools/dashboard/dashboardController.ts
@@ -25,7 +25,7 @@ import type { BrowserDescriptor } from '../../serverRegistry';
export class DashboardConnection implements Transport, DashboardChannel {
readonly version = 1;
- sendEvent?: (method: string, params: any) => void;
+ sendMessage?: (message: string) => void;
close?: () => void;
selectedPage: api.Page | null = null;
@@ -63,7 +63,7 @@ export class DashboardConnection implements Transport, DashboardChannel {
}
private _emit<K extends keyof DashboardChannelEvents>(event: K, params: DashboardChannelEvents[K]): void {
- this.sendEvent?.(event, params);
+ this.sendMessage?.(JSON.stringify({ method: event, params }));
const set = this._eventListeners.get(event);
if (set) {
for (const fn of set)
@@ -104,10 +104,16 @@ export class DashboardConnection implements Transport, DashboardChannel {
this._browser?.close().catch(() => {});
}
- async dispatch(method: string, params: any): Promise<any> {
+ async onmessage(message: string) {
+ const { id, method, params } = JSON.parse(message);
await this._initPromise;
- // eslint-disable-next-line no-restricted-syntax
- return (this as any)[method]?.(params);
+ try {
+ // eslint-disable-next-line no-restricted-syntax
+ const result = await (this as any)[method]?.(params);
+ this.sendMessage?.(JSON.stringify({ id, result }));
+ } catch (e) {
+ this.sendMessage?.(JSON.stringify({ id, error: String(e) }));
+ }
}
async selectTab(params: { pageId: string }) {
@@ -311,7 +317,7 @@ async function getBrowserRevision(page: api.Page): Promise<string | null> {
}
export class CDPConnection implements Transport {
- sendEvent?: (method: string, params: any) => void;
+ sendMessage?: (message: string) => void;
close?: () => void;
private _page: api.Page;
@@ -327,11 +333,17 @@ export class CDPConnection implements Transport {
this._initializePromise = this._initializeRawSession();
}
- async dispatch(method: string, params: any): Promise<any> {
+ async onmessage(message: string) {
+ const { id, method, params } = JSON.parse(message);
await this._initializePromise;
if (!this._rawSession)
throw new Error('CDP session is not initialized');
- return await this._rawSession.send(method as Parameters<api.CDPSession['send']>[0], params);
+ try {
+ const result = await this._rawSession.send(method as Parameters<api.CDPSession['send']>[0], params);
+ this.sendMessage?.(JSON.stringify({ id, result }));
+ } catch (e) {
+ this.sendMessage?.(JSON.stringify({ id, error: String(e) }));
+ }
}
onclose() {
@@ -346,7 +358,7 @@ export class CDPConnection implements Transport {
this._rawSession = session;
this._rawSessionListeners = [
eventsHelper.addEventListener(session, 'event', ({ method, params }) => {
- this.sendEvent?.(method, params);
+ this.sendMessage?.(JSON.stringify({ method, params }));
}),
eventsHelper.addEventListener(session, 'close', () => {
this.close?.();
diff --git a/packages/playwright/src/runner/testServer.ts b/packages/playwright/src/runner/testServer.ts
index e5cb70a98e..d6e8c0e80e 100644
--- a/packages/playwright/src/runner/testServer.ts
+++ b/packages/playwright/src/runner/testServer.ts
@@ -105,14 +105,22 @@ export class TestServerDispatcher implements TestServerInterface {
this._testRunner = new TestRunner(configLocation, configCLIOverrides);
this.transport = {
onconnect: () => {},
- dispatch: (method, params) => (this as any)[method](params),
+ onmessage: async message => {
+ const { id, method, params } = JSON.parse(message);
+ try {
+ const result = await (this as any)[method](params);
+ this.transport.sendMessage?.(JSON.stringify({ id, result }));
+ } catch (e) {
+ this.transport.sendMessage?.(JSON.stringify({ id, error: String(e) }));
+ }
+ },
onclose: () => {
if (this._closeOnDisconnect)
gracefullyProcessExitDoNotHang(0);
},
};
- this._dispatchEvent = (method, params) => this.transport.sendEvent?.(method, params);
+ this._dispatchEvent = (method, params) => this.transport.sendMessage?.(JSON.stringify({ method, params }));
this._testRunner.on(TestRunnerEvent.TestFilesChanged, testFiles => this._dispatchEvent('testFilesChanged', { testFiles }));
this._testRunner.on(TestRunnerEvent.TestPaused, params => this._dispatchEvent('testPaused', { errors: params.errors }));
}
diff --git a/packages/playwright/src/runner/watchMode.ts b/packages/playwright/src/runner/watchMode.ts
index 706a7ceb39..d405187c8d 100644
--- a/packages/playwright/src/runner/watchMode.ts
+++ b/packages/playwright/src/runner/watchMode.ts
@@ -38,9 +38,9 @@ import type { TestServerTransport } from '../isomorphic/testServerConnection';
/* eslint-disable no-restricted-properties */
class InMemoryTransport extends EventEmitter implements TestServerTransport {
- public readonly _send: (data: string) => void;
+ public readonly _send: (message: string) => void;
- constructor(send: (data: any) => void) {
+ constructor(send: (message: string) => void) {
super();
this._send = send;
}
@@ -81,19 +81,9 @@ export async function runWatchModeLoop(configLocation: ConfigLocation, initialOp
let bufferMode = false;
const testServerDispatcher = new TestServerDispatcher(configLocation, {});
- const transport = new InMemoryTransport(
- async data => {
- const { id, method, params } = JSON.parse(data);
- try {
- const result = await testServerDispatcher.transport.dispatch(method, params);
- transport.emit('message', JSON.stringify({ id, result }));
- } catch (e) {
- transport.emit('message', JSON.stringify({ id, error: String(e) }));
- }
- }
- );
- testServerDispatcher.transport.sendEvent = (method, params) => {
- transport.emit('message', JSON.stringify({ method, params }));
+ const transport = new InMemoryTransport(message => testServerDispatcher.transport.onmessage(message));
+ testServerDispatcher.transport.sendMessage = message => {
+ transport.emit('message', message);
};
const testServerConnection = new TestServerConnection(transport);
transport.emit('open');
diff --git a/packages/utils/httpServer.ts b/packages/utils/httpServer.ts
index b62dc2d53e..c571143410 100644
--- a/packages/utils/httpServer.ts
+++ b/packages/utils/httpServer.ts
@@ -28,10 +28,10 @@ import type http from 'http';
export type ServerRouteHandler = (request: http.IncomingMessage, response: http.ServerResponse) => boolean;
export type Transport = {
- sendEvent?: (method: string, params: any) => void;
+ sendMessage?: (message: string) => void;
close?: () => void;
onconnect: () => void;
- dispatch: (method: string, params: any) => Promise<any>;
+ onmessage: (message: string) => void;
onclose: () => void;
};
@@ -71,18 +71,10 @@ export class HttpServer {
wss.on('connection', (ws, request) => {
const url = new URL(request.url ?? '/', 'http://localhost');
const transport = transportFactory(url);
- transport.sendEvent = (method, params) => ws.send(JSON.stringify({ method, params }));
+ transport.sendMessage = message => ws.send(message);
transport.close = () => ws.close();
transport.onconnect();
- ws.on('message', async message => {
- const { id, method, params } = JSON.parse(String(message));
- try {
- const result = await transport.dispatch(method, params);
- ws.send(JSON.stringify({ id, result }));
- } catch (e) {
- ws.send(JSON.stringify({ id, error: String(e) }));
- }
- });
+ ws.on('message', message => transport.onmessage(String(message)));
ws.on('close', () => transport.onclose());
ws.on('error', () => transport.onclose());
});