Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore(sockets): unify socket path computation via makeSocketPath (#39851)
Yury Semikhatskyae2c141bf556
diff --git a/packages/playwright-core/src/server/browser.ts b/packages/playwright-core/src/server/browser.tsindex 0ebca4d41b..645eafc715 100644--- a/packages/playwright-core/src/server/browser.ts+++ b/packages/playwright-core/src/server/browser.ts@@ -15,8 +15,6 @@*/import fs from 'fs';-import path from 'path';-import os from 'os';import { Artifact } from './artifact';import { BrowserContext, validateBrowserContextOptions } from './browserContext';@@ -27,6 +25,7 @@ import { ClientCertificatesProxy } from './socksClientCertificatesInterceptor';import { PlaywrightPipeServer } from '../remote/playwrightPipeServer';import { PlaywrightWebSocketServer } from '../remote/playwrightWebSocketServer';import { BrowserInfo, serverRegistry } from '../serverRegistry';+import { makeSocketPath } from './utils/fileUtils';import type * as types from './types';import type { ProxySettings } from './types';@@ -257,12 +256,7 @@ export class BrowserServer {}private async _socketPath() {- const socketName = `${this._browser.guid.slice(0, 14)}.sock`;- if (process.platform === 'win32')- return `\\\\.\\pipe\\${socketName}`;- const socketsDir = process.env.PLAYWRIGHT_BROWSER_SOCKETS_DIR || path.join(os.tmpdir(), 'playwright');- await fs.promises.mkdir(socketsDir, { recursive: true });- return path.join(socketsDir, socketName);+ return makeSocketPath('browser', this._browser.guid.slice(0, 14));}}diff --git a/packages/playwright-core/src/server/utils/fileUtils.ts b/packages/playwright-core/src/server/utils/fileUtils.tsindex 3eab2c0366..7317677981 100644--- a/packages/playwright-core/src/server/utils/fileUtils.ts+++ b/packages/playwright-core/src/server/utils/fileUtils.ts@@ -15,8 +15,11 @@*/import fs from 'fs';+import os from 'os';import path from 'path';+import { calculateSha1 } from './crypto';+import { ManualPromise } from '../../utils/isomorphic/manualPromise';import { yazl } from '../../zipBundle';@@ -60,6 +63,17 @@ export function toPosixPath(aPath: string): string {return aPath.split(path.sep).join(path.posix.sep);}+export function makeSocketPath(domain: string, name: string): string {+ const userNameHash = calculateSha1(process.env.USERNAME || process.env.USER || 'default').slice(0, 8);+ if (process.platform === 'win32')+ return `\\\\.\\pipe\\pw-${userNameHash}-${domain}-${name}`;+ const baseDir = process.env.PLAYWRIGHT_SOCKETS_DIR || path.join(os.tmpdir(), `pw-${userNameHash}`);+ const dir = path.join(baseDir, domain);+ const result = path.join(dir, `${name}.sock`);+ fs.mkdirSync(dir, { recursive: true });+ return result;+}+type NameValue = { name: string, value: string };type SerializedFSOperation = {op: 'mkdir', dir: string,diff --git a/packages/playwright-core/src/tools/cli-daemon/daemon.ts b/packages/playwright-core/src/tools/cli-daemon/daemon.tsindex 60518b49bb..15cb5df3e1 100644--- a/packages/playwright-core/src/tools/cli-daemon/daemon.ts+++ b/packages/playwright-core/src/tools/cli-daemon/daemon.ts@@ -16,13 +16,10 @@import fs from 'fs';import net from 'net';-import os from 'os';import path from 'path';-import { calculateSha1 } from '../../utils';-import { debug } from '../../utilsBundle';-import { decorateServer } from '../../server/utils/network';+import { makeSocketPath } from '../../server/utils/fileUtils';import { gracefullyProcessExitDoNotHang } from '../../server/utils/processLauncher';import { BrowserBackend } from '../backend/browserBackend';@@ -39,8 +36,6 @@ import type { CallToolRequest, CallToolResult } from '../backend/tool';import type { ContextConfig } from '../backend/context';import type { BrowserInfo } from '../../serverRegistry';-const daemonDebug = debug('pw:daemon');-async function socketExists(socketPath: string): Promise<boolean> {try {const stat = await fs.promises.stat(socketPath);@@ -67,11 +62,9 @@ export async function startCliDaemonServer(// Clean up existing socket file on Unixif (process.platform !== 'win32' && await socketExists(socketPath)) {- daemonDebug(`Socket already exists, removing: ${socketPath}`);try {await fs.promises.unlink(socketPath);} catch (error) {- daemonDebug(`Failed to remove existing socket: ${error}`);throw error;}}@@ -79,23 +72,15 @@ export async function startCliDaemonServer(const backend = new BrowserBackend(contextConfig, browserContext, browserTools);await backend.initialize({ cwd: process.cwd() });- await fs.promises.mkdir(path.dirname(socketPath), { recursive: true });-if (browserContext.isClosed())throw new Error('Browser context was closed before the daemon could start');const server = net.createServer(socket => {- daemonDebug('new client connection');const connection = new SocketConnection(socket);- connection.onclose = () => {- daemonDebug('client disconnected');- };connection.onmessage = async message => {const { id, method, params } = message;try {- daemonDebug('received command', method);if (method === 'stop') {- daemonDebug('stop command received, shutting down');await deleteSessionFile(clientInfo, sessionConfig);const sendAck = async () => connection.send({ id, result: 'ok' }).catch(() => {});if (options?.exitOnClose)@@ -112,7 +97,6 @@ export async function startCliDaemonServer(throw new Error(`Unknown method: ${method}`);}} catch (e) {- daemonDebug('command failed', e);const error = process.env.PWDEBUGIMPL ? (e as Error).stack || (e as Error).message : (e as Error).message;connection.send({ id, error }).catch(() => {});}@@ -127,10 +111,7 @@ export async function startCliDaemonServer(}));await new Promise<void>((resolve, reject) => {- server.on('error', (error: NodeJS.ErrnoException) => {- daemonDebug(`server error: ${error.message}`);- reject(error);- });+ server.on('error', reject);server.listen(socketPath, () => resolve());});@@ -166,12 +147,7 @@ function parseCliCommand(args: Record<string, string> & { _: string[] }): { tool}function daemonSocketPath(clientInfo: ClientInfo, sessionName: string): string {- const userNameHash = calculateSha1(process.env.USERNAME || 'default').slice(0, 8);- const socketName = `${sessionName}-${userNameHash}.sock`;- if (process.platform === 'win32')- return `\\\\.\\pipe\\${clientInfo.workspaceDirHash}-${socketName}`;- const socketsDir = process.env.PLAYWRIGHT_DAEMON_SOCKETS_DIR || path.join(os.tmpdir(), 'playwright-cli');- return path.join(socketsDir, clientInfo.workspaceDirHash, socketName);+ return makeSocketPath('cli', `${clientInfo.workspaceDirHash}-${sessionName}`);}function createSessionConfig(clientInfo: ClientInfo, sessionName: string, browserInfo: BrowserInfo, options: {diff --git a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts b/packages/playwright-core/src/tools/dashboard/dashboardApp.tsindex f2d8d336c6..4bb1ab8bb3 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts@@ -16,15 +16,14 @@import fs from 'fs';import path from 'path';-import os from 'os';import net from 'net';import http from 'http';import { chromium } from '../../..';import { HttpServer } from '../../server/utils/httpServer';+import { makeSocketPath } from '../../server/utils/fileUtils';import { gracefullyProcessExitDoNotHang } from '../../server/utils/processLauncher';import { findChromiumChannelBestEffort, registryDirectory } from '../../server/registry/index';-import { calculateSha1 } from '../../utils';import { CDPConnection, DashboardConnection } from './dashboardController';import { serverRegistry } from '../../serverRegistry';import { connectToBrowserAcrossVersions } from '../utils/connect';@@ -248,15 +247,8 @@ export async function syncLocalStorageWithSettings(page: api.Page, appName: stri`);}-function socketsDirectory() {- return process.env.PLAYWRIGHT_DAEMON_SOCKETS_DIR || path.join(os.tmpdir(), 'playwright-cli');-}-function dashboardSocketPath() {- const userNameHash = calculateSha1(process.env.USERNAME || 'default').slice(0, 8);- return process.platform === 'win32'- ? `\\\\.\\pipe\\playwright-dashboard-${userNameHash}`- : path.join(socketsDirectory(), `dashboard-${userNameHash}.sock`);+ return makeSocketPath('dashboard', 'app');}async function acquireSingleton(): Promise<net.Server> {diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.tsindex 14862722bf..fc82631455 100644--- a/tests/mcp/cli-fixtures.ts+++ b/tests/mcp/cli-fixtures.ts@@ -91,7 +91,7 @@ function cliEnv() {return {PLAYWRIGHT_SERVER_REGISTRY: test.info().outputPath('registry'),PLAYWRIGHT_DAEMON_SESSION_DIR: test.info().outputPath('daemon'),- PLAYWRIGHT_DAEMON_SOCKETS_DIR: path.join(test.info().project.outputDir, 'ds'),+ PLAYWRIGHT_SOCKETS_DIR: path.join(test.info().project.outputDir, 'ds'),};}