Skip to content

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

chore(cli): make sure open starts daemon and run does not (#39396)

Pavel Feldman49d2906f9ece
diff --git a/packages/playwright/src/cli/client/program.ts b/packages/playwright/src/cli/client/program.ts
index 9cc6afd3a9..cd37b22fb2 100644
--- a/packages/playwright/src/cli/client/program.ts
+++ b/packages/playwright/src/cli/client/program.ts
@@ -169,7 +169,7 @@ export async function program(options?: { embedderVersion?: string}) {
for (const globalOption of globalOptions)
delete args[globalOption];
- const result = await session.run(clientInfo, args);
+ const result = await session.open(args);
console.log(result.text);
return;
}
@@ -209,7 +209,8 @@ export async function program(options?: { embedderVersion?: string}) {
for (const globalOption of globalOptions)
delete args[globalOption];
- const result = await new Session(defaultEntry).run(clientInfo, args);
+ const session = new Session(defaultEntry);
+ const result = await session.run(clientInfo, args);
console.log(result.text);
}
}
@@ -321,7 +322,7 @@ function sessionConfigFromArgs(clientInfo: ClientInfo, sessionName: string, args
return {
name: sessionName,
version: clientInfo.version,
- timestamp: 0,
+ timestamp: Date.now(),
socketPath: daemonSocketPath(clientInfo, sessionName),
cli: {
headed: args.headed,
diff --git a/packages/playwright/src/cli/client/session.ts b/packages/playwright/src/cli/client/session.ts
index a520eeab2b..44ca7f42c9 100644
--- a/packages/playwright/src/cli/client/session.ts
+++ b/packages/playwright/src/cli/client/session.ts
@@ -37,9 +37,6 @@ export class Session {
readonly name: string;
readonly config: SessionConfig;
private _sessionFile: SessionFile;
- private _connection: SocketConnection | undefined;
- private _nextMessageId = 1;
- private _callbacks = new Map<number, { resolve: (o: any) => void, reject: (e: Error) => void, method: string, params: any }>();
constructor(sessionFile: SessionFile) {
this.config = sessionFile.config;
@@ -51,26 +48,19 @@ export class Session {
return compareSemver(clientInfo.version, this.config.version) >= 0;
}
- checkCompatible(clientInfo: ClientInfo) {
- if (!this.isCompatible(clientInfo)) {
- throw new Error(`Client is v${clientInfo.version}, session '${this.name}' is v${this.config.version}. Run
-
- playwright-cli${this.name !== 'default' ? ` -s=${this.name}` : ''} open
-
-to restart the browser session.`);
- }
- }
-
- async open(): Promise<void> {
- await this._startDaemonIfNeeded();
- this.disconnect();
+ async open(args: MinimistArgs, cwd?: string): Promise<{ text: string }> {
+ const socket = await this._startDaemon();
+ return await SocketConnectionClient.sendAndClose(socket, 'run', { args, cwd: cwd || process.cwd() });
}
async run(clientInfo: ClientInfo, args: MinimistArgs, cwd?: string): Promise<{ text: string }> {
- this.checkCompatible(clientInfo);
- const result = await this._send('run', { args, cwd: cwd || process.cwd() });
- this.disconnect();
- return result;
+ if (!this.isCompatible(clientInfo))
+ throw new Error(`Client is v${clientInfo.version}, session '${this.name}' is v${this.config.version}. Run\n\n playwright-cli${this.name !== 'default' ? ` -s=${this.name}` : ''} open\n\nto restart the browser session.`);
+
+ const { socket } = await this._connect();
+ if (!socket)
+ throw new Error(`Browser '${this.name}' is not open. Run\n\n playwright-cli${this.name !== 'default' ? ` -s=${this.name}` : ''} open\n\nto start the browser session.`);
+ return await SocketConnectionClient.sendAndClose(socket, 'run', { args, cwd: cwd || process.cwd() });
}
async stop(quiet: boolean = false): Promise<void> {
@@ -85,32 +75,6 @@ to restart the browser session.`);
console.log(`Browser '${this.name}' closed\n`);
}
- private async _send(method: string, params: any = {}): Promise<any> {
- const connection = await this._startDaemonIfNeeded();
- const messageId = this._nextMessageId++;
- const message = {
- id: messageId,
- method,
- params,
- version: this.config.version,
- };
- const responsePromise = new Promise<any>((resolve, reject) => {
- this._callbacks.set(messageId, { resolve, reject, method, params });
- });
- const [result] = await Promise.all([responsePromise, connection.send(message)]);
- return result;
- }
-
- disconnect() {
- if (!this._connection)
- return;
- for (const callback of this._callbacks.values())
- callback.reject(new Error('Session closed'));
- this._callbacks.clear();
- this._connection.close();
- this._connection = undefined;
- }
-
async deleteData() {
await this.stop();
@@ -142,7 +106,7 @@ to restart the browser session.`);
}
}
- async _connect(): Promise<{ socket?: net.Socket, error?: Error }> {
+ private async _connect(): Promise<{ socket?: net.Socket, error?: Error }> {
return await new Promise(resolve => {
const socket = net.createConnection(this.config.socketPath, () => {
resolve({ socket });
@@ -165,44 +129,12 @@ to restart the browser session.`);
return false;
}
- private async _startDaemonIfNeeded() {
- if (this._connection)
- return this._connection;
-
- let { socket } = await this._connect();
- if (!socket)
- socket = await this._startDaemon();
-
- this._connection = new SocketConnection(socket);
- this._connection.onmessage = message => this._onMessage(message);
- this._connection.onclose = () => this.disconnect();
- return this._connection;
- }
-
- private _onMessage(object: { id: number, error?: string, result: any }) {
- if (object.id && this._callbacks.has(object.id)) {
- const callback = this._callbacks.get(object.id)!;
- this._callbacks.delete(object.id);
- if (object.error)
- callback.reject(new Error(object.error));
- else
- callback.resolve(object.result);
- } else if (object.id) {
- throw new Error(`Unexpected message id: ${object.id}`);
- } else {
- throw new Error(`Unexpected message without id: ${JSON.stringify(object)}`);
- }
- }
-
private async _startDaemon(): Promise<net.Socket> {
await fs.promises.mkdir(this._sessionFile.daemonDir, { recursive: true });
const cliPath = path.join(__dirname, '../../../cli.js');
-
- this.config.version = this.config.version;
- this.config.timestamp = Date.now();
await fs.promises.writeFile(this._sessionFile.file, JSON.stringify(this.config, null, 2));
- const errLog = this._sessionFile.file.replace('.session', '.err');
+ const errLog = this._sessionFile.file.replace(/\.session$/, '.err');
const err = fs.openSync(errLog, 'w');
const args = [
@@ -279,12 +211,16 @@ to restart the browser session.`);
}
private async _stopDaemon(): Promise<void> {
+ const { socket, error: socketError } = await this._connect();
+ if (!socket) {
+ console.log(`Browser '${this.name}' is not open.${socketError ? ' Error: ' + socketError.message : ''}`);
+ return;
+ }
+
let error: Error | undefined;
- await this._send('stop').catch(e => { error = e; });
+ await SocketConnectionClient.sendAndClose(socket, 'stop', {}).catch(e => error = e);
if (os.platform() !== 'win32')
await fs.promises.unlink(this.config.socketPath).catch(() => {});
-
- this.disconnect();
if (!this.config.cli.persistent)
await this.deleteSessionConfig();
if (error && !error?.message?.includes('Session closed'))
@@ -325,3 +261,63 @@ async function parseResolvedConfig(errLog: string): Promise<FullConfig | null> {
return null;
}
}
+
+class SocketConnectionClient {
+ private _connection: SocketConnection;
+ private _nextMessageId = 1;
+ private _callbacks = new Map<number, { resolve: (o: any) => void, reject: (e: Error) => void, method: string, params: any }>();
+
+ constructor(socket: net.Socket) {
+ this._connection = new SocketConnection(socket);
+ this._connection.onmessage = message => this._onMessage(message);
+ this._connection.onclose = () => this._rejectCallbacks();
+ }
+
+ async send(method: string, params: any = {}): Promise<any> {
+ const messageId = this._nextMessageId++;
+ const message = {
+ id: messageId,
+ method,
+ params,
+ };
+ const responsePromise = new Promise<any>((resolve, reject) => {
+ this._callbacks.set(messageId, { resolve, reject, method, params });
+ });
+ const [result] = await Promise.all([responsePromise, this._connection.send(message)]);
+ return result;
+ }
+
+ static async sendAndClose(socket: net.Socket, method: string, params: any = {}): Promise<any> {
+ const connection = new SocketConnectionClient(socket);
+ try {
+ return await connection.send(method, params);
+ } finally {
+ connection.close();
+ }
+ }
+
+ close() {
+ this._connection.close();
+ }
+
+ private _onMessage(object: { id: number, error?: string, result: any }) {
+ if (object.id && this._callbacks.has(object.id)) {
+ const callback = this._callbacks.get(object.id)!;
+ this._callbacks.delete(object.id);
+ if (object.error)
+ callback.reject(new Error(object.error));
+ else
+ callback.resolve(object.result);
+ } else if (object.id) {
+ throw new Error(`Unexpected message id: ${object.id}`);
+ } else {
+ throw new Error(`Unexpected message without id: ${JSON.stringify(object)}`);
+ }
+ }
+
+ private _rejectCallbacks() {
+ for (const callback of this._callbacks.values())
+ callback.reject(new Error('Session closed'));
+ this._callbacks.clear();
+ }
+}