From f34feb0bb3f7044850a6a5841b3ab2670a6cc797 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Wed, 4 Nov 2026 20:45:05 -0500 Subject: [PATCH 01/34] Revert "[ php-wasm ] Reject browser clients in the outbound networking proxy (#4492)" This reverts commit 3ab87ab8e2e6a35abadaaab030c6f74359973f89. The next commit removes the outbound WebSocket proxy server entirely, so the Origin check is no longer needed. Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/php-wasm/node/project.json | 2 - .../networking/outbound-ws-to-tcp-proxy.ts | 17 +--- .../src/test/outbound-ws-to-tcp-proxy.spec.ts | 93 ------------------- 3 files changed, 1 insertion(+), 111 deletions(-) delete mode 100644 packages/php-wasm/node/src/test/outbound-ws-to-tcp-proxy.spec.ts diff --git a/packages/php-wasm/node/project.json b/packages/php-wasm/node/project.json index 66143cc7722..3429f8ae98b 100644 --- a/packages/php-wasm/node/project.json +++ b/packages/php-wasm/node/project.json @@ -233,7 +233,6 @@ "php-sqlite3.spec.ts", "php-networking.spec.ts", "networking-port-allocation.spec.ts", - "outbound-ws-to-tcp-proxy.spec.ts", "php-dynamic-loading.spec.ts", "php-mysqli.spec.ts", "php-process-manager.spec.ts", @@ -252,7 +251,6 @@ "php-sqlite3.spec.ts", "php-networking.spec.ts", "networking-port-allocation.spec.ts", - "outbound-ws-to-tcp-proxy.spec.ts", "php-dynamic-loading.spec.ts", "php-mysqli.spec.ts", "php-process-manager.spec.ts", diff --git a/packages/php-wasm/node/src/lib/networking/outbound-ws-to-tcp-proxy.ts b/packages/php-wasm/node/src/lib/networking/outbound-ws-to-tcp-proxy.ts index bf952e1e754..4cdb64fb896 100644 --- a/packages/php-wasm/node/src/lib/networking/outbound-ws-to-tcp-proxy.ts +++ b/packages/php-wasm/node/src/lib/networking/outbound-ws-to-tcp-proxy.ts @@ -134,19 +134,6 @@ export function initOutboundWebsocketProxyServer( // Handle new WebSocket client async function onWsConnect(client: any, request: http.IncomingMessage) { - // CAUTION: Do not accept connections that send an Origin header. - // Only the PHP runtime's own Node `ws` client may use this proxy. It sends - // no Origin header, while browsers always send one. A web page connected - // here would get raw TCP access to any host the Node process can reach, - // including services that only listen on localhost. Binding to 127.0.0.1 - // doesn't stop this because browsers can connect to loopback. Allowing an - // Origin, even a trusted one, gives that access to every page served from it. - // To prevent this, let's close any connection that has an Origin header - // before it can open a TCP connection. - if (request.headers.origin) { - client.close(1008, 'Origin not allowed'); - return; - } const clientAddr = client?._socket?.remoteAddress || client.url; const clientLog = function (...args: any[]) { log(' ' + clientAddr + ': ', ...args); @@ -207,9 +194,7 @@ async function onWsConnect(client: any, request: http.IncomingMessage) { } } else { clientLog('Unknown command type: ' + commandType); - client.close(3000); - target.end(); - return; + process.exit(); } } } diff --git a/packages/php-wasm/node/src/test/outbound-ws-to-tcp-proxy.spec.ts b/packages/php-wasm/node/src/test/outbound-ws-to-tcp-proxy.spec.ts deleted file mode 100644 index 7105c3a3b05..00000000000 --- a/packages/php-wasm/node/src/test/outbound-ws-to-tcp-proxy.spec.ts +++ /dev/null @@ -1,93 +0,0 @@ -import type http from 'node:http'; -import net from 'node:net'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { WebSocket } from 'ws'; -import { - COMMAND_CHUNK, - initOutboundWebsocketProxyServer, -} from '../lib/networking/outbound-ws-to-tcp-proxy'; -import { getServerPort } from '../lib/networking/utils'; - -describe('outbound websocket to TCP proxy', () => { - let target: net.Server; - let proxy: http.Server; - - beforeEach(async () => { - target = net.createServer((socket) => socket.pipe(socket)); - await new Promise((resolve) => - target.listen(0, '127.0.0.1', resolve) - ); - proxy = await initOutboundWebsocketProxyServer(0); - }); - - afterEach(async () => { - proxy.closeAllConnections(); - await new Promise((resolve) => proxy.close(resolve)); - await new Promise((resolve) => target.close(resolve)); - }); - - it('relays TCP traffic for the owning runtime', async () => { - const client = connect(); - await opened(client); - - client.send(Buffer.from([COMMAND_CHUNK, ...Buffer.from('bar')])); - - expect(await nextMessage(client)).toBe('bar'); - client.close(); - }); - - it.each(['https://example.com', 'null'])( - 'closes the connection of the %s browser origin', - async (origin) => { - const client = connect(origin); - client.once('open', () => - client.send(Buffer.from([COMMAND_CHUNK, ...Buffer.from('bar')])) - ); - - expect(await closed(client)).toBe(1008); - expect(await connections(target)).toBe(0); - } - ); - - it('closes the connection on an unknown command', async () => { - const client = connect(); - await opened(client); - - client.send(Buffer.from([0xff])); - - expect(await closed(client)).toBe(3000); - }); - - function connect(origin?: string) { - const params = new URLSearchParams({ - host: '127.0.0.1', - port: String(getServerPort(target)), - }); - return new WebSocket( - `ws://127.0.0.1:${getServerPort(proxy)}/?${params}`, - { origin } - ); - } -}); - -function opened(client: WebSocket) { - return new Promise((resolve) => client.once('open', resolve)); -} - -function nextMessage(client: WebSocket) { - return new Promise((resolve) => - client.once('message', (data) => resolve(data.toString())) - ); -} - -function closed(client: WebSocket) { - return new Promise((resolve) => - client.once('close', (code) => resolve(code)) - ); -} - -function connections(server: net.Server) { - return new Promise((resolve) => - server.getConnections((_, count) => resolve(count)) - ); -} From acdb9a40801d686f01d03ba5c38b9287e6bc214c Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Wed, 4 Nov 2026 20:49:56 -0500 Subject: [PATCH 02/34] [ php-wasm ] Open outbound TCP connections without a local server The Node runtime started a WebSocket-to-TCP proxy on 127.0.0.1 so PHP could open network connections. Any program on the machine could connect to it and choose the target host and port. That included programs that are blocked from the network themselves, such as sandboxed apps, programs a per-app firewall blocks, and other users' processes. Emscripten creates PHP's sockets through the `websocket.decorator` option. The decorator now returns `OutboundTcpSocket`, a class with the part of the `ws` API that Emscripten uses, backed by a TCP connection in the same process. Nothing listens on a port, so no other program can use PHP's connections. A connection that is refused now fails without opening. Before, the WebSocket to the proxy opened first, so connect() succeeded and PHP read the end of the stream. The runtime closes its open connections when it exits. The `outboundNetworkProxyServer` Emscripten option is replaced by `closeOutboundConnections`. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../23-architecture/02-wasm-php-overview.md | 2 +- packages/php-wasm/node/project.json | 2 + .../src/lib/networking/outbound-tcp-socket.ts | 206 +++++++++++++ .../networking/outbound-ws-to-tcp-proxy.ts | 283 ------------------ .../src/lib/networking/with-networking.ts | 26 +- .../test/networking-port-allocation.spec.ts | 37 +-- .../node/src/test/outbound-tcp-socket.spec.ts | 33 ++ .../node/src/test/php-networking.spec.ts | 46 +-- .../universal/src/lib/load-php-runtime.ts | 11 +- 9 files changed, 289 insertions(+), 357 deletions(-) create mode 100644 packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts delete mode 100644 packages/php-wasm/node/src/lib/networking/outbound-ws-to-tcp-proxy.ts create mode 100644 packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts diff --git a/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md b/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md index 37d81c204b0..839d43c71dc 100644 --- a/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md +++ b/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md @@ -22,7 +22,7 @@ Because every PHP version is just a static .wasm file, the PHP version switcher When it comes to networking, WebAssembly programs are limited to calling JavaScript APIs. It is a safety feature, but also presents a challenge. How do you support low-level, synchronous networking code used by PHP with the high-level asynchronous APIs available in JavaScript? -In Node.js, the answer involves a WebSocket to TCP socket proxy, [Asyncify](https://emscripten.org/docs/porting/asyncify.html), and patching deep PHP internals like php_select. It's complex, but there's a reward. The Node.js-targeted PHP build can request web APIs, install composer packages, and even connect to a MySQL server. +In Node.js, the answer involves giving Emscripten's WebSocket-based sockets a WebSocket-like object backed by a TCP connection, [Asyncify](https://emscripten.org/docs/porting/asyncify.html), and patching deep PHP internals like php_select. It's complex, but there's a reward. The Node.js-targeted PHP build can request web APIs, install composer packages, and even connect to a MySQL server. In the browser, networking is supported in two ways: diff --git a/packages/php-wasm/node/project.json b/packages/php-wasm/node/project.json index 3429f8ae98b..737e1659657 100644 --- a/packages/php-wasm/node/project.json +++ b/packages/php-wasm/node/project.json @@ -233,6 +233,7 @@ "php-sqlite3.spec.ts", "php-networking.spec.ts", "networking-port-allocation.spec.ts", + "outbound-tcp-socket.spec.ts", "php-dynamic-loading.spec.ts", "php-mysqli.spec.ts", "php-process-manager.spec.ts", @@ -251,6 +252,7 @@ "php-sqlite3.spec.ts", "php-networking.spec.ts", "networking-port-allocation.spec.ts", + "outbound-tcp-socket.spec.ts", "php-dynamic-loading.spec.ts", "php-mysqli.spec.ts", "php-process-manager.spec.ts", diff --git a/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts new file mode 100644 index 00000000000..f7474ffa415 --- /dev/null +++ b/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts @@ -0,0 +1,206 @@ +/** + * Lets PHP open outbound TCP connections in Node.js. + * + * Emscripten implements sockets with WebSockets, and WebAssembly has no + * network access of its own. Emscripten creates those WebSockets through the + * `websocket.decorator` option, so we give it a class with the subset of the + * `ws` API it uses, backed by a TCP connection in the same process. + * + * CAUTION: Do not replace this with a WebSocket server. A server would need + * a listening port, and any program or web page on the machine could then use + * it to open TCP connections as this Node.js process. + */ +import * as dns from 'dns'; +import { EventEmitter } from 'events'; +import * as net from 'net'; +import { debugLog } from './utils'; + +function log(...args: any[]) { + debugLog('[Outbound TCP]', ...args); +} + +const SOL_SOCKET = 1; +const SO_KEEPALIVE = 9; +const IPPROTO_TCP = 6; +const TCP_NODELAY = 1; + +/** + * Builds the URL Emscripten passes to the socket constructor. + * + * Nothing listens at this URL. It only carries the target host and port. + */ +export function getOutboundTcpSocketUrl(host: string, port: string) { + const query = new URLSearchParams({ host, port }).toString(); + return `tcp://php-wasm/?${query}`; +} + +/** + * Creates a socket class for one PHP runtime. + * + * Its `closeAll()` method closes the runtime's open connections when the + * runtime exits. + */ +export function createOutboundTcpSocketClass() { + const openSockets = new Set(); + return class RuntimeOutboundTcpSocket extends OutboundTcpSocket { + static closeAll() { + for (const socket of openSockets) { + socket.close(); + } + } + + constructor(url: string) { + super(url); + openSockets.add(this); + this.once('close', () => openSockets.delete(this)); + } + }; +} + +/** + * A TCP connection with the subset of the `ws` WebSocket API that + * Emscripten's SOCKFS and the php-wasm socket functions use. + */ +export class OutboundTcpSocket extends EventEmitter { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + + readonly CONNECTING = OutboundTcpSocket.CONNECTING; + readonly OPEN = OutboundTcpSocket.OPEN; + readonly CLOSING = OutboundTcpSocket.CLOSING; + readonly CLOSED = OutboundTcpSocket.CLOSED; + + readonly url: string; + readyState: number = OutboundTcpSocket.CONNECTING; + binaryType = 'arraybuffer'; + private target?: net.Socket; + + constructor(url: string) { + super(); + this.url = url; + const { searchParams } = new URL(url); + this.connect( + searchParams.get('host'), + Number(searchParams.get('port')) + ); + } + + send(data: ArrayBuffer | ArrayBufferView) { + if (this.readyState !== this.OPEN) { + throw new Error('The TCP connection is not open'); + } + const bytes = ArrayBuffer.isView(data) + ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) + : new Uint8Array(data); + this.target!.write(bytes); + } + + setSocketOpt(level: number, optionName: number, optionValue: number) { + if (level === SOL_SOCKET && optionName === SO_KEEPALIVE) { + this.target?.setKeepAlive(Boolean(optionValue)); + } else if (level === IPPROTO_TCP && optionName === TCP_NODELAY) { + this.target?.setNoDelay(Boolean(optionValue)); + } + } + + close() { + this.shutDown(); + } + + addEventListener(event: string, listener: (...args: any[]) => void) { + this.on(event, listener); + } + + removeEventListener(event: string, listener: (...args: any[]) => void) { + this.off(event, listener); + } + + private async connect(host: string | null, port: number) { + if (!host || !Number.isInteger(port) || port < 1 || port > 65535) { + this.shutDown(new Error(`Invalid TCP address: ${host}:${port}`)); + return; + } + + let ip = host; + if (net.isIP(host) === 0) { + try { + ip = await lookupIPv4(host); + } catch (e) { + this.shutDown(e as Error); + return; + } + // PHP may have closed the socket during the lookup. + if (this.readyState !== this.CONNECTING) { + return; + } + } + + log(`Connecting to ${ip}:${port}`); + const target = net.createConnection(port, ip); + this.target = target; + target.on('connect', () => { + if (this.readyState === this.CONNECTING) { + this.readyState = this.OPEN; + this.emit('open'); + } + }); + target.on('data', (data: Buffer) => { + // Emscripten ignores messages that aren't marked as binary. + this.emit('message', data, true); + }); + target.on('end', () => this.shutDown()); + target.on('error', (e) => this.shutDown(e)); + } + + /** + * Closes the connection and emits `close` on the next tick, like `ws`. + * + * Only a connection that never opened emits `error`. Emscripten records it + * as a refused connection. An established connection that fails closes + * without an error, so PHP reads the end of the stream. + */ + private shutDown(error?: Error) { + if ( + this.readyState === this.CLOSING || + this.readyState === this.CLOSED + ) { + return; + } + const wasOpen = this.readyState === this.OPEN; + if (error) { + log('Connection error', error); + } + this.readyState = this.CLOSING; + if (wasOpen && !error) { + this.target!.end(); + } else { + this.target?.destroy(); + } + process.nextTick(() => { + this.readyState = this.CLOSED; + if (error && !wasOpen && this.listenerCount('error') > 0) { + this.emit('error', error); + } + this.emit('close'); + }); + } +} + +/** + * Resolve a hostname to an IPv4 address. + * Prefers IPv4 because many services (including Redis) only listen on IPv4 + * by default, and macOS's dns.lookup returns IPv6 for 'localhost'. + */ +function lookupIPv4(hostname: string): Promise { + return new Promise((resolve, reject) => { + dns.lookup(hostname, { family: 4 }, (err, address) => { + if (err) { + reject(err); + } else { + resolve(address); + } + }); + }); +} diff --git a/packages/php-wasm/node/src/lib/networking/outbound-ws-to-tcp-proxy.ts b/packages/php-wasm/node/src/lib/networking/outbound-ws-to-tcp-proxy.ts deleted file mode 100644 index 4cdb64fb896..00000000000 --- a/packages/php-wasm/node/src/lib/networking/outbound-ws-to-tcp-proxy.ts +++ /dev/null @@ -1,283 +0,0 @@ -/** - * This is a simple TCP proxy server that allows PHP to connect to a remote - * server via WebSockets. This is necessary because WebAssembly has no access - * to the network. - * - * This module was forked from the @maximegris/node-websockify npm package. - */ -'use strict'; - -import * as dns from 'dns'; -import * as http from 'http'; -import * as net from 'net'; -import { WebSocketServer } from 'ws'; -import { debugLog } from './utils'; - -function log(...args: any[]) { - debugLog('[WS Server]', ...args); -} - -/** - * Resolve a hostname to an IPv4 address. - * Prefers IPv4 because many services (including Redis) only listen on IPv4 - * by default, and macOS's dns.lookup returns IPv6 for 'localhost'. - */ -function lookupIPv4(hostname: string): Promise { - return new Promise((resolve, reject) => { - dns.lookup(hostname, { family: 4 }, (err, address) => { - if (err) { - reject(err); - } else { - resolve(address); - } - }); - }); -} - -function prependByte( - chunk: string | ArrayBuffer | ArrayLike, - byte: number -) { - if (typeof chunk === 'string') { - chunk = String.fromCharCode(byte) + chunk; - } else if ( - chunk instanceof ArrayBuffer || - 'byteLength' in chunk /* for Node.js */ - ) { - const buffer = new Uint8Array((chunk as ArrayBuffer).byteLength + 1); - buffer[0] = byte; - buffer.set(new Uint8Array(chunk), 1); - chunk = buffer.buffer; - } else { - log({ chunk }); - throw new Error('Unsupported chunk type: ' + typeof chunk); - } - return chunk; -} - -/** - * Send a chunk of data to the remote server. - */ -export const COMMAND_CHUNK = 0x01; -/** - * Set a TCP socket option. - */ -export const COMMAND_SET_SOCKETOPT = 0x02; - -/** - * Adds support for TCP socket options to WebSocket class. - * - * Socket options are implemented by adopting a specific data transmission - * protocol between WS client and WS server The first byte - * of every message is a command type, and the remaining bytes - * are the actual data. - * - * @param WebSocketConstructor - * @returns Decorated constructor - */ -export function addSocketOptionsSupportToWebSocketClass( - WebSocketConstructor: typeof WebSocket -) { - return class PHPWasmWebSocketConstructor extends WebSocketConstructor { - // @ts-ignore - send(chunk: any, callback: any) { - return this.sendCommand(COMMAND_CHUNK, chunk, callback); - } - - setSocketOpt( - optionClass: number, - optionName: number, - optionValue: number - ) { - return this.sendCommand( - COMMAND_SET_SOCKETOPT, - new Uint8Array([optionClass, optionName, optionValue]).buffer, - () => undefined - ); - } - sendCommand( - commandType: number, - chunk: string | ArrayBuffer | ArrayLike, - callback: any - ) { - return (WebSocketConstructor.prototype.send as any).call( - this, - prependByte(chunk, commandType), - callback - ); - } - }; -} - -export function initOutboundWebsocketProxyServer( - listenPort: number, - listenHost = '127.0.0.1' -): Promise { - log(`Binding the WebSockets server to ${listenHost}:${listenPort}...`); - const webServer = http.createServer((request, response) => { - response.writeHead(403, { 'Content-Type': 'text/plain' }); - response.write( - '403 Permission Denied\nOnly websockets are allowed here.\n' - ); - response.end(); - }); - return new Promise((resolve, reject) => { - webServer.once('error', reject); - webServer.listen(listenPort, listenHost, function () { - webServer.off('error', reject); - const wsServer = new WebSocketServer({ server: webServer }); - wsServer.on('connection', onWsConnect); - resolve(webServer); - }); - }); -} - -// Handle new WebSocket client -async function onWsConnect(client: any, request: http.IncomingMessage) { - const clientAddr = client?._socket?.remoteAddress || client.url; - const clientLog = function (...args: any[]) { - log(' ' + clientAddr + ': ', ...args); - }; - - clientLog( - 'WebSocket connection from : ' + - clientAddr + - ' at URL ' + - (request ? request.url : client.upgradeReq.url) - ); - clientLog( - 'Version ' + - client.protocolVersion + - ', subprotocol: ' + - client.protocol - ); - - // Parse the search params (the host doesn't matter): - const reqUrl = new URL(`ws://0.0.0.0` + request.url); - const reqTargetPort = Number(reqUrl.searchParams.get('port')); - const reqTargetHost = reqUrl.searchParams.get('host'); - if (!reqTargetPort || !reqTargetHost) { - clientLog('Missing host or port information'); - client.close(3000); - return; - } - - // Validate port range - if (reqTargetPort < 0 || reqTargetPort > 65535) { - clientLog('Invalid port number: ' + reqTargetPort); - // Send empty binary data to notify requester that connection failed - client.send([]); - client.close(3000); - return; - } - - // eslint-disable-next-line prefer-const - let target: any; - const recvQueue: Buffer[] = []; - function flushMessagesQueue() { - while (recvQueue.length > 0) { - const msg = recvQueue.pop()! as Buffer; - const commandType = msg[0]; - clientLog('flushing', { commandType }, msg); - if (commandType === COMMAND_CHUNK) { - target.write(msg.slice(1)); - } else if (commandType === COMMAND_SET_SOCKETOPT) { - const SOL_SOCKET = 1; - const SO_KEEPALIVE = 9; - - const IPPROTO_TCP = 6; - const TCP_NODELAY = 1; - if (msg[1] === SOL_SOCKET && msg[2] === SO_KEEPALIVE) { - target.setKeepAlive(msg[3]); - } else if (msg[1] === IPPROTO_TCP && msg[2] === TCP_NODELAY) { - target.setNoDelay(msg[3]); - } - } else { - clientLog('Unknown command type: ' + commandType); - process.exit(); - } - } - } - - client.on('message', function (msg: Buffer) { - // clientLog('PHP -> network buffer:', msg); - recvQueue.unshift(msg); - if (target) { - flushMessagesQueue(); - } - }); - client.on('close', function (code: any, reason: any) { - clientLog( - 'WebSocket client disconnected: ' + code + ' [' + reason + ']' - ); - if (target) { - target.end(); - } - } as any); - client.on('error', function (a: string | Buffer) { - clientLog('WebSocket client error: ' + a); - target.end(); - }); - - // Resolve the target host to an IP address if it isn't one already. - // Prefer IPv4 addresses because many services (including Redis) only listen - // on IPv4 by default, and macOS's dns.lookup returns IPv6 for 'localhost'. - let reqTargetIp; - if (net.isIP(reqTargetHost) === 0) { - clientLog('resolving ' + reqTargetHost + '... '); - try { - reqTargetIp = await lookupIPv4(reqTargetHost); - clientLog('resolved ' + reqTargetHost + ' -> ' + reqTargetIp); - } catch (e) { - clientLog("can't resolve " + reqTargetHost + ' due to:', e); - // Send empty binary data to notify requester that connection was - // initiated - client.send([]); - // Without this random timeout, PHP sometimes doesn't notice the socket - // disconnected. TODO: figure out why. - setTimeout(() => { - client.close(3000); - }); - return; - } - } else { - reqTargetIp = reqTargetHost; - } - clientLog( - 'Opening a socket connection to ' + reqTargetIp + ':' + reqTargetPort - ); - target = net.createConnection(reqTargetPort, reqTargetIp, function () { - clientLog('Connected to target'); - flushMessagesQueue(); - }); - target.on('data', function (data: any) { - // clientLog( - // 'network -> PHP buffer:', - // [...data.slice(0, 100)].join(', ') + '...' - // ); - try { - client.send(data); - } catch { - clientLog('Client closed, cleaning up target'); - target.end(); - } - }); - target.on('end', function () { - clientLog('target disconnected'); - client.close(); - }); - target.on('error', function (e: any) { - clientLog('target connection error', e); - client.send([]); - // Without this random timeout, PHP sometimes doesn't notice the socket - // disconnected. TODO: figure out why. - setTimeout(() => { - client.close(3000); - try { - target.end(); - } catch { - // Ignore - } - }); - }); -} diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 3f334ff5cce..c494b3a4eb2 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -1,32 +1,26 @@ import type { EmscriptenOptions } from '@php-wasm/universal'; import { - initOutboundWebsocketProxyServer, - addSocketOptionsSupportToWebSocketClass, -} from './outbound-ws-to-tcp-proxy'; + createOutboundTcpSocketClass, + getOutboundTcpSocketUrl, +} from './outbound-tcp-socket'; import { addTCPServerToWebSocketServerClass } from './inbound-tcp-to-ws-proxy'; -import { getServerPort } from './utils'; export async function withNetworking( phpModuleArgs: EmscriptenOptions = {} ): Promise { - const outboundNetworkProxyServer = - await initOutboundWebsocketProxyServer(0); - const outboundProxyWsServerPort = getServerPort(outboundNetworkProxyServer); + const OutboundTcpSocket = createOutboundTcpSocketClass(); return { ...phpModuleArgs, - outboundNetworkProxyServer, + closeOutboundConnections: () => OutboundTcpSocket.closeAll(), websocket: { ...(phpModuleArgs['websocket'] || {}), - url: (_: any, host: string, port: string) => { - const query = new URLSearchParams({ - host, - port, - }).toString(); - return `ws://127.0.0.1:${outboundProxyWsServerPort}/?${query}`; - }, + url: (_: any, host: string, port: string) => + getOutboundTcpSocketUrl(host, port), subprotocol: 'binary', - decorator: addSocketOptionsSupportToWebSocketClass, + // Emscripten passes the `ws` WebSocket class here. Outbound + // connections use TCP directly instead of a local WebSocket server. + decorator: () => OutboundTcpSocket, serverDecorator: addTCPServerToWebSocketServerClass, }, }; diff --git a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts index ecf8ab998a0..e98756dc861 100644 --- a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts +++ b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts @@ -1,45 +1,24 @@ -import http from 'node:http'; import net from 'node:net'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { withNetworking } from '../lib/networking/with-networking'; import { addTCPServerToWebSocketServerClass } from '../lib/networking/inbound-tcp-to-ws-proxy'; -import { getServerPort } from '../lib/networking/utils'; describe('networking port allocation', () => { afterEach(() => { vi.restoreAllMocks(); }); - it('binds the outbound websocket proxy directly on an automatic port', async () => { - const originalListen = http.Server.prototype.listen; - const listenCalls: unknown[][] = []; - const listenSpy = vi - .spyOn(http.Server.prototype, 'listen') - .mockImplementation(function ( - this: http.Server, - ...args: Parameters - ) { - listenCalls.push(args); - return originalListen.apply(this, args); - }); + it('does not listen on a port for outbound connections', async () => { + const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); const emscriptenOptions = await withNetworking({}); - const server = - emscriptenOptions.outboundNetworkProxyServer as http.Server; + const OutboundSocket = emscriptenOptions['websocket'].decorator(); + const socket = new OutboundSocket( + emscriptenOptions['websocket'].url(null, '127.0.0.1', '9') + ); + socket.close(); - try { - expect(listenCalls).toContainEqual([ - 0, - '127.0.0.1', - expect.any(Function), - ]); - expect( - emscriptenOptions['websocket']?.url(null, 'example.com', '80') - ).toContain(`127.0.0.1:${getServerPort(server)}`); - expect(listenSpy).toHaveBeenCalled(); - } finally { - await new Promise((resolve) => server.close(resolve)); - } + expect(listenSpy).not.toHaveBeenCalled(); }); it('binds the inbound websocket proxy directly on an automatic port', async () => { diff --git a/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts b/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts new file mode 100644 index 00000000000..0dcd8da1ac6 --- /dev/null +++ b/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts @@ -0,0 +1,33 @@ +import net from 'node:net'; +import { describe, expect, it } from 'vitest'; +import { + OutboundTcpSocket, + getOutboundTcpSocketUrl, +} from '../lib/networking/outbound-tcp-socket'; + +describe('OutboundTcpSocket', () => { + it('reports a refused connection without opening', async () => { + const port = await getClosedPort(); + const socket = new OutboundTcpSocket( + getOutboundTcpSocketUrl('127.0.0.1', String(port)) + ); + const events: string[] = []; + socket.on('open', () => events.push('open')); + socket.on('error', () => events.push('error')); + + await new Promise((resolve) => socket.once('close', resolve)); + + expect(events).toEqual(['error']); + expect(socket.readyState).toBe(OutboundTcpSocket.CLOSED); + }); +}); + +async function getClosedPort() { + const server = net.createServer(); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + await new Promise((resolve) => server.close(resolve)); + return port; +} diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 436eb55a9b6..19a98fdf794 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -2,14 +2,13 @@ import { PHP, SupportedPHPVersions, setPhpIniEntries, - popLoadedRuntime, type SupportedPHPVersion, } from '@php-wasm/universal'; import express from 'express'; import { rootCertificates } from 'tls'; import { loadNodeRuntime } from '../lib'; import type { PHPLoaderOptions } from '../lib'; -import http from 'http'; +import net from 'net'; const phpVersions = 'PHP' in process.env @@ -417,26 +416,35 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { { timeout: 15000 } ); - it('should close server when runtime is exited', async () => { - const id = await loadNodeRuntime(phpVersion, options); - const rt = popLoadedRuntime(id, { - dangerouslyKeepTheRuntimeInTheMap: true, - }); - const php = new PHP(id); - - expect(rt.outboundNetworkProxyServer).toBeDefined(); - expect(rt.outboundNetworkProxyServer).toBeInstanceOf( - http.Server + it('should close open connections when runtime is exited', async () => { + const tcpServer = net.createServer(); + const connection = new Promise((resolve) => + tcpServer.once('connection', resolve) ); - expect(rt.outboundNetworkProxyServer.listening).toBe(true); - php.exit(); + await new Promise((resolve) => + tcpServer.listen(0, '127.0.0.1', resolve) + ); + const { port } = tcpServer.address() as net.AddressInfo; + try { + const php = new PHP( + await loadNodeRuntime(phpVersion, options) + ); + // A persistent socket stays open after the request ends. + await php.run({ + code: ` + socket.once('close', resolve) + ); + socket.resume(); - // Wait for the server to close - await new Promise((resolve) => { - rt.outboundNetworkProxyServer.on('close', resolve); - }); + php.exit(); - expect(rt.outboundNetworkProxyServer.listening).toBe(false); + await closed; + } finally { + tcpServer.close(); + } }); }); }); diff --git a/packages/php-wasm/universal/src/lib/load-php-runtime.ts b/packages/php-wasm/universal/src/lib/load-php-runtime.ts index cfd1b0a230b..e4877654020 100644 --- a/packages/php-wasm/universal/src/lib/load-php-runtime.ts +++ b/packages/php-wasm/universal/src/lib/load-php-runtime.ts @@ -1,5 +1,4 @@ import { logger } from '@php-wasm/logger'; -import type { IncomingMessage, Server, ServerResponse } from 'http'; const RuntimeId = Symbol('RuntimeId'); const loadedRuntimes: Map = new Map(); @@ -172,10 +171,7 @@ export async function loadPHPRuntime( PHPRuntime.originalExit = PHPRuntime._exit; PHPRuntime._exit = function (code: number) { - if (PHPRuntime.outboundNetworkProxyServer) { - PHPRuntime.outboundNetworkProxyServer.close(); - PHPRuntime.outboundNetworkProxyServer.closeAllConnections(); - } + PHPRuntime.closeOutboundConnections?.(); loadedRuntimes.delete(id); return PHPRuntime.originalExit(code); }; @@ -303,10 +299,7 @@ export type EmscriptenOptions = { onRuntimeInitialized?: (phpRuntime: PHPRuntime) => void; monitorRunDependencies?: (left: number) => void; onMessage?: (listener: EmscriptenMessageListener) => void; - outboundNetworkProxyServer?: Server< - typeof IncomingMessage, - typeof ServerResponse - >; + closeOutboundConnections?: () => void; instantiateWasm?: ( info: WebAssembly.Imports, receiveInstance: ( From 1052308a990d38e95618532908df18efaa7eea74 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Wed, 4 Nov 2026 21:01:53 -0500 Subject: [PATCH 03/34] [ php-wasm ] Keep outboundNetworkProxyServer as a deprecated option `EmscriptenOptions` is exported from `@php-wasm/universal`, so removing the field would break code that references it. The field stays, marked as deprecated with the reason, and a server passed in is still closed when the runtime exits. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../universal/src/lib/load-php-runtime.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/packages/php-wasm/universal/src/lib/load-php-runtime.ts b/packages/php-wasm/universal/src/lib/load-php-runtime.ts index e4877654020..162de11b6bb 100644 --- a/packages/php-wasm/universal/src/lib/load-php-runtime.ts +++ b/packages/php-wasm/universal/src/lib/load-php-runtime.ts @@ -1,4 +1,5 @@ import { logger } from '@php-wasm/logger'; +import type { IncomingMessage, Server, ServerResponse } from 'http'; const RuntimeId = Symbol('RuntimeId'); const loadedRuntimes: Map = new Map(); @@ -172,6 +173,10 @@ export async function loadPHPRuntime( PHPRuntime._exit = function (code: number) { PHPRuntime.closeOutboundConnections?.(); + if (PHPRuntime.outboundNetworkProxyServer) { + PHPRuntime.outboundNetworkProxyServer.close(); + PHPRuntime.outboundNetworkProxyServer.closeAllConnections(); + } loadedRuntimes.delete(id); return PHPRuntime.originalExit(code); }; @@ -299,7 +304,25 @@ export type EmscriptenOptions = { onRuntimeInitialized?: (phpRuntime: PHPRuntime) => void; monitorRunDependencies?: (left: number) => void; onMessage?: (listener: EmscriptenMessageListener) => void; + /** + * Closes PHP's open outbound TCP connections. The runtime calls it on exit. + */ closeOutboundConnections?: () => void; + /** + * @deprecated php-wasm no longer sets this. Use `closeOutboundConnections`. + * + * Node.js runtimes used to start a WebSocket-to-TCP proxy server on + * 127.0.0.1 for PHP's outbound connections. Any program on the machine + * could connect to it and open TCP connections through the Node.js + * process, including programs blocked from the network themselves. + * Runtimes now open TCP connections in-process, without a listening port. + * + * A server passed here is still closed when the runtime exits. + */ + outboundNetworkProxyServer?: Server< + typeof IncomingMessage, + typeof ServerResponse + >; instantiateWasm?: ( info: WebAssembly.Imports, receiveInstance: ( From 4bc6dcf951a6c4939fd8ec8779f9413deea07489 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Wed, 4 Nov 2026 21:05:10 -0500 Subject: [PATCH 04/34] [ php-wasm ] Name the return type of createOutboundTcpSocketClass The build failed while generating declarations, because the function returned a class expression that extends a class with private members. An explicit return type gives the declaration a name it can use. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../php-wasm/node/src/lib/networking/outbound-tcp-socket.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts index f7474ffa415..c30ff46a65f 100644 --- a/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts @@ -40,7 +40,9 @@ export function getOutboundTcpSocketUrl(host: string, port: string) { * Its `closeAll()` method closes the runtime's open connections when the * runtime exits. */ -export function createOutboundTcpSocketClass() { +export function createOutboundTcpSocketClass(): typeof OutboundTcpSocket & { + closeAll(): void; +} { const openSockets = new Set(); return class RuntimeOutboundTcpSocket extends OutboundTcpSocket { static closeAll() { From 0f0f51322577c7a31faad585ccc6e4b1973f86cd Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Wed, 4 Nov 2026 21:23:35 -0500 Subject: [PATCH 05/34] [ php-wasm ] Open outbound sockets before the TCP connection completes With JSPI, reporting a refused connection from connect() made cURL wait until its timeout. cURL's connect() returns before the attempt finishes, and php-wasm's connect() drops a socket whose connection fails, so cURL's polls never saw the failure. The socket now reports itself open right away and lets Node buffer writes until the TCP connection is established, like the WebSocket proxy did. A connection that fails then closes, and PHP reads the end of the stream. `net.createConnection()` now does the IPv4 lookup. New PHP-level tests check that cURL fails promptly on a closed port, and that PHP reads the data and the end of the stream when the peer resets the connection. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/lib/networking/outbound-tcp-socket.ts | 106 +++++++----------- .../node/src/test/outbound-tcp-socket.spec.ts | 4 +- .../node/src/test/php-networking.spec.ts | 80 +++++++++++++ 3 files changed, 121 insertions(+), 69 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts index c30ff46a65f..6e948d81796 100644 --- a/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts @@ -10,7 +10,6 @@ * a listening port, and any program or web page on the machine could then use * it to open TCP connections as this Node.js process. */ -import * as dns from 'dns'; import { EventEmitter } from 'events'; import * as net from 'net'; import { debugLog } from './utils'; @@ -62,6 +61,14 @@ export function createOutboundTcpSocketClass(): typeof OutboundTcpSocket & { /** * A TCP connection with the subset of the `ws` WebSocket API that * Emscripten's SOCKFS and the php-wasm socket functions use. + * + * The socket reports itself open right away and buffers writes until the TCP + * connection is established, like the WebSocket proxy it replaces. A connection + * that fails then closes, and PHP reads the end of the stream. + * + * CAUTION: Reporting the failure from connect() instead breaks cURL with JSPI. + * php-wasm's connect() drops a socket whose connection fails, so cURL's polls + * never see the failure, and it waits until its timeout. */ export class OutboundTcpSocket extends EventEmitter { static readonly CONNECTING = 0; @@ -83,10 +90,23 @@ export class OutboundTcpSocket extends EventEmitter { super(); this.url = url; const { searchParams } = new URL(url); - this.connect( - searchParams.get('host'), - Number(searchParams.get('port')) - ); + const host = searchParams.get('host'); + const port = Number(searchParams.get('port')); + if (host && Number.isInteger(port) && port > 0 && port < 65536) { + this.target = this.connect(host, port); + } else { + log(`Invalid TCP address: ${host}:${port}`); + } + process.nextTick(() => { + if (this.readyState !== this.CONNECTING) { + return; + } + this.readyState = this.OPEN; + this.emit('open'); + if (!this.target) { + this.shutDown(); + } + }); } send(data: ArrayBuffer | ArrayBufferView) { @@ -119,90 +139,42 @@ export class OutboundTcpSocket extends EventEmitter { this.off(event, listener); } - private async connect(host: string | null, port: number) { - if (!host || !Number.isInteger(port) || port < 1 || port > 65535) { - this.shutDown(new Error(`Invalid TCP address: ${host}:${port}`)); - return; - } - - let ip = host; - if (net.isIP(host) === 0) { - try { - ip = await lookupIPv4(host); - } catch (e) { - this.shutDown(e as Error); - return; - } - // PHP may have closed the socket during the lookup. - if (this.readyState !== this.CONNECTING) { - return; - } - } - - log(`Connecting to ${ip}:${port}`); - const target = net.createConnection(port, ip); - this.target = target; - target.on('connect', () => { - if (this.readyState === this.CONNECTING) { - this.readyState = this.OPEN; - this.emit('open'); - } - }); + private connect(host: string, port: number) { + log(`Connecting to ${host}:${port}`); + // Prefer IPv4 because many services (including Redis) only listen on + // IPv4 by default, and macOS resolves 'localhost' to IPv6 first. + const target = net.createConnection({ host, port, family: 4 }); target.on('data', (data: Buffer) => { // Emscripten ignores messages that aren't marked as binary. this.emit('message', data, true); }); target.on('end', () => this.shutDown()); - target.on('error', (e) => this.shutDown(e)); + target.on('error', (error) => { + log('Connection error', error); + this.shutDown(true); + }); + return target; } /** * Closes the connection and emits `close` on the next tick, like `ws`. - * - * Only a connection that never opened emits `error`. Emscripten records it - * as a refused connection. An established connection that fails closes - * without an error, so PHP reads the end of the stream. */ - private shutDown(error?: Error) { + private shutDown(destroy = false) { if ( this.readyState === this.CLOSING || this.readyState === this.CLOSED ) { return; } - const wasOpen = this.readyState === this.OPEN; - if (error) { - log('Connection error', error); - } this.readyState = this.CLOSING; - if (wasOpen && !error) { - this.target!.end(); - } else { + if (destroy) { this.target?.destroy(); + } else { + this.target?.end(); } process.nextTick(() => { this.readyState = this.CLOSED; - if (error && !wasOpen && this.listenerCount('error') > 0) { - this.emit('error', error); - } this.emit('close'); }); } } - -/** - * Resolve a hostname to an IPv4 address. - * Prefers IPv4 because many services (including Redis) only listen on IPv4 - * by default, and macOS's dns.lookup returns IPv6 for 'localhost'. - */ -function lookupIPv4(hostname: string): Promise { - return new Promise((resolve, reject) => { - dns.lookup(hostname, { family: 4 }, (err, address) => { - if (err) { - reject(err); - } else { - resolve(address); - } - }); - }); -} diff --git a/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts b/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts index 0dcd8da1ac6..5123fc2ac75 100644 --- a/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts @@ -6,7 +6,7 @@ import { } from '../lib/networking/outbound-tcp-socket'; describe('OutboundTcpSocket', () => { - it('reports a refused connection without opening', async () => { + it('opens and then closes when the connection is refused', async () => { const port = await getClosedPort(); const socket = new OutboundTcpSocket( getOutboundTcpSocketUrl('127.0.0.1', String(port)) @@ -17,7 +17,7 @@ describe('OutboundTcpSocket', () => { await new Promise((resolve) => socket.once('close', resolve)); - expect(events).toEqual(['error']); + expect(events).toEqual(['open']); expect(socket.readyState).toBe(OutboundTcpSocket.CLOSED); }); }); diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 19a98fdf794..b584fef2161 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -447,5 +447,85 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { } }); }); + + describe('Connection failures', () => { + it('should fail promptly when cURL connects to a closed port', async () => { + const port = await getClosedPort(); + const php = new PHP(await loadNodeRuntime(phpVersion, options)); + try { + const { text } = await php.run({ + code: ` $result, + 'errno' => curl_errno($ch), + 'seconds' => microtime(true) - $start, + ]); + `, + }); + const { result, errno, seconds } = JSON.parse(text); + expect(result).toBe(false); + // 28 is CURLE_OPERATION_TIMEDOUT. + expect(errno).not.toBe(28); + expect(seconds).toBeLessThan(5); + } finally { + php.exit(); + } + }); + + it('should read the data and the end of the stream when the peer resets the connection', async () => { + const tcpServer = net.createServer((socket) => { + socket.write('partial'); + setTimeout(() => socket.resetAndDestroy(), 50); + }); + await new Promise((resolve) => + tcpServer.listen(0, '127.0.0.1', resolve) + ); + const { port } = tcpServer.address() as net.AddressInfo; + const php = new PHP(await loadNodeRuntime(phpVersion, options)); + try { + const { text } = await php.run({ + code: ` $data, + 'eof' => feof($socket), + 'seconds' => microtime(true) - $start, + ]); + `, + }); + const { data, eof, seconds } = JSON.parse(text); + expect(data).toBe('partial'); + expect(eof).toBe(true); + expect(seconds).toBeLessThan(5); + } finally { + php.exit(); + tcpServer.close(); + } + }); + }); }); }); + +async function getClosedPort() { + const server = net.createServer(); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + await new Promise((resolve) => server.close(resolve)); + return port; +} From 6cabf3235ec3b3c3b382d1f317a051477f390746 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Wed, 4 Nov 2026 21:34:48 -0500 Subject: [PATCH 06/34] [ php-wasm ] Accept inbound TCP connections without a WebSocket bridge When PHP listened on a port, the Node runtime started an internal WebSocket server and a TCP server that bridged each connection to it. The TCP server listened on every interface, even when PHP bound to 127.0.0.1. PHP saw every client as the bridge's local address. Local programs and web pages could also reach PHP's server socket through the internal WebSocket port. Emscripten creates listening sockets through the `websocket.serverDecorator` option. It now returns `TcpServer`, which listens on the host and port PHP binds to and passes accepted connections to PHP as `TcpSocket` objects. Outbound connections use the same `TcpSocket` class. PHP now sees the real address of each client. The runtime closes its listening sockets and accepted connections when it exits, so `closeOutboundConnections` becomes `closeNetworkConnections`. The compiled PHP runtime still calls require('ws') before passing the `ws` classes to the decorators, so `with-networking.ts` imports `ws` to keep it a package dependency. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../23-architecture/02-wasm-php-overview.md | 2 +- .../lib/networking/inbound-tcp-to-ws-proxy.ts | 117 ---------- .../src/lib/networking/outbound-tcp-socket.ts | 180 --------------- .../node/src/lib/networking/tcp-socket.ts | 218 ++++++++++++++++++ .../src/lib/networking/with-networking.ts | 47 +++- .../test/networking-port-allocation.spec.ts | 92 +------- .../node/src/test/outbound-tcp-socket.spec.ts | 2 +- .../node/src/test/php-networking.spec.ts | 62 ++++- .../universal/src/lib/load-php-runtime.ts | 9 +- 9 files changed, 332 insertions(+), 397 deletions(-) delete mode 100644 packages/php-wasm/node/src/lib/networking/inbound-tcp-to-ws-proxy.ts delete mode 100644 packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts create mode 100644 packages/php-wasm/node/src/lib/networking/tcp-socket.ts diff --git a/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md b/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md index 839d43c71dc..60583447cae 100644 --- a/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md +++ b/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md @@ -22,7 +22,7 @@ Because every PHP version is just a static .wasm file, the PHP version switcher When it comes to networking, WebAssembly programs are limited to calling JavaScript APIs. It is a safety feature, but also presents a challenge. How do you support low-level, synchronous networking code used by PHP with the high-level asynchronous APIs available in JavaScript? -In Node.js, the answer involves giving Emscripten's WebSocket-based sockets a WebSocket-like object backed by a TCP connection, [Asyncify](https://emscripten.org/docs/porting/asyncify.html), and patching deep PHP internals like php_select. It's complex, but there's a reward. The Node.js-targeted PHP build can request web APIs, install composer packages, and even connect to a MySQL server. +In Node.js, the answer involves giving Emscripten's WebSocket-based sockets WebSocket-like objects backed by TCP sockets, [Asyncify](https://emscripten.org/docs/porting/asyncify.html), and patching deep PHP internals like php_select. It's complex, but there's a reward. The Node.js-targeted PHP build can request web APIs, install composer packages, and even connect to a MySQL server. In the browser, networking is supported in two ways: diff --git a/packages/php-wasm/node/src/lib/networking/inbound-tcp-to-ws-proxy.ts b/packages/php-wasm/node/src/lib/networking/inbound-tcp-to-ws-proxy.ts deleted file mode 100644 index ca2160a788e..00000000000 --- a/packages/php-wasm/node/src/lib/networking/inbound-tcp-to-ws-proxy.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { createServer, type Server } from 'net'; -import type { WebSocketServer } from 'ws'; -import { WebSocket } from 'ws'; -import { debugLog, getServerPort } from './utils'; -function log(...args: any[]) { - debugLog('[TCP Server]', ...args); -} - -export function addTCPServerToWebSocketServerClass( - WSServer: typeof WebSocketServer -): any { - return class PHPWasmWebSocketServer extends WSServer { - private tcpToWsProxyServer?: Server; - - constructor(options: any, callback: any) { - const requestedPort = options.port; - options.port = 0; - super(options, undefined); - this.once('listening', () => { - this.tcpToWsProxyServer = listenTCPToWSProxy( - { - tcpListenPort: requestedPort, - wsConnectPort: getServerPort(this), - }, - () => callback?.call(this) - ); - }); - } - - override close(callback?: (err?: Error) => void) { - const tcpToWsProxyServer = this.tcpToWsProxyServer; - this.tcpToWsProxyServer = undefined; - - tcpToWsProxyServer?.close( - (error: NodeJS.ErrnoException | undefined) => { - if (error?.code !== 'ERR_SERVER_NOT_RUNNING') { - log('TCP server close error', error); - } - } - ); - - return super.close(callback); - } - }; -} - -export interface InboundTcpToWsProxyOptions { - tcpListenPort: number; - wsConnectHost?: string; - wsConnectPort: number; -} -export function listenTCPToWSProxy( - options: InboundTcpToWsProxyOptions, - onListening?: () => void -) { - options = { - wsConnectHost: '127.0.0.1', - ...options, - }; - const { tcpListenPort, wsConnectHost, wsConnectPort } = options; - const server = createServer(); - server.on('connection', function handleConnection(tcpSource) { - const inBuffer: Buffer[] = []; - - const wsTarget = new WebSocket( - `ws://${wsConnectHost}:${wsConnectPort}/` - ); - wsTarget.binaryType = 'arraybuffer'; - function wsSend(data: Buffer) { - wsTarget.send(new Uint8Array(data)); - } - - wsTarget.addEventListener('open', function () { - log('Outbound WebSocket connection established'); - while (inBuffer.length > 0) { - wsSend(inBuffer.shift()!); - } - }); - wsTarget.addEventListener('message', (e) => { - log( - 'WS->TCP message:', - new TextDecoder().decode(e.data as ArrayBuffer) - ); - // @ts-ignore-next-line - tcpSource.write(Buffer.from(e.data as ArrayBuffer)); - }); - wsTarget.addEventListener('close', () => { - log('WebSocket connection closed'); - tcpSource.end(); - }); - - tcpSource.on('data', function (data) { - log('TCP->WS message:', data); - if (wsTarget.readyState === WebSocket.OPEN) { - while (inBuffer.length > 0) { - wsSend(inBuffer.shift()!); - } - wsSend(data); - } else { - inBuffer.push(data); - } - }); - tcpSource.once('close', function () { - log('TCP connection closed'); - wsTarget.close(); - }); - tcpSource.on('error', function () { - log('TCP connection error'); - wsTarget.close(); - }); - }); - server.listen(tcpListenPort, function () { - log('TCP server listening'); - onListening?.(); - }); - return server; -} diff --git a/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts deleted file mode 100644 index 6e948d81796..00000000000 --- a/packages/php-wasm/node/src/lib/networking/outbound-tcp-socket.ts +++ /dev/null @@ -1,180 +0,0 @@ -/** - * Lets PHP open outbound TCP connections in Node.js. - * - * Emscripten implements sockets with WebSockets, and WebAssembly has no - * network access of its own. Emscripten creates those WebSockets through the - * `websocket.decorator` option, so we give it a class with the subset of the - * `ws` API it uses, backed by a TCP connection in the same process. - * - * CAUTION: Do not replace this with a WebSocket server. A server would need - * a listening port, and any program or web page on the machine could then use - * it to open TCP connections as this Node.js process. - */ -import { EventEmitter } from 'events'; -import * as net from 'net'; -import { debugLog } from './utils'; - -function log(...args: any[]) { - debugLog('[Outbound TCP]', ...args); -} - -const SOL_SOCKET = 1; -const SO_KEEPALIVE = 9; -const IPPROTO_TCP = 6; -const TCP_NODELAY = 1; - -/** - * Builds the URL Emscripten passes to the socket constructor. - * - * Nothing listens at this URL. It only carries the target host and port. - */ -export function getOutboundTcpSocketUrl(host: string, port: string) { - const query = new URLSearchParams({ host, port }).toString(); - return `tcp://php-wasm/?${query}`; -} - -/** - * Creates a socket class for one PHP runtime. - * - * Its `closeAll()` method closes the runtime's open connections when the - * runtime exits. - */ -export function createOutboundTcpSocketClass(): typeof OutboundTcpSocket & { - closeAll(): void; -} { - const openSockets = new Set(); - return class RuntimeOutboundTcpSocket extends OutboundTcpSocket { - static closeAll() { - for (const socket of openSockets) { - socket.close(); - } - } - - constructor(url: string) { - super(url); - openSockets.add(this); - this.once('close', () => openSockets.delete(this)); - } - }; -} - -/** - * A TCP connection with the subset of the `ws` WebSocket API that - * Emscripten's SOCKFS and the php-wasm socket functions use. - * - * The socket reports itself open right away and buffers writes until the TCP - * connection is established, like the WebSocket proxy it replaces. A connection - * that fails then closes, and PHP reads the end of the stream. - * - * CAUTION: Reporting the failure from connect() instead breaks cURL with JSPI. - * php-wasm's connect() drops a socket whose connection fails, so cURL's polls - * never see the failure, and it waits until its timeout. - */ -export class OutboundTcpSocket extends EventEmitter { - static readonly CONNECTING = 0; - static readonly OPEN = 1; - static readonly CLOSING = 2; - static readonly CLOSED = 3; - - readonly CONNECTING = OutboundTcpSocket.CONNECTING; - readonly OPEN = OutboundTcpSocket.OPEN; - readonly CLOSING = OutboundTcpSocket.CLOSING; - readonly CLOSED = OutboundTcpSocket.CLOSED; - - readonly url: string; - readyState: number = OutboundTcpSocket.CONNECTING; - binaryType = 'arraybuffer'; - private target?: net.Socket; - - constructor(url: string) { - super(); - this.url = url; - const { searchParams } = new URL(url); - const host = searchParams.get('host'); - const port = Number(searchParams.get('port')); - if (host && Number.isInteger(port) && port > 0 && port < 65536) { - this.target = this.connect(host, port); - } else { - log(`Invalid TCP address: ${host}:${port}`); - } - process.nextTick(() => { - if (this.readyState !== this.CONNECTING) { - return; - } - this.readyState = this.OPEN; - this.emit('open'); - if (!this.target) { - this.shutDown(); - } - }); - } - - send(data: ArrayBuffer | ArrayBufferView) { - if (this.readyState !== this.OPEN) { - throw new Error('The TCP connection is not open'); - } - const bytes = ArrayBuffer.isView(data) - ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) - : new Uint8Array(data); - this.target!.write(bytes); - } - - setSocketOpt(level: number, optionName: number, optionValue: number) { - if (level === SOL_SOCKET && optionName === SO_KEEPALIVE) { - this.target?.setKeepAlive(Boolean(optionValue)); - } else if (level === IPPROTO_TCP && optionName === TCP_NODELAY) { - this.target?.setNoDelay(Boolean(optionValue)); - } - } - - close() { - this.shutDown(); - } - - addEventListener(event: string, listener: (...args: any[]) => void) { - this.on(event, listener); - } - - removeEventListener(event: string, listener: (...args: any[]) => void) { - this.off(event, listener); - } - - private connect(host: string, port: number) { - log(`Connecting to ${host}:${port}`); - // Prefer IPv4 because many services (including Redis) only listen on - // IPv4 by default, and macOS resolves 'localhost' to IPv6 first. - const target = net.createConnection({ host, port, family: 4 }); - target.on('data', (data: Buffer) => { - // Emscripten ignores messages that aren't marked as binary. - this.emit('message', data, true); - }); - target.on('end', () => this.shutDown()); - target.on('error', (error) => { - log('Connection error', error); - this.shutDown(true); - }); - return target; - } - - /** - * Closes the connection and emits `close` on the next tick, like `ws`. - */ - private shutDown(destroy = false) { - if ( - this.readyState === this.CLOSING || - this.readyState === this.CLOSED - ) { - return; - } - this.readyState = this.CLOSING; - if (destroy) { - this.target?.destroy(); - } else { - this.target?.end(); - } - process.nextTick(() => { - this.readyState = this.CLOSED; - this.emit('close'); - }); - } -} diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts new file mode 100644 index 00000000000..19495c75538 --- /dev/null +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -0,0 +1,218 @@ +/** + * Lets PHP open and accept TCP connections in Node.js. + * + * Emscripten implements sockets with WebSockets, and WebAssembly has no + * network access of its own. Emscripten creates WebSockets through the + * `websocket.decorator` option and WebSocket servers through + * `websocket.serverDecorator`. We give it classes with the subset of the `ws` + * API it uses, backed by TCP sockets and servers in the same process. + * + * CAUTION: Do not route PHP's connections through a local WebSocket server. + * Any program or web page on the machine could connect to it and use PHP's + * connections, or open TCP connections as this Node.js process. + */ +import { EventEmitter } from 'events'; +import * as net from 'net'; +import { debugLog } from './utils'; + +function log(...args: any[]) { + debugLog('[TCP]', ...args); +} + +const SOL_SOCKET = 1; +const SO_KEEPALIVE = 9; +const IPPROTO_TCP = 6; +const TCP_NODELAY = 1; + +/** + * Builds the URL Emscripten passes to the socket constructor. + * + * Nothing listens at this URL. It only carries the target host and port. + */ +export function getOutboundTcpSocketUrl(host: string, port: string) { + const query = new URLSearchParams({ host, port }).toString(); + return `tcp://php-wasm/?${query}`; +} + +/** + * A TCP connection with the subset of the `ws` WebSocket API that + * Emscripten's SOCKFS and the php-wasm socket functions use. + */ +export class TcpSocket extends EventEmitter { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + + readonly CONNECTING = TcpSocket.CONNECTING; + readonly OPEN = TcpSocket.OPEN; + readonly CLOSING = TcpSocket.CLOSING; + readonly CLOSED = TcpSocket.CLOSED; + + readyState: number; + binaryType = 'arraybuffer'; + /** + * Emscripten reads the address of an accepted connection's peer from + * `_socket`, like it does for `ws` WebSockets. + */ + readonly _socket?: net.Socket; + + constructor(socket: net.Socket | undefined, readyState: number) { + super(); + this._socket = socket; + this.readyState = readyState; + socket?.on('data', (data: Buffer) => { + // Emscripten ignores messages that aren't marked as binary. + this.emit('message', data, true); + }); + socket?.on('end', () => this.shutDown()); + socket?.on('error', (error) => { + log('Connection error', error); + this.shutDown(true); + }); + } + + send(data: ArrayBuffer | ArrayBufferView) { + if (this.readyState !== this.OPEN) { + throw new Error('The TCP connection is not open'); + } + const bytes = ArrayBuffer.isView(data) + ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) + : new Uint8Array(data); + this._socket!.write(bytes); + } + + setSocketOpt(level: number, optionName: number, optionValue: number) { + if (level === SOL_SOCKET && optionName === SO_KEEPALIVE) { + this._socket?.setKeepAlive(Boolean(optionValue)); + } else if (level === IPPROTO_TCP && optionName === TCP_NODELAY) { + this._socket?.setNoDelay(Boolean(optionValue)); + } + } + + close() { + this.shutDown(); + } + + addEventListener(event: string, listener: (...args: any[]) => void) { + this.on(event, listener); + } + + removeEventListener(event: string, listener: (...args: any[]) => void) { + this.off(event, listener); + } + + /** + * Closes the connection and emits `close` on the next tick, like `ws`. + */ + protected shutDown(destroy = false) { + if ( + this.readyState === this.CLOSING || + this.readyState === this.CLOSED + ) { + return; + } + this.readyState = this.CLOSING; + if (destroy) { + this._socket?.destroy(); + } else { + this._socket?.end(); + } + process.nextTick(() => { + this.readyState = this.CLOSED; + this.emit('close'); + }); + } +} + +/** + * A TCP connection PHP opens. + * + * The socket reports itself open right away and buffers writes until the TCP + * connection is established, like the WebSocket proxy it replaces. A connection + * that fails then closes, and PHP reads the end of the stream. + * + * CAUTION: Reporting the failure from connect() instead breaks cURL with JSPI. + * php-wasm's connect() drops a socket whose connection fails, so cURL's polls + * never see the failure, and it waits until its timeout. + */ +export class OutboundTcpSocket extends TcpSocket { + readonly url: string; + + constructor(url: string) { + const { searchParams } = new URL(url); + const host = searchParams.get('host'); + const port = Number(searchParams.get('port')); + const isValid = + !!host && Number.isInteger(port) && port > 0 && port < 65536; + if (!isValid) { + log(`Invalid TCP address: ${host}:${port}`); + } + super(isValid ? connect(host, port) : undefined, TcpSocket.CONNECTING); + this.url = url; + process.nextTick(() => { + if (this.readyState !== this.CONNECTING) { + return; + } + this.readyState = this.OPEN; + this.emit('open'); + if (!this._socket) { + this.shutDown(); + } + }); + } +} + +export interface TcpServerOptions { + host?: string; + port?: number; +} + +/** + * A TCP server PHP listens on, with the subset of the `ws` WebSocketServer + * API that Emscripten's SOCKFS uses. + * + * It listens on the host and port PHP binds to, and emits each accepted + * connection as a `TcpSocket`. + */ +export class TcpServer extends EventEmitter { + readonly clients = new Set(); + private readonly server: net.Server; + + constructor({ host, port }: TcpServerOptions) { + super(); + this.server = net.createServer((socket) => { + const client = new TcpSocket(socket, TcpSocket.OPEN); + this.clients.add(client); + client.once('close', () => this.clients.delete(client)); + this.emit('connection', client); + }); + this.server.on('listening', () => this.emit('listening')); + this.server.on('close', () => this.emit('close')); + this.server.on('error', (error) => { + log('Server error', error); + this.emit('error', error); + }); + log(`Listening on ${host}:${port}`); + this.server.listen(port, host); + } + + address() { + return this.server.address(); + } + + /** + * Stops accepting connections. Accepted connections stay open, like + * closing a listening socket. + */ + close(callback?: (error?: Error) => void) { + this.server.close(callback); + } +} + +function connect(host: string, port: number) { + log(`Connecting to ${host}:${port}`); + // Prefer IPv4 because many services (including Redis) only listen on + // IPv4 by default, and macOS resolves 'localhost' to IPv6 first. + return net.createConnection({ host, port, family: 4 }); +} diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index c494b3a4eb2..996f17fdc4e 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -1,27 +1,56 @@ import type { EmscriptenOptions } from '@php-wasm/universal'; +// The compiled PHP runtime calls require('ws') before it passes the `ws` +// classes to the decorators below, so the package must keep depending on it. +import 'ws'; +import type { TcpServerOptions } from './tcp-socket'; import { - createOutboundTcpSocketClass, + OutboundTcpSocket, + TcpServer, + type TcpSocket, getOutboundTcpSocketUrl, -} from './outbound-tcp-socket'; -import { addTCPServerToWebSocketServerClass } from './inbound-tcp-to-ws-proxy'; +} from './tcp-socket'; export async function withNetworking( phpModuleArgs: EmscriptenOptions = {} ): Promise { - const OutboundTcpSocket = createOutboundTcpSocketClass(); + // The runtime closes these when it exits. + const openHandles = new Set(); + const track = (handle: TcpSocket | TcpServer) => { + openHandles.add(handle); + handle.once('close', () => openHandles.delete(handle)); + }; + + class RuntimeOutboundTcpSocket extends OutboundTcpSocket { + constructor(url: string) { + super(url); + track(this); + } + } + + class RuntimeTcpServer extends TcpServer { + constructor(options: TcpServerOptions) { + super(options); + track(this); + this.on('connection', track); + } + } return { ...phpModuleArgs, - closeOutboundConnections: () => OutboundTcpSocket.closeAll(), + closeNetworkConnections: () => { + for (const handle of openHandles) { + handle.close(); + } + }, websocket: { ...(phpModuleArgs['websocket'] || {}), url: (_: any, host: string, port: string) => getOutboundTcpSocketUrl(host, port), subprotocol: 'binary', - // Emscripten passes the `ws` WebSocket class here. Outbound - // connections use TCP directly instead of a local WebSocket server. - decorator: () => OutboundTcpSocket, - serverDecorator: addTCPServerToWebSocketServerClass, + // Emscripten passes the `ws` classes to these decorators. PHP's + // sockets use TCP directly instead of local WebSocket servers. + decorator: () => RuntimeOutboundTcpSocket, + serverDecorator: () => RuntimeTcpServer, }, }; } diff --git a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts index e98756dc861..49c1619d078 100644 --- a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts +++ b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts @@ -1,7 +1,6 @@ import net from 'node:net'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { withNetworking } from '../lib/networking/with-networking'; -import { addTCPServerToWebSocketServerClass } from '../lib/networking/inbound-tcp-to-ws-proxy'; describe('networking port allocation', () => { afterEach(() => { @@ -21,92 +20,19 @@ describe('networking port allocation', () => { expect(listenSpy).not.toHaveBeenCalled(); }); - it('binds the inbound websocket proxy directly on an automatic port', async () => { - class StubWebSocketServer extends EventTarget { - private readonly port = 43210; - public options: { port: number }; - - constructor(options: { port: number }) { - super(); - this.options = options; - process.nextTick(() => - this.dispatchEvent(new Event('listening')) - ); - } - - once(event: string, callback: () => void) { - this.addEventListener(event, callback, { once: true }); - } - - close(callback?: () => void) { - callback?.(); - } - - address() { - return { - address: '127.0.0.1', - family: 'IPv4', - port: this.port, - }; - } - } - - let closeCalled = false; - const listenCalls: unknown[][] = []; - const listenSpy = vi - .spyOn(net.Server.prototype, 'listen') - .mockImplementation(function ( - this: net.Server, - ...args: Parameters - ) { - listenCalls.push(args); - Object.defineProperty(this, 'listening', { - value: true, - configurable: true, - }); - process.nextTick(() => { - const callback = [...args] - .reverse() - .find( - (arg): arg is () => void => - typeof arg === 'function' - ); - callback?.(); - this.emit('listening'); - }); - return this; - }); - const closeSpy = vi - .spyOn(net.Server.prototype, 'close') - .mockImplementation(function (this: net.Server) { - closeCalled = true; - return this; - }); - - const DecoratedServer = addTCPServerToWebSocketServerClass( - StubWebSocketServer as any - ); - const onListening = vi.fn(function (this: unknown) { - expect(this).toBe(websocketServer); - }); - const websocketServer = new DecoratedServer( - { port: 12345 }, - onListening - ); + it('listens only on the host and port PHP binds to', async () => { + const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); - await new Promise((resolve) => process.nextTick(resolve)); - await new Promise((resolve) => process.nextTick(resolve)); + const emscriptenOptions = await withNetworking({}); + const Server = emscriptenOptions['websocket'].serverDecorator(); + const server = new Server({ host: '127.0.0.1', port: 0 }); + await new Promise((resolve) => server.once('listening', resolve)); try { - expect(websocketServer.options.port).toBe(0); - expect(listenCalls).toContainEqual([12345, expect.any(Function)]); - expect(onListening).toHaveBeenCalledOnce(); - websocketServer.close(); - expect(closeCalled).toBe(true); - expect(listenSpy).toHaveBeenCalled(); + expect(listenSpy).toHaveBeenCalledOnce(); + expect(server.address()).toMatchObject({ address: '127.0.0.1' }); } finally { - listenSpy.mockRestore(); - closeSpy.mockRestore(); + await new Promise((resolve) => server.close(resolve)); } }); }); diff --git a/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts b/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts index 5123fc2ac75..4f9320a99d9 100644 --- a/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'; import { OutboundTcpSocket, getOutboundTcpSocketUrl, -} from '../lib/networking/outbound-tcp-socket'; +} from '../lib/networking/tcp-socket'; describe('OutboundTcpSocket', () => { it('opens and then closes when the connection is refused', async () => { diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index b584fef2161..15645ca6406 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -448,9 +448,67 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { }); }); + describe('Listening sockets', () => { + it('should accept a connection and report the real peer address', async () => { + const port = await getUnusedPort(); + const php = new PHP(await loadNodeRuntime(phpVersion, options)); + let clientPort = 0; + let received = ''; + // PHP's server starts during php.run(), so retry until it listens. + const client = (async () => { + for (let attempt = 0; attempt < 100; attempt++) { + try { + await new Promise((resolve, reject) => { + const socket = net.connect(port, '127.0.0.1'); + socket.once('error', reject); + socket.once('connect', () => { + clientPort = socket.localPort!; + socket.write('hello from node'); + }); + socket.on('data', (data) => (received += data)); + socket.once('close', () => resolve()); + }); + return; + } catch { + await new Promise((resolve) => + setTimeout(resolve, 20) + ); + } + } + })(); + try { + const { text } = await php.run({ + code: ` $data, 'peer' => $peer]); + `, + }); + await client; + const { data, peer } = JSON.parse(text); + expect(data).toBe('hello from node'); + expect(peer).toBe(`127.0.0.1:${clientPort}`); + expect(received).toBe('hello from php'); + } finally { + php.exit(); + } + }); + }); + describe('Connection failures', () => { it('should fail promptly when cURL connects to a closed port', async () => { - const port = await getClosedPort(); + const port = await getUnusedPort(); const php = new PHP(await loadNodeRuntime(phpVersion, options)); try { const { text } = await php.run({ @@ -520,7 +578,7 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { }); }); -async function getClosedPort() { +async function getUnusedPort() { const server = net.createServer(); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve) diff --git a/packages/php-wasm/universal/src/lib/load-php-runtime.ts b/packages/php-wasm/universal/src/lib/load-php-runtime.ts index 162de11b6bb..7d5d68b14bd 100644 --- a/packages/php-wasm/universal/src/lib/load-php-runtime.ts +++ b/packages/php-wasm/universal/src/lib/load-php-runtime.ts @@ -172,7 +172,7 @@ export async function loadPHPRuntime( PHPRuntime.originalExit = PHPRuntime._exit; PHPRuntime._exit = function (code: number) { - PHPRuntime.closeOutboundConnections?.(); + PHPRuntime.closeNetworkConnections?.(); if (PHPRuntime.outboundNetworkProxyServer) { PHPRuntime.outboundNetworkProxyServer.close(); PHPRuntime.outboundNetworkProxyServer.closeAllConnections(); @@ -305,11 +305,12 @@ export type EmscriptenOptions = { monitorRunDependencies?: (left: number) => void; onMessage?: (listener: EmscriptenMessageListener) => void; /** - * Closes PHP's open outbound TCP connections. The runtime calls it on exit. + * Closes PHP's open TCP connections and listening sockets. The runtime + * calls it on exit. */ - closeOutboundConnections?: () => void; + closeNetworkConnections?: () => void; /** - * @deprecated php-wasm no longer sets this. Use `closeOutboundConnections`. + * @deprecated php-wasm no longer sets this. Use `closeNetworkConnections`. * * Node.js runtimes used to start a WebSocket-to-TCP proxy server on * 127.0.0.1 for PHP's outbound connections. Any program on the machine From 45eef64e246b4624e2c976093e06c4867d755538 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Wed, 4 Nov 2026 22:01:09 -0500 Subject: [PATCH 07/34] [ php-wasm ] Rename the socket spec to match tcp-socket.ts Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/php-wasm/node/project.json | 4 ++-- .../test/{outbound-tcp-socket.spec.ts => tcp-socket.spec.ts} | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename packages/php-wasm/node/src/test/{outbound-tcp-socket.spec.ts => tcp-socket.spec.ts} (100%) diff --git a/packages/php-wasm/node/project.json b/packages/php-wasm/node/project.json index 737e1659657..bda8a64def2 100644 --- a/packages/php-wasm/node/project.json +++ b/packages/php-wasm/node/project.json @@ -233,7 +233,7 @@ "php-sqlite3.spec.ts", "php-networking.spec.ts", "networking-port-allocation.spec.ts", - "outbound-tcp-socket.spec.ts", + "tcp-socket.spec.ts", "php-dynamic-loading.spec.ts", "php-mysqli.spec.ts", "php-process-manager.spec.ts", @@ -252,7 +252,7 @@ "php-sqlite3.spec.ts", "php-networking.spec.ts", "networking-port-allocation.spec.ts", - "outbound-tcp-socket.spec.ts", + "tcp-socket.spec.ts", "php-dynamic-loading.spec.ts", "php-mysqli.spec.ts", "php-process-manager.spec.ts", diff --git a/packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts similarity index 100% rename from packages/php-wasm/node/src/test/outbound-tcp-socket.spec.ts rename to packages/php-wasm/node/src/test/tcp-socket.spec.ts From 496f41fdf70968b9a0e2dff3dd0cff7bd078fbe8 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Thu, 5 Nov 2026 14:03:02 -0500 Subject: [PATCH 08/34] [ php-wasm ] Release TCP sockets when the runtime exits On exit, the runtime ended each socket gracefully. A socket still connecting to an unresponsive host, or one whose peer never closed its side, stayed open and kept the Node.js event loop alive. A socket that PHP had already closed was no longer tracked at all, though it could also stay open until the peer closed its side. `TcpSocket.destroy()` now releases the socket immediately, and the runtime calls it on exit. Sockets stay tracked until the TCP socket itself closes. Listening sockets still close normally. The exit test now uses a server that keeps its side open and writes to each connection after the runtime exits. It fails without this change. Also rewords the architecture doc sentence about Node.js networking. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../23-architecture/02-wasm-php-overview.md | 2 +- .../node/src/lib/networking/tcp-socket.ts | 9 ++++ .../src/lib/networking/with-networking.ts | 14 ++++-- .../node/src/test/php-networking.spec.ts | 48 +++++++++++++++---- 4 files changed, 59 insertions(+), 14 deletions(-) diff --git a/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md b/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md index 60583447cae..0d1fd7473f8 100644 --- a/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md +++ b/packages/docs/site/docs/developers/23-architecture/02-wasm-php-overview.md @@ -22,7 +22,7 @@ Because every PHP version is just a static .wasm file, the PHP version switcher When it comes to networking, WebAssembly programs are limited to calling JavaScript APIs. It is a safety feature, but also presents a challenge. How do you support low-level, synchronous networking code used by PHP with the high-level asynchronous APIs available in JavaScript? -In Node.js, the answer involves giving Emscripten's WebSocket-based sockets WebSocket-like objects backed by TCP sockets, [Asyncify](https://emscripten.org/docs/porting/asyncify.html), and patching deep PHP internals like php_select. It's complex, but there's a reward. The Node.js-targeted PHP build can request web APIs, install composer packages, and even connect to a MySQL server. +In Node.js, the answer involves TCP sockets that stand in for Emscripten's WebSockets, [Asyncify](https://emscripten.org/docs/porting/asyncify.html), and patching deep PHP internals like php_select. It's complex, but there's a reward. The Node.js-targeted PHP build can request web APIs, install composer packages, and even connect to a MySQL server. In the browser, networking is supported in two ways: diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 19495c75538..f9b9fa38a04 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -94,6 +94,15 @@ export class TcpSocket extends EventEmitter { this.shutDown(); } + /** + * Releases the TCP socket right away. A socket that PHP closed stays + * open until the peer closes its side, so this also releases those. + */ + destroy() { + this._socket?.destroy(); + this.shutDown(true); + } + addEventListener(event: string, listener: (...args: any[]) => void) { this.on(event, listener); } diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 996f17fdc4e..394249014a3 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -13,11 +13,15 @@ import { export async function withNetworking( phpModuleArgs: EmscriptenOptions = {} ): Promise { - // The runtime closes these when it exits. + // The runtime releases these when it exits. const openHandles = new Set(); const track = (handle: TcpSocket | TcpServer) => { openHandles.add(handle); - handle.once('close', () => openHandles.delete(handle)); + // A socket that PHP closed stays open until the peer closes its side, + // so keep tracking it until the TCP socket itself closes. + const closeEvents = + handle instanceof TcpServer ? handle : (handle._socket ?? handle); + closeEvents.once('close', () => openHandles.delete(handle)); }; class RuntimeOutboundTcpSocket extends OutboundTcpSocket { @@ -39,7 +43,11 @@ export async function withNetworking( ...phpModuleArgs, closeNetworkConnections: () => { for (const handle of openHandles) { - handle.close(); + if (handle instanceof TcpServer) { + handle.close(); + } else { + handle.destroy(); + } } }, websocket: { diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 15645ca6406..bdd24c9f881 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -416,10 +416,20 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { { timeout: 15000 } ); - it('should close open connections when runtime is exited', async () => { - const tcpServer = net.createServer(); - const connection = new Promise((resolve) => - tcpServer.once('connection', resolve) + it('should release open connections when runtime is exited', async () => { + // The server keeps its side open after the client closes. It then + // writes to each connection: a released socket answers with a reset + // and the connection closes, while a half-closed one accepts the data. + const tcpServer = net.createServer({ allowHalfOpen: true }); + const connections: net.Socket[] = []; + const bothConnected = new Promise((resolve) => + tcpServer.on('connection', (socket) => { + socket.resume(); + connections.push(socket); + if (connections.length === 2) { + resolve(); + } + }) ); await new Promise((resolve) => tcpServer.listen(0, '127.0.0.1', resolve) @@ -430,18 +440,36 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { await loadNodeRuntime(phpVersion, options) ); // A persistent socket stays open after the request ends. + // The other socket is closed by PHP but not by the server. await php.run({ - code: ` - socket.once('close', resolve) + await bothConnected; + const closed = connections.map( + (socket) => + new Promise((resolve) => { + socket.on('error', () => {}); + socket.once('close', resolve); + }) ); - socket.resume(); php.exit(); - await closed; + const writes = setInterval(() => { + for (const socket of connections) { + if (socket.writable) { + socket.write('x'); + } + } + }, 20); + try { + await Promise.all(closed); + } finally { + clearInterval(writes); + } } finally { tcpServer.close(); } From 0efe03f2274af3f10ef5270df633bd91ecfc0217 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Thu, 5 Nov 2026 19:54:46 -0500 Subject: [PATCH 09/34] [ php-wasm ] Stop on listen errors and listen on IPv4 for hostnames A TcpServer forwarded listen errors such as EADDRINUSE to Emscripten, which records them on the socket and moves on. PHP had already returned from listen(), so a server on an in-use port waited for connections forever. With the WebSocket bridge, the error went unhandled and stopped the process. Errors before the server listens are now left unhandled again, so the process exits with the error. Later errors still reach PHP's socket. When PHP binds to a hostname, the server now listens on its IPv4 address. Emscripten only represents IPv4 addresses, so a hostname that resolved to IPv6 first made PHP see every client as 0.0.0.0. Also removes the unused getServerPort(), moves the runtime exit test out of the cURL tests, and updates the php-wasm Node docs, which still described a WebSocket-to-TCP proxy. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../05-local-development/03-php-wasm-node.md | 4 +- .../node/src/lib/networking/tcp-socket.ts | 38 +++++++++++--- .../php-wasm/node/src/lib/networking/utils.ts | 12 ----- .../node/src/test/php-networking.spec.ts | 2 + .../php-wasm/node/src/test/tcp-socket.spec.ts | 50 +++++++++++++++++++ 5 files changed, 85 insertions(+), 21 deletions(-) diff --git a/packages/docs/site/docs/developers/05-local-development/03-php-wasm-node.md b/packages/docs/site/docs/developers/05-local-development/03-php-wasm-node.md index 9caa9080aaa..002e970089c 100644 --- a/packages/docs/site/docs/developers/05-local-development/03-php-wasm-node.md +++ b/packages/docs/site/docs/developers/05-local-development/03-php-wasm-node.md @@ -26,8 +26,8 @@ Consult the [complete list](/api/node) of Classes, Functions, Interfaces, and Ty Together, `@php-wasm/node` and a version-specific package provide the compiled PHP runtime and JavaScript API optimized for Node.js. PHP starts with an in-memory filesystem; use the Node.js filesystem helpers to mount host paths. -The runtime can access the network if you plug in a custom WebSocket-to-TCP -proxy. +PHP can open TCP connections and listen for them. The runtime uses Node.js +TCP sockets directly. ### Basic usage diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index f9b9fa38a04..a86f3bed450 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -11,6 +11,7 @@ * Any program or web page on the machine could connect to it and use PHP's * connections, or open TCP connections as this Node.js process. */ +import * as dns from 'dns'; import { EventEmitter } from 'events'; import * as net from 'net'; import { debugLog } from './utils'; @@ -183,6 +184,11 @@ export interface TcpServerOptions { * * It listens on the host and port PHP binds to, and emits each accepted * connection as a `TcpSocket`. + * + * CAUTION: An error before the server listens, such as EADDRINUSE, is left + * unhandled so that it stops the process. Emscripten's listen() has already + * returned by then, so PHP can't report it. If the error reached PHP's socket, + * PHP would wait for connections forever. */ export class TcpServer extends EventEmitter { readonly clients = new Set(); @@ -196,14 +202,27 @@ export class TcpServer extends EventEmitter { client.once('close', () => this.clients.delete(client)); this.emit('connection', client); }); - this.server.on('listening', () => this.emit('listening')); - this.server.on('close', () => this.emit('close')); - this.server.on('error', (error) => { - log('Server error', error); - this.emit('error', error); + this.server.on('listening', () => { + this.server.on('error', (error) => { + log('Server error', error); + this.emit('error', error); + }); + this.emit('listening'); }); - log(`Listening on ${host}:${port}`); - this.server.listen(port, host); + this.server.on('close', () => this.emit('close')); + if (host && net.isIP(host) === 0) { + // Emscripten only represents IPv4 addresses. A hostname that resolves + // to IPv6 first would make PHP see every client as 0.0.0.0. + dns.lookup(host, { family: 4 }, (error, address) => { + if (error) { + this.server.emit('error', error); + } else { + this.listen(port, address); + } + }); + } else { + this.listen(port, host); + } } address() { @@ -217,6 +236,11 @@ export class TcpServer extends EventEmitter { close(callback?: (error?: Error) => void) { this.server.close(callback); } + + private listen(port: number | undefined, host: string | undefined) { + log(`Listening on ${host}:${port}`); + this.server.listen(port, host); + } } function connect(host: string, port: number) { diff --git a/packages/php-wasm/node/src/lib/networking/utils.ts b/packages/php-wasm/node/src/lib/networking/utils.ts index 3e3c70b4490..f4f2fc1a129 100644 --- a/packages/php-wasm/node/src/lib/networking/utils.ts +++ b/packages/php-wasm/node/src/lib/networking/utils.ts @@ -1,4 +1,3 @@ -import type { AddressInfo } from 'net'; import { logger } from '@php-wasm/logger'; export function debugLog(message: any, ...args: any[]) { @@ -6,14 +5,3 @@ export function debugLog(message: any, ...args: any[]) { logger.log(message, ...args); } } - -export function getServerPort(server: { - address(): AddressInfo | string | null; -}): number { - const address = server.address(); - if (address === null || typeof address === 'string') { - throw new Error('Server address is not available'); - } - - return address.port; -} diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index bdd24c9f881..318ad45adbc 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -415,7 +415,9 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { }, { timeout: 15000 } ); + }); + describe('Runtime exit', () => { it('should release open connections when runtime is exited', async () => { // The server keeps its side open after the client closes. It then // writes to each connection: a released socket answers with a reset diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 4f9320a99d9..7268065a9d5 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -1,4 +1,6 @@ +import { execFile } from 'node:child_process'; import net from 'node:net'; +import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { OutboundTcpSocket, @@ -22,6 +24,54 @@ describe('OutboundTcpSocket', () => { }); }); +describe('TcpServer', () => { + it('stops the process when the port is already in use', async () => { + const blocker = net.createServer(); + await new Promise((resolve) => + blocker.listen(0, '127.0.0.1', resolve) + ); + const { port } = blocker.address() as net.AddressInfo; + // The error is uncaught by design, so run the server in a child process. + // Like Emscripten, the script listens for the server's `error` events. + const repoRoot = path.resolve(__dirname, '../../../../..'); + const loader = path.join( + repoRoot, + 'packages/meta/src/node-es-module-loader/loader.mts' + ); + const module = path.join(__dirname, '../lib/networking/tcp-socket.ts'); + const script = ` + import { TcpServer } from ${JSON.stringify(module)}; + const server = new TcpServer({ host: '127.0.0.1', port: ${port} }); + server.on('error', () => {}); + setTimeout(() => process.exit(0), 5000); + `; + try { + const { code, stderr } = await new Promise<{ + code: number; + stderr: string; + }>((resolve) => { + execFile( + process.execPath, + [ + '--no-warnings', + `--loader=${loader}`, + '--input-type=module', + '-e', + script, + ], + (error, _stdout, stderr) => + resolve({ code: Number(error?.code ?? 0), stderr }) + ); + }); + + expect(code).not.toBe(0); + expect(stderr).toContain('EADDRINUSE'); + } finally { + blocker.close(); + } + }, 15000); +}); + async function getClosedPort() { const server = net.createServer(); await new Promise((resolve) => From e5e7509df5320a4b2f6cf4e1e2bb0ce4b95b3356 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 00:53:01 -0500 Subject: [PATCH 10/34] [ php-wasm ] Don't listen after a server closes during its hostname lookup When PHP binds to a hostname, TcpServer looks up its IPv4 address before listening. If PHP or the runtime closed the server during the lookup, the server reported `close` and the runtime stopped tracking it, but it still started listening once the lookup finished. That listener stayed open after the runtime exited. The server now remembers that it was closed and skips listening. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 6 +++++ .../php-wasm/node/src/test/tcp-socket.spec.ts | 26 ++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index a86f3bed450..9bc920a8d61 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -193,6 +193,7 @@ export interface TcpServerOptions { export class TcpServer extends EventEmitter { readonly clients = new Set(); private readonly server: net.Server; + private closed = false; constructor({ host, port }: TcpServerOptions) { super(); @@ -214,6 +215,10 @@ export class TcpServer extends EventEmitter { // Emscripten only represents IPv4 addresses. A hostname that resolves // to IPv6 first would make PHP see every client as 0.0.0.0. dns.lookup(host, { family: 4 }, (error, address) => { + // PHP or the runtime may have closed the server during the lookup. + if (this.closed) { + return; + } if (error) { this.server.emit('error', error); } else { @@ -234,6 +239,7 @@ export class TcpServer extends EventEmitter { * closing a listening socket. */ close(callback?: (error?: Error) => void) { + this.closed = true; this.server.close(callback); } diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 7268065a9d5..40bed0ec13f 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -1,9 +1,11 @@ import { execFile } from 'node:child_process'; +import dns from 'node:dns'; import net from 'node:net'; import path from 'node:path'; -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { OutboundTcpSocket, + TcpServer, getOutboundTcpSocketUrl, } from '../lib/networking/tcp-socket'; @@ -25,6 +27,28 @@ describe('OutboundTcpSocket', () => { }); describe('TcpServer', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('does not listen when it closes during a hostname lookup', async () => { + const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); + + const server = new TcpServer({ host: 'localhost', port: 0 }); + server.close(); + // Let the server's own lookup of the same name finish first. + await new Promise((resolve) => + dns.lookup('localhost', { family: 4 }, resolve) + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + + try { + expect(listenSpy).not.toHaveBeenCalled(); + } finally { + server.close(); + } + }); + it('stops the process when the port is already in use', async () => { const blocker = net.createServer(); await new Promise((resolve) => From 8420138708895b8af8d7f37cbe14f7e4c0b31708 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 02:02:40 -0500 Subject: [PATCH 11/34] [ php-wasm ] Run the networking tests with Asyncify in CI Node.js enables JSPI by default from 24.20.0, so the test-unit-asyncify jobs load the JSPI build too. Node 24.18.0, the oldest supported version, still loads the Asyncify build, and nothing tested it. A new job runs the @php-wasm/node networking tests on Node 24.18.0. It first checks that JSPI is off, so it fails instead of quietly testing the JSPI build if the version changes. The inbound connection test gave up connecting after about two seconds, while PHP waited up to five. Under load on Asyncify, it timed out, and PHP kept running after the test ended. The client now retries until PHP stops waiting, and the test allows more time than PHP does. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/ci.yml | 44 +++++++++++++++++++ AGENTS.md | 4 ++ packages/php-wasm/node/project.json | 18 ++++++++ .../node/src/test/php-networking.spec.ts | 12 +++-- 4 files changed, 74 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c319a36a2fc..e36e6313004 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -257,6 +257,50 @@ jobs: MYSQL_DATABASE: test_db MYSQL_USER: user MYSQL_PASSWORD: password + # Node.js enables JSPI by default from 24.20.0, so the test-unit-asyncify + # jobs above load the JSPI build too. Node 24.18.0, the oldest supported + # version, still loads the Asyncify build. Run the networking tests there. + test-networking-asyncify: + needs: set-nx-shas + if: github.repository == 'WordPress/wordpress-playground' || github.event_name == 'pull_request' + name: 'Networking tests with Asyncify (Node 24.18.0)' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read # Required to clone the repo. + env: + NX_BASE: ${{ needs.set-nx-shas.outputs.base }} + NX_HEAD: ${{ needs.set-nx-shas.outputs.head }} + services: + mysql: + image: mysql:5.7 + env: + MYSQL_DATABASE: test_db + MYSQL_USER: user + MYSQL_PASSWORD: password + MYSQL_ROOT_PASSWORD: rootpassword + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping --silent" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - uses: ./.github/actions/prepare-playground + - uses: actions/setup-node@v4 + with: + node-version: 24.18.0 + - name: Check that this Node.js version loads the Asyncify build + run: node -e "if ('Suspending' in WebAssembly) { console.error('JSPI is enabled, so PHP would load the JSPI build.'); process.exit(1); }" + - run: node --expose-gc node_modules/nx/bin/nx affected --target=test-networking-asyncify + env: + MYSQL_DATABASE: test_db + MYSQL_USER: user + MYSQL_PASSWORD: password test-playground-cli: needs: set-nx-shas if: github.repository == 'WordPress/wordpress-playground' || github.event_name == 'pull_request' diff --git a/AGENTS.md b/AGENTS.md index 0278718d068..be4ab0791f3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -306,6 +306,10 @@ and runs PHP/SQLite, CLI multi-worker, and worker-wait tests with that addon mov out of resolution. The addon is restored before the shared dependency cache is saved. +Node.js enables JSPI by default from 24.20.0, so the `-asyncify` unit test targets +load the JSPI build in CI. The `test-networking-asyncify` job runs the +`@php-wasm/node` networking tests on Node 24.18.0, which loads the Asyncify build. + Dependabot's daily version check opens PRs for `fs-ext-extra-prebuilt` patch releases. It raises the minimum package version and updates the lockfile; the existing Dependabot lockfile workflow preserves workspace links. An explicit diff --git a/packages/php-wasm/node/project.json b/packages/php-wasm/node/project.json index bda8a64def2..da0ba788c82 100644 --- a/packages/php-wasm/node/project.json +++ b/packages/php-wasm/node/project.json @@ -312,6 +312,24 @@ "testFiles": ["php-part-2.spec.ts"] } }, + "test-networking-asyncify": { + "executor": "@nx/vitest:test", + "outputs": ["{workspaceRoot}/coverage/packages/php-wasm/node"], + "options": { + "reportsDirectory": "../../../coverage/packages/php-wasm/node", + "testFiles": [ + "tcp-socket.spec.ts", + "networking-port-allocation.spec.ts", + "php-networking.spec.ts", + "php-fsockopen.spec.ts", + "php-socket-timeouts.spec.ts", + "php-file-get-contents.spec.ts", + "php-fopen.spec.ts", + "php-gethostbyname.spec.ts", + "php-mysqli.spec.ts" + ] + } + }, "test-redis-extension-jspi": { "executor": "@nx/vitest:test", "outputs": ["{workspaceRoot}/coverage/packages/php-wasm/node"], diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 318ad45adbc..b5b3077665b 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -484,9 +484,11 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { const php = new PHP(await loadNodeRuntime(phpVersion, options)); let clientPort = 0; let received = ''; - // PHP's server starts during php.run(), so retry until it listens. + let phpFinished = false; + // PHP's server starts during php.run(), so retry until it listens + // or PHP stops waiting for a connection. const client = (async () => { - for (let attempt = 0; attempt < 100; attempt++) { + while (!phpFinished) { try { await new Promise((resolve, reject) => { const socket = net.connect(port, '127.0.0.1'); @@ -512,7 +514,7 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { $server = stream_socket_server("tcp://127.0.0.1:${port}"); $start = microtime(true); $connection = false; - while (!$connection && microtime(true) - $start < 5) { + while (!$connection && microtime(true) - $start < 10) { $connection = @stream_socket_accept($server, 0.1, $peer); if (!$connection) { usleep(10000); @@ -525,15 +527,17 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { echo json_encode(['data' => $data, 'peer' => $peer]); `, }); + phpFinished = true; await client; const { data, peer } = JSON.parse(text); expect(data).toBe('hello from node'); expect(peer).toBe(`127.0.0.1:${clientPort}`); expect(received).toBe('hello from php'); } finally { + phpFinished = true; php.exit(); } - }); + }, 15000); }); describe('Connection failures', () => { From a2a1bf761898bfd19cddc172fcf6aa7579b9948a Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 02:02:41 -0500 Subject: [PATCH 12/34] [ php-wasm ] Test networking in the built npm packages The compiled PHP runtime loads `ws` when PHP opens a socket, but no source file needs it. If the published @php-wasm/node stopped depending on it, every connection would fail with "host unreachable". The built-package tests now open a TCP connection from PHP and check that @php-wasm/node depends on `ws`. The connection test alone can't catch a missing dependency, because the test project sits inside the repository and resolves `ws` from the root node_modules. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../es-modules-and-vitest/run-tests.ts | 1 + .../tests/networking.spec.ts | 59 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 packages/playground/test-built-npm-packages/es-modules-and-vitest/tests/networking.spec.ts diff --git a/packages/playground/test-built-npm-packages/es-modules-and-vitest/run-tests.ts b/packages/playground/test-built-npm-packages/es-modules-and-vitest/run-tests.ts index d871ce2ffce..2ad28e6ac68 100644 --- a/packages/playground/test-built-npm-packages/es-modules-and-vitest/run-tests.ts +++ b/packages/playground/test-built-npm-packages/es-modules-and-vitest/run-tests.ts @@ -43,6 +43,7 @@ const testFiles = [ './tests/wp.spec.ts', './tests/git-directory.spec.ts', './tests/assets.spec.ts', + './tests/networking.spec.ts', ]; for (const phpVersion of SupportedPHPVersions) { diff --git a/packages/playground/test-built-npm-packages/es-modules-and-vitest/tests/networking.spec.ts b/packages/playground/test-built-npm-packages/es-modules-and-vitest/tests/networking.spec.ts new file mode 100644 index 00000000000..8e73a8d6b5d --- /dev/null +++ b/packages/playground/test-built-npm-packages/es-modules-and-vitest/tests/networking.spec.ts @@ -0,0 +1,59 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import net from 'node:net'; +import { fileURLToPath } from 'node:url'; +import { loadNodeRuntime } from '@php-wasm/node'; +import type { SupportedPHPVersion } from '@php-wasm/universal'; +import { PHP, SupportedPHPVersions } from '@php-wasm/universal'; + +const phpVersion = process.env.PHP_VERSION as SupportedPHPVersion; +if (!phpVersion) { + throw new Error('PHP_VERSION is not set'); +} +if (!SupportedPHPVersions.includes(phpVersion)) { + throw new Error(`PHP_VERSION '${phpVersion}' is not supported`); +} + +describe(`PHP ${phpVersion}`, () => { + it('Should open a TCP connection', { timeout: 60000 }, async () => { + const server = net.createServer((socket) => socket.end('pong')); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + const php = new PHP( + await loadNodeRuntime(phpVersion, { + emscriptenOptions: { processId: 1 }, + }) + ); + try { + const { text } = await php.run({ + code: ` { + const packageJsonPath = fileURLToPath( + import.meta.resolve('@php-wasm/node/package.json') + ); + const { dependencies } = JSON.parse( + await readFile(packageJsonPath, 'utf8') + ); + assert.ok(dependencies?.ws, '@php-wasm/node must depend on ws'); + }); +}); From f1aaf8b6a2b5d82ecb5b17454f2255aad34f83d9 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 13:48:06 -0500 Subject: [PATCH 13/34] [ php-wasm ] Refuse to run the Asyncify networking tests with JSPI test-networking-asyncify loaded the JSPI build on Node.js 24.20.0 and later without saying so, because only the CI job checked the Node.js version. JSPI can't be turned off in those versions. The target now uses vite.asyncify.config.ts, which stops with an error when JSPI is enabled and suggests Node.js 24.18 or 24.19. The CI job no longer needs its own check. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/ci.yml | 2 -- AGENTS.md | 1 + packages/php-wasm/node/project.json | 1 + .../php-wasm/node/vite.asyncify.config.ts | 20 +++++++++++++++++++ 4 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 packages/php-wasm/node/vite.asyncify.config.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e36e6313004..9e445f802ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -294,8 +294,6 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 24.18.0 - - name: Check that this Node.js version loads the Asyncify build - run: node -e "if ('Suspending' in WebAssembly) { console.error('JSPI is enabled, so PHP would load the JSPI build.'); process.exit(1); }" - run: node --expose-gc node_modules/nx/bin/nx affected --target=test-networking-asyncify env: MYSQL_DATABASE: test_db diff --git a/AGENTS.md b/AGENTS.md index be4ab0791f3..2ae781872f4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -309,6 +309,7 @@ The addon is restored before the shared dependency cache is saved. Node.js enables JSPI by default from 24.20.0, so the `-asyncify` unit test targets load the JSPI build in CI. The `test-networking-asyncify` job runs the `@php-wasm/node` networking tests on Node 24.18.0, which loads the Asyncify build. +Its `vite.asyncify.config.ts` stops with an error on Node versions that enable JSPI. Dependabot's daily version check opens PRs for `fs-ext-extra-prebuilt` patch releases. It raises the minimum package version and updates the lockfile; the diff --git a/packages/php-wasm/node/project.json b/packages/php-wasm/node/project.json index da0ba788c82..79edfe9de1e 100644 --- a/packages/php-wasm/node/project.json +++ b/packages/php-wasm/node/project.json @@ -316,6 +316,7 @@ "executor": "@nx/vitest:test", "outputs": ["{workspaceRoot}/coverage/packages/php-wasm/node"], "options": { + "configFile": "packages/php-wasm/node/vite.asyncify.config.ts", "reportsDirectory": "../../../coverage/packages/php-wasm/node", "testFiles": [ "tcp-socket.spec.ts", diff --git a/packages/php-wasm/node/vite.asyncify.config.ts b/packages/php-wasm/node/vite.asyncify.config.ts new file mode 100644 index 00000000000..ccb48c9330b --- /dev/null +++ b/packages/php-wasm/node/vite.asyncify.config.ts @@ -0,0 +1,20 @@ +import { defineConfig } from 'vite'; +import config from './vite.config'; + +/** + * For tests that must load the Asyncify PHP build. + * + * loadNodeRuntime() loads the JSPI build whenever Node.js supports JSPI. + * Node.js enables JSPI by default from 24.20.0, and it can't be turned off, + * so these tests need an older Node.js version. + */ +export default defineConfig((env) => { + if ('Suspending' in WebAssembly) { + throw new Error( + `Node.js ${process.version} enables JSPI, so PHP would load the JSPI ` + + 'build instead of Asyncify. Run these tests with Node.js 24.18 or ' + + '24.19, for example after `nvm install 24.18.0`.' + ); + } + return config(env); +}); From 7bdeba1923a75228b82cd2193131f865de637893 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 13:48:07 -0500 Subject: [PATCH 14/34] [ php-wasm ] Drop data after PHP closes a TCP socket After PHP closed a socket, data the peer kept sending was still passed to Emscripten, which queued it for a socket nobody reads. The socket now drops that data and resets the connection, like a closed native socket. The test for closing a server during its hostname lookup now controls the lookup callback. Before, it could pass without exercising the fix if the lookup finished late. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 9 +++ .../php-wasm/node/src/test/tcp-socket.spec.ts | 74 +++++++++++++++---- 2 files changed, 70 insertions(+), 13 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 9bc920a8d61..1828f68fba7 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -63,6 +63,15 @@ export class TcpSocket extends EventEmitter { this._socket = socket; this.readyState = readyState; socket?.on('data', (data: Buffer) => { + // PHP has closed the socket, so nothing will read this data. Reset + // the connection like a closed native socket would. + if ( + this.readyState === this.CLOSING || + this.readyState === this.CLOSED + ) { + socket.destroy(); + return; + } // Emscripten ignores messages that aren't marked as binary. this.emit('message', data, true); }); diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 40bed0ec13f..144ca207d34 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -1,5 +1,5 @@ import { execFile } from 'node:child_process'; -import dns from 'node:dns'; +import * as dns from 'dns'; import net from 'node:net'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -9,6 +9,11 @@ import { getOutboundTcpSocketUrl, } from '../lib/networking/tcp-socket'; +vi.mock('dns', async (importOriginal) => { + const original = await importOriginal(); + return { ...original, lookup: vi.fn(original.lookup) }; +}); + describe('OutboundTcpSocket', () => { it('opens and then closes when the connection is refused', async () => { const port = await getClosedPort(); @@ -24,6 +29,49 @@ describe('OutboundTcpSocket', () => { expect(events).toEqual(['open']); expect(socket.readyState).toBe(OutboundTcpSocket.CLOSED); }); + + it('drops data and resets the connection after it closes', async () => { + // The server keeps its side open and keeps writing after the client + // closes. Only a reset from the client closes the server's socket. + const server = net.createServer({ allowHalfOpen: true }); + const connection = new Promise((resolve) => + server.once('connection', resolve) + ); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + const socket = new OutboundTcpSocket( + getOutboundTcpSocketUrl('127.0.0.1', String(port)) + ); + const messages: Buffer[] = []; + socket.on('message', (data: Buffer) => messages.push(data)); + const serverSocket = await connection; + serverSocket.on('error', () => {}); + const ended = new Promise((resolve) => + serverSocket.once('end', resolve) + ); + serverSocket.resume(); + + socket.close(); + await ended; + const closed = new Promise((resolve) => + serverSocket.once('close', resolve) + ); + const writes = setInterval(() => { + if (serverSocket.writable) { + serverSocket.write('sent after close'); + } + }, 20); + try { + await closed; + } finally { + clearInterval(writes); + server.close(); + } + + expect(messages).toEqual([]); + }); }); describe('TcpServer', () => { @@ -31,22 +79,22 @@ describe('TcpServer', () => { vi.restoreAllMocks(); }); - it('does not listen when it closes during a hostname lookup', async () => { + it('does not listen when it closes during a hostname lookup', () => { + let finishLookup = () => {}; + vi.mocked(dns.lookup).mockImplementationOnce((( + _hostname: string, + _options: dns.LookupOptions, + callback: (error: null, address: string, family: number) => void + ) => { + finishLookup = () => callback(null, '127.0.0.1', 4); + }) as typeof dns.lookup); const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); - const server = new TcpServer({ host: 'localhost', port: 0 }); + const server = new TcpServer({ host: 'php-wasm.test', port: 0 }); server.close(); - // Let the server's own lookup of the same name finish first. - await new Promise((resolve) => - dns.lookup('localhost', { family: 4 }, resolve) - ); - await new Promise((resolve) => setTimeout(resolve, 50)); + finishLookup(); - try { - expect(listenSpy).not.toHaveBeenCalled(); - } finally { - server.close(); - } + expect(listenSpy).not.toHaveBeenCalled(); }); it('stops the process when the port is already in use', async () => { From 8dbdf7688759c45fe935ac0a6f84e615e3367f2f Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 13:48:08 -0500 Subject: [PATCH 15/34] [ php-wasm ] Avoid an Asyncify accept() crash in the inbound test With Asyncify, PHP crashes if stream_socket_accept() has to wait inside its internal poll, for a connection that hasn't sent data yet. Trunk crashes the same way; zif_stream_socket_accept and php_stream_xport_accept are missing from ASYNCIFY_ONLY. Fixing that needs a PHP rebuild, tracked in #4576. The inbound test now waits briefly after stream_select() reports the connection, so its data has arrived before PHP accepts it. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../php-wasm/node/src/test/php-networking.spec.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index b5b3077665b..607ba9c9002 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -514,9 +514,16 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { $server = stream_socket_server("tcp://127.0.0.1:${port}"); $start = microtime(true); $connection = false; + // Accept only after the connection's data has arrived. With + // Asyncify, PHP crashes if stream_socket_accept() has to wait. + // See https://github.com/WordPress/wordpress-playground/issues/4576. while (!$connection && microtime(true) - $start < 10) { - $connection = @stream_socket_accept($server, 0.1, $peer); - if (!$connection) { + $read = [$server]; + $write = $except = null; + if (stream_select($read, $write, $except, 0, 100000)) { + usleep(50000); + $connection = stream_socket_accept($server, 0, $peer); + } else { usleep(10000); } } From 6ea6cf8d1d72e3c7726c8365ee7379a4509600d3 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 21:09:09 -0500 Subject: [PATCH 16/34] [ php-wasm ] Fix reset handling in the TCP socket adapters A client that reset its connection before Node.js handled it reached PHP without a remote address. Emscripten's accept() then failed with a JavaScript TypeError instead of an errno, so any client that could reach PHP's port could crash it. TcpServer now drops such connections. When the peer sent data after PHP closed a socket, the socket was destroyed right away, discarding what PHP had written but Node.js had not sent yet. It now resets the connection only after those writes are sent. send() also checks that the socket exists instead of relying on a non-null assertion, and the hostname lookup test checks that its mock was used. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 32 ++++++-- .../php-wasm/node/src/test/tcp-socket.spec.ts | 78 +++++++++++++++++++ 2 files changed, 105 insertions(+), 5 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 1828f68fba7..dbb2286a106 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -57,19 +57,19 @@ export class TcpSocket extends EventEmitter { * `_socket`, like it does for `ws` WebSockets. */ readonly _socket?: net.Socket; + private resetPending = false; constructor(socket: net.Socket | undefined, readyState: number) { super(); this._socket = socket; this.readyState = readyState; socket?.on('data', (data: Buffer) => { - // PHP has closed the socket, so nothing will read this data. Reset - // the connection like a closed native socket would. + // PHP has closed the socket, so nothing will read this data. if ( this.readyState === this.CLOSING || this.readyState === this.CLOSED ) { - socket.destroy(); + this.resetAfterWrites(); return; } // Emscripten ignores messages that aren't marked as binary. @@ -83,13 +83,13 @@ export class TcpSocket extends EventEmitter { } send(data: ArrayBuffer | ArrayBufferView) { - if (this.readyState !== this.OPEN) { + if (this.readyState !== this.OPEN || !this._socket) { throw new Error('The TCP connection is not open'); } const bytes = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data); - this._socket!.write(bytes); + this._socket.write(bytes); } setSocketOpt(level: number, optionName: number, optionValue: number) { @@ -142,6 +142,21 @@ export class TcpSocket extends EventEmitter { this.emit('close'); }); } + + /** + * Resets a connection PHP has closed, like a closed native socket would, + * once Node.js has sent everything PHP wrote. PHP's writes don't block, so + * resetting right away could discard them. + */ + private resetAfterWrites() { + const socket = this._socket!; + if (socket.writableFinished) { + socket.destroy(); + } else if (!this.resetPending) { + this.resetPending = true; + socket.once('finish', () => socket.destroy()); + } + } } /** @@ -207,6 +222,13 @@ export class TcpServer extends EventEmitter { constructor({ host, port }: TcpServerOptions) { super(); this.server = net.createServer((socket) => { + // A client that reset the connection before Node.js handled it has + // no address. Emscripten's accept() fails on that with a JavaScript + // error instead of an errno, so drop the connection. + if (!socket.remoteAddress) { + socket.destroy(); + return; + } const client = new TcpSocket(socket, TcpSocket.OPEN); this.clients.add(client); client.once('close', () => this.clients.delete(client)); diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 144ca207d34..2ba5a5b6069 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { OutboundTcpSocket, TcpServer, + type TcpSocket, getOutboundTcpSocketUrl, } from '../lib/networking/tcp-socket'; @@ -72,6 +73,48 @@ describe('OutboundTcpSocket', () => { expect(messages).toEqual([]); }); + + it('sends everything written before it closes, even if the peer replies', async () => { + // The server stops reading, so the writes stay buffered in Node.js + // when the socket closes. Its reply then arrives after the close. + const size = 16 * 1024 * 1024; + const server = net.createServer({ allowHalfOpen: true }); + const connection = new Promise((resolve) => + server.once('connection', resolve) + ); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + const socket = new OutboundTcpSocket( + getOutboundTcpSocketUrl('127.0.0.1', String(port)) + ); + await new Promise((resolve) => socket.once('open', resolve)); + const serverSocket = await connection; + serverSocket.pause(); + serverSocket.on('error', () => {}); + let received = 0; + const ended = new Promise((resolve) => { + serverSocket.on('data', (data) => (received += data.length)); + serverSocket.once('end', resolve); + serverSocket.once('close', resolve); + }); + + socket.send(new Uint8Array(size)); + socket.close(); + await new Promise((resolve) => socket.once('close', resolve)); + serverSocket.write('+OK'); + await new Promise((resolve) => setTimeout(resolve, 100)); + serverSocket.resume(); + try { + await ended; + } finally { + serverSocket.destroy(); + server.close(); + } + + expect(received).toBe(size); + }); }); describe('TcpServer', () => { @@ -94,9 +137,44 @@ describe('TcpServer', () => { server.close(); finishLookup(); + expect(dns.lookup).toHaveBeenCalled(); expect(listenSpy).not.toHaveBeenCalled(); }); + it('does not pass on connections that were reset before they were handled', async () => { + const server = new TcpServer({ host: '127.0.0.1', port: 0 }); + await new Promise((resolve) => server.once('listening', resolve)); + const { port } = server.address() as net.AddressInfo; + const addresses: Array = []; + server.on('connection', (client: TcpSocket) => { + addresses.push(client._socket?.remoteAddress); + }); + + try { + // Most of these reach the server already reset. + await Promise.all( + Array.from( + { length: 50 }, + () => + new Promise((resolve) => { + const socket: net.Socket = net.connect( + port, + '127.0.0.1', + () => socket.resetAndDestroy() + ); + socket.on('error', () => {}); + socket.once('close', () => resolve()); + }) + ) + ); + await new Promise((resolve) => setTimeout(resolve, 100)); + } finally { + server.close(); + } + + expect(addresses).not.toContain(undefined); + }); + it('stops the process when the port is already in use', async () => { const blocker = net.createServer(); await new Promise((resolve) => From 05f42cdfc1bd892360122752202ce8b629deb155 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 21:09:10 -0500 Subject: [PATCH 17/34] [ php-wasm ] Make the runtime exit test check exit cleanup directly Since data sent after PHP closes a socket resets the connection, the exit test's server writes released the closed socket even when exit cleanup didn't. The test now checks that exiting the runtime destroys both client sockets, and fails if tracking stops when PHP closes one. Also corrects the inbound test's comment about stream_select(). Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/test/php-networking.spec.ts | 49 ++++++++++--------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 607ba9c9002..420d62543b3 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -419,9 +419,8 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { describe('Runtime exit', () => { it('should release open connections when runtime is exited', async () => { - // The server keeps its side open after the client closes. It then - // writes to each connection: a released socket answers with a reset - // and the connection closes, while a half-closed one accepts the data. + // The server keeps its side open after the client closes, so only + // the runtime can release these connections. const tcpServer = net.createServer({ allowHalfOpen: true }); const connections: net.Socket[] = []; const bothConnected = new Promise((resolve) => @@ -450,29 +449,29 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { `, }); await bothConnected; - const closed = connections.map( - (socket) => - new Promise((resolve) => { - socket.on('error', () => {}); - socket.once('close', resolve); - }) - ); - - php.exit(); - - const writes = setInterval(() => { - for (const socket of connections) { - if (socket.writable) { - socket.write('x'); + const destroyed = new Set(); + const destroy = net.Socket.prototype.destroy; + const destroySpy = vi + .spyOn(net.Socket.prototype, 'destroy') + .mockImplementation(function ( + this: net.Socket, + ...args: Parameters + ) { + if (this.remotePort === port) { + destroyed.add(this); } - } - }, 20); + return destroy.apply(this, args); + }); + try { - await Promise.all(closed); + php.exit(); } finally { - clearInterval(writes); + destroySpy.mockRestore(); } + + expect(destroyed.size).toBe(2); } finally { + connections.forEach((socket) => socket.destroy()); tcpServer.close(); } }); @@ -514,9 +513,11 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { $server = stream_socket_server("tcp://127.0.0.1:${port}"); $start = microtime(true); $connection = false; - // Accept only after the connection's data has arrived. With - // Asyncify, PHP crashes if stream_socket_accept() has to wait. - // See https://github.com/WordPress/wordpress-playground/issues/4576. + // stream_select() reports the server as soon as a connection is + // pending, before its data arrives. Pause so the data is there + // before accepting: with Asyncify, PHP crashes if + // stream_socket_accept() has to wait. See + // https://github.com/WordPress/wordpress-playground/issues/4576. while (!$connection && microtime(true) - $start < 10) { $read = [$server]; $write = $except = null; From 264dabbf36838aabab52d5c9980fe5c1be789d5c Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 21:16:15 -0500 Subject: [PATCH 18/34] [ php-wasm ] Explain the less obvious choices in the TCP adapters Adds comments on why the adapters match parts of the `ws` API that Emscripten relies on, why a socket closes without reporting errors, why an invalid address opens before it closes, why exit cleanup destroys sockets, and why the Asyncify CI job switches Node.js versions after installing dependencies. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/ci.yml | 2 ++ .../node/src/lib/networking/tcp-socket.ts | 22 ++++++++++++++++++- .../src/lib/networking/with-networking.ts | 3 +++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9e445f802ba..7f3adc20b80 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -290,6 +290,8 @@ jobs: - uses: actions/checkout@v4 with: submodules: true + # Install with Node 24 to reuse the shared dependency cache, then + # switch to the version that loads the Asyncify build. - uses: ./.github/actions/prepare-playground - uses: actions/setup-node@v4 with: diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index dbb2286a106..356289ff6df 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -45,12 +45,15 @@ export class TcpSocket extends EventEmitter { static readonly CLOSING = 2; static readonly CLOSED = 3; + // Emscripten compares readyState with these on the instance, like + // `ws.readyState === ws.OPEN`. readonly CONNECTING = TcpSocket.CONNECTING; readonly OPEN = TcpSocket.OPEN; readonly CLOSING = TcpSocket.CLOSING; readonly CLOSED = TcpSocket.CLOSED; readyState: number; + // Emscripten sets this. The socket always delivers binary data. binaryType = 'arraybuffer'; /** * Emscripten reads the address of an accepted connection's peer from @@ -75,7 +78,11 @@ export class TcpSocket extends EventEmitter { // Emscripten ignores messages that aren't marked as binary. this.emit('message', data, true); }); + // Emscripten has no half-closed state. PHP reads the data it already + // received and then the end of the stream. socket?.on('end', () => this.shutDown()); + // Close without emitting `error`, so PHP reads the end of the stream as it + // did with the WebSocket proxy. See the CAUTION on OutboundTcpSocket. socket?.on('error', (error) => { log('Connection error', error); this.shutDown(true); @@ -92,6 +99,11 @@ export class TcpSocket extends EventEmitter { this._socket.write(bytes); } + /** + * For php-wasm's setsockopt() with SO_KEEPALIVE and TCP_NODELAY. The current + * PHP builds look the socket up by file descriptor and never find it, so + * this isn't called yet. + */ setSocketOpt(level: number, optionName: number, optionValue: number) { if (level === SOL_SOCKET && optionName === SO_KEEPALIVE) { this._socket?.setKeepAlive(Boolean(optionValue)); @@ -113,6 +125,7 @@ export class TcpSocket extends EventEmitter { this.shutDown(true); } + // php-wasm's connect() listens with the DOM-style event API. addEventListener(event: string, listener: (...args: any[]) => void) { this.on(event, listener); } @@ -184,12 +197,14 @@ export class OutboundTcpSocket extends TcpSocket { } super(isValid ? connect(host, port) : undefined, TcpSocket.CONNECTING); this.url = url; + // Emscripten attaches its listeners after the constructor returns. process.nextTick(() => { if (this.readyState !== this.CONNECTING) { return; } this.readyState = this.OPEN; this.emit('open'); + // Treat an invalid address like a failed connection: open, then close. if (!this._socket) { this.shutDown(); } @@ -215,6 +230,7 @@ export interface TcpServerOptions { * PHP would wait for connections forever. */ export class TcpServer extends EventEmitter { + // php-wasm's poll() waits on these for data on a listening socket. readonly clients = new Set(); private readonly server: net.Server; private closed = false; @@ -234,6 +250,8 @@ export class TcpServer extends EventEmitter { client.once('close', () => this.clients.delete(client)); this.emit('connection', client); }); + // Forward errors only once the server listens. Earlier errors stay + // unhandled; see the CAUTION above. this.server.on('listening', () => { this.server.on('error', (error) => { log('Server error', error); @@ -251,6 +269,7 @@ export class TcpServer extends EventEmitter { return; } if (error) { + // Unhandled, like an error from listen(). this.server.emit('error', error); } else { this.listen(port, address); @@ -283,6 +302,7 @@ export class TcpServer extends EventEmitter { function connect(host: string, port: number) { log(`Connecting to ${host}:${port}`); // Prefer IPv4 because many services (including Redis) only listen on - // IPv4 by default, and macOS resolves 'localhost' to IPv6 first. + // IPv4 by default, and macOS resolves 'localhost' to IPv6 first. `family` + // only affects hostname lookups; IPv6 addresses still connect directly. return net.createConnection({ host, port, family: 4 }); } diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 394249014a3..9a1744e611f 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -24,6 +24,7 @@ export async function withNetworking( closeEvents.once('close', () => openHandles.delete(handle)); }; + // Each runtime gets its own classes, so it only releases its own sockets. class RuntimeOutboundTcpSocket extends OutboundTcpSocket { constructor(url: string) { super(url); @@ -42,6 +43,8 @@ export async function withNetworking( return { ...phpModuleArgs, closeNetworkConnections: () => { + // Destroy sockets instead of ending them: an ended socket stays open + // until the peer closes its side, and keeps Node.js running. for (const handle of openHandles) { if (handle instanceof TcpServer) { handle.close(); From 22bb66cf3d3ec11500dba46193f029dc42d1cafd Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Fri, 6 Nov 2026 22:17:57 -0500 Subject: [PATCH 19/34] [ php-wasm ] Test the missing-address check deterministically The test that reset 50 connections only exercised the check when some of them reached the server already reset, which depends on timing and the OS. It could pass with the check removed. The test now hands the server a socket without a remote address directly and checks that it is destroyed and never reaches PHP. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../php-wasm/node/src/test/tcp-socket.spec.ts | 36 +++++++------------ 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 2ba5a5b6069..03752506462 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -6,7 +6,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { OutboundTcpSocket, TcpServer, - type TcpSocket, getOutboundTcpSocketUrl, } from '../lib/networking/tcp-socket'; @@ -141,38 +140,27 @@ describe('TcpServer', () => { expect(listenSpy).not.toHaveBeenCalled(); }); - it('does not pass on connections that were reset before they were handled', async () => { + it('drops a connection that has no remote address', async () => { const server = new TcpServer({ host: '127.0.0.1', port: 0 }); await new Promise((resolve) => server.once('listening', resolve)); - const { port } = server.address() as net.AddressInfo; - const addresses: Array = []; - server.on('connection', (client: TcpSocket) => { - addresses.push(client._socket?.remoteAddress); - }); + const onConnection = vi.fn(); + server.on('connection', onConnection); + // A connection reset before Node.js handles it has no remote address, + // like a socket that was never connected. + const socket = new net.Socket(); + const destroy = vi.spyOn(socket, 'destroy'); try { - // Most of these reach the server already reset. - await Promise.all( - Array.from( - { length: 50 }, - () => - new Promise((resolve) => { - const socket: net.Socket = net.connect( - port, - '127.0.0.1', - () => socket.resetAndDestroy() - ); - socket.on('error', () => {}); - socket.once('close', () => resolve()); - }) - ) + (server as unknown as { server: net.Server }).server.emit( + 'connection', + socket ); - await new Promise((resolve) => setTimeout(resolve, 100)); } finally { server.close(); } - expect(addresses).not.toContain(undefined); + expect(destroy).toHaveBeenCalled(); + expect(onConnection).not.toHaveBeenCalled(); }); it('stops the process when the port is already in use', async () => { From 37322d0c13321f0f592a4d9880dd44865060ad1d Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 00:43:49 -0500 Subject: [PATCH 20/34] [ php-wasm ] Drop data after close without resetting the connection When the peer sent data after PHP closed a socket, the socket was reset once Node.js had passed PHP's writes to the kernel. A reset still makes the kernel discard what the peer hasn't received yet, so PHP's last writes could be lost while the peer kept sending. Trunk never reset and delivered everything. The socket now just drops that data, as trunk did. It closes when the peer closes its side or the runtime exits. The delivery test now has the peer keep sending after the close, which fails with the reset. Also corrects the comments on setSocketOpt() and TcpServer.close(), and makes the runtime exit test count sockets without relying on remotePort, which can be unset while a client finishes connecting. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 29 ++++--------- .../node/src/test/php-networking.spec.ts | 5 ++- .../php-wasm/node/src/test/tcp-socket.spec.ts | 42 ++++++++----------- 3 files changed, 30 insertions(+), 46 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 356289ff6df..d6173dc2af1 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -60,19 +60,20 @@ export class TcpSocket extends EventEmitter { * `_socket`, like it does for `ws` WebSockets. */ readonly _socket?: net.Socket; - private resetPending = false; constructor(socket: net.Socket | undefined, readyState: number) { super(); this._socket = socket; this.readyState = readyState; socket?.on('data', (data: Buffer) => { - // PHP has closed the socket, so nothing will read this data. + // PHP has closed the socket, so nothing will read this data. Drop it + // rather than resetting the connection: a reset makes the kernel + // discard what PHP wrote but the peer hasn't received yet. The socket + // closes when the peer closes its side or the runtime exits. if ( this.readyState === this.CLOSING || this.readyState === this.CLOSED ) { - this.resetAfterWrites(); return; } // Emscripten ignores messages that aren't marked as binary. @@ -102,7 +103,8 @@ export class TcpSocket extends EventEmitter { /** * For php-wasm's setsockopt() with SO_KEEPALIVE and TCP_NODELAY. The current * PHP builds look the socket up by file descriptor and never find it, so - * this isn't called yet. + * this isn't called yet. They also pass a pointer to the option's value + * rather than the value, so a fixed lookup alone would turn every option on. */ setSocketOpt(level: number, optionName: number, optionValue: number) { if (level === SOL_SOCKET && optionName === SO_KEEPALIVE) { @@ -155,21 +157,6 @@ export class TcpSocket extends EventEmitter { this.emit('close'); }); } - - /** - * Resets a connection PHP has closed, like a closed native socket would, - * once Node.js has sent everything PHP wrote. PHP's writes don't block, so - * resetting right away could discard them. - */ - private resetAfterWrites() { - const socket = this._socket!; - if (socket.writableFinished) { - socket.destroy(); - } else if (!this.resetPending) { - this.resetPending = true; - socket.once('finish', () => socket.destroy()); - } - } } /** @@ -285,8 +272,8 @@ export class TcpServer extends EventEmitter { } /** - * Stops accepting connections. Accepted connections stay open, like - * closing a listening socket. + * Stops listening. Connections already made stay open, including ones PHP + * hasn't accepted yet. */ close(callback?: (error?: Error) => void) { this.closed = true; diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 420d62543b3..b880594c087 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -457,7 +457,10 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { this: net.Socket, ...args: Parameters ) { - if (this.remotePort === port) { + // Count the runtime's sockets, not the server's. + // A client's remotePort can still be unset while it + // finishes connecting. + if (!connections.includes(this)) { destroyed.add(this); } return destroy.apply(this, args); diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 03752506462..d524a163cd5 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -30,9 +30,7 @@ describe('OutboundTcpSocket', () => { expect(socket.readyState).toBe(OutboundTcpSocket.CLOSED); }); - it('drops data and resets the connection after it closes', async () => { - // The server keeps its side open and keeps writing after the client - // closes. Only a reset from the client closes the server's socket. + it('drops data that arrives after it closes', async () => { const server = net.createServer({ allowHalfOpen: true }); const connection = new Promise((resolve) => server.once('connection', resolve) @@ -47,7 +45,6 @@ describe('OutboundTcpSocket', () => { const messages: Buffer[] = []; socket.on('message', (data: Buffer) => messages.push(data)); const serverSocket = await connection; - serverSocket.on('error', () => {}); const ended = new Promise((resolve) => serverSocket.once('end', resolve) ); @@ -55,27 +52,20 @@ describe('OutboundTcpSocket', () => { socket.close(); await ended; - const closed = new Promise((resolve) => - serverSocket.once('close', resolve) + await new Promise((resolve) => + serverSocket.write('sent after close', () => resolve()) ); - const writes = setInterval(() => { - if (serverSocket.writable) { - serverSocket.write('sent after close'); - } - }, 20); - try { - await closed; - } finally { - clearInterval(writes); - server.close(); - } + await new Promise((resolve) => setTimeout(resolve, 50)); + serverSocket.destroy(); + server.close(); expect(messages).toEqual([]); }); - it('sends everything written before it closes, even if the peer replies', async () => { - // The server stops reading, so the writes stay buffered in Node.js - // when the socket closes. Its reply then arrives after the close. + it('sends everything written before it closes while the peer keeps sending', async () => { + // The server stops reading, so the writes stay buffered when the socket + // closes, and keeps sending. A reset at that point would make the + // kernel discard writes the server hasn't received yet. const size = 16 * 1024 * 1024; const server = net.createServer({ allowHalfOpen: true }); const connection = new Promise((resolve) => @@ -101,13 +91,17 @@ describe('OutboundTcpSocket', () => { socket.send(new Uint8Array(size)); socket.close(); - await new Promise((resolve) => socket.once('close', resolve)); - serverSocket.write('+OK'); - await new Promise((resolve) => setTimeout(resolve, 100)); - serverSocket.resume(); + const writes = setInterval(() => { + if (serverSocket.writable) { + serverSocket.write(Buffer.alloc(1024)); + } + }, 1); try { + await new Promise((resolve) => setTimeout(resolve, 100)); + serverSocket.resume(); await ended; } finally { + clearInterval(writes); serverSocket.destroy(); server.close(); } From 4c3e36e7dfb0947afd3c62eaa05e95a93a2ae653 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 01:56:24 -0500 Subject: [PATCH 21/34] [ php-wasm ] Keep sending a closed socket's writes when the runtime exits Exiting the runtime destroyed every tracked socket, including ones PHP had already closed whose writes were still buffered. That discarded the writes, and the peer saw a normal close. Runtimes exit often: after php.cli(), after 400 requests, and after a crash. Exit cleanup now only unrefs sockets PHP closed, so they no longer keep Node.js running. They keep sending, close when the peer does, and are destroyed after 30 seconds at the latest. Sockets PHP still has open are destroyed as before. Destroying a closed socket once its writes are sent would not be enough: data arriving afterwards resets the connection, which discards writes the peer hasn't received. The after-close tests are now deterministic: one checks that data arriving after close neither reaches PHP nor resets the connection, and one checks that a released socket delivers everything it wrote. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 26 ++++++++- .../src/lib/networking/with-networking.ts | 6 +- .../node/src/test/php-networking.spec.ts | 29 ++++++++-- .../php-wasm/node/src/test/tcp-socket.spec.ts | 57 ++++++++++--------- 4 files changed, 79 insertions(+), 39 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index d6173dc2af1..c193f05560f 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -20,6 +20,9 @@ function log(...args: any[]) { debugLog('[TCP]', ...args); } +// How long a socket PHP closed may keep sending after the runtime exits. +const CLOSED_SOCKET_TIMEOUT_MS = 30_000; + const SOL_SOCKET = 1; const SO_KEEPALIVE = 9; const IPPROTO_TCP = 6; @@ -119,10 +122,27 @@ export class TcpSocket extends EventEmitter { } /** - * Releases the TCP socket right away. A socket that PHP closed stays - * open until the peer closes its side, so this also releases those. + * Releases the TCP socket when the runtime exits. + * + * A socket PHP still has open is destroyed. A socket PHP closed may still + * be sending what PHP wrote, and destroying it would discard that. It's + * only unref'd, so it no longer keeps Node.js running. It closes when the + * peer closes its side, or is destroyed after a timeout. */ - destroy() { + release() { + const socket = this._socket; + if ( + socket && + (this.readyState === this.CLOSING || + this.readyState === this.CLOSED) + ) { + socket.unref(); + setTimeout( + () => socket.destroy(), + CLOSED_SOCKET_TIMEOUT_MS + ).unref(); + return; + } this._socket?.destroy(); this.shutDown(true); } diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 9a1744e611f..f29aa334427 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -43,13 +43,13 @@ export async function withNetworking( return { ...phpModuleArgs, closeNetworkConnections: () => { - // Destroy sockets instead of ending them: an ended socket stays open - // until the peer closes its side, and keeps Node.js running. + // Ending a socket isn't enough: it would stay open until the peer + // closes its side, and keep Node.js running. for (const handle of openHandles) { if (handle instanceof TcpServer) { handle.close(); } else { - handle.destroy(); + handle.release(); } } }, diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index b880594c087..5e5c1e085fd 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -419,8 +419,8 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { describe('Runtime exit', () => { it('should release open connections when runtime is exited', async () => { - // The server keeps its side open after the client closes, so only - // the runtime can release these connections. + // The server keeps its side open after the client closes, so the + // runtime has to release both connections itself. const tcpServer = net.createServer({ allowHalfOpen: true }); const connections: net.Socket[] = []; const bothConnected = new Promise((resolve) => @@ -449,30 +449,47 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { `, }); await bothConnected; + // Record what exiting does to the runtime's sockets, not the + // server's. A client's remotePort can still be unset while it + // finishes connecting, so don't match on it. const destroyed = new Set(); + const unrefed = new Set(); const destroy = net.Socket.prototype.destroy; + const unref = net.Socket.prototype.unref; const destroySpy = vi .spyOn(net.Socket.prototype, 'destroy') .mockImplementation(function ( this: net.Socket, ...args: Parameters ) { - // Count the runtime's sockets, not the server's. - // A client's remotePort can still be unset while it - // finishes connecting. if (!connections.includes(this)) { destroyed.add(this); } return destroy.apply(this, args); }); + const unrefSpy = vi + .spyOn(net.Socket.prototype, 'unref') + .mockImplementation(function (this: net.Socket) { + if (!connections.includes(this)) { + unrefed.add(this); + } + return unref.apply(this); + }); try { php.exit(); } finally { destroySpy.mockRestore(); + unrefSpy.mockRestore(); } - expect(destroyed.size).toBe(2); + // The persistent socket is destroyed. The socket PHP closed may + // still be sending, so it only stops keeping Node.js running. + expect(destroyed.size).toBe(1); + expect(unrefed.size).toBe(1); + expect( + [...unrefed].some((socket) => destroyed.has(socket)) + ).toBe(false); } finally { connections.forEach((socket) => socket.destroy()); tcpServer.close(); diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index d524a163cd5..702be05f9b7 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -30,7 +30,7 @@ describe('OutboundTcpSocket', () => { expect(socket.readyState).toBe(OutboundTcpSocket.CLOSED); }); - it('drops data that arrives after it closes', async () => { + it('drops data after it closes, and stays open until the peer closes', async () => { const server = net.createServer({ allowHalfOpen: true }); const connection = new Promise((resolve) => server.once('connection', resolve) @@ -50,24 +50,34 @@ describe('OutboundTcpSocket', () => { ); serverSocket.resume(); - socket.close(); - await ended; - await new Promise((resolve) => - serverSocket.write('sent after close', () => resolve()) - ); - await new Promise((resolve) => setTimeout(resolve, 50)); - serverSocket.destroy(); - server.close(); + try { + socket.close(); + await ended; + await new Promise((resolve) => + serverSocket.write('sent after close', () => resolve()) + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(messages).toEqual([]); + // A reset here could discard what PHP wrote before closing. + expect(socket._socket?.destroyed).toBe(false); - expect(messages).toEqual([]); + const closed = new Promise((resolve) => + socket._socket!.once('close', resolve) + ); + serverSocket.end(); + await closed; + } finally { + serverSocket.destroy(); + server.close(); + } }); - it('sends everything written before it closes while the peer keeps sending', async () => { - // The server stops reading, so the writes stay buffered when the socket - // closes, and keeps sending. A reset at that point would make the - // kernel discard writes the server hasn't received yet. - const size = 16 * 1024 * 1024; - const server = net.createServer({ allowHalfOpen: true }); + it('keeps sending what it wrote when released after closing', async () => { + // The server stops reading, so the writes are still buffered when the + // socket closes and the runtime releases it. + const size = 8 * 1024 * 1024; + const server = net.createServer(); const connection = new Promise((resolve) => server.once('connection', resolve) ); @@ -81,27 +91,20 @@ describe('OutboundTcpSocket', () => { await new Promise((resolve) => socket.once('open', resolve)); const serverSocket = await connection; serverSocket.pause(); - serverSocket.on('error', () => {}); let received = 0; const ended = new Promise((resolve) => { serverSocket.on('data', (data) => (received += data.length)); - serverSocket.once('end', resolve); serverSocket.once('close', resolve); }); - socket.send(new Uint8Array(size)); - socket.close(); - const writes = setInterval(() => { - if (serverSocket.writable) { - serverSocket.write(Buffer.alloc(1024)); - } - }, 1); try { - await new Promise((resolve) => setTimeout(resolve, 100)); + socket.send(new Uint8Array(size)); + socket.close(); + socket.release(); + await new Promise((resolve) => setTimeout(resolve, 50)); serverSocket.resume(); await ended; } finally { - clearInterval(writes); serverSocket.destroy(); server.close(); } From 34bfb909c0aaeaf66e307184806f893a0a367bf6 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 10:46:59 -0500 Subject: [PATCH 22/34] [ php-wasm ] Tighten exit cleanup tests and comments The runtime exit test only counted one destroyed and one unref'd socket, so it passed even if release() swapped the two cases. It now matches each runtime socket to its server connection by port, and checks that the persistent socket is destroyed and the one PHP closed is only unref'd. A new test uses fake timers to check that a released socket whose peer never closes is destroyed after CLOSED_SOCKET_TIMEOUT_MS. The runtime now exits even if closing its network connections throws, and logs the error. PHP.exit() swallows errors, so the runtime would otherwise keep running unnoticed. Comments on release(), the after-close data handler and the Redis test now match the behavior: a released socket keeps Node.js running only while its writes are pending, for at most the timeout. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 20 ++++--- .../src/lib/networking/with-networking.ts | 2 +- .../node/src/test/php-networking.spec.ts | 55 ++++++++++++++----- .../php-wasm/node/src/test/php-redis.spec.ts | 4 +- .../php-wasm/node/src/test/tcp-socket.spec.ts | 37 +++++++++++++ .../universal/src/lib/load-php-runtime.ts | 14 +++-- 6 files changed, 102 insertions(+), 30 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index c193f05560f..099c058b52c 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -21,7 +21,7 @@ function log(...args: any[]) { } // How long a socket PHP closed may keep sending after the runtime exits. -const CLOSED_SOCKET_TIMEOUT_MS = 30_000; +export const CLOSED_SOCKET_TIMEOUT_MS = 30_000; const SOL_SOCKET = 1; const SO_KEEPALIVE = 9; @@ -69,10 +69,10 @@ export class TcpSocket extends EventEmitter { this._socket = socket; this.readyState = readyState; socket?.on('data', (data: Buffer) => { - // PHP has closed the socket, so nothing will read this data. Drop it - // rather than resetting the connection: a reset makes the kernel - // discard what PHP wrote but the peer hasn't received yet. The socket - // closes when the peer closes its side or the runtime exits. + // The socket is closed, so nothing will read this data. Drop it rather + // than resetting the connection: a reset makes the kernel discard what + // PHP wrote but the peer hasn't received yet. The socket closes when + // the peer closes its side, or after a timeout once the runtime exits. if ( this.readyState === this.CLOSING || this.readyState === this.CLOSED @@ -124,10 +124,12 @@ export class TcpSocket extends EventEmitter { /** * Releases the TCP socket when the runtime exits. * - * A socket PHP still has open is destroyed. A socket PHP closed may still - * be sending what PHP wrote, and destroying it would discard that. It's - * only unref'd, so it no longer keeps Node.js running. It closes when the - * peer closes its side, or is destroyed after a timeout. + * A socket that's still open is destroyed. A closed one, whether PHP or + * the peer closed it, may still be sending what PHP wrote, and destroying + * it would discard that. It's only unref'd: once its writes are sent, it no + * longer keeps Node.js running. It closes when the peer closes its side, or + * is destroyed after a timeout, which also bounds how long pending writes + * can keep Node.js running. */ release() { const socket = this._socket; diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index f29aa334427..00dde5748fc 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -44,7 +44,7 @@ export async function withNetworking( ...phpModuleArgs, closeNetworkConnections: () => { // Ending a socket isn't enough: it would stay open until the peer - // closes its side, and keep Node.js running. + // closes its side, and keep Node.js running. See TcpSocket.release(). for (const handle of openHandles) { if (handle instanceof TcpServer) { handle.close(); diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 5e5c1e085fd..68bc408547f 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -423,10 +423,17 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { // runtime has to release both connections itself. const tcpServer = net.createServer({ allowHalfOpen: true }); const connections: net.Socket[] = []; + const ended = new Map>(); const bothConnected = new Promise((resolve) => tcpServer.on('connection', (socket) => { socket.resume(); connections.push(socket); + ended.set( + socket, + new Promise((resolveEnd) => + socket.once('end', () => resolveEnd()) + ) + ); if (connections.length === 2) { resolve(); } @@ -449,11 +456,24 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { `, }); await bothConnected; - // Record what exiting does to the runtime's sockets, not the - // server's. A client's remotePort can still be unset while it - // finishes connecting, so don't match on it. - const destroyed = new Set(); - const unrefed = new Set(); + // The connection PHP closed is the one that ends first. + const closedConnection = await Promise.race( + connections.map((socket) => + ended.get(socket)!.then(() => socket) + ) + ); + const persistentConnection = connections.find( + (socket) => socket !== closedConnection + )!; + // Record the local port of each runtime socket that exiting + // destroys or unrefs. The server sees it as the connection's + // remotePort. A client's own remotePort can still be unset while + // it finishes connecting, but its localPort is assigned when it + // starts. + // A socket can be destroyed more than once, and it has no port + // after the first time, so record each socket once. + const destroyed = new Map(); + const unrefed = new Map(); const destroy = net.Socket.prototype.destroy; const unref = net.Socket.prototype.unref; const destroySpy = vi @@ -462,16 +482,22 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { this: net.Socket, ...args: Parameters ) { - if (!connections.includes(this)) { - destroyed.add(this); + if ( + !connections.includes(this) && + !destroyed.has(this) + ) { + destroyed.set(this, this.localPort); } return destroy.apply(this, args); }); const unrefSpy = vi .spyOn(net.Socket.prototype, 'unref') .mockImplementation(function (this: net.Socket) { - if (!connections.includes(this)) { - unrefed.add(this); + if ( + !connections.includes(this) && + !unrefed.has(this) + ) { + unrefed.set(this, this.localPort); } return unref.apply(this); }); @@ -485,11 +511,12 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { // The persistent socket is destroyed. The socket PHP closed may // still be sending, so it only stops keeping Node.js running. - expect(destroyed.size).toBe(1); - expect(unrefed.size).toBe(1); - expect( - [...unrefed].some((socket) => destroyed.has(socket)) - ).toBe(false); + expect([...destroyed.values()]).toEqual([ + persistentConnection.remotePort, + ]); + expect([...unrefed.values()]).toEqual([ + closedConnection.remotePort, + ]); } finally { connections.forEach((socket) => socket.destroy()); tcpServer.close(); diff --git a/packages/php-wasm/node/src/test/php-redis.spec.ts b/packages/php-wasm/node/src/test/php-redis.spec.ts index 1af2a470d5f..aa9601e1f45 100644 --- a/packages/php-wasm/node/src/test/php-redis.spec.ts +++ b/packages/php-wasm/node/src/test/php-redis.spec.ts @@ -53,12 +53,12 @@ if (!isJspiAvailable) { /** * PHP helper function that creates a configured Redis instance with proper - * timeout settings for WebSocket-based TCP connections. + * timeout settings. */ const createRedisPHP = () => ` function createRedis() { $r = new Redis(); - // Set timeouts to give WebSocket proxy time to connect + // Allow time for the TCP connection to be established $r->connect('${REDIS_HOST}', ${REDIS_PORT}, 5.0); return $r; } diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 702be05f9b7..a33a510c9c4 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -4,6 +4,7 @@ import net from 'node:net'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { + CLOSED_SOCKET_TIMEOUT_MS, OutboundTcpSocket, TcpServer, getOutboundTcpSocketUrl, @@ -111,6 +112,42 @@ describe('OutboundTcpSocket', () => { expect(received).toBe(size); }); + it('destroys a released socket after a timeout if the peer never closes', async () => { + // The peer keeps its side open, so nothing but the timeout would ever + // close the socket. + const server = net.createServer({ allowHalfOpen: true }); + const connection = new Promise((resolve) => + server.once('connection', resolve) + ); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + const socket = new OutboundTcpSocket( + getOutboundTcpSocketUrl('127.0.0.1', String(port)) + ); + const serverSocket = await connection; + const ended = new Promise((resolve) => + serverSocket.once('end', resolve) + ); + serverSocket.resume(); + socket.close(); + await ended; + + // Fake only the timer, so the socket itself keeps running for real. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + socket.release(); + vi.advanceTimersByTime(CLOSED_SOCKET_TIMEOUT_MS - 1); + expect(socket._socket?.destroyed).toBe(false); + vi.advanceTimersByTime(1); + expect(socket._socket?.destroyed).toBe(true); + } finally { + vi.useRealTimers(); + serverSocket.destroy(); + server.close(); + } + }); }); describe('TcpServer', () => { diff --git a/packages/php-wasm/universal/src/lib/load-php-runtime.ts b/packages/php-wasm/universal/src/lib/load-php-runtime.ts index 7d5d68b14bd..817db6c68c0 100644 --- a/packages/php-wasm/universal/src/lib/load-php-runtime.ts +++ b/packages/php-wasm/universal/src/lib/load-php-runtime.ts @@ -172,10 +172,16 @@ export async function loadPHPRuntime( PHPRuntime.originalExit = PHPRuntime._exit; PHPRuntime._exit = function (code: number) { - PHPRuntime.closeNetworkConnections?.(); - if (PHPRuntime.outboundNetworkProxyServer) { - PHPRuntime.outboundNetworkProxyServer.close(); - PHPRuntime.outboundNetworkProxyServer.closeAllConnections(); + // Exit even if closing the network fails. PHP.exit() swallows errors, + // so a throw here would leave the runtime running without notice. + try { + PHPRuntime.closeNetworkConnections?.(); + if (PHPRuntime.outboundNetworkProxyServer) { + PHPRuntime.outboundNetworkProxyServer.close(); + PHPRuntime.outboundNetworkProxyServer.closeAllConnections(); + } + } catch (error) { + logger.error('Failed to close network connections', error); } loadedRuntimes.delete(id); return PHPRuntime.originalExit(code); From 1d7043e7790bb82c5859c95f33b7bcccf4a5fa8d Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 12:44:58 -0500 Subject: [PATCH 23/34] [ php-wasm ] Release every network handle even if one fails closeNetworkConnections stopped at the first handle that threw, leaving the remaining servers listening and sockets open. It now catches and logs errors per handle. The fake-timer test now also checks that the closed-socket timeout is unref'd, so it can't keep Node.js running for the whole timeout, and its setup runs inside the try block that cleans up the server. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 2 +- .../src/lib/networking/with-networking.ts | 17 +++++-- .../php-wasm/node/src/test/tcp-socket.spec.ts | 46 ++++++++++--------- 3 files changed, 39 insertions(+), 26 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 099c058b52c..1d7c1e6770b 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -20,7 +20,7 @@ function log(...args: any[]) { debugLog('[TCP]', ...args); } -// How long a socket PHP closed may keep sending after the runtime exits. +// How long a closed socket may keep sending after the runtime exits. export const CLOSED_SOCKET_TIMEOUT_MS = 30_000; const SOL_SOCKET = 1; diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 00dde5748fc..76f30c92e9e 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -1,3 +1,4 @@ +import { logger } from '@php-wasm/logger'; import type { EmscriptenOptions } from '@php-wasm/universal'; // The compiled PHP runtime calls require('ws') before it passes the `ws` // classes to the decorators below, so the package must keep depending on it. @@ -45,11 +46,19 @@ export async function withNetworking( closeNetworkConnections: () => { // Ending a socket isn't enough: it would stay open until the peer // closes its side, and keep Node.js running. See TcpSocket.release(). + // Release each handle even if another one fails. for (const handle of openHandles) { - if (handle instanceof TcpServer) { - handle.close(); - } else { - handle.release(); + try { + if (handle instanceof TcpServer) { + handle.close(); + } else { + handle.release(); + } + } catch (error) { + logger.error( + 'Failed to release a network connection', + error + ); } } }, diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index a33a510c9c4..6af482e627a 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -116,35 +116,39 @@ describe('OutboundTcpSocket', () => { // The peer keeps its side open, so nothing but the timeout would ever // close the socket. const server = net.createServer({ allowHalfOpen: true }); - const connection = new Promise((resolve) => - server.once('connection', resolve) - ); - await new Promise((resolve) => - server.listen(0, '127.0.0.1', resolve) - ); - const { port } = server.address() as net.AddressInfo; - const socket = new OutboundTcpSocket( - getOutboundTcpSocketUrl('127.0.0.1', String(port)) - ); - const serverSocket = await connection; - const ended = new Promise((resolve) => - serverSocket.once('end', resolve) - ); - serverSocket.resume(); - socket.close(); - await ended; - - // Fake only the timer, so the socket itself keeps running for real. - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + let serverSocket: net.Socket | undefined; try { + const connection = new Promise((resolve) => + server.once('connection', resolve) + ); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + const socket = new OutboundTcpSocket( + getOutboundTcpSocketUrl('127.0.0.1', String(port)) + ); + serverSocket = await connection; + const ended = new Promise((resolve) => + serverSocket!.once('end', resolve) + ); + serverSocket.resume(); + socket.close(); + await ended; + + // Fake only the timer, so the socket itself keeps running for real. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout'); socket.release(); + // The timer must not keep Node.js running for the whole timeout. + expect(setTimeoutSpy.mock.results[0].value.hasRef()).toBe(false); vi.advanceTimersByTime(CLOSED_SOCKET_TIMEOUT_MS - 1); expect(socket._socket?.destroyed).toBe(false); vi.advanceTimersByTime(1); expect(socket._socket?.destroyed).toBe(true); } finally { vi.useRealTimers(); - serverSocket.destroy(); + serverSocket?.destroy(); server.close(); } }); From 8f697e7cf95d5b929d97efa8a1395bf9bafa6fd5 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 12:59:36 -0500 Subject: [PATCH 24/34] [ php-wasm ] Stop the timeout test from breaking setTimeout for later tests The fake-timer test spied on the global setTimeout while fake timers were installed. A later afterEach(vi.restoreAllMocks) restored that spy again and put the fake setTimeout back, so timers in any later test in the file would never fire. The unref check now has its own test, which counts the timers keeping Node.js running before and after release() instead of spying on setTimeout. The fake-timer test only checks the timing, and both share a helper that closes a socket while its peer stays open. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../php-wasm/node/src/test/tcp-socket.spec.ts | 86 ++++++++++++------- 1 file changed, 57 insertions(+), 29 deletions(-) diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 6af482e627a..8e9ab2646da 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -113,43 +113,35 @@ describe('OutboundTcpSocket', () => { expect(received).toBe(size); }); it('destroys a released socket after a timeout if the peer never closes', async () => { - // The peer keeps its side open, so nothing but the timeout would ever - // close the socket. - const server = net.createServer({ allowHalfOpen: true }); - let serverSocket: net.Socket | undefined; + const { socket, cleanUp } = await closeWithPeerOpen(); + // Fake only the timer, so the socket itself keeps running for real. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); try { - const connection = new Promise((resolve) => - server.once('connection', resolve) - ); - await new Promise((resolve) => - server.listen(0, '127.0.0.1', resolve) - ); - const { port } = server.address() as net.AddressInfo; - const socket = new OutboundTcpSocket( - getOutboundTcpSocketUrl('127.0.0.1', String(port)) - ); - serverSocket = await connection; - const ended = new Promise((resolve) => - serverSocket!.once('end', resolve) - ); - serverSocket.resume(); - socket.close(); - await ended; - - // Fake only the timer, so the socket itself keeps running for real. - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); - const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout'); socket.release(); - // The timer must not keep Node.js running for the whole timeout. - expect(setTimeoutSpy.mock.results[0].value.hasRef()).toBe(false); vi.advanceTimersByTime(CLOSED_SOCKET_TIMEOUT_MS - 1); expect(socket._socket?.destroyed).toBe(false); vi.advanceTimersByTime(1); expect(socket._socket?.destroyed).toBe(true); } finally { vi.useRealTimers(); - serverSocket?.destroy(); - server.close(); + cleanUp(); + } + }); + + it('does not keep Node.js running while a released socket waits', async () => { + const { socket, cleanUp } = await closeWithPeerOpen(); + const countTimers = () => + process + .getActiveResourcesInfo() + .filter((resource) => resource === 'Timeout').length; + try { + const timersBefore = countTimers(); + socket.release(); + // Node.js doesn't count an unref'd timer as keeping it running. + expect(countTimers()).toBe(timersBefore); + } finally { + socket._socket?.destroy(); + cleanUp(); } }); }); @@ -257,3 +249,39 @@ async function getClosedPort() { await new Promise((resolve) => server.close(resolve)); return port; } + +/** + * Opens a socket, closes it, and waits until the peer sees the close. The peer + * keeps its side open, so nothing but a timeout would ever close the socket. + */ +async function closeWithPeerOpen() { + const server = net.createServer({ allowHalfOpen: true }); + let serverSocket: net.Socket | undefined; + const cleanUp = () => { + serverSocket?.destroy(); + server.close(); + }; + try { + const connection = new Promise((resolve) => + server.once('connection', resolve) + ); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + const socket = new OutboundTcpSocket( + getOutboundTcpSocketUrl('127.0.0.1', String(port)) + ); + serverSocket = await connection; + const ended = new Promise((resolve) => + serverSocket!.once('end', resolve) + ); + serverSocket.resume(); + socket.close(); + await ended; + return { socket, cleanUp }; + } catch (error) { + cleanUp(); + throw error; + } +} From 0167dda24a668d65481052a4fd066fcb58dc0b32 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 13:02:35 -0500 Subject: [PATCH 25/34] [ php-wasm ] Keep a closeNetworkConnections option passed to withNetworking withNetworking() spread the caller's Emscripten options and then set its own closeNetworkConnections, silently replacing one the caller passed in. It now calls the caller's after releasing its own sockets and servers. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/with-networking.ts | 2 ++ .../node/src/test/networking-port-allocation.spec.ts | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 76f30c92e9e..d8ef56bcac0 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -61,6 +61,8 @@ export async function withNetworking( ); } } + // The options above replace one the caller passed in, so call it too. + phpModuleArgs.closeNetworkConnections?.(); }, websocket: { ...(phpModuleArgs['websocket'] || {}), diff --git a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts index 49c1619d078..c3f74d21b10 100644 --- a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts +++ b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts @@ -20,6 +20,17 @@ describe('networking port allocation', () => { expect(listenSpy).not.toHaveBeenCalled(); }); + it('keeps a closeNetworkConnections option passed in', async () => { + const closeNetworkConnections = vi.fn(); + const emscriptenOptions = await withNetworking({ + closeNetworkConnections, + }); + + emscriptenOptions.closeNetworkConnections!(); + + expect(closeNetworkConnections).toHaveBeenCalledOnce(); + }); + it('listens only on the host and port PHP binds to', async () => { const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); From b748716ce6132f087647c3b36603ca7afb9d75fe Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 13:30:52 -0500 Subject: [PATCH 26/34] [ php-wasm ] Drain TCP writes and release cleanup timers on exit --- .../node/src/lib/networking/tcp-socket.ts | 52 +++--- .../src/lib/networking/with-networking.ts | 4 +- .../node/src/test/php-networking.spec.ts | 110 ++++--------- .../php-wasm/node/src/test/tcp-socket.spec.ts | 149 +++++++++++++----- 4 files changed, 175 insertions(+), 140 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 1d7c1e6770b..95347e6d867 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -20,8 +20,8 @@ function log(...args: any[]) { debugLog('[TCP]', ...args); } -// How long a closed socket may keep sending after the runtime exits. -export const CLOSED_SOCKET_TIMEOUT_MS = 30_000; +// How long a socket may keep sending after the runtime exits. +export const RELEASED_SOCKET_TIMEOUT_MS = 30_000; const SOL_SOCKET = 1; const SO_KEEPALIVE = 9; @@ -63,6 +63,7 @@ export class TcpSocket extends EventEmitter { * `_socket`, like it does for `ws` WebSockets. */ readonly _socket?: net.Socket; + private released = false; constructor(socket: net.Socket | undefined, readyState: number) { super(); @@ -124,29 +125,32 @@ export class TcpSocket extends EventEmitter { /** * Releases the TCP socket when the runtime exits. * - * A socket that's still open is destroyed. A closed one, whether PHP or - * the peer closed it, may still be sending what PHP wrote, and destroying - * it would discard that. It's only unref'd: once its writes are sent, it no - * longer keeps Node.js running. It closes when the peer closes its side, or - * is destroyed after a timeout, which also bounds how long pending writes - * can keep Node.js running. + * End the write side so queued writes can drain, including those on + * persistent sockets PHP left open. Unref the socket so it doesn't keep + * Node.js running once those writes are sent. A timeout bounds how long + * pending writes or a peer that never closes can retain the connection. */ release() { + if (this.released) { + return; + } + this.released = true; const socket = this._socket; - if ( - socket && - (this.readyState === this.CLOSING || - this.readyState === this.CLOSED) - ) { - socket.unref(); - setTimeout( - () => socket.destroy(), - CLOSED_SOCKET_TIMEOUT_MS - ).unref(); + // Don't wait for an unused connection attempt after the runtime exits. + // A connecting socket with queued writes still needs to drain them. + this.shutDown(socket?.connecting && socket.writableLength === 0); + if (!socket || socket.destroyed) { return; } - this._socket?.destroy(); - this.shutDown(true); + socket.unref(); + const timeout = setTimeout( + () => socket.destroy(), + RELEASED_SOCKET_TIMEOUT_MS + ); + timeout.unref(); + // The socket's listeners retain the runtime, so cancel the timer as + // soon as TCP closes rather than retaining it for the whole timeout. + socket.once('close', () => clearTimeout(timeout)); } // php-wasm's connect() listens with the DOM-style event API. @@ -162,6 +166,10 @@ export class TcpSocket extends EventEmitter { * Closes the connection and emits `close` on the next tick, like `ws`. */ protected shutDown(destroy = false) { + // A logical close can leave TCP connecting or draining. + if (destroy) { + this._socket?.destroy(); + } if ( this.readyState === this.CLOSING || this.readyState === this.CLOSED @@ -169,9 +177,7 @@ export class TcpSocket extends EventEmitter { return; } this.readyState = this.CLOSING; - if (destroy) { - this._socket?.destroy(); - } else { + if (!destroy) { this._socket?.end(); } process.nextTick(() => { diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index d8ef56bcac0..276a221901e 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -44,8 +44,8 @@ export async function withNetworking( return { ...phpModuleArgs, closeNetworkConnections: () => { - // Ending a socket isn't enough: it would stay open until the peer - // closes its side, and keep Node.js running. See TcpSocket.release(). + // Drain queued writes and bound the lifetime of connections whose + // peers keep them open. See TcpSocket.release(). // Release each handle even if another one fails. for (const handle of openHandles) { try { diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 68bc408547f..1625c4dd7fe 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -418,18 +418,24 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { }); describe('Runtime exit', () => { - it('should release open connections when runtime is exited', async () => { - // The server keeps its side open after the client closes, so the - // runtime has to release both connections itself. - const tcpServer = net.createServer({ allowHalfOpen: true }); + it('should flush persistent and closed connections when the runtime exits', async () => { + const size = 8 * 1024 * 1024; + const tcpServer = net.createServer(); const connections: net.Socket[] = []; - const ended = new Map>(); + const received: number[] = []; + const ended: Promise[] = []; const bothConnected = new Promise((resolve) => tcpServer.on('connection', (socket) => { - socket.resume(); + const index = connections.length; connections.push(socket); - ended.set( - socket, + received.push(0); + // Keep writes queued until after the runtime exits. + socket.pause(); + socket.write('ready'); + socket.on('data', (data) => { + received[index] += data.length; + }); + ended.push( new Promise((resolveEnd) => socket.once('end', () => resolveEnd()) ) @@ -443,83 +449,33 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { tcpServer.listen(0, '127.0.0.1', resolve) ); const { port } = tcpServer.address() as net.AddressInfo; + let php: PHP | undefined; try { - const php = new PHP( - await loadNodeRuntime(phpVersion, options) - ); - // A persistent socket stays open after the request ends. - // The other socket is closed by PHP but not by the server. - await php.run({ + php = new PHP(await loadNodeRuntime(phpVersion, options)); + const { text } = await php.run({ code: ` - ended.get(socket)!.then(() => socket) - ) - ); - const persistentConnection = connections.find( - (socket) => socket !== closedConnection - )!; - // Record the local port of each runtime socket that exiting - // destroys or unrefs. The server sees it as the connection's - // remotePort. A client's own remotePort can still be unset while - // it finishes connecting, but its localPort is assigned when it - // starts. - // A socket can be destroyed more than once, and it has no port - // after the first time, so record each socket once. - const destroyed = new Map(); - const unrefed = new Map(); - const destroy = net.Socket.prototype.destroy; - const unref = net.Socket.prototype.unref; - const destroySpy = vi - .spyOn(net.Socket.prototype, 'destroy') - .mockImplementation(function ( - this: net.Socket, - ...args: Parameters - ) { - if ( - !connections.includes(this) && - !destroyed.has(this) - ) { - destroyed.set(this, this.localPort); - } - return destroy.apply(this, args); - }); - const unrefSpy = vi - .spyOn(net.Socket.prototype, 'unref') - .mockImplementation(function (this: net.Socket) { - if ( - !connections.includes(this) && - !unrefed.has(this) - ) { - unrefed.set(this, this.localPort); - } - return unref.apply(this); - }); - - try { - php.exit(); - } finally { - destroySpy.mockRestore(); - unrefSpy.mockRestore(); - } + php.exit(); + connections.forEach((socket) => socket.resume()); + await Promise.all(ended); - // The persistent socket is destroyed. The socket PHP closed may - // still be sending, so it only stops keeping Node.js running. - expect([...destroyed.values()]).toEqual([ - persistentConnection.remotePort, - ]); - expect([...unrefed.values()]).toEqual([ - closedConnection.remotePort, - ]); + expect(JSON.parse(text)).toEqual([size, size]); + expect(received).toEqual([size, size]); } finally { + php?.exit(); connections.forEach((socket) => socket.destroy()); - tcpServer.close(); + await new Promise((resolve) => tcpServer.close(resolve)); } }); }); diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 8e9ab2646da..7a32e937ca4 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -4,7 +4,7 @@ import net from 'node:net'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { - CLOSED_SOCKET_TIMEOUT_MS, + RELEASED_SOCKET_TIMEOUT_MS, OutboundTcpSocket, TcpServer, getOutboundTcpSocketUrl, @@ -31,6 +31,30 @@ describe('OutboundTcpSocket', () => { expect(socket.readyState).toBe(OutboundTcpSocket.CLOSED); }); + it.each(['open', 'closed'])( + 'cancels an unused connection attempt when released while %s', + async (state) => { + const port = await getClosedPort(); + const socket = new OutboundTcpSocket( + getOutboundTcpSocketUrl('127.0.0.1', String(port)) + ); + const opened = vi.fn(); + socket.on('open', opened); + const closed = new Promise((resolve) => + socket.once('close', resolve) + ); + + if (state === 'closed') { + socket.close(); + } + socket.release(); + expect(socket._socket?.destroyed).toBe(true); + await closed; + expect(opened).not.toHaveBeenCalled(); + expect(socket.readyState).toBe(OutboundTcpSocket.CLOSED); + } + ); + it('drops data after it closes, and stays open until the peer closes', async () => { const server = net.createServer({ allowHalfOpen: true }); const connection = new Promise((resolve) => @@ -74,51 +98,64 @@ describe('OutboundTcpSocket', () => { } }); - it('keeps sending what it wrote when released after closing', async () => { - // The server stops reading, so the writes are still buffered when the - // socket closes and the runtime releases it. - const size = 8 * 1024 * 1024; - const server = net.createServer(); - const connection = new Promise((resolve) => - server.once('connection', resolve) - ); - await new Promise((resolve) => - server.listen(0, '127.0.0.1', resolve) - ); - const { port } = server.address() as net.AddressInfo; - const socket = new OutboundTcpSocket( - getOutboundTcpSocketUrl('127.0.0.1', String(port)) - ); - await new Promise((resolve) => socket.once('open', resolve)); - const serverSocket = await connection; - serverSocket.pause(); - let received = 0; - const ended = new Promise((resolve) => { - serverSocket.on('data', (data) => (received += data.length)); - serverSocket.once('close', resolve); - }); - - try { + it.each(['open', 'closed'])( + 'keeps sending queued writes when released while %s', + async (state) => { + // The server stops reading, so the writes are still buffered when the + // socket closes and the runtime releases it. + const size = 8 * 1024 * 1024; + const server = net.createServer(); + const connection = new Promise((resolve) => + server.once('connection', (socket) => { + socket.pause(); + resolve(socket); + }) + ); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + const socket = new OutboundTcpSocket( + getOutboundTcpSocketUrl('127.0.0.1', String(port)) + ); + await new Promise((resolve) => socket.once('open', resolve)); + // The adapter opens before TCP connects. These writes must survive + // release even while the underlying connection is still in progress. socket.send(new Uint8Array(size)); - socket.close(); + if (state === 'closed') { + socket.close(); + } socket.release(); - await new Promise((resolve) => setTimeout(resolve, 50)); - serverSocket.resume(); - await ended; - } finally { - serverSocket.destroy(); - server.close(); + const serverSocket = await connection; + let received = 0; + const ended = new Promise((resolve) => { + serverSocket.on('data', (data) => (received += data.length)); + serverSocket.once('close', resolve); + }); + + try { + await new Promise((resolve) => setTimeout(resolve, 50)); + serverSocket.resume(); + await ended; + } finally { + serverSocket.destroy(); + server.close(); + } + + expect(received).toBe(size); } + ); - expect(received).toBe(size); - }); - it('destroys a released socket after a timeout if the peer never closes', async () => { + it('enforces the original release deadline if the peer never closes', async () => { const { socket, cleanUp } = await closeWithPeerOpen(); // Fake only the timer, so the socket itself keeps running for real. vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); try { socket.release(); - vi.advanceTimersByTime(CLOSED_SOCKET_TIMEOUT_MS - 1); + vi.advanceTimersByTime(RELEASED_SOCKET_TIMEOUT_MS - 1); + // Repeated cleanup must neither extend the deadline nor add timers. + socket.release(); + expect(vi.getTimerCount()).toBe(1); expect(socket._socket?.destroyed).toBe(false); vi.advanceTimersByTime(1); expect(socket._socket?.destroyed).toBe(true); @@ -128,6 +165,42 @@ describe('OutboundTcpSocket', () => { } }); + it('cancels the release timeout when TCP closes', async () => { + const { socket, serverSocket, cleanUp } = await closeWithPeerOpen(); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + socket.release(); + expect(vi.getTimerCount()).toBe(1); + const closed = new Promise((resolve) => + socket._socket!.once('close', resolve) + ); + serverSocket.end(); + await closed; + + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + cleanUp(); + } + }); + + it('does not schedule cleanup for a destroyed TCP socket', async () => { + const { socket, cleanUp } = await closeWithPeerOpen(); + const closed = new Promise((resolve) => + socket._socket!.once('close', resolve) + ); + socket._socket!.destroy(); + await closed; + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + socket.release(); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + cleanUp(); + } + }); + it('does not keep Node.js running while a released socket waits', async () => { const { socket, cleanUp } = await closeWithPeerOpen(); const countTimers = () => @@ -279,7 +352,7 @@ async function closeWithPeerOpen() { serverSocket.resume(); socket.close(); await ended; - return { socket, cleanUp }; + return { socket, serverSocket, cleanUp }; } catch (error) { cleanUp(); throw error; From d73cccce7fee28e7d2c23aab8520ef2ecda51103 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 18:41:07 -0500 Subject: [PATCH 27/34] [ php-wasm ] Test that exit unrefs every socket, and explain tradeoffs b748716ce changed exit cleanup to end every socket gracefully instead of destroying the ones PHP still had open, so their queued writes drain. Its rewritten exit test used a server that closes as soon as PHP's side ends, so two regressions passed every test: exit cleanup skipping sockets PHP had closed, and release() not unrefing the socket. Either would keep Node.js running while a peer holds a connection open. A new exit test uses a server that keeps its side open and checks that php.exit() unrefs both the persistent socket and the one PHP closed. The unit test for release() now counts TCP sockets as well as timers. The case named 'open' in the connection-attempt test is renamed to 'connecting', which is what it tests. Comments now explain the tradeoffs the reviews settled: why sockets are ended rather than destroyed at exit and what that costs, why the timeout exists, what a connecting socket can still lose, why shutDown() destroys a socket that's already closing, why there's no backpressure, what listening only where PHP binds changes for localhost, what leaving listen errors unhandled costs, and why stream_select() reports a listening socket ready before data arrives. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 33 +++++++++-- .../node/src/test/php-networking.spec.ts | 56 +++++++++++++++++++ .../php-wasm/node/src/test/tcp-socket.spec.ts | 19 ++++--- 3 files changed, 96 insertions(+), 12 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 95347e6d867..3284ca2567a 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -20,7 +20,9 @@ function log(...args: any[]) { debugLog('[TCP]', ...args); } -// How long a socket may keep sending after the runtime exits. +// How long a socket may keep sending after the runtime exits. It gives the peer +// time to read what PHP wrote, while bounding how long a peer that never reads +// or closes can hold the socket, the exited runtime's memory, and a process exit. export const RELEASED_SOCKET_TIMEOUT_MS = 30_000; const SOL_SOCKET = 1; @@ -80,6 +82,9 @@ export class TcpSocket extends EventEmitter { ) { return; } + // There's no backpressure: data goes to Emscripten as it arrives, as it + // did with the WebSocket proxy. Emscripten doesn't tell us when PHP has + // read it, so we can't pause the socket until then. // Emscripten ignores messages that aren't marked as binary. this.emit('message', data, true); }); @@ -129,6 +134,11 @@ export class TcpSocket extends EventEmitter { * persistent sockets PHP left open. Unref the socket so it doesn't keep * Node.js running once those writes are sent. A timeout bounds how long * pending writes or a peer that never closes can retain the connection. + * + * Ending rather than destroying means the peer sees a normal end of stream, + * even for a connection PHP left open mid-conversation, because destroying + * would discard PHP's queued writes. Until the socket closes, its listeners + * keep the exited runtime's memory alive. */ release() { if (this.released) { @@ -138,6 +148,9 @@ export class TcpSocket extends EventEmitter { const socket = this._socket; // Don't wait for an unused connection attempt after the runtime exits. // A connecting socket with queued writes still needs to drain them. + // Writes PHP made before the socket reported itself open are still in + // Emscripten's own queue, not Node.js's, and are lost, as they were with + // the WebSocket proxy. this.shutDown(socket?.connecting && socket.writableLength === 0); if (!socket || socket.destroyed) { return; @@ -166,7 +179,9 @@ export class TcpSocket extends EventEmitter { * Closes the connection and emits `close` on the next tick, like `ws`. */ protected shutDown(destroy = false) { - // A logical close can leave TCP connecting or draining. + // Destroy even if the socket already closed for PHP: a close only ends + // the write side, so TCP can still be connecting or sending. release() + // relies on this to stop a connection attempt nothing will use. if (destroy) { this._socket?.destroy(); } @@ -237,15 +252,23 @@ export interface TcpServerOptions { * API that Emscripten's SOCKFS uses. * * It listens on the host and port PHP binds to, and emits each accepted - * connection as a `TcpSocket`. + * connection as a `TcpSocket`. Listening only there, rather than on every + * interface like the WebSocket bridge, keeps a server bound to 127.0.0.1 off + * the network. As a result, a server bound to `localhost`, which PHP resolves + * to 127.0.0.1, doesn't accept IPv6 clients. * * CAUTION: An error before the server listens, such as EADDRINUSE, is left * unhandled so that it stops the process. Emscripten's listen() has already * returned by then, so PHP can't report it. If the error reached PHP's socket, - * PHP would wait for connections forever. + * PHP would wait for connections forever. The cost is that PHP code binding a + * busy port, an address that isn't local, or a hostname that doesn't resolve + * stops the whole process, such as a Playground CLI worker. */ export class TcpServer extends EventEmitter { - // php-wasm's poll() waits on these for data on a listening socket. + // php-wasm's poll() waits on these for data on a listening socket. Its + // select() also checks a read set for writability, and an open socket is + // always writable, so stream_select() reports the listening socket ready as + // soon as a connection is pending, before its data arrives. readonly clients = new Set(); private readonly server: net.Server; private closed = false; diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 1625c4dd7fe..abe992b1258 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -478,6 +478,62 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { await new Promise((resolve) => tcpServer.close(resolve)); } }); + it('should unref every connection when the runtime exits', async () => { + // The server keeps its side open after the client closes, so a + // connection the runtime doesn't unref would keep Node.js running. + const tcpServer = net.createServer({ allowHalfOpen: true }); + const connections: net.Socket[] = []; + const bothConnected = new Promise((resolve) => + tcpServer.on('connection', (socket) => { + socket.resume(); + connections.push(socket); + if (connections.length === 2) { + resolve(); + } + }) + ); + await new Promise((resolve) => + tcpServer.listen(0, '127.0.0.1', resolve) + ); + const { port } = tcpServer.address() as net.AddressInfo; + let php: PHP | undefined; + try { + php = new PHP(await loadNodeRuntime(phpVersion, options)); + await php.run({ + code: `(); + const unref = net.Socket.prototype.unref; + const unrefSpy = vi + .spyOn(net.Socket.prototype, 'unref') + .mockImplementation(function (this: net.Socket) { + if (!connections.includes(this)) { + unrefedPorts.add(this.localPort); + } + return unref.apply(this); + }); + try { + php.exit(); + } finally { + unrefSpy.mockRestore(); + } + + expect([...unrefedPorts].sort()).toEqual( + connections.map((socket) => socket.remotePort).sort() + ); + } finally { + php?.exit(); + connections.forEach((socket) => socket.destroy()); + tcpServer.close(); + } + }); }); describe('Listening sockets', () => { diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 7a32e937ca4..cccbe1ce9c0 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -31,7 +31,7 @@ describe('OutboundTcpSocket', () => { expect(socket.readyState).toBe(OutboundTcpSocket.CLOSED); }); - it.each(['open', 'closed'])( + it.each(['connecting', 'closed by PHP while connecting'])( 'cancels an unused connection attempt when released while %s', async (state) => { const port = await getClosedPort(); @@ -44,7 +44,8 @@ describe('OutboundTcpSocket', () => { socket.once('close', resolve) ); - if (state === 'closed') { + // release() runs before the socket reports itself open. + if (state !== 'connecting') { socket.close(); } socket.release(); @@ -203,15 +204,19 @@ describe('OutboundTcpSocket', () => { it('does not keep Node.js running while a released socket waits', async () => { const { socket, cleanUp } = await closeWithPeerOpen(); - const countTimers = () => + // Node.js doesn't count unref'd sockets and timers as keeping it running. + const countKeepingNodeRunning = () => process .getActiveResourcesInfo() - .filter((resource) => resource === 'Timeout').length; + .filter( + (resource) => + resource === 'Timeout' || resource === 'TCPSocketWrap' + ).length; try { - const timersBefore = countTimers(); + const before = countKeepingNodeRunning(); socket.release(); - // Node.js doesn't count an unref'd timer as keeping it running. - expect(countTimers()).toBe(timersBefore); + // The released socket stops counting, and its timeout never does. + expect(countKeepingNodeRunning()).toBe(before - 1); } finally { socket._socket?.destroy(); cleanUp(); From c57cf61fc13ea4ce5a35de80b69ccb15f459387f Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 19:21:44 -0500 Subject: [PATCH 28/34] [ php-wasm ] State what a released socket retains, and for how long A standalone check with forced garbage collection confirmed that a released socket whose peer keeps the connection open retains the exited runtime, including its WebAssembly heap. The runtime is freed once the peer closes, or once the release timeout destroys the socket. The release() comment now says so. Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/php-wasm/node/src/lib/networking/tcp-socket.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 3284ca2567a..05198acfef6 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -138,7 +138,8 @@ export class TcpSocket extends EventEmitter { * Ending rather than destroying means the peer sees a normal end of stream, * even for a connection PHP left open mid-conversation, because destroying * would discard PHP's queued writes. Until the socket closes, its listeners - * keep the exited runtime's memory alive. + * keep the exited runtime alive, including its WebAssembly heap. The + * timeout bounds that, and the runtime is freed once the socket closes. */ release() { if (this.released) { From 20d233b1c7015da14375ebc9434c715412ec3d7c Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 19:37:56 -0500 Subject: [PATCH 29/34] [ php-wasm ] Say when stream_select() reports a listening socket ready Emscripten counts every open connection in the server's clients, so the listener stays ready while any connection to it is open, including ones PHP already accepted, not only while one is pending. Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/php-wasm/node/src/lib/networking/tcp-socket.ts | 6 ++++-- packages/php-wasm/node/src/test/php-networking.spec.ts | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 05198acfef6..b9dc794353b 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -268,8 +268,10 @@ export interface TcpServerOptions { export class TcpServer extends EventEmitter { // php-wasm's poll() waits on these for data on a listening socket. Its // select() also checks a read set for writability, and an open socket is - // always writable, so stream_select() reports the listening socket ready as - // soon as a connection is pending, before its data arrives. + // always writable. A socket leaves this set only when it closes, so + // stream_select() reports the listening socket ready while any connection + // to it is open, including one PHP already accepted, and before its data + // arrives. `ws` servers' clients behaved the same way. readonly clients = new Set(); private readonly server: net.Server; private closed = false; diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index abe992b1258..3185e598955 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -572,8 +572,8 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { $server = stream_socket_server("tcp://127.0.0.1:${port}"); $start = microtime(true); $connection = false; - // stream_select() reports the server as soon as a connection is - // pending, before its data arrives. Pause so the data is there + // stream_select() reports the server ready as soon as a client + // connects, before its data arrives. Pause so the data is there // before accepting: with Asyncify, PHP crashes if // stream_socket_accept() has to wait. See // https://github.com/WordPress/wordpress-playground/issues/4576. From b236becdeb320930c53dadcd1aa110539b83aaf7 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sat, 7 Nov 2026 19:40:23 -0500 Subject: [PATCH 30/34] [ php-wasm ] Wait for PHP's connections before testing exit unrefs them php.run() can return before PHP's TCP connections finish, and the server can see both connections before the client sockets do. A socket still connecting at exit is destroyed rather than unref'd, so the test could fail. PHP now reads a byte from each connection first, like the flush test. Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/php-wasm/node/src/test/php-networking.spec.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 3185e598955..8db4b059617 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -486,6 +486,7 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { const bothConnected = new Promise((resolve) => tcpServer.on('connection', (socket) => { socket.resume(); + socket.write('ready'); connections.push(socket); if (connections.length === 2) { resolve(); @@ -499,10 +500,15 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { let php: PHP | undefined; try { php = new PHP(await loadNodeRuntime(phpVersion, options)); + // Wait for both TCP connections. The runtime destroys a + // socket that's still connecting at exit instead of unrefing it. await php.run({ code: ` Date: Sun, 8 Nov 2026 18:09:07 -0500 Subject: [PATCH 31/34] [ php-wasm ] Don't wake PHP when the runtime exits If the runtime exited while PHP waited on a socket, release() emitted close to Emscripten, which woke PHP. The script then ran after exit and could open sockets that nothing releases. Detach Emscripten's listeners when releasing a socket, so PHP stays suspended, as it did with the WebSocket proxy. The exited runtime can also be garbage-collected without waiting for its released sockets to close. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../node/src/lib/networking/tcp-socket.ts | 18 ++++--- .../node/src/test/php-networking.spec.ts | 47 ++++++++++++++++++- .../php-wasm/node/src/test/tcp-socket.spec.ts | 2 +- 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index b9dc794353b..046af538948 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -22,7 +22,7 @@ function log(...args: any[]) { // How long a socket may keep sending after the runtime exits. It gives the peer // time to read what PHP wrote, while bounding how long a peer that never reads -// or closes can hold the socket, the exited runtime's memory, and a process exit. +// or closes can hold the socket and delay a process exit. export const RELEASED_SOCKET_TIMEOUT_MS = 30_000; const SOL_SOCKET = 1; @@ -137,9 +137,7 @@ export class TcpSocket extends EventEmitter { * * Ending rather than destroying means the peer sees a normal end of stream, * even for a connection PHP left open mid-conversation, because destroying - * would discard PHP's queued writes. Until the socket closes, its listeners - * keep the exited runtime alive, including its WebAssembly heap. The - * timeout bounds that, and the runtime is freed once the socket closes. + * would discard PHP's queued writes. */ release() { if (this.released) { @@ -153,6 +151,14 @@ export class TcpSocket extends EventEmitter { // Emscripten's own queue, not Node.js's, and are lost, as they were with // the WebSocket proxy. this.shutDown(socket?.connecting && socket.writableLength === 0); + // Detach Emscripten so nothing reaches the exited runtime. PHP may be + // waiting on this socket, for example in fread(), and the `close` that + // shutDown() emits would wake it. PHP would then run the rest of its + // script after exit and could open sockets that nothing releases. The + // listeners would also keep the exited runtime, including its + // WebAssembly heap, in memory until the socket closes. The TCP socket's + // own listeners stay, so queued writes still drain. + this.removeAllListeners(); if (!socket || socket.destroyed) { return; } @@ -162,8 +168,8 @@ export class TcpSocket extends EventEmitter { RELEASED_SOCKET_TIMEOUT_MS ); timeout.unref(); - // The socket's listeners retain the runtime, so cancel the timer as - // soon as TCP closes rather than retaining it for the whole timeout. + // Cancel the timer once TCP closes, so it doesn't keep the closed + // socket in memory for the rest of the timeout. socket.once('close', () => clearTimeout(timeout)); } diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 8db4b059617..65dcfa556ed 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -513,8 +513,7 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { }); await bothConnected; // Record the local port of each socket the runtime unrefs. The - // server sees it as the connection's remotePort, and a client - // gets its local port as soon as it starts connecting. + // server sees it as the connection's remotePort. const unrefedPorts = new Set(); const unref = net.Socket.prototype.unref; const unrefSpy = vi @@ -540,6 +539,50 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { tcpServer.close(); } }); + + it('should not resume PHP waiting on a socket when the runtime exits', async () => { + const tcpServer = net.createServer({ allowHalfOpen: true }); + const connections: net.Socket[] = []; + const waiting = new Promise((resolve) => + tcpServer.on('connection', (socket) => { + connections.push(socket); + socket.once('data', () => resolve()); + }) + ); + await new Promise((resolve) => + tcpServer.listen(0, '127.0.0.1', resolve) + ); + const { port } = tcpServer.address() as net.AddressInfo; + let php: PHP | undefined; + try { + php = new PHP(await loadNodeRuntime(phpVersion, options)); + let settled = false; + php.run({ + code: ` (settled = true)); + // PHP is waiting in fread() once its write arrives. + await waiting; + const ended = new Promise((resolve) => + connections[0].once('end', resolve) + ); + php.exit(); + await ended; + // A resumed script would open a second connection right away. + await new Promise((resolve) => setTimeout(resolve, 200)); + + expect(connections).toHaveLength(1); + expect(settled).toBe(false); + } finally { + php?.exit(); + connections.forEach((socket) => socket.destroy()); + tcpServer.close(); + } + }); }); describe('Listening sockets', () => { diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index cccbe1ce9c0..9aaffae853b 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -41,7 +41,7 @@ describe('OutboundTcpSocket', () => { const opened = vi.fn(); socket.on('open', opened); const closed = new Promise((resolve) => - socket.once('close', resolve) + socket._socket!.once('close', resolve) ); // release() runs before the socket reports itself open. From f64d33a99825adb08f6a80d7f442a262c52f5d86 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sun, 8 Nov 2026 21:10:43 -0500 Subject: [PATCH 32/34] [ php-wasm ] Cancel network waits before releasing exited runtimes Own pending socket polls, extension receives, and connect waits in a per-runtime registry. Exit clears their timers and listeners before TCP cleanup. JSPI cancellation rejects with Emscripten's exit status so the native stack unwinds without continuing the PHP script or retaining its heap; Asyncify waits are abandoned without resuming PHP. Prevent exited runtimes from opening outbound or listening sockets, and drop incoming connections queued after a server closes. Preserve bounded TCP write draining and cleanup-timer cancellation. Keep source and all 32 generated JavaScript loaders synchronized without changing the WASM ABI or binaries. Document the exit contract and replace source-string timeout checks with behavior tests for finite deadlines, queued completions, process termination, collection, and runtime isolation. Validation: JSPI group 4 (699 passed), Asyncify networking (2971 passed), 28 lifecycle tests per mode, Redis networking (112 passed), universal unit tests (201 passed), web unit tests (107 passed), five browser networking tests, Node build, type checks, and tracked-code lint. MySQL integration requires the CI service and was not run locally. --- AGENTS.md | 8 + packages/php-wasm/compile/php/php_wasm.c | 58 ++-- .../compile/php/phpwasm-emscripten-library.js | 112 ++++++-- .../node-builds/5-2/asyncify/php_5_2.js | 170 ++++++++---- .../php-wasm/node-builds/5-2/jspi/php_5_2.js | 174 ++++++++---- .../node-builds/7-4/asyncify/php_7_4.js | 202 ++++++++++---- .../php-wasm/node-builds/7-4/jspi/php_7_4.js | 206 ++++++++++---- .../node-builds/8-0/asyncify/php_8_0.js | 202 ++++++++++---- .../php-wasm/node-builds/8-0/jspi/php_8_0.js | 206 ++++++++++---- .../node-builds/8-1/asyncify/php_8_1.js | 202 ++++++++++---- .../php-wasm/node-builds/8-1/jspi/php_8_1.js | 206 ++++++++++---- .../node-builds/8-2/asyncify/php_8_2.js | 202 ++++++++++---- .../php-wasm/node-builds/8-2/jspi/php_8_2.js | 206 ++++++++++---- .../node-builds/8-3/asyncify/php_8_3.js | 202 ++++++++++---- .../php-wasm/node-builds/8-3/jspi/php_8_3.js | 206 ++++++++++---- .../node-builds/8-4/asyncify/php_8_4.js | 202 ++++++++++---- .../php-wasm/node-builds/8-4/jspi/php_8_4.js | 206 ++++++++++---- .../node-builds/8-5/asyncify/php_8_5.js | 202 ++++++++++---- .../php-wasm/node-builds/8-5/jspi/php_8_5.js | 206 ++++++++++---- packages/php-wasm/node/README.md | 19 +- .../node/src/lib/networking/tcp-socket.ts | 14 +- .../src/lib/networking/with-networking.ts | 11 + .../test/fixtures/exit-during-network-read.ts | 56 ++++ .../test/networking-port-allocation.spec.ts | 21 ++ .../node/src/test/php-networking.spec.ts | 86 +++--- .../php-wasm/node/src/test/php-redis.spec.ts | 44 +++ .../node/src/test/php-socket-timeouts.spec.ts | 254 +++++++++++------- .../universal/src/lib/load-php-runtime.ts | 7 + .../web-builds/5-2/asyncify/php_5_2.js | 176 +++++++++--- .../php-wasm/web-builds/5-2/jspi/php_5_2.js | 180 ++++++++++--- .../web-builds/7-4/asyncify/php_7_4.js | 189 ++++++++++--- .../php-wasm/web-builds/7-4/jspi/php_7_4.js | 193 ++++++++++--- .../web-builds/8-0/asyncify/php_8_0.js | 189 ++++++++++--- .../php-wasm/web-builds/8-0/jspi/php_8_0.js | 193 ++++++++++--- .../web-builds/8-1/asyncify/php_8_1.js | 189 ++++++++++--- .../php-wasm/web-builds/8-1/jspi/php_8_1.js | 193 ++++++++++--- .../web-builds/8-2/asyncify/php_8_2.js | 189 ++++++++++--- .../php-wasm/web-builds/8-2/jspi/php_8_2.js | 193 ++++++++++--- .../web-builds/8-3/asyncify/php_8_3.js | 189 ++++++++++--- .../php-wasm/web-builds/8-3/jspi/php_8_3.js | 193 ++++++++++--- .../web-builds/8-4/asyncify/php_8_4.js | 189 ++++++++++--- .../php-wasm/web-builds/8-4/jspi/php_8_4.js | 193 ++++++++++--- .../web-builds/8-5/asyncify/php_8_5.js | 189 ++++++++++--- .../php-wasm/web-builds/8-5/jspi/php_8_5.js | 193 ++++++++++--- 44 files changed, 5147 insertions(+), 1773 deletions(-) create mode 100644 packages/php-wasm/node/src/test/fixtures/exit-during-network-read.ts diff --git a/AGENTS.md b/AGENTS.md index 2ae781872f4..31a76ad8aa3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -311,6 +311,14 @@ load the JSPI build in CI. The `test-networking-asyncify` job runs the `@php-wasm/node` networking tests on Node 24.18.0, which loads the Asyncify build. Its `vite.asyncify.config.ts` stops with an error on Node versions that enable JSPI. +Runtime exit cancels pending network waits before releasing TCP handles. The +wait registry lives in `phpwasm-emscripten-library.js`; socket polls in `php_wasm.c` +use the same registry as extension receives and connects. Keep the generated +Node and web loader JavaScript in sync when changing this glue. Preserve the +exit contracts in the Node networking, socket-timeout, and Redis tests: no PHP +resumption or new connections after exit, bounded write draining, timer cleanup, +and cancellation isolated to the exiting runtime. + Dependabot's daily version check opens PRs for `fs-ext-extra-prebuilt` patch releases. It raises the minimum package version and updates the lockfile; the existing Dependabot lockfile workflow preserves workspace links. An explicit diff --git a/packages/php-wasm/compile/php/php_wasm.c b/packages/php-wasm/compile/php/php_wasm.c index 6c2258a01c7..482895ebf85 100644 --- a/packages/php-wasm/compile/php/php_wasm.c +++ b/packages/php-wasm/compile/php/php_wasm.c @@ -150,7 +150,7 @@ EM_JS(char*, js_popen_to_file, (const char *command, const char *mode, uint8_t * */ #ifdef PLAYGROUND_JSPI EM_ASYNC_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => new Promise((resolve, reject) => resolver(resolve, reject)); #else EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { const returnCallback = (resolver) => Asyncify.handleSleep(resolver); @@ -162,8 +162,16 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { const POLLHUP = 0x0010; /* Hung up */ const POLLNVAL = 0x0020; /* Invalid request: fd not open */ - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait(wakeUp, () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, abort); + if (!wait.active) { + return; + } /** * Special semantics for polling sockets. * @@ -178,7 +186,7 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); @@ -187,19 +195,19 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -231,6 +239,7 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { // Poll the stream for data. // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { // Inlined ___syscall_poll with added await support: @@ -251,7 +260,9 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise(resolve => setTimeout(resolve, 10)); + await new Promise(resolve => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; @@ -262,11 +273,12 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); } ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -276,35 +288,15 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); - + Promise.race(polls.map(([promise]) => promise)).then(() => wait.finish(1)); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/compile/php/phpwasm-emscripten-library.js b/packages/php-wasm/compile/php/phpwasm-emscripten-library.js index 4a1cc0ff59d..09086298861 100644 --- a/packages/php-wasm/compile/php/phpwasm-emscripten-library.js +++ b/packages/php-wasm/compile/php/phpwasm-emscripten-library.js @@ -35,7 +35,7 @@ const LibraryExample = { }, // Emscripten dependencies: - $PHPWASM__deps: ['$allocateUTF8OnStack', '$addOnInit'], + $PHPWASM__deps: ['$allocateUTF8OnStack', '$addOnInit', '$ExitStatus'], $PHPWASM__postset: 'PHPWASM.init();', // Functions not exposed to C but available in the generated @@ -51,11 +51,20 @@ const LibraryExample = { SETFL_MASK: Number('{{{cDefs.O_APPEND}}}') | Number('{{{cDefs.O_NONBLOCK}}}'), socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, // These macros are not defined in Emscripten at the time of writing: // emscripten_O_NDELAY | // emscripten_O_DIRECT | // emscripten_O_NOATIME init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -485,13 +494,58 @@ const LibraryExample = { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); + // Do not settle cancelled waits: that could resume exited PHP. }; return [promise, cancel]; }, + + /** + * Owns the lifetime of an asynchronous socket operation. Exit cancels + * its timers and listeners without continuing the PHP script. JSPI + * must unwind its suspended native stack so V8 can release the runtime. + * Completion checks active even for callbacks already queued at exit. + */ + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync(() => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { @@ -1073,14 +1127,18 @@ const LibraryExample = { * @returns {Promise} Resolved with the number of bytes recieved */ wasm_recv: function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { - const receiveTimeout = - PHPWASM.socketTimeouts.get(sockfd)?.receive; + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -1092,21 +1150,18 @@ const LibraryExample = { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -1122,8 +1177,8 @@ const LibraryExample = { * SO_KEEPALIVE and TCP_NODELAY are propagated to the WebSockets proxy * server, which then sets them on the underlying TCP connection. * - * SO_RCVTIMEO and SO_SNDTIMEO are stored per socket. wasm_recv() - * uses SO_RCVTIMEO and wasm_connect() uses SO_SNDTIMEO. + * SO_RCVTIMEO and SO_SNDTIMEO are stored per socket. wasm_recv() + * uses SO_RCVTIMEO and wasm_connect() uses SO_SNDTIMEO. * * @param {int} socketd Socket descriptor * @param {int} level Level at which the option is defined @@ -1210,13 +1265,13 @@ const LibraryExample = { * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. */ - if (!("Suspending" in WebAssembly)) { + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -1282,7 +1337,6 @@ const LibraryExample = { // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; const timeout = sendTimeout ?? 30000; - let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -1300,6 +1354,14 @@ const LibraryExample = { ws.removeEventListener('close', handleClose); }; + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -1319,13 +1381,11 @@ const LibraryExample = { }; const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; diff --git a/packages/php-wasm/node-builds/5-2/asyncify/php_5_2.js b/packages/php-wasm/node-builds/5-2/asyncify/php_5_2.js index 87aa7ab64bb..67df984972d 100644 --- a/packages/php-wasm/node-builds/5-2/asyncify/php_5_2.js +++ b/packages/php-wasm/node-builds/5-2/asyncify/php_5_2.js @@ -6145,8 +6145,17 @@ export function init(RuntimeName, PHPLoader) { O_NONBLOCK: 2048, POLLHUP: 16, SETFL_MASK: 3072, - socketTimeouts: new Map, + socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6567,13 +6576,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6671,13 +6718,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6686,10 +6734,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6702,6 +6752,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6713,6 +6764,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6720,22 +6772,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6753,6 +6808,14 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('close', handleClose); }; + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6772,13 +6835,11 @@ export function init(RuntimeName, PHPLoader) { }; const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; @@ -6799,6 +6860,7 @@ export function init(RuntimeName, PHPLoader) { handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10086,32 +10148,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10123,6 +10209,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10138,9 +10226,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10150,6 +10242,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10157,9 +10250,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10174,11 +10267,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10188,33 +10282,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/node-builds/5-2/jspi/php_5_2.js b/packages/php-wasm/node-builds/5-2/jspi/php_5_2.js index c6c0bf0970a..a935937be97 100644 --- a/packages/php-wasm/node-builds/5-2/jspi/php_5_2.js +++ b/packages/php-wasm/node-builds/5-2/jspi/php_5_2.js @@ -6086,8 +6086,17 @@ export function init(RuntimeName, PHPLoader) { O_NONBLOCK: 2048, POLLHUP: 16, SETFL_MASK: 3072, - socketTimeouts: new Map, + socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6508,13 +6517,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6612,13 +6659,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6627,10 +6675,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6643,6 +6693,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6654,6 +6705,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6661,22 +6713,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6694,6 +6749,14 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('close', handleClose); }; + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6713,13 +6776,11 @@ export function init(RuntimeName, PHPLoader) { }; const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; @@ -6740,6 +6801,7 @@ export function init(RuntimeName, PHPLoader) { handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9819,39 +9881,64 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -9863,6 +9950,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -9878,9 +9967,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -9890,6 +9983,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -9897,9 +9991,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -9914,11 +10008,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -9928,34 +10023,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/node-builds/7-4/asyncify/php_7_4.js b/packages/php-wasm/node-builds/7-4/asyncify/php_7_4.js index 15bc1ec3f8e..a4134d03903 100644 --- a/packages/php-wasm/node-builds/7-4/asyncify/php_7_4.js +++ b/packages/php-wasm/node-builds/7-4/asyncify/php_7_4.js @@ -6244,7 +6244,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6665,13 +6674,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6769,13 +6816,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6784,10 +6832,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6800,6 +6850,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6811,6 +6862,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6818,22 +6870,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6841,6 +6896,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6849,6 +6905,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6857,37 +6922,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10282,12 +10353,18 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -10299,21 +10376,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10478,32 +10552,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10515,6 +10613,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10530,9 +10630,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10542,6 +10646,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10549,9 +10654,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10566,11 +10671,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10580,33 +10686,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/node-builds/7-4/jspi/php_7_4.js b/packages/php-wasm/node-builds/7-4/jspi/php_7_4.js index d52c805eddd..17edf613ed2 100644 --- a/packages/php-wasm/node-builds/7-4/jspi/php_7_4.js +++ b/packages/php-wasm/node-builds/7-4/jspi/php_7_4.js @@ -6087,7 +6087,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6508,13 +6517,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6612,13 +6659,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6627,10 +6675,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6643,6 +6693,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6654,6 +6705,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6661,22 +6713,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6684,6 +6739,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6692,6 +6748,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6700,37 +6765,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9943,12 +10014,18 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -9960,21 +10037,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10122,39 +10196,64 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10166,6 +10265,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10181,9 +10282,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10193,6 +10298,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10200,9 +10306,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10217,11 +10323,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10231,34 +10338,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-0/asyncify/php_8_0.js b/packages/php-wasm/node-builds/8-0/asyncify/php_8_0.js index 320210d3a6f..efc8260e7de 100644 --- a/packages/php-wasm/node-builds/8-0/asyncify/php_8_0.js +++ b/packages/php-wasm/node-builds/8-0/asyncify/php_8_0.js @@ -6244,7 +6244,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6665,13 +6674,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6769,13 +6816,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6784,10 +6832,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6800,6 +6850,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6811,6 +6862,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6818,22 +6870,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6841,6 +6896,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6849,6 +6905,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6857,37 +6922,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10282,12 +10353,18 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -10299,21 +10376,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10478,32 +10552,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10515,6 +10613,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10530,9 +10630,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10542,6 +10646,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10549,9 +10654,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10566,11 +10671,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10580,33 +10686,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-0/jspi/php_8_0.js b/packages/php-wasm/node-builds/8-0/jspi/php_8_0.js index fee8dedb09a..a318a65664e 100644 --- a/packages/php-wasm/node-builds/8-0/jspi/php_8_0.js +++ b/packages/php-wasm/node-builds/8-0/jspi/php_8_0.js @@ -6087,7 +6087,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6508,13 +6517,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6612,13 +6659,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6627,10 +6675,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6643,6 +6693,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6654,6 +6705,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6661,22 +6713,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6684,6 +6739,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6692,6 +6748,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6700,37 +6765,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9943,12 +10014,18 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -9960,21 +10037,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10122,39 +10196,64 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10166,6 +10265,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10181,9 +10282,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10193,6 +10298,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10200,9 +10306,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10217,11 +10323,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10231,34 +10338,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-1/asyncify/php_8_1.js b/packages/php-wasm/node-builds/8-1/asyncify/php_8_1.js index 807f571fc2d..805d15e3922 100644 --- a/packages/php-wasm/node-builds/8-1/asyncify/php_8_1.js +++ b/packages/php-wasm/node-builds/8-1/asyncify/php_8_1.js @@ -6244,7 +6244,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6665,13 +6674,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6769,13 +6816,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6784,10 +6832,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6800,6 +6850,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6811,6 +6862,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6818,22 +6870,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6841,6 +6896,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6849,6 +6905,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6857,37 +6922,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10300,12 +10371,18 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -10317,21 +10394,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10496,32 +10570,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10533,6 +10631,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10548,9 +10648,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10560,6 +10664,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10567,9 +10672,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10584,11 +10689,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10598,33 +10704,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-1/jspi/php_8_1.js b/packages/php-wasm/node-builds/8-1/jspi/php_8_1.js index c92c2605d5c..1d4ec44e74c 100644 --- a/packages/php-wasm/node-builds/8-1/jspi/php_8_1.js +++ b/packages/php-wasm/node-builds/8-1/jspi/php_8_1.js @@ -6087,7 +6087,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6508,13 +6517,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6612,13 +6659,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6627,10 +6675,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6643,6 +6693,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6654,6 +6705,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6661,22 +6713,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6684,6 +6739,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6692,6 +6748,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6700,37 +6765,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9961,12 +10032,18 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -9978,21 +10055,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10140,39 +10214,64 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10184,6 +10283,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10199,9 +10300,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10211,6 +10316,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10218,9 +10324,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10235,11 +10341,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10249,34 +10356,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-2/asyncify/php_8_2.js b/packages/php-wasm/node-builds/8-2/asyncify/php_8_2.js index 5ffbfc2bd33..901760367be 100644 --- a/packages/php-wasm/node-builds/8-2/asyncify/php_8_2.js +++ b/packages/php-wasm/node-builds/8-2/asyncify/php_8_2.js @@ -6244,7 +6244,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6665,13 +6674,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6769,13 +6816,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6784,10 +6832,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6800,6 +6850,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6811,6 +6862,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6818,22 +6870,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6841,6 +6896,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6849,6 +6905,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6857,37 +6922,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10302,12 +10373,18 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -10319,21 +10396,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10498,32 +10572,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10535,6 +10633,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10550,9 +10650,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10562,6 +10666,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10569,9 +10674,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10586,11 +10691,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10600,33 +10706,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-2/jspi/php_8_2.js b/packages/php-wasm/node-builds/8-2/jspi/php_8_2.js index 48aa7b07058..d9f7074f839 100644 --- a/packages/php-wasm/node-builds/8-2/jspi/php_8_2.js +++ b/packages/php-wasm/node-builds/8-2/jspi/php_8_2.js @@ -6087,7 +6087,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6508,13 +6517,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6612,13 +6659,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6627,10 +6675,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6643,6 +6693,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6654,6 +6705,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6661,22 +6713,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6684,6 +6739,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6692,6 +6748,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6700,37 +6765,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9963,12 +10034,18 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -9980,21 +10057,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10142,39 +10216,64 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10186,6 +10285,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10201,9 +10302,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10213,6 +10318,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10220,9 +10326,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10237,11 +10343,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10251,34 +10358,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-3/asyncify/php_8_3.js b/packages/php-wasm/node-builds/8-3/asyncify/php_8_3.js index 66513a6c6c5..07c5b959502 100644 --- a/packages/php-wasm/node-builds/8-3/asyncify/php_8_3.js +++ b/packages/php-wasm/node-builds/8-3/asyncify/php_8_3.js @@ -6244,7 +6244,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6665,13 +6674,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6769,13 +6816,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6784,10 +6832,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6800,6 +6850,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6811,6 +6862,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6818,22 +6870,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6841,6 +6896,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6849,6 +6905,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6857,37 +6922,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10302,12 +10373,18 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -10319,21 +10396,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10498,32 +10572,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10535,6 +10633,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10550,9 +10650,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10562,6 +10666,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10569,9 +10674,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10586,11 +10691,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10600,33 +10706,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-3/jspi/php_8_3.js b/packages/php-wasm/node-builds/8-3/jspi/php_8_3.js index df6ae79ee41..93803e75722 100644 --- a/packages/php-wasm/node-builds/8-3/jspi/php_8_3.js +++ b/packages/php-wasm/node-builds/8-3/jspi/php_8_3.js @@ -6087,7 +6087,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6508,13 +6517,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6612,13 +6659,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6627,10 +6675,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6643,6 +6693,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6654,6 +6705,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6661,22 +6713,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6684,6 +6739,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6692,6 +6748,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6700,37 +6765,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9963,12 +10034,18 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -9980,21 +10057,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10142,39 +10216,64 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10186,6 +10285,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10201,9 +10302,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10213,6 +10318,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10220,9 +10326,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10237,11 +10343,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10251,34 +10358,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-4/asyncify/php_8_4.js b/packages/php-wasm/node-builds/8-4/asyncify/php_8_4.js index 6fb83c733ce..6e346656deb 100644 --- a/packages/php-wasm/node-builds/8-4/asyncify/php_8_4.js +++ b/packages/php-wasm/node-builds/8-4/asyncify/php_8_4.js @@ -6244,7 +6244,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6665,13 +6674,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6769,13 +6816,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6784,10 +6832,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6800,6 +6850,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6811,6 +6862,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6818,22 +6870,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6841,6 +6896,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6849,6 +6905,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6857,37 +6922,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10302,12 +10373,18 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -10319,21 +10396,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10498,32 +10572,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10535,6 +10633,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10550,9 +10650,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10562,6 +10666,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10569,9 +10674,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10586,11 +10691,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10600,33 +10706,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-4/jspi/php_8_4.js b/packages/php-wasm/node-builds/8-4/jspi/php_8_4.js index 3e94113685c..0dae2bff55b 100644 --- a/packages/php-wasm/node-builds/8-4/jspi/php_8_4.js +++ b/packages/php-wasm/node-builds/8-4/jspi/php_8_4.js @@ -6087,7 +6087,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6508,13 +6517,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6612,13 +6659,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6627,10 +6675,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6643,6 +6693,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6654,6 +6705,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6661,22 +6713,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6684,6 +6739,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6692,6 +6748,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6700,37 +6765,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9963,12 +10034,18 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -9980,21 +10057,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10142,39 +10216,64 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10186,6 +10285,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10201,9 +10302,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10213,6 +10318,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10220,9 +10326,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10237,11 +10343,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10251,34 +10358,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-5/asyncify/php_8_5.js b/packages/php-wasm/node-builds/8-5/asyncify/php_8_5.js index 88f8b455046..6eacbf8f9e4 100644 --- a/packages/php-wasm/node-builds/8-5/asyncify/php_8_5.js +++ b/packages/php-wasm/node-builds/8-5/asyncify/php_8_5.js @@ -6244,7 +6244,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6665,13 +6674,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6769,13 +6816,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6784,10 +6832,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6800,6 +6850,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6811,6 +6862,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6818,22 +6870,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6841,6 +6896,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6849,6 +6905,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6857,37 +6922,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10302,12 +10373,18 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -10319,21 +10396,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10500,32 +10574,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10537,6 +10635,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10552,9 +10652,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10564,6 +10668,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10571,9 +10676,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10588,11 +10693,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10602,33 +10708,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-5/jspi/php_8_5.js b/packages/php-wasm/node-builds/8-5/jspi/php_8_5.js index e69833ad012..ce1cd45d96e 100644 --- a/packages/php-wasm/node-builds/8-5/jspi/php_8_5.js +++ b/packages/php-wasm/node-builds/8-5/jspi/php_8_5.js @@ -6087,7 +6087,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6508,13 +6517,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - // Rejecting the promises bubbles up and kills the entire - // node process. Let's resolve them on the next tick instead - // to give the caller some space to unbind any handlers. - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6612,13 +6659,14 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { + */ + if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { // Get the socket let sock; try { @@ -6627,10 +6675,12 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + // Parse the address let info; try { @@ -6643,6 +6693,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6654,6 +6705,7 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6661,22 +6713,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -6684,6 +6739,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6692,6 +6748,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -6700,37 +6765,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9963,12 +10034,18 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let resolved = false; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => clearTimeout(timeoutId), + abort + ); + const poll = function () { - if (resolved) { + if (!wait.active) { return; } let newl = ___syscall_recvfrom( @@ -9980,21 +10057,18 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - resolved = true; - wakeUp(newl); + wait.finish(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - resolved = true; - wakeUp(-ERRNO_CODES.EAGAIN); + wait.finish(-ERRNO_CODES.EAGAIN); return; } - setTimeout(poll, 20); + timeoutId = setTimeout(poll, 20); } else { - resolved = true; - wakeUp(0); + wait.finish(0); } }; poll(); @@ -10144,39 +10218,64 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -10188,6 +10287,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10203,9 +10304,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10215,6 +10320,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10222,9 +10328,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -10239,11 +10345,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -10253,34 +10360,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/node/README.md b/packages/php-wasm/node/README.md index bf24307c66a..50810eda707 100644 --- a/packages/php-wasm/node/README.md +++ b/packages/php-wasm/node/README.md @@ -9,8 +9,7 @@ This package ships WebAssembly PHP binaries and the JavaScript API optimized for - OpenSSL - MySQL -It uses the host filesystem directly and can access the network if you plug in a custom -WS proxy. +It uses the host filesystem and TCP sockets directly. Here's how to use it: @@ -27,6 +26,22 @@ const output = await php.runStream({ console.log(await output.stdoutText); ``` +## Runtime exit and networking + +`php.exit()` cancels pending socket polls, receives, and connection waits before +releasing network handles. Cancelled waits do not resume PHP, and an exited +runtime cannot create new TCP connections or listening sockets. Cancellation is +per runtime; it does not affect other PHP instances. + +TCP sockets drain writes already queued in Node.js, including writes on persistent +connections. They stop keeping Node.js alive once those writes finish. Cleanup +cancels its timer when TCP closes and destroys connections still open after 30 +seconds. A peer that does not read can therefore lose queued data at that deadline. +Writes still queued inside Emscripten before the socket opens are not guaranteed +to drain. JSPI unwinds cancelled waits with the requested exit status so V8 can +release the suspended stack; Asyncify abandons them without resuming PHP. Do not +rely on an in-flight request completing after exit; discard the exited runtime. + ## Loading PHP extensions Pass `extensions` to `loadNodeRuntime()` to load optional PHP extensions before diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index 046af538948..c6ecb0bddf3 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -151,13 +151,9 @@ export class TcpSocket extends EventEmitter { // Emscripten's own queue, not Node.js's, and are lost, as they were with // the WebSocket proxy. this.shutDown(socket?.connecting && socket.writableLength === 0); - // Detach Emscripten so nothing reaches the exited runtime. PHP may be - // waiting on this socket, for example in fread(), and the `close` that - // shutDown() emits would wake it. PHP would then run the rest of its - // script after exit and could open sockets that nothing releases. The - // listeners would also keep the exited runtime, including its - // WebAssembly heap, in memory until the socket closes. The TCP socket's - // own listeners stay, so queued writes still drain. + // The runtime cancels pending waits before releasing sockets. Detach + // remaining Emscripten listeners as well, so draining TCP cannot send + // events into exited PHP. TCP's own listeners stay to drain queued writes. this.removeAllListeners(); if (!socket || socket.destroyed) { return; @@ -285,6 +281,10 @@ export class TcpServer extends EventEmitter { constructor({ host, port }: TcpServerOptions) { super(); this.server = net.createServer((socket) => { + if (this.closed) { + socket.destroy(); + return; + } // A client that reset the connection before Node.js handled it has // no address. Emscripten's accept() fails on that with a JavaScript // error instead of an errno, so drop the connection. diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 276a221901e..8c91883f099 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -16,6 +16,7 @@ export async function withNetworking( ): Promise { // The runtime releases these when it exits. const openHandles = new Set(); + let closed = false; const track = (handle: TcpSocket | TcpServer) => { openHandles.add(handle); // A socket that PHP closed stays open until the peer closes its side, @@ -28,6 +29,9 @@ export async function withNetworking( // Each runtime gets its own classes, so it only releases its own sockets. class RuntimeOutboundTcpSocket extends OutboundTcpSocket { constructor(url: string) { + if (closed) { + throw new Error('The PHP runtime has exited'); + } super(url); track(this); } @@ -35,6 +39,9 @@ export async function withNetworking( class RuntimeTcpServer extends TcpServer { constructor(options: TcpServerOptions) { + if (closed) { + throw new Error('The PHP runtime has exited'); + } super(options); track(this); this.on('connection', track); @@ -44,6 +51,10 @@ export async function withNetworking( return { ...phpModuleArgs, closeNetworkConnections: () => { + if (closed) { + return; + } + closed = true; // Drain queued writes and bound the lifetime of connections whose // peers keep them open. See TcpSocket.release(). // Release each handle even if another one fails. diff --git a/packages/php-wasm/node/src/test/fixtures/exit-during-network-read.ts b/packages/php-wasm/node/src/test/fixtures/exit-during-network-read.ts new file mode 100644 index 00000000000..2ed0b3727c2 --- /dev/null +++ b/packages/php-wasm/node/src/test/fixtures/exit-during-network-read.ts @@ -0,0 +1,56 @@ +import net from 'node:net'; +import { + PHP, + popLoadedRuntime, + type SupportedPHPVersion, +} from '@php-wasm/universal'; +import { loadNodeRuntime } from '../../lib'; + +const connections: net.Socket[] = []; +let notifyWaiting: () => void; +const waiting = new Promise((resolve) => (notifyWaiting = resolve)); +const server = net.createServer((socket) => { + connections.push(socket); + socket.once('data', () => notifyWaiting()); +}); +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); +const { port } = server.address() as net.AddressInfo; +const weak = await runAndExit(); +connections.forEach((socket) => socket.destroy()); +await new Promise((resolve) => server.close(resolve)); +if (process.getActiveResourcesInfo().includes('Timeout')) { + throw new Error('A pending network wait still has a referenced timer'); +} +// Use a file rather than --eval: Node's eval scope itself retains the runtime. +for (let i = 0; i < 10; i++) { + await new Promise((resolve) => setTimeout(resolve, 10)); + global.gc!(); +} +if (weak.deref()) { + throw new Error('The cancelled network wait still retains the runtime'); +} + +async function runAndExit() { + const id = await loadNodeRuntime( + process.env['PHP_VERSION'] as SupportedPHPVersion, + { + emscriptenOptions: { processId: 1 }, + } + ); + const runtime = popLoadedRuntime(id, { + dangerouslyKeepTheRuntimeInTheMap: true, + }); + const weak = new WeakRef(runtime); + const php = new PHP(id); + php.run({ + code: ` {}); + await waiting; + php.exit(); + return weak; +} diff --git a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts index c3f74d21b10..769a9574d8b 100644 --- a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts +++ b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts @@ -31,6 +31,27 @@ describe('networking port allocation', () => { expect(closeNetworkConnections).toHaveBeenCalledOnce(); }); + it('does not open outbound or listening sockets after exit', async () => { + const emscriptenOptions = await withNetworking({}); + const OutboundSocket = emscriptenOptions['websocket'].decorator(); + const Server = emscriptenOptions['websocket'].serverDecorator(); + const connectSpy = vi.spyOn(net, 'createConnection'); + const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); + emscriptenOptions.closeNetworkConnections!(); + + expect( + () => + new OutboundSocket( + emscriptenOptions['websocket'].url(null, '127.0.0.1', '9') + ) + ).toThrow('The PHP runtime has exited'); + expect(() => new Server({ host: '127.0.0.1', port: 0 })).toThrow( + 'The PHP runtime has exited' + ); + expect(connectSpy).not.toHaveBeenCalled(); + expect(listenSpy).not.toHaveBeenCalled(); + }); + it('listens only on the host and port PHP binds to', async () => { const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 65dcfa556ed..752a5d63980 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -540,49 +540,63 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { } }); - it('should not resume PHP waiting on a socket when the runtime exits', async () => { - const tcpServer = net.createServer({ allowHalfOpen: true }); - const connections: net.Socket[] = []; - const waiting = new Promise((resolve) => - tcpServer.on('connection', (socket) => { - connections.push(socket); - socket.once('data', () => resolve()); - }) - ); - await new Promise((resolve) => - tcpServer.listen(0, '127.0.0.1', resolve) - ); - const { port } = tcpServer.address() as net.AddressInfo; - let php: PHP | undefined; - try { - php = new PHP(await loadNodeRuntime(phpVersion, options)); - let settled = false; - php.run({ - code: ` { + const tcpServer = net.createServer({ allowHalfOpen: true }); + const connections: net.Socket[] = []; + const waiting = new Promise((resolve) => + tcpServer.on('connection', (socket) => { + connections.push(socket); + socket.once('data', () => resolve()); + }) + ); + await new Promise((resolve) => + tcpServer.listen(0, '127.0.0.1', resolve) + ); + const { port } = tcpServer.address() as net.AddressInfo; + let php: PHP | undefined; + try { + php = new PHP( + await loadNodeRuntime(phpVersion, options) + ); + let output: string | undefined; + let failure: unknown; + php.run({ + code: ` (settled = true)); - // PHP is waiting in fread() once its write arrives. - await waiting; - const ended = new Promise((resolve) => - connections[0].once('end', resolve) - ); - php.exit(); - await ended; - // A resumed script would open a second connection right away. - await new Promise((resolve) => setTimeout(resolve, 200)); + }).then( + (result) => (output = result.text), + (error) => (failure = error) + ); + // PHP is waiting in fread() once its write arrives. + await waiting; + const ended = new Promise((resolve) => + connections[0].once('end', resolve) + ); + php.exit(); + await ended; + // Wait beyond the finite read timeout as well as queued close events. + await new Promise((resolve) => + setTimeout(resolve, 250) + ); - expect(connections).toHaveLength(1); - expect(settled).toBe(false); - } finally { - php?.exit(); - connections.forEach((socket) => socket.destroy()); - tcpServer.close(); + expect(connections).toHaveLength(1); + expect(output ?? '').toBe(''); + expect(failure).toBeUndefined(); + } finally { + php?.exit(); + connections.forEach((socket) => socket.destroy()); + tcpServer.close(); + } } - }); + ); }); describe('Listening sockets', () => { diff --git a/packages/php-wasm/node/src/test/php-redis.spec.ts b/packages/php-wasm/node/src/test/php-redis.spec.ts index aa9601e1f45..3714414175c 100644 --- a/packages/php-wasm/node/src/test/php-redis.spec.ts +++ b/packages/php-wasm/node/src/test/php-redis.spec.ts @@ -18,6 +18,7 @@ import { } from '@php-wasm/universal'; import { loadNodeRuntime } from '../lib'; import { jspi } from 'wasm-feature-detect'; +import net from 'node:net'; // Check JSPI availability at module load time (top-level await) const isJspiAvailable = await jspi(); @@ -292,6 +293,49 @@ if (!isJspiAvailable) { } }); + it('does not resume a pending extension receive after exit', async () => { + const connections: net.Socket[] = []; + let notifyWaiting: () => void; + const waiting = new Promise( + (resolve) => (notifyWaiting = resolve) + ); + // Accept the Redis command but never reply, forcing wasm_recv() to wait. + const server = net.createServer((socket) => { + connections.push(socket); + socket.once('data', () => notifyWaiting()); + }); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + let output: string | undefined; + let failure: unknown; + try { + php.run({ + code: `connect('127.0.0.1', ${port}); + $r->setOption(Redis::OPT_READ_TIMEOUT, 0.1); + try { $r->get('waiting'); } catch (Throwable $e) {} + echo 'continued after exit'; + fsockopen('127.0.0.1', ${port}); + `, + }).then( + (result) => (output = result.text), + (error) => (failure = error) + ); + await waiting; + php.exit(); + await new Promise((resolve) => setTimeout(resolve, 250)); + expect(output ?? '').toBe(''); + expect(failure).toBeUndefined(); + expect(connections).toHaveLength(1); + } finally { + connections.forEach((socket) => socket.destroy()); + await new Promise((resolve) => server.close(resolve)); + } + }); + it('can set values with expiration', async () => { const testKey = `test_expiry_${Date.now()}_${Math.random().toString(36).substring(7)}`; diff --git a/packages/php-wasm/node/src/test/php-socket-timeouts.spec.ts b/packages/php-wasm/node/src/test/php-socket-timeouts.spec.ts index 0bdf0e1e6ff..f1577cb01bf 100644 --- a/packages/php-wasm/node/src/test/php-socket-timeouts.spec.ts +++ b/packages/php-wasm/node/src/test/php-socket-timeouts.spec.ts @@ -1,104 +1,176 @@ -import { readdirSync, readFileSync, statSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { execFile } from 'node:child_process'; +import net from 'node:net'; +import path from 'node:path'; +import { + PHP, + SupportedPHPVersions, + popLoadedRuntime, + type SupportedPHPVersion, +} from '@php-wasm/universal'; +import { loadNodeRuntime } from '../lib'; -const repoRoot = resolve( - dirname(fileURLToPath(import.meta.url)), - '../../../../..' -); +const phpVersions = process.env['PHP'] + ? [process.env['PHP'] as SupportedPHPVersion] + : SupportedPHPVersions; -function collectGeneratedPhpLoaders(directory: string): string[] { - return readdirSync(directory) - .flatMap((entry) => { - const fullPath = join(directory, entry); - if (statSync(fullPath).isDirectory()) { - return collectGeneratedPhpLoaders(fullPath); - } - return /php_\d+_\d+\.js$/.test(entry) ? [fullPath] : []; - }) - .sort(); -} - -describe('socket timeout support', () => { - it('is present in the Emscripten library source', () => { - const source = readFileSync( - join( - repoRoot, - 'packages/php-wasm/compile/php/phpwasm-emscripten-library.js' - ), - 'utf8' +describe.each(phpVersions)('PHP %s socket timeouts', (phpVersion) => { + it('ignores a queued socket completion after exit', async () => { + const connections: net.Socket[] = []; + const server = net.createServer((socket) => connections.push(socket)); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) ); + const { port } = server.address() as net.AddressInfo; + let php: PHP | undefined; + try { + const id = await loadNodeRuntime(phpVersion); + const runtime = popLoadedRuntime(id, { + dangerouslyKeepTheRuntimeInTheMap: true, + }); + php = new PHP(id); + const exited = new Promise((resolve) => { + // SOCKFS handles open before the connect wait's listener. Exit + // inside that event, while EventEmitter still has the latter queued. + runtime.websocket.on('open', () => { + php!.exit(); + resolve(); + }); + }); + let output: string | undefined; + let failure: unknown; + php.run({ + code: ` (output = result.text), + (error) => (failure = error) + ); + await exited; + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(output ?? '').toBe(''); + expect(failure).toBeUndefined(); + } finally { + php?.exit(); + connections.forEach((socket) => socket.destroy()); + await new Promise((resolve) => server.close(resolve)); + } + }); - expect(source).toContain('socketTimeouts: new Map()'); - expect(source).toContain('parseSocketTimeout'); - expect(source).toContain('SO_RCVTIMEO'); - expect(source).toContain('SO_SNDTIMEO'); - expect(source).toContain( - 'PHPWASM.socketTimeouts.set(socketd, timeouts)' - ); - expect(source).toContain('const receiveTimeout ='); - expect(source).toContain('PHPWASM.socketTimeouts.get(sockfd)?.receive'); - expect(source).toContain('wakeUp(-ERRNO_CODES.EAGAIN)'); - expect(source).toContain( - 'const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send' + it('returns a read timeout while the runtime remains active', async () => { + const connections: net.Socket[] = []; + const server = net.createServer((socket) => connections.push(socket)); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) ); - expect(source).toContain('const timeout = sendTimeout ?? 30000'); - expect(source).toContain('const cleanupConnectListeners = () =>'); - expect(source).toContain('const cleanupFailedConnect = (errno) =>'); - expect(source).toContain('sock.connecting = false'); - expect(source).toContain('sock.error = errno'); - expect(source).not.toContain('?.send || 30000'); - expect(source).not.toContain('const isIgnorable'); + const { port } = server.address() as net.AddressInfo; + let php: PHP | undefined; + try { + php = new PHP(await loadNodeRuntime(phpVersion)); + const result = await php.run({ + code: ` socket.destroy()); + await new Promise((resolve) => server.close(resolve)); + } }); - it('is present in all checked-in generated PHP loaders', () => { - const loaderFiles = [ - ...collectGeneratedPhpLoaders( - join(repoRoot, 'packages/php-wasm/node-builds') - ), - ...collectGeneratedPhpLoaders( - join(repoRoot, 'packages/php-wasm/web-builds') - ), - ]; - - expect(loaderFiles).toHaveLength(32); - - for (const loaderFile of loaderFiles) { - const loader = readFileSync(loaderFile, 'utf8'); - expect(loader, loaderFile).toContain('socketTimeouts: new Map'); - expect(loader, loaderFile).toContain('parseSocketTimeout'); - expect(loader, loaderFile).toContain('SO_RCVTIMEO'); - expect(loader, loaderFile).toContain('SO_SNDTIMEO'); - expect(loader, loaderFile).toContain( - 'PHPWASM.socketTimeouts.set(socketd, timeouts)' - ); - expect(loader, loaderFile).toContain( - 'parseSocketTimeout: function' + it('releases read timers and runtime memory on exit', async () => { + const repoRoot = path.resolve(__dirname, '../../../../..'); + const loader = path.join( + repoRoot, + 'packages/meta/src/node-es-module-loader/loader.mts' + ); + // A child isolates the event loop from Vitest's own timers and servers. + // Its 30-second read must not keep it alive after every TCP handle closes. + const fixture = path.join( + __dirname, + 'fixtures/exit-during-network-read.ts' + ); + await new Promise((resolve, reject) => { + execFile( + process.execPath, + ['--no-warnings', '--expose-gc', `--loader=${loader}`, fixture], + { + timeout: 10000, + env: { ...process.env, TEST: '1', PHP_VERSION: phpVersion }, + }, + (error, _stdout, stderr) => { + if (error) { + reject(new Error(stderr || error.message)); + } else { + resolve(); + } + } ); - if (loader.includes('___syscall_recvfrom(sockfd')) { - expect(loader, loaderFile).toContain( - 'PHPWASM.socketTimeouts.get(sockfd)?.receive' - ); - expect(loader, loaderFile).toContain( - 'wakeUp(-ERRNO_CODES.EAGAIN)' - ); + }); + }, 15000); + + it("keeps another runtime's pending read active when one runtime exits", async () => { + const connections: net.Socket[] = []; + const ready = new Map(); + let bothWaiting: () => void; + const waiting = new Promise((resolve) => (bothWaiting = resolve)); + const server = net.createServer((socket) => { + connections.push(socket); + socket.once('data', (data) => { + ready.set(data.toString(), socket); + if (ready.size === 2) { + bothWaiting(); + } + }); + }); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + const { port } = server.address() as net.AddressInfo; + const runtimes: PHP[] = []; + try { + for (let i = 0; i < 2; i++) { + runtimes.push(new PHP(await loadNodeRuntime(phpVersion))); } - expect(loader, loaderFile).toContain( - 'PHPWASM.socketTimeouts.get(sockfd)?.send' - ); - expect(loader, loaderFile).toContain( - 'const timeout = sendTimeout ?? 3e4' + let exitedOutput: string | undefined; + let exitedFailure: unknown; + const run = (php: PHP, id: string) => + php.run({ + code: ` (exitedOutput = result.text), + (error) => (exitedFailure = error) ); - expect(loader, loaderFile).toContain('cleanupConnectListeners'); - expect(loader, loaderFile).toContain('cleanupFailedConnect'); - expect(loader, loaderFile).toContain('sock.connecting = false'); - expect(loader, loaderFile).toContain('sock.error = errno'); - expect(loader, loaderFile).not.toContain('?.send || 3e4'); - // Match the old socket-connect helper declaration specifically. - // A bare 'isIgnorable' substring would collide with exported PHP - // ABI symbols such as _zim_PhpToken_isIgnorable (PhpToken::isIgnorable()) - // that the full-ABI export bakes into JSPI loaders. - expect(loader, loaderFile).not.toContain('const isIgnorable'); + const secondRun = run(runtimes[1], 'second'); + await waiting; + runtimes[0].exit(); + ready.get('second')!.write('hello'); + expect((await secondRun).text).toBe('hello:finished'); + await new Promise((resolve) => setTimeout(resolve, 150)); + expect(exitedOutput ?? '').toBe(''); + expect(exitedFailure).toBeUndefined(); + } finally { + runtimes.forEach((php) => php.exit()); + connections.forEach((socket) => socket.destroy()); + await new Promise((resolve) => server.close(resolve)); } }); }); diff --git a/packages/php-wasm/universal/src/lib/load-php-runtime.ts b/packages/php-wasm/universal/src/lib/load-php-runtime.ts index 817db6c68c0..a5a5e008e4d 100644 --- a/packages/php-wasm/universal/src/lib/load-php-runtime.ts +++ b/packages/php-wasm/universal/src/lib/load-php-runtime.ts @@ -172,6 +172,13 @@ export async function loadPHPRuntime( PHPRuntime.originalExit = PHPRuntime._exit; PHPRuntime._exit = function (code: number) { + // Cancel PHP's pending network waits before closing TCP. Otherwise a + // close event or poll timeout can resume PHP after exit cleanup ran. + try { + PHPRuntime.cancelNetworkWaits?.(code); + } catch (error) { + logger.error('Failed to cancel network waits', error); + } // Exit even if closing the network fails. PHP.exit() swallows errors, // so a throw here would leave the runtime running without notice. try { diff --git a/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js b/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js index 89e08f903be..857817e7b96 100644 --- a/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js +++ b/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js @@ -4718,7 +4718,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5076,10 +5085,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5149,13 +5199,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5163,10 +5221,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5178,6 +5239,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5188,25 +5251,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5224,6 +5295,14 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('close', handleClose); }; + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5243,13 +5322,11 @@ export function init(RuntimeName, PHPLoader) { }; const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; @@ -5270,6 +5347,7 @@ export function init(RuntimeName, PHPLoader) { handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7919,32 +7997,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7956,6 +8058,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7971,9 +8075,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7983,6 +8091,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7990,9 +8099,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -8007,11 +8116,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -8021,33 +8131,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js b/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js index bd786bffe54..d12cad98cf0 100644 --- a/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js +++ b/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js @@ -4675,7 +4675,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5033,10 +5042,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5106,13 +5156,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5120,10 +5178,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5135,6 +5196,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5145,25 +5208,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5181,6 +5252,14 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('close', handleClose); }; + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5200,13 +5279,11 @@ export function init(RuntimeName, PHPLoader) { }; const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; @@ -5227,6 +5304,7 @@ export function init(RuntimeName, PHPLoader) { handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7728,39 +7806,64 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7772,6 +7875,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7787,9 +7892,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7799,6 +7908,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7806,9 +7916,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -7823,11 +7933,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -7837,34 +7948,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js b/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js index 94ffb91013a..79153935ca1 100644 --- a/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js +++ b/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js @@ -4718,7 +4718,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5076,10 +5085,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5149,13 +5199,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5163,10 +5221,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5178,6 +5239,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5188,23 +5251,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5212,6 +5285,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5220,6 +5294,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5228,37 +5311,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8036,32 +8125,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -8073,6 +8186,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8088,9 +8203,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8100,6 +8219,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8107,9 +8227,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -8124,11 +8244,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -8138,33 +8259,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js b/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js index 95cab9b22c9..ead1f0a1e2b 100644 --- a/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js +++ b/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js @@ -4675,7 +4675,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5033,10 +5042,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5106,13 +5156,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5120,10 +5178,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5135,6 +5196,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5145,23 +5208,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5169,6 +5242,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5177,6 +5251,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5185,37 +5268,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7798,39 +7887,64 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7842,6 +7956,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7857,9 +7973,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7869,6 +7989,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7876,9 +7997,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -7893,11 +8014,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -7907,34 +8029,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js b/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js index 806d49b0d81..0fc1c700ecd 100644 --- a/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js +++ b/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js @@ -4718,7 +4718,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5076,10 +5085,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5149,13 +5199,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5163,10 +5221,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5178,6 +5239,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5188,23 +5251,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5212,6 +5285,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5220,6 +5294,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5228,37 +5311,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8036,32 +8125,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -8073,6 +8186,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8088,9 +8203,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8100,6 +8219,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8107,9 +8227,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -8124,11 +8244,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -8138,33 +8259,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js b/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js index dce394f7aab..ac2ee0031fa 100644 --- a/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js +++ b/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js @@ -4675,7 +4675,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5033,10 +5042,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5106,13 +5156,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5120,10 +5178,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5135,6 +5196,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5145,23 +5208,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5169,6 +5242,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5177,6 +5251,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5185,37 +5268,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7798,39 +7887,64 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7842,6 +7956,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7857,9 +7973,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7869,6 +7989,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7876,9 +7997,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -7893,11 +8014,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -7907,34 +8029,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js b/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js index 25222ae64e4..d7401df5583 100644 --- a/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js +++ b/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js @@ -4718,7 +4718,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5076,10 +5085,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5149,13 +5199,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5163,10 +5221,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5178,6 +5239,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5188,23 +5251,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5212,6 +5285,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5220,6 +5294,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5228,37 +5311,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8049,32 +8138,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -8086,6 +8199,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8101,9 +8216,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8113,6 +8232,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8120,9 +8240,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -8137,11 +8257,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -8151,33 +8272,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js b/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js index af27e8bb503..f09cffde297 100644 --- a/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js +++ b/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js @@ -4675,7 +4675,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5033,10 +5042,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5106,13 +5156,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5120,10 +5178,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5135,6 +5196,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5145,23 +5208,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5169,6 +5242,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5177,6 +5251,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5185,37 +5268,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7811,39 +7900,64 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7855,6 +7969,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7870,9 +7986,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7882,6 +8002,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7889,9 +8010,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -7906,11 +8027,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -7920,34 +8042,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js b/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js index 7755628dd8e..9ae4cc79a94 100644 --- a/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js +++ b/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js @@ -4718,7 +4718,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5076,10 +5085,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5149,13 +5199,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5163,10 +5221,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5178,6 +5239,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5188,23 +5251,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5212,6 +5285,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5220,6 +5294,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5228,37 +5311,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8050,32 +8139,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -8087,6 +8200,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8102,9 +8217,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8114,6 +8233,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8121,9 +8241,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -8138,11 +8258,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -8152,33 +8273,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js b/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js index 34178e5d5ad..e05f04e34ef 100644 --- a/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js +++ b/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js @@ -4675,7 +4675,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5033,10 +5042,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5106,13 +5156,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5120,10 +5178,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5135,6 +5196,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5145,23 +5208,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5169,6 +5242,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5177,6 +5251,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5185,37 +5268,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7812,39 +7901,64 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7856,6 +7970,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7871,9 +7987,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7883,6 +8003,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7890,9 +8011,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -7907,11 +8028,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -7921,34 +8043,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js b/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js index cad692c54b1..3d10bfbf806 100644 --- a/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js +++ b/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js @@ -4718,7 +4718,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5076,10 +5085,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5149,13 +5199,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5163,10 +5221,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5178,6 +5239,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5188,23 +5251,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5212,6 +5285,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5220,6 +5294,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5228,37 +5311,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8050,32 +8139,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -8087,6 +8200,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8102,9 +8217,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8114,6 +8233,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8121,9 +8241,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -8138,11 +8258,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -8152,33 +8273,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js b/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js index 61c5088a711..6a2907151cb 100644 --- a/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js +++ b/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js @@ -4675,7 +4675,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5033,10 +5042,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5106,13 +5156,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5120,10 +5178,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5135,6 +5196,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5145,23 +5208,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5169,6 +5242,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5177,6 +5251,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5185,37 +5268,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7812,39 +7901,64 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7856,6 +7970,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7871,9 +7987,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7883,6 +8003,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7890,9 +8011,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -7907,11 +8028,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -7921,34 +8043,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js b/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js index fc9efd207eb..f2f81fe245e 100644 --- a/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js +++ b/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js @@ -4718,7 +4718,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5076,10 +5085,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5149,13 +5199,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5163,10 +5221,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5178,6 +5239,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5188,23 +5251,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5212,6 +5285,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5220,6 +5294,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5228,37 +5311,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8050,32 +8139,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -8087,6 +8200,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8102,9 +8217,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8114,6 +8233,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8121,9 +8241,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -8138,11 +8258,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -8152,33 +8273,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js b/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js index 778b38fa412..8f1e8d66d58 100644 --- a/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js +++ b/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js @@ -4675,7 +4675,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5033,10 +5042,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5106,13 +5156,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5120,10 +5178,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5135,6 +5196,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5145,23 +5208,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5169,6 +5242,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5177,6 +5251,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5185,37 +5268,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7812,39 +7901,64 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7856,6 +7970,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7871,9 +7987,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7883,6 +8003,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7890,9 +8011,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -7907,11 +8028,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -7921,34 +8043,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js b/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js index f43b98f7219..c0964a344f0 100644 --- a/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js +++ b/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js @@ -4718,7 +4718,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5076,10 +5085,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5149,13 +5199,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5163,10 +5221,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5178,6 +5239,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5188,23 +5251,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5212,6 +5285,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5220,6 +5294,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5228,37 +5311,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8051,32 +8140,56 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -8088,6 +8201,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8103,9 +8218,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8115,6 +8234,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8122,9 +8242,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -8139,11 +8259,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -8153,33 +8274,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js b/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js index 9f297d34f29..ca59945a1cd 100644 --- a/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js +++ b/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js @@ -4675,7 +4675,16 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), + pendingNetworkWaits: new Set(), + networkingExited: false, init: function () { + Module['cancelNetworkWaits'] = (code = 0) => { + PHPWASM.networkingExited = true; + for (const wait of PHPWASM.pendingNetworkWaits) { + wait.cancel(code); + } + PHPWASM.socketTimeouts.clear(); + }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5033,10 +5042,51 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); - setTimeout(resolve); }; return [promise, cancel]; }, + createNetworkWait: function (wakeUp, cleanup, abort) { + const wait = { + active: !PHPWASM.networkingExited, + finish(result) { + if (!wait.active) { + return; + } + stop(); + wakeUp(result); + }, + cancel(code) { + if (!wait.active) { + return; + } + stop(); + abort?.(new ExitStatus(code)); + }, + }; + function stop() { + wait.active = false; + PHPWASM.pendingNetworkWaits.delete(wait); + cleanup(); + } + if (wait.active) { + PHPWASM.pendingNetworkWaits.add(wait); + } + return wait; + }, + awaitNetworkOperation: function (start) { + if (typeof Asyncify.makeAsyncFunction === 'function') { + const operation = Asyncify.handleAsync( + () => + new Promise((resolve, reject) => start(resolve, reject)) + ); + // Some syscall shims ignore the returned promise. Mark it handled + // so cancelling them isn't an unhandled rejection. JSPI still + // receives the original rejection and unwinds the suspended stack. + operation.catch(PHPWASM.noop); + return operation; + } + return Asyncify.handleSleep(start); + }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5106,13 +5156,21 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { + /** + * Use a synchronous connect() call when Asyncify is used. + * + * The async version was originally introduced to support the Memcached and Redis extensions, + * and both are only available with JSPI. Asyncify is too difficult to maintain and + * it's not getting that upgrade. + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return Asyncify.handleSleep((wakeUp) => { + return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + // Get the socket let sock; try { sock = getSocketFromFD(sockfd); @@ -5120,10 +5178,13 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } + if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } + + // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5135,6 +5196,8 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5145,23 +5208,33 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } + + // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { + // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + const ws = webSockets[0]; + + // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } + + // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } + + // Wait for the connection to be established. A zero timeval + // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 3e4; - let resolved = false; + const timeout = sendTimeout ?? 30000; let timeoutId; let handleOpen; let handleError; @@ -5169,6 +5242,7 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); + const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5177,6 +5251,15 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; + + const wait = PHPWASM.createNetworkWait( + wakeUp, + cleanupConnectListeners, + abort + ); + if (!wait.active) { + return; + } const cleanupFailedConnect = (errno) => { try { if ( @@ -5185,37 +5268,43 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) {} + } catch (e) { + // Ignore close errors on an already-failed connect. + } if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; + const finishConnect = (result) => { - if (!resolved) { - resolved = true; - cleanupConnectListeners(); + if (wait.active) { if (result < 0) { cleanupFailedConnect(-result); } - wakeUp(result); + wait.finish(result); } }; + if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } + handleOpen = () => { finishConnect(0); }; + handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; + ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7813,39 +7902,64 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => new Promise(resolver); + const returnCallback = (resolver) => + new Promise((resolve, reject) => resolver(resolve, reject)); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp) => { + return returnCallback((wakeUp, abort) => { const polls = []; + let timeoutId; + const wait = PHPWASM.createNetworkWait( + wakeUp, + () => { + clearTimeout(timeoutId); + polls.forEach(([, cancel]) => cancel()); + }, + abort + ); + if (!wait.active) { + return; + } + /** + * Special semantics for polling sockets. + * + * @TODO: Remove this code branch entirely and poll sockets using the second if/else + * branch below. The only reason this wasn't done yet is that the original PR + * was focusing on removing child process-related special casing and did not + * want to increase the risk of breaking other code, especially around listening + * network sockets. + */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { + // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wakeUp(0); + wait.finish(0); return; } const lookingFor = new Set(); + if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wakeUp(1); + wait.finish(1); return; } } + const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wakeUp(0); + wait.finish(0); return; } for (const ws of webSockets) { @@ -7857,6 +7971,8 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } + // Notify the user the socket is now closed even if the only requested + // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7872,9 +7988,13 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { + // Poll the stream for data. + // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; + let pollTimeoutId; async function poll() { try { + // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7884,6 +8004,7 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } + mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7891,9 +8012,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => - setTimeout(resolve, 10) - ); + await new Promise((resolve) => { + pollTimeoutId = setTimeout(resolve, 10); + }); } } catch (e) { if ( @@ -7908,11 +8029,12 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; + clearTimeout(pollTimeoutId); }, ]); } else { - setTimeout(function () { - wakeUp(1); + timeoutId = setTimeout(function () { + wait.finish(1); }, timeout); return; } @@ -7922,34 +8044,17 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - setTimeout(function () { - wakeUp(0); + timeoutId = setTimeout(function () { + wait.finish(0); }, timeout); return; } - const promises = polls.map(([promise]) => promise); - const clearPolling = () => - polls.forEach(([, clear]) => clear()); - let awaken = false; - let timeoutId; - Promise.race(promises).then(function (results) { - if (!awaken) { - awaken = true; - wakeUp(1); - if (timeoutId) { - clearTimeout(timeoutId); - } - clearPolling(); - } - }); + + Promise.race(polls.map(([promise]) => promise)).then(() => + wait.finish(1) + ); if (timeout !== -1) { - timeoutId = setTimeout(function () { - if (!awaken) { - awaken = true; - wakeUp(0); - clearPolling(); - } - }, timeout); + timeoutId = setTimeout(() => wait.finish(0), timeout); } }); }); From eeb449bad9bb9414a854a431f463c2e2e79d71c8 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sun, 8 Nov 2026 21:30:55 -0500 Subject: [PATCH 33/34] [ php-wasm ] Keep exit handling in the Node TCP adapters Undo f64d33a99 and 60d31f544's runtime cancellation changes. Restore all PHP build sources and generated Node/web JavaScript loaders to the versions used before that rewrite. Keep the original direct-TCP design, bounded write draining, and cleanup-timer fixes. Closing PHP's connections at exit can return control to PHP that was waiting on one, and PHP then finishes its script. Trunk never closed those connections, so such waits resumed only when their own timeouts expired, and waits without a timeout stayed suspended. Mark the Node networking adapter closed before cleanup so that resumed code cannot open new TCP connections or listening sockets. Use the existing failed-address path for late outbound attempts: throwing from the constructor escapes PHP under Asyncify. Drop queued incoming connections after their listening server closes. Test the actual boundary instead of requiring general cancellation of running PHP: a blocked read may return, but no new native socket opens. Keep broader runtime cancellation outside this PR. Validation: 215 targeted networking checks passed in each mode across PHP 7.4-8.5; Node type checks and tracked-code lint passed. The two-second read/exit repro terminates in about 0.1 seconds. No net changes remain under compile/, node-builds/, or web-builds/ relative to the PR base. The prior implementation is preserved at the local backup branch backup/network-exit-stabilization-f64d33a99. --- AGENTS.md | 8 - packages/php-wasm/compile/php/php_wasm.c | 58 ++-- .../compile/php/phpwasm-emscripten-library.js | 112 ++------ .../node-builds/5-2/asyncify/php_5_2.js | 170 ++++-------- .../php-wasm/node-builds/5-2/jspi/php_5_2.js | 174 ++++-------- .../node-builds/7-4/asyncify/php_7_4.js | 202 ++++---------- .../php-wasm/node-builds/7-4/jspi/php_7_4.js | 206 ++++---------- .../node-builds/8-0/asyncify/php_8_0.js | 202 ++++---------- .../php-wasm/node-builds/8-0/jspi/php_8_0.js | 206 ++++---------- .../node-builds/8-1/asyncify/php_8_1.js | 202 ++++---------- .../php-wasm/node-builds/8-1/jspi/php_8_1.js | 206 ++++---------- .../node-builds/8-2/asyncify/php_8_2.js | 202 ++++---------- .../php-wasm/node-builds/8-2/jspi/php_8_2.js | 206 ++++---------- .../node-builds/8-3/asyncify/php_8_3.js | 202 ++++---------- .../php-wasm/node-builds/8-3/jspi/php_8_3.js | 206 ++++---------- .../node-builds/8-4/asyncify/php_8_4.js | 202 ++++---------- .../php-wasm/node-builds/8-4/jspi/php_8_4.js | 206 ++++---------- .../node-builds/8-5/asyncify/php_8_5.js | 202 ++++---------- .../php-wasm/node-builds/8-5/jspi/php_8_5.js | 206 ++++---------- packages/php-wasm/node/README.md | 19 +- .../node/src/lib/networking/tcp-socket.ts | 14 +- .../src/lib/networking/with-networking.ts | 9 +- .../test/fixtures/exit-during-network-read.ts | 56 ---- .../test/networking-port-allocation.spec.ts | 10 +- .../node/src/test/php-networking.spec.ts | 107 ++++---- .../php-wasm/node/src/test/php-redis.spec.ts | 44 --- .../node/src/test/php-socket-timeouts.spec.ts | 254 +++++++----------- .../php-wasm/node/src/test/tcp-socket.spec.ts | 2 +- .../universal/src/lib/load-php-runtime.ts | 7 - .../web-builds/5-2/asyncify/php_5_2.js | 176 +++--------- .../php-wasm/web-builds/5-2/jspi/php_5_2.js | 180 +++---------- .../web-builds/7-4/asyncify/php_7_4.js | 189 +++---------- .../php-wasm/web-builds/7-4/jspi/php_7_4.js | 193 +++---------- .../web-builds/8-0/asyncify/php_8_0.js | 189 +++---------- .../php-wasm/web-builds/8-0/jspi/php_8_0.js | 193 +++---------- .../web-builds/8-1/asyncify/php_8_1.js | 189 +++---------- .../php-wasm/web-builds/8-1/jspi/php_8_1.js | 193 +++---------- .../web-builds/8-2/asyncify/php_8_2.js | 189 +++---------- .../php-wasm/web-builds/8-2/jspi/php_8_2.js | 193 +++---------- .../web-builds/8-3/asyncify/php_8_3.js | 189 +++---------- .../php-wasm/web-builds/8-3/jspi/php_8_3.js | 193 +++---------- .../web-builds/8-4/asyncify/php_8_4.js | 189 +++---------- .../php-wasm/web-builds/8-4/jspi/php_8_4.js | 193 +++---------- .../web-builds/8-5/asyncify/php_8_5.js | 189 +++---------- .../php-wasm/web-builds/8-5/jspi/php_8_5.js | 193 +++---------- 45 files changed, 1796 insertions(+), 5134 deletions(-) delete mode 100644 packages/php-wasm/node/src/test/fixtures/exit-during-network-read.ts diff --git a/AGENTS.md b/AGENTS.md index 31a76ad8aa3..2ae781872f4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -311,14 +311,6 @@ load the JSPI build in CI. The `test-networking-asyncify` job runs the `@php-wasm/node` networking tests on Node 24.18.0, which loads the Asyncify build. Its `vite.asyncify.config.ts` stops with an error on Node versions that enable JSPI. -Runtime exit cancels pending network waits before releasing TCP handles. The -wait registry lives in `phpwasm-emscripten-library.js`; socket polls in `php_wasm.c` -use the same registry as extension receives and connects. Keep the generated -Node and web loader JavaScript in sync when changing this glue. Preserve the -exit contracts in the Node networking, socket-timeout, and Redis tests: no PHP -resumption or new connections after exit, bounded write draining, timer cleanup, -and cancellation isolated to the exiting runtime. - Dependabot's daily version check opens PRs for `fs-ext-extra-prebuilt` patch releases. It raises the minimum package version and updates the lockfile; the existing Dependabot lockfile workflow preserves workspace links. An explicit diff --git a/packages/php-wasm/compile/php/php_wasm.c b/packages/php-wasm/compile/php/php_wasm.c index 482895ebf85..6c2258a01c7 100644 --- a/packages/php-wasm/compile/php/php_wasm.c +++ b/packages/php-wasm/compile/php/php_wasm.c @@ -150,7 +150,7 @@ EM_JS(char*, js_popen_to_file, (const char *command, const char *mode, uint8_t * */ #ifdef PLAYGROUND_JSPI EM_ASYNC_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { - const returnCallback = (resolver) => new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); #else EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { const returnCallback = (resolver) => Asyncify.handleSleep(resolver); @@ -162,16 +162,8 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { const POLLHUP = 0x0010; /* Hung up */ const POLLNVAL = 0x0020; /* Invalid request: fd not open */ - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait(wakeUp, () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, abort); - if (!wait.active) { - return; - } /** * Special semantics for polling sockets. * @@ -186,7 +178,7 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); @@ -195,19 +187,19 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -239,7 +231,6 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { // Poll the stream for data. // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { // Inlined ___syscall_poll with added await support: @@ -260,9 +251,7 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise(resolve => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise(resolve => setTimeout(resolve, 10)); } } catch (e) { if (typeof FS == 'undefined' || !(e.name === 'ErrnoError')) throw e; @@ -273,12 +262,11 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); } ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -288,15 +276,35 @@ EM_JS(int, wasm_poll_socket, (php_socket_t socketd, int events, int timeout), { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - Promise.race(polls.map(([promise]) => promise)).then(() => wait.finish(1)); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); + if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/compile/php/phpwasm-emscripten-library.js b/packages/php-wasm/compile/php/phpwasm-emscripten-library.js index 09086298861..4a1cc0ff59d 100644 --- a/packages/php-wasm/compile/php/phpwasm-emscripten-library.js +++ b/packages/php-wasm/compile/php/phpwasm-emscripten-library.js @@ -35,7 +35,7 @@ const LibraryExample = { }, // Emscripten dependencies: - $PHPWASM__deps: ['$allocateUTF8OnStack', '$addOnInit', '$ExitStatus'], + $PHPWASM__deps: ['$allocateUTF8OnStack', '$addOnInit'], $PHPWASM__postset: 'PHPWASM.init();', // Functions not exposed to C but available in the generated @@ -51,20 +51,11 @@ const LibraryExample = { SETFL_MASK: Number('{{{cDefs.O_APPEND}}}') | Number('{{{cDefs.O_NONBLOCK}}}'), socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, // These macros are not defined in Emscripten at the time of writing: // emscripten_O_NDELAY | // emscripten_O_DIRECT | // emscripten_O_NOATIME init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -494,58 +485,13 @@ const LibraryExample = { }); const cancel = () => { ws.removeListener(event, listener); - // Do not settle cancelled waits: that could resume exited PHP. + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - - /** - * Owns the lifetime of an asynchronous socket operation. Exit cancels - * its timers and listeners without continuing the PHP script. JSPI - * must unwind its suspended native stack so V8 can release the runtime. - * Completion checks active even for callbacks already queued at exit. - */ - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync(() => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { @@ -1127,18 +1073,14 @@ const LibraryExample = { * @returns {Promise} Resolved with the number of bytes recieved */ wasm_recv: function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; + return Asyncify.handleSleep((wakeUp) => { + const receiveTimeout = + PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -1150,18 +1092,21 @@ const LibraryExample = { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -1177,8 +1122,8 @@ const LibraryExample = { * SO_KEEPALIVE and TCP_NODELAY are propagated to the WebSockets proxy * server, which then sets them on the underlying TCP connection. * - * SO_RCVTIMEO and SO_SNDTIMEO are stored per socket. wasm_recv() - * uses SO_RCVTIMEO and wasm_connect() uses SO_SNDTIMEO. + * SO_RCVTIMEO and SO_SNDTIMEO are stored per socket. wasm_recv() + * uses SO_RCVTIMEO and wasm_connect() uses SO_SNDTIMEO. * * @param {int} socketd Socket descriptor * @param {int} level Level at which the option is defined @@ -1265,13 +1210,13 @@ const LibraryExample = { * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. */ - if (!('Suspending' in WebAssembly)) { + if (!("Suspending" in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -1337,6 +1282,7 @@ const LibraryExample = { // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; const timeout = sendTimeout ?? 30000; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -1354,14 +1300,6 @@ const LibraryExample = { ws.removeEventListener('close', handleClose); }; - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -1381,11 +1319,13 @@ const LibraryExample = { }; const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; diff --git a/packages/php-wasm/node-builds/5-2/asyncify/php_5_2.js b/packages/php-wasm/node-builds/5-2/asyncify/php_5_2.js index 67df984972d..87aa7ab64bb 100644 --- a/packages/php-wasm/node-builds/5-2/asyncify/php_5_2.js +++ b/packages/php-wasm/node-builds/5-2/asyncify/php_5_2.js @@ -6145,17 +6145,8 @@ export function init(RuntimeName, PHPLoader) { O_NONBLOCK: 2048, POLLHUP: 16, SETFL_MASK: 3072, - socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, + socketTimeouts: new Map, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6576,51 +6567,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6718,14 +6671,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6734,12 +6686,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6752,7 +6702,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6764,7 +6713,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6772,25 +6720,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6808,14 +6753,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('close', handleClose); }; - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6835,11 +6772,13 @@ export function init(RuntimeName, PHPLoader) { }; const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; @@ -6860,7 +6799,6 @@ export function init(RuntimeName, PHPLoader) { handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10148,56 +10086,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10209,8 +10123,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10226,13 +10138,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10242,7 +10150,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10250,9 +10157,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10267,12 +10174,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10282,17 +10188,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/node-builds/5-2/jspi/php_5_2.js b/packages/php-wasm/node-builds/5-2/jspi/php_5_2.js index a935937be97..c6c0bf0970a 100644 --- a/packages/php-wasm/node-builds/5-2/jspi/php_5_2.js +++ b/packages/php-wasm/node-builds/5-2/jspi/php_5_2.js @@ -6086,17 +6086,8 @@ export function init(RuntimeName, PHPLoader) { O_NONBLOCK: 2048, POLLHUP: 16, SETFL_MASK: 3072, - socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, + socketTimeouts: new Map, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6517,51 +6508,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6659,14 +6612,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6675,12 +6627,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6693,7 +6643,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6705,7 +6654,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6713,25 +6661,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6749,14 +6694,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('close', handleClose); }; - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6776,11 +6713,13 @@ export function init(RuntimeName, PHPLoader) { }; const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; @@ -6801,7 +6740,6 @@ export function init(RuntimeName, PHPLoader) { handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -9881,64 +9819,39 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -9950,8 +9863,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -9967,13 +9878,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -9983,7 +9890,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -9991,9 +9897,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10008,12 +9914,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10023,17 +9928,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/node-builds/7-4/asyncify/php_7_4.js b/packages/php-wasm/node-builds/7-4/asyncify/php_7_4.js index a4134d03903..15bc1ec3f8e 100644 --- a/packages/php-wasm/node-builds/7-4/asyncify/php_7_4.js +++ b/packages/php-wasm/node-builds/7-4/asyncify/php_7_4.js @@ -6244,16 +6244,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6674,51 +6665,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6816,14 +6769,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6832,12 +6784,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6850,7 +6800,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6862,7 +6811,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6870,25 +6818,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6896,7 +6841,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6905,15 +6849,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6922,43 +6857,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10353,18 +10282,12 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10376,18 +10299,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10552,56 +10478,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10613,8 +10515,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10630,13 +10530,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10646,7 +10542,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10654,9 +10549,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10671,12 +10566,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10686,17 +10580,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/node-builds/7-4/jspi/php_7_4.js b/packages/php-wasm/node-builds/7-4/jspi/php_7_4.js index 17edf613ed2..d52c805eddd 100644 --- a/packages/php-wasm/node-builds/7-4/jspi/php_7_4.js +++ b/packages/php-wasm/node-builds/7-4/jspi/php_7_4.js @@ -6087,16 +6087,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6517,51 +6508,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6659,14 +6612,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6675,12 +6627,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6693,7 +6643,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6705,7 +6654,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6713,25 +6661,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6739,7 +6684,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6748,15 +6692,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6765,43 +6700,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10014,18 +9943,12 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10037,18 +9960,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10196,64 +10122,39 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10265,8 +10166,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10282,13 +10181,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10298,7 +10193,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10306,9 +10200,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10323,12 +10217,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10338,17 +10231,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-0/asyncify/php_8_0.js b/packages/php-wasm/node-builds/8-0/asyncify/php_8_0.js index efc8260e7de..320210d3a6f 100644 --- a/packages/php-wasm/node-builds/8-0/asyncify/php_8_0.js +++ b/packages/php-wasm/node-builds/8-0/asyncify/php_8_0.js @@ -6244,16 +6244,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6674,51 +6665,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6816,14 +6769,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6832,12 +6784,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6850,7 +6800,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6862,7 +6811,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6870,25 +6818,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6896,7 +6841,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6905,15 +6849,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6922,43 +6857,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10353,18 +10282,12 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10376,18 +10299,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10552,56 +10478,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10613,8 +10515,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10630,13 +10530,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10646,7 +10542,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10654,9 +10549,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10671,12 +10566,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10686,17 +10580,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-0/jspi/php_8_0.js b/packages/php-wasm/node-builds/8-0/jspi/php_8_0.js index a318a65664e..fee8dedb09a 100644 --- a/packages/php-wasm/node-builds/8-0/jspi/php_8_0.js +++ b/packages/php-wasm/node-builds/8-0/jspi/php_8_0.js @@ -6087,16 +6087,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6517,51 +6508,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6659,14 +6612,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6675,12 +6627,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6693,7 +6643,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6705,7 +6654,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6713,25 +6661,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6739,7 +6684,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6748,15 +6692,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6765,43 +6700,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10014,18 +9943,12 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10037,18 +9960,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10196,64 +10122,39 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10265,8 +10166,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10282,13 +10181,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10298,7 +10193,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10306,9 +10200,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10323,12 +10217,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10338,17 +10231,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-1/asyncify/php_8_1.js b/packages/php-wasm/node-builds/8-1/asyncify/php_8_1.js index 805d15e3922..807f571fc2d 100644 --- a/packages/php-wasm/node-builds/8-1/asyncify/php_8_1.js +++ b/packages/php-wasm/node-builds/8-1/asyncify/php_8_1.js @@ -6244,16 +6244,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6674,51 +6665,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6816,14 +6769,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6832,12 +6784,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6850,7 +6800,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6862,7 +6811,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6870,25 +6818,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6896,7 +6841,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6905,15 +6849,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6922,43 +6857,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10371,18 +10300,12 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10394,18 +10317,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10570,56 +10496,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10631,8 +10533,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10648,13 +10548,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10664,7 +10560,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10672,9 +10567,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10689,12 +10584,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10704,17 +10598,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-1/jspi/php_8_1.js b/packages/php-wasm/node-builds/8-1/jspi/php_8_1.js index 1d4ec44e74c..c92c2605d5c 100644 --- a/packages/php-wasm/node-builds/8-1/jspi/php_8_1.js +++ b/packages/php-wasm/node-builds/8-1/jspi/php_8_1.js @@ -6087,16 +6087,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6517,51 +6508,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6659,14 +6612,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6675,12 +6627,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6693,7 +6643,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6705,7 +6654,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6713,25 +6661,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6739,7 +6684,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6748,15 +6692,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6765,43 +6700,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10032,18 +9961,12 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10055,18 +9978,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10214,64 +10140,39 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10283,8 +10184,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10300,13 +10199,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10316,7 +10211,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10324,9 +10218,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10341,12 +10235,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10356,17 +10249,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-2/asyncify/php_8_2.js b/packages/php-wasm/node-builds/8-2/asyncify/php_8_2.js index 901760367be..5ffbfc2bd33 100644 --- a/packages/php-wasm/node-builds/8-2/asyncify/php_8_2.js +++ b/packages/php-wasm/node-builds/8-2/asyncify/php_8_2.js @@ -6244,16 +6244,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6674,51 +6665,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6816,14 +6769,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6832,12 +6784,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6850,7 +6800,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6862,7 +6811,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6870,25 +6818,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6896,7 +6841,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6905,15 +6849,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6922,43 +6857,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10373,18 +10302,12 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10396,18 +10319,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10572,56 +10498,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10633,8 +10535,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10650,13 +10550,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10666,7 +10562,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10674,9 +10569,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10691,12 +10586,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10706,17 +10600,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-2/jspi/php_8_2.js b/packages/php-wasm/node-builds/8-2/jspi/php_8_2.js index d9f7074f839..48aa7b07058 100644 --- a/packages/php-wasm/node-builds/8-2/jspi/php_8_2.js +++ b/packages/php-wasm/node-builds/8-2/jspi/php_8_2.js @@ -6087,16 +6087,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6517,51 +6508,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6659,14 +6612,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6675,12 +6627,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6693,7 +6643,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6705,7 +6654,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6713,25 +6661,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6739,7 +6684,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6748,15 +6692,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6765,43 +6700,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10034,18 +9963,12 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10057,18 +9980,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10216,64 +10142,39 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10285,8 +10186,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10302,13 +10201,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10318,7 +10213,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10326,9 +10220,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10343,12 +10237,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10358,17 +10251,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-3/asyncify/php_8_3.js b/packages/php-wasm/node-builds/8-3/asyncify/php_8_3.js index 07c5b959502..66513a6c6c5 100644 --- a/packages/php-wasm/node-builds/8-3/asyncify/php_8_3.js +++ b/packages/php-wasm/node-builds/8-3/asyncify/php_8_3.js @@ -6244,16 +6244,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6674,51 +6665,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6816,14 +6769,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6832,12 +6784,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6850,7 +6800,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6862,7 +6811,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6870,25 +6818,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6896,7 +6841,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6905,15 +6849,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6922,43 +6857,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10373,18 +10302,12 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10396,18 +10319,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10572,56 +10498,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10633,8 +10535,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10650,13 +10550,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10666,7 +10562,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10674,9 +10569,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10691,12 +10586,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10706,17 +10600,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-3/jspi/php_8_3.js b/packages/php-wasm/node-builds/8-3/jspi/php_8_3.js index 93803e75722..df6ae79ee41 100644 --- a/packages/php-wasm/node-builds/8-3/jspi/php_8_3.js +++ b/packages/php-wasm/node-builds/8-3/jspi/php_8_3.js @@ -6087,16 +6087,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6517,51 +6508,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6659,14 +6612,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6675,12 +6627,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6693,7 +6643,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6705,7 +6654,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6713,25 +6661,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6739,7 +6684,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6748,15 +6692,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6765,43 +6700,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10034,18 +9963,12 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10057,18 +9980,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10216,64 +10142,39 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10285,8 +10186,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10302,13 +10201,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10318,7 +10213,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10326,9 +10220,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10343,12 +10237,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10358,17 +10251,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-4/asyncify/php_8_4.js b/packages/php-wasm/node-builds/8-4/asyncify/php_8_4.js index 6e346656deb..6fb83c733ce 100644 --- a/packages/php-wasm/node-builds/8-4/asyncify/php_8_4.js +++ b/packages/php-wasm/node-builds/8-4/asyncify/php_8_4.js @@ -6244,16 +6244,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6674,51 +6665,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6816,14 +6769,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6832,12 +6784,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6850,7 +6800,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6862,7 +6811,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6870,25 +6818,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6896,7 +6841,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6905,15 +6849,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6922,43 +6857,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10373,18 +10302,12 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10396,18 +10319,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10572,56 +10498,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10633,8 +10535,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10650,13 +10550,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10666,7 +10562,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10674,9 +10569,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10691,12 +10586,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10706,17 +10600,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-4/jspi/php_8_4.js b/packages/php-wasm/node-builds/8-4/jspi/php_8_4.js index 0dae2bff55b..3e94113685c 100644 --- a/packages/php-wasm/node-builds/8-4/jspi/php_8_4.js +++ b/packages/php-wasm/node-builds/8-4/jspi/php_8_4.js @@ -6087,16 +6087,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6517,51 +6508,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6659,14 +6612,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6675,12 +6627,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6693,7 +6643,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6705,7 +6654,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6713,25 +6661,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6739,7 +6684,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6748,15 +6692,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6765,43 +6700,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10034,18 +9963,12 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10057,18 +9980,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10216,64 +10142,39 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10285,8 +10186,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10302,13 +10201,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10318,7 +10213,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10326,9 +10220,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10343,12 +10237,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10358,17 +10251,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/node-builds/8-5/asyncify/php_8_5.js b/packages/php-wasm/node-builds/8-5/asyncify/php_8_5.js index 6eacbf8f9e4..88f8b455046 100644 --- a/packages/php-wasm/node-builds/8-5/asyncify/php_8_5.js +++ b/packages/php-wasm/node-builds/8-5/asyncify/php_8_5.js @@ -6244,16 +6244,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6674,51 +6665,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6816,14 +6769,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6832,12 +6784,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6850,7 +6800,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6862,7 +6811,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6870,25 +6818,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6896,7 +6841,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6905,15 +6849,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6922,43 +6857,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10373,18 +10302,12 @@ export function init(RuntimeName, PHPLoader) { ___cxa_throw.sig = 'vppp'; var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10396,18 +10319,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10574,56 +10500,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10635,8 +10537,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10652,13 +10552,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10668,7 +10564,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10676,9 +10571,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10693,12 +10588,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10708,17 +10602,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/node-builds/8-5/jspi/php_8_5.js b/packages/php-wasm/node-builds/8-5/jspi/php_8_5.js index ce1cd45d96e..e69833ad012 100644 --- a/packages/php-wasm/node-builds/8-5/jspi/php_8_5.js +++ b/packages/php-wasm/node-builds/8-5/jspi/php_8_5.js @@ -6087,16 +6087,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; // TODO: Move this to a library function that is made an onInit callback by the `__postset` suffix. if (PHPLoader.bindUserSpace) { /** @@ -6517,51 +6508,13 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + // Rejecting the promises bubbles up and kills the entire + // node process. Let's resolve them on the next tick instead + // to give the caller some space to unbind any handlers. + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -6659,14 +6612,13 @@ export function init(RuntimeName, PHPLoader) { * The async version was originally introduced to support the Memcached and Redis extensions, * and both are only available with JSPI. Asyncify is too difficult to maintain and * it's not getting that upgrade. - */ - if (!('Suspending' in WebAssembly)) { + */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { // Get the socket let sock; try { @@ -6675,12 +6627,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - // Parse the address let info; try { @@ -6693,7 +6643,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); @@ -6705,7 +6654,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { @@ -6713,25 +6661,22 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -6739,7 +6684,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -6748,15 +6692,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -6765,43 +6700,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -10034,18 +9963,12 @@ export function init(RuntimeName, PHPLoader) { var FS_createDevice = (...args) => FS.createDevice(...args); var _wasm_recv = function (sockfd, buffer, size, flags) { - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { + return Asyncify.handleSleep((wakeUp) => { const receiveTimeout = PHPWASM.socketTimeouts.get(sockfd)?.receive; const startedAt = Date.now(); - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => clearTimeout(timeoutId), - abort - ); - + let resolved = false; const poll = function () { - if (!wait.active) { + if (resolved) { return; } let newl = ___syscall_recvfrom( @@ -10057,18 +9980,21 @@ export function init(RuntimeName, PHPLoader) { null ); if (newl > 0) { - wait.finish(newl); + resolved = true; + wakeUp(newl); } else if (newl === -ERRNO_CODES.EAGAIN) { if ( receiveTimeout > 0 && Date.now() - startedAt >= receiveTimeout ) { - wait.finish(-ERRNO_CODES.EAGAIN); + resolved = true; + wakeUp(-ERRNO_CODES.EAGAIN); return; } - timeoutId = setTimeout(poll, 20); + setTimeout(poll, 20); } else { - wait.finish(0); + resolved = true; + wakeUp(0); } }; poll(); @@ -10218,64 +10144,39 @@ export function init(RuntimeName, PHPLoader) { function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -10287,8 +10188,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -10304,13 +10203,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -10320,7 +10215,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -10328,9 +10222,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -10345,12 +10239,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -10360,17 +10253,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/node/README.md b/packages/php-wasm/node/README.md index 50810eda707..ac1df92c82c 100644 --- a/packages/php-wasm/node/README.md +++ b/packages/php-wasm/node/README.md @@ -26,21 +26,10 @@ const output = await php.runStream({ console.log(await output.stdoutText); ``` -## Runtime exit and networking - -`php.exit()` cancels pending socket polls, receives, and connection waits before -releasing network handles. Cancelled waits do not resume PHP, and an exited -runtime cannot create new TCP connections or listening sockets. Cancellation is -per runtime; it does not affect other PHP instances. - -TCP sockets drain writes already queued in Node.js, including writes on persistent -connections. They stop keeping Node.js alive once those writes finish. Cleanup -cancels its timer when TCP closes and destroys connections still open after 30 -seconds. A peer that does not read can therefore lose queued data at that deadline. -Writes still queued inside Emscripten before the socket opens are not guaranteed -to drain. JSPI unwinds cancelled waits with the requested exit status so V8 can -release the suspended stack; Asyncify abandons them without resuming PHP. Do not -rely on an in-flight request completing after exit; discard the exited runtime. +On runtime exit, listening sockets close and TCP sockets have up to 30 seconds +to drain queued writes. The exited runtime cannot open new network connections. +As on previous runtimes, `php.exit()` does not provide general cancellation of +PHP code that was already executing. ## Loading PHP extensions diff --git a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts index c6ecb0bddf3..7edda3dc140 100644 --- a/packages/php-wasm/node/src/lib/networking/tcp-socket.ts +++ b/packages/php-wasm/node/src/lib/networking/tcp-socket.ts @@ -22,7 +22,7 @@ function log(...args: any[]) { // How long a socket may keep sending after the runtime exits. It gives the peer // time to read what PHP wrote, while bounding how long a peer that never reads -// or closes can hold the socket and delay a process exit. +// or closes can hold the socket, the exited runtime's memory, and a process exit. export const RELEASED_SOCKET_TIMEOUT_MS = 30_000; const SOL_SOCKET = 1; @@ -137,7 +137,9 @@ export class TcpSocket extends EventEmitter { * * Ending rather than destroying means the peer sees a normal end of stream, * even for a connection PHP left open mid-conversation, because destroying - * would discard PHP's queued writes. + * would discard PHP's queued writes. Until the socket closes, its listeners + * keep the exited runtime alive, including its WebAssembly heap. The + * timeout bounds that, and the runtime is freed once the socket closes. */ release() { if (this.released) { @@ -151,10 +153,6 @@ export class TcpSocket extends EventEmitter { // Emscripten's own queue, not Node.js's, and are lost, as they were with // the WebSocket proxy. this.shutDown(socket?.connecting && socket.writableLength === 0); - // The runtime cancels pending waits before releasing sockets. Detach - // remaining Emscripten listeners as well, so draining TCP cannot send - // events into exited PHP. TCP's own listeners stay to drain queued writes. - this.removeAllListeners(); if (!socket || socket.destroyed) { return; } @@ -164,8 +162,8 @@ export class TcpSocket extends EventEmitter { RELEASED_SOCKET_TIMEOUT_MS ); timeout.unref(); - // Cancel the timer once TCP closes, so it doesn't keep the closed - // socket in memory for the rest of the timeout. + // The socket's listeners retain the runtime, so cancel the timer as + // soon as TCP closes rather than retaining it for the whole timeout. socket.once('close', () => clearTimeout(timeout)); } diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 8c91883f099..98032728c76 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -29,11 +29,12 @@ export async function withNetworking( // Each runtime gets its own classes, so it only releases its own sockets. class RuntimeOutboundTcpSocket extends OutboundTcpSocket { constructor(url: string) { - if (closed) { - throw new Error('The PHP runtime has exited'); + // Use the existing failed-address path after exit. Throwing here + // escapes PHP with Asyncify instead of reporting a failed connection. + super(closed ? getOutboundTcpSocketUrl('', '0') : url); + if (!closed) { + track(this); } - super(url); - track(this); } } diff --git a/packages/php-wasm/node/src/test/fixtures/exit-during-network-read.ts b/packages/php-wasm/node/src/test/fixtures/exit-during-network-read.ts deleted file mode 100644 index 2ed0b3727c2..00000000000 --- a/packages/php-wasm/node/src/test/fixtures/exit-during-network-read.ts +++ /dev/null @@ -1,56 +0,0 @@ -import net from 'node:net'; -import { - PHP, - popLoadedRuntime, - type SupportedPHPVersion, -} from '@php-wasm/universal'; -import { loadNodeRuntime } from '../../lib'; - -const connections: net.Socket[] = []; -let notifyWaiting: () => void; -const waiting = new Promise((resolve) => (notifyWaiting = resolve)); -const server = net.createServer((socket) => { - connections.push(socket); - socket.once('data', () => notifyWaiting()); -}); -await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); -const { port } = server.address() as net.AddressInfo; -const weak = await runAndExit(); -connections.forEach((socket) => socket.destroy()); -await new Promise((resolve) => server.close(resolve)); -if (process.getActiveResourcesInfo().includes('Timeout')) { - throw new Error('A pending network wait still has a referenced timer'); -} -// Use a file rather than --eval: Node's eval scope itself retains the runtime. -for (let i = 0; i < 10; i++) { - await new Promise((resolve) => setTimeout(resolve, 10)); - global.gc!(); -} -if (weak.deref()) { - throw new Error('The cancelled network wait still retains the runtime'); -} - -async function runAndExit() { - const id = await loadNodeRuntime( - process.env['PHP_VERSION'] as SupportedPHPVersion, - { - emscriptenOptions: { processId: 1 }, - } - ); - const runtime = popLoadedRuntime(id, { - dangerouslyKeepTheRuntimeInTheMap: true, - }); - const weak = new WeakRef(runtime); - const php = new PHP(id); - php.run({ - code: ` {}); - await waiting; - php.exit(); - return weak; -} diff --git a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts index 769a9574d8b..2c5d80c14f1 100644 --- a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts +++ b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts @@ -39,12 +39,10 @@ describe('networking port allocation', () => { const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); emscriptenOptions.closeNetworkConnections!(); - expect( - () => - new OutboundSocket( - emscriptenOptions['websocket'].url(null, '127.0.0.1', '9') - ) - ).toThrow('The PHP runtime has exited'); + const socket = new OutboundSocket( + emscriptenOptions['websocket'].url(null, '127.0.0.1', '9') + ); + await new Promise((resolve) => socket.once('close', resolve)); expect(() => new Server({ host: '127.0.0.1', port: 0 })).toThrow( 'The PHP runtime has exited' ); diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 752a5d63980..0c9d5e489a6 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -418,6 +418,52 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { }); describe('Runtime exit', () => { + it('should reject new connections after a blocked read returns during exit', async () => { + const connections: net.Socket[] = []; + let notifyWaiting: () => void; + const waiting = new Promise( + (resolve) => (notifyWaiting = resolve) + ); + const tcpServer = net.createServer((socket) => { + connections.push(socket); + socket.once('data', () => notifyWaiting()); + }); + await new Promise((resolve) => + tcpServer.listen(0, '127.0.0.1', resolve) + ); + const { port } = tcpServer.address() as net.AddressInfo; + let php: PHP | undefined; + try { + php = new PHP(await loadNodeRuntime(phpVersion, options)); + const request = php.run({ + code: ` socket.destroy()); + await new Promise((resolve) => tcpServer.close(resolve)); + } + }); + it('should flush persistent and closed connections when the runtime exits', async () => { const size = 8 * 1024 * 1024; const tcpServer = net.createServer(); @@ -513,7 +559,8 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { }); await bothConnected; // Record the local port of each socket the runtime unrefs. The - // server sees it as the connection's remotePort. + // server sees it as the connection's remotePort, and a client + // gets its local port as soon as it starts connecting. const unrefedPorts = new Set(); const unref = net.Socket.prototype.unref; const unrefSpy = vi @@ -539,64 +586,6 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { tcpServer.close(); } }); - - it.each([false, true])( - 'should not resume PHP after exit (finite read timeout: %s)', - async (finiteTimeout) => { - const tcpServer = net.createServer({ allowHalfOpen: true }); - const connections: net.Socket[] = []; - const waiting = new Promise((resolve) => - tcpServer.on('connection', (socket) => { - connections.push(socket); - socket.once('data', () => resolve()); - }) - ); - await new Promise((resolve) => - tcpServer.listen(0, '127.0.0.1', resolve) - ); - const { port } = tcpServer.address() as net.AddressInfo; - let php: PHP | undefined; - try { - php = new PHP( - await loadNodeRuntime(phpVersion, options) - ); - let output: string | undefined; - let failure: unknown; - php.run({ - code: ` (output = result.text), - (error) => (failure = error) - ); - // PHP is waiting in fread() once its write arrives. - await waiting; - const ended = new Promise((resolve) => - connections[0].once('end', resolve) - ); - php.exit(); - await ended; - // Wait beyond the finite read timeout as well as queued close events. - await new Promise((resolve) => - setTimeout(resolve, 250) - ); - - expect(connections).toHaveLength(1); - expect(output ?? '').toBe(''); - expect(failure).toBeUndefined(); - } finally { - php?.exit(); - connections.forEach((socket) => socket.destroy()); - tcpServer.close(); - } - } - ); }); describe('Listening sockets', () => { diff --git a/packages/php-wasm/node/src/test/php-redis.spec.ts b/packages/php-wasm/node/src/test/php-redis.spec.ts index 3714414175c..aa9601e1f45 100644 --- a/packages/php-wasm/node/src/test/php-redis.spec.ts +++ b/packages/php-wasm/node/src/test/php-redis.spec.ts @@ -18,7 +18,6 @@ import { } from '@php-wasm/universal'; import { loadNodeRuntime } from '../lib'; import { jspi } from 'wasm-feature-detect'; -import net from 'node:net'; // Check JSPI availability at module load time (top-level await) const isJspiAvailable = await jspi(); @@ -293,49 +292,6 @@ if (!isJspiAvailable) { } }); - it('does not resume a pending extension receive after exit', async () => { - const connections: net.Socket[] = []; - let notifyWaiting: () => void; - const waiting = new Promise( - (resolve) => (notifyWaiting = resolve) - ); - // Accept the Redis command but never reply, forcing wasm_recv() to wait. - const server = net.createServer((socket) => { - connections.push(socket); - socket.once('data', () => notifyWaiting()); - }); - await new Promise((resolve) => - server.listen(0, '127.0.0.1', resolve) - ); - const { port } = server.address() as net.AddressInfo; - let output: string | undefined; - let failure: unknown; - try { - php.run({ - code: `connect('127.0.0.1', ${port}); - $r->setOption(Redis::OPT_READ_TIMEOUT, 0.1); - try { $r->get('waiting'); } catch (Throwable $e) {} - echo 'continued after exit'; - fsockopen('127.0.0.1', ${port}); - `, - }).then( - (result) => (output = result.text), - (error) => (failure = error) - ); - await waiting; - php.exit(); - await new Promise((resolve) => setTimeout(resolve, 250)); - expect(output ?? '').toBe(''); - expect(failure).toBeUndefined(); - expect(connections).toHaveLength(1); - } finally { - connections.forEach((socket) => socket.destroy()); - await new Promise((resolve) => server.close(resolve)); - } - }); - it('can set values with expiration', async () => { const testKey = `test_expiry_${Date.now()}_${Math.random().toString(36).substring(7)}`; diff --git a/packages/php-wasm/node/src/test/php-socket-timeouts.spec.ts b/packages/php-wasm/node/src/test/php-socket-timeouts.spec.ts index f1577cb01bf..0bdf0e1e6ff 100644 --- a/packages/php-wasm/node/src/test/php-socket-timeouts.spec.ts +++ b/packages/php-wasm/node/src/test/php-socket-timeouts.spec.ts @@ -1,176 +1,104 @@ -import { execFile } from 'node:child_process'; -import net from 'node:net'; -import path from 'node:path'; -import { - PHP, - SupportedPHPVersions, - popLoadedRuntime, - type SupportedPHPVersion, -} from '@php-wasm/universal'; -import { loadNodeRuntime } from '../lib'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; -const phpVersions = process.env['PHP'] - ? [process.env['PHP'] as SupportedPHPVersion] - : SupportedPHPVersions; +const repoRoot = resolve( + dirname(fileURLToPath(import.meta.url)), + '../../../../..' +); -describe.each(phpVersions)('PHP %s socket timeouts', (phpVersion) => { - it('ignores a queued socket completion after exit', async () => { - const connections: net.Socket[] = []; - const server = net.createServer((socket) => connections.push(socket)); - await new Promise((resolve) => - server.listen(0, '127.0.0.1', resolve) - ); - const { port } = server.address() as net.AddressInfo; - let php: PHP | undefined; - try { - const id = await loadNodeRuntime(phpVersion); - const runtime = popLoadedRuntime(id, { - dangerouslyKeepTheRuntimeInTheMap: true, - }); - php = new PHP(id); - const exited = new Promise((resolve) => { - // SOCKFS handles open before the connect wait's listener. Exit - // inside that event, while EventEmitter still has the latter queued. - runtime.websocket.on('open', () => { - php!.exit(); - resolve(); - }); - }); - let output: string | undefined; - let failure: unknown; - php.run({ - code: ` (output = result.text), - (error) => (failure = error) - ); - await exited; - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(output ?? '').toBe(''); - expect(failure).toBeUndefined(); - } finally { - php?.exit(); - connections.forEach((socket) => socket.destroy()); - await new Promise((resolve) => server.close(resolve)); - } - }); +function collectGeneratedPhpLoaders(directory: string): string[] { + return readdirSync(directory) + .flatMap((entry) => { + const fullPath = join(directory, entry); + if (statSync(fullPath).isDirectory()) { + return collectGeneratedPhpLoaders(fullPath); + } + return /php_\d+_\d+\.js$/.test(entry) ? [fullPath] : []; + }) + .sort(); +} - it('returns a read timeout while the runtime remains active', async () => { - const connections: net.Socket[] = []; - const server = net.createServer((socket) => connections.push(socket)); - await new Promise((resolve) => - server.listen(0, '127.0.0.1', resolve) +describe('socket timeout support', () => { + it('is present in the Emscripten library source', () => { + const source = readFileSync( + join( + repoRoot, + 'packages/php-wasm/compile/php/phpwasm-emscripten-library.js' + ), + 'utf8' ); - const { port } = server.address() as net.AddressInfo; - let php: PHP | undefined; - try { - php = new PHP(await loadNodeRuntime(phpVersion)); - const result = await php.run({ - code: ` socket.destroy()); - await new Promise((resolve) => server.close(resolve)); - } - }); - it('releases read timers and runtime memory on exit', async () => { - const repoRoot = path.resolve(__dirname, '../../../../..'); - const loader = path.join( - repoRoot, - 'packages/meta/src/node-es-module-loader/loader.mts' + expect(source).toContain('socketTimeouts: new Map()'); + expect(source).toContain('parseSocketTimeout'); + expect(source).toContain('SO_RCVTIMEO'); + expect(source).toContain('SO_SNDTIMEO'); + expect(source).toContain( + 'PHPWASM.socketTimeouts.set(socketd, timeouts)' ); - // A child isolates the event loop from Vitest's own timers and servers. - // Its 30-second read must not keep it alive after every TCP handle closes. - const fixture = path.join( - __dirname, - 'fixtures/exit-during-network-read.ts' + expect(source).toContain('const receiveTimeout ='); + expect(source).toContain('PHPWASM.socketTimeouts.get(sockfd)?.receive'); + expect(source).toContain('wakeUp(-ERRNO_CODES.EAGAIN)'); + expect(source).toContain( + 'const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send' ); - await new Promise((resolve, reject) => { - execFile( - process.execPath, - ['--no-warnings', '--expose-gc', `--loader=${loader}`, fixture], - { - timeout: 10000, - env: { ...process.env, TEST: '1', PHP_VERSION: phpVersion }, - }, - (error, _stdout, stderr) => { - if (error) { - reject(new Error(stderr || error.message)); - } else { - resolve(); - } - } - ); - }); - }, 15000); + expect(source).toContain('const timeout = sendTimeout ?? 30000'); + expect(source).toContain('const cleanupConnectListeners = () =>'); + expect(source).toContain('const cleanupFailedConnect = (errno) =>'); + expect(source).toContain('sock.connecting = false'); + expect(source).toContain('sock.error = errno'); + expect(source).not.toContain('?.send || 30000'); + expect(source).not.toContain('const isIgnorable'); + }); - it("keeps another runtime's pending read active when one runtime exits", async () => { - const connections: net.Socket[] = []; - const ready = new Map(); - let bothWaiting: () => void; - const waiting = new Promise((resolve) => (bothWaiting = resolve)); - const server = net.createServer((socket) => { - connections.push(socket); - socket.once('data', (data) => { - ready.set(data.toString(), socket); - if (ready.size === 2) { - bothWaiting(); - } - }); - }); - await new Promise((resolve) => - server.listen(0, '127.0.0.1', resolve) - ); - const { port } = server.address() as net.AddressInfo; - const runtimes: PHP[] = []; - try { - for (let i = 0; i < 2; i++) { - runtimes.push(new PHP(await loadNodeRuntime(phpVersion))); + it('is present in all checked-in generated PHP loaders', () => { + const loaderFiles = [ + ...collectGeneratedPhpLoaders( + join(repoRoot, 'packages/php-wasm/node-builds') + ), + ...collectGeneratedPhpLoaders( + join(repoRoot, 'packages/php-wasm/web-builds') + ), + ]; + + expect(loaderFiles).toHaveLength(32); + + for (const loaderFile of loaderFiles) { + const loader = readFileSync(loaderFile, 'utf8'); + expect(loader, loaderFile).toContain('socketTimeouts: new Map'); + expect(loader, loaderFile).toContain('parseSocketTimeout'); + expect(loader, loaderFile).toContain('SO_RCVTIMEO'); + expect(loader, loaderFile).toContain('SO_SNDTIMEO'); + expect(loader, loaderFile).toContain( + 'PHPWASM.socketTimeouts.set(socketd, timeouts)' + ); + expect(loader, loaderFile).toContain( + 'parseSocketTimeout: function' + ); + if (loader.includes('___syscall_recvfrom(sockfd')) { + expect(loader, loaderFile).toContain( + 'PHPWASM.socketTimeouts.get(sockfd)?.receive' + ); + expect(loader, loaderFile).toContain( + 'wakeUp(-ERRNO_CODES.EAGAIN)' + ); } - let exitedOutput: string | undefined; - let exitedFailure: unknown; - const run = (php: PHP, id: string) => - php.run({ - code: ` (exitedOutput = result.text), - (error) => (exitedFailure = error) + expect(loader, loaderFile).toContain( + 'PHPWASM.socketTimeouts.get(sockfd)?.send' + ); + expect(loader, loaderFile).toContain( + 'const timeout = sendTimeout ?? 3e4' ); - const secondRun = run(runtimes[1], 'second'); - await waiting; - runtimes[0].exit(); - ready.get('second')!.write('hello'); - expect((await secondRun).text).toBe('hello:finished'); - await new Promise((resolve) => setTimeout(resolve, 150)); - expect(exitedOutput ?? '').toBe(''); - expect(exitedFailure).toBeUndefined(); - } finally { - runtimes.forEach((php) => php.exit()); - connections.forEach((socket) => socket.destroy()); - await new Promise((resolve) => server.close(resolve)); + expect(loader, loaderFile).toContain('cleanupConnectListeners'); + expect(loader, loaderFile).toContain('cleanupFailedConnect'); + expect(loader, loaderFile).toContain('sock.connecting = false'); + expect(loader, loaderFile).toContain('sock.error = errno'); + expect(loader, loaderFile).not.toContain('?.send || 3e4'); + // Match the old socket-connect helper declaration specifically. + // A bare 'isIgnorable' substring would collide with exported PHP + // ABI symbols such as _zim_PhpToken_isIgnorable (PhpToken::isIgnorable()) + // that the full-ABI export bakes into JSPI loaders. + expect(loader, loaderFile).not.toContain('const isIgnorable'); } }); }); diff --git a/packages/php-wasm/node/src/test/tcp-socket.spec.ts b/packages/php-wasm/node/src/test/tcp-socket.spec.ts index 9aaffae853b..cccbe1ce9c0 100644 --- a/packages/php-wasm/node/src/test/tcp-socket.spec.ts +++ b/packages/php-wasm/node/src/test/tcp-socket.spec.ts @@ -41,7 +41,7 @@ describe('OutboundTcpSocket', () => { const opened = vi.fn(); socket.on('open', opened); const closed = new Promise((resolve) => - socket._socket!.once('close', resolve) + socket.once('close', resolve) ); // release() runs before the socket reports itself open. diff --git a/packages/php-wasm/universal/src/lib/load-php-runtime.ts b/packages/php-wasm/universal/src/lib/load-php-runtime.ts index a5a5e008e4d..817db6c68c0 100644 --- a/packages/php-wasm/universal/src/lib/load-php-runtime.ts +++ b/packages/php-wasm/universal/src/lib/load-php-runtime.ts @@ -172,13 +172,6 @@ export async function loadPHPRuntime( PHPRuntime.originalExit = PHPRuntime._exit; PHPRuntime._exit = function (code: number) { - // Cancel PHP's pending network waits before closing TCP. Otherwise a - // close event or poll timeout can resume PHP after exit cleanup ran. - try { - PHPRuntime.cancelNetworkWaits?.(code); - } catch (error) { - logger.error('Failed to cancel network waits', error); - } // Exit even if closing the network fails. PHP.exit() swallows errors, // so a throw here would leave the runtime running without notice. try { diff --git a/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js b/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js index 857817e7b96..89e08f903be 100644 --- a/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js +++ b/packages/php-wasm/web-builds/5-2/asyncify/php_5_2.js @@ -4718,16 +4718,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5085,51 +5076,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5199,21 +5149,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5221,13 +5163,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5239,8 +5178,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5251,33 +5188,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5295,14 +5224,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('close', handleClose); }; - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5322,11 +5243,13 @@ export function init(RuntimeName, PHPLoader) { }; const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; @@ -5347,7 +5270,6 @@ export function init(RuntimeName, PHPLoader) { handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7997,56 +7919,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -8058,8 +7956,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8075,13 +7971,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8091,7 +7983,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8099,9 +7990,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8116,12 +8007,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8131,17 +8021,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js b/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js index d12cad98cf0..bd786bffe54 100644 --- a/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js +++ b/packages/php-wasm/web-builds/5-2/jspi/php_5_2.js @@ -4675,16 +4675,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5042,51 +5033,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5156,21 +5106,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5178,13 +5120,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5196,8 +5135,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5208,33 +5145,25 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - // Wait for the connection to be established. A zero timeval // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5252,14 +5181,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('close', handleClose); }; - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5279,11 +5200,13 @@ export function init(RuntimeName, PHPLoader) { }; const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; @@ -5304,7 +5227,6 @@ export function init(RuntimeName, PHPLoader) { handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7806,64 +7728,39 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -7875,8 +7772,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7892,13 +7787,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7908,7 +7799,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7916,9 +7806,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -7933,12 +7823,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -7948,17 +7837,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js b/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js index 79153935ca1..94ffb91013a 100644 --- a/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js +++ b/packages/php-wasm/web-builds/7-4/asyncify/php_7_4.js @@ -4718,16 +4718,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5085,51 +5076,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5199,21 +5149,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5221,13 +5163,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5239,8 +5178,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5251,33 +5188,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5285,7 +5212,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5294,15 +5220,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5311,43 +5228,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8125,56 +8036,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -8186,8 +8073,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8203,13 +8088,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8219,7 +8100,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8227,9 +8107,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8244,12 +8124,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8259,17 +8138,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js b/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js index ead1f0a1e2b..95cab9b22c9 100644 --- a/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js +++ b/packages/php-wasm/web-builds/7-4/jspi/php_7_4.js @@ -4675,16 +4675,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5042,51 +5033,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5156,21 +5106,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5178,13 +5120,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5196,8 +5135,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5208,33 +5145,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5242,7 +5169,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5251,15 +5177,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5268,43 +5185,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7887,64 +7798,39 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -7956,8 +7842,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7973,13 +7857,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7989,7 +7869,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7997,9 +7876,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8014,12 +7893,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8029,17 +7907,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js b/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js index 0fc1c700ecd..806d49b0d81 100644 --- a/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js +++ b/packages/php-wasm/web-builds/8-0/asyncify/php_8_0.js @@ -4718,16 +4718,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5085,51 +5076,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5199,21 +5149,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5221,13 +5163,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5239,8 +5178,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5251,33 +5188,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5285,7 +5212,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5294,15 +5220,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5311,43 +5228,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8125,56 +8036,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -8186,8 +8073,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8203,13 +8088,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8219,7 +8100,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8227,9 +8107,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8244,12 +8124,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8259,17 +8138,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js b/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js index ac2ee0031fa..dce394f7aab 100644 --- a/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js +++ b/packages/php-wasm/web-builds/8-0/jspi/php_8_0.js @@ -4675,16 +4675,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5042,51 +5033,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5156,21 +5106,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5178,13 +5120,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5196,8 +5135,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5208,33 +5145,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5242,7 +5169,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5251,15 +5177,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5268,43 +5185,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7887,64 +7798,39 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -7956,8 +7842,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7973,13 +7857,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -7989,7 +7869,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -7997,9 +7876,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8014,12 +7893,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8029,17 +7907,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js b/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js index d7401df5583..25222ae64e4 100644 --- a/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js +++ b/packages/php-wasm/web-builds/8-1/asyncify/php_8_1.js @@ -4718,16 +4718,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5085,51 +5076,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5199,21 +5149,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5221,13 +5163,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5239,8 +5178,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5251,33 +5188,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5285,7 +5212,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5294,15 +5220,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5311,43 +5228,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8138,56 +8049,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -8199,8 +8086,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8216,13 +8101,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8232,7 +8113,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8240,9 +8120,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8257,12 +8137,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8272,17 +8151,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js b/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js index f09cffde297..af27e8bb503 100644 --- a/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js +++ b/packages/php-wasm/web-builds/8-1/jspi/php_8_1.js @@ -4675,16 +4675,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5042,51 +5033,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5156,21 +5106,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5178,13 +5120,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5196,8 +5135,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5208,33 +5145,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5242,7 +5169,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5251,15 +5177,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5268,43 +5185,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7900,64 +7811,39 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -7969,8 +7855,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7986,13 +7870,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8002,7 +7882,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8010,9 +7889,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8027,12 +7906,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8042,17 +7920,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js b/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js index 9ae4cc79a94..7755628dd8e 100644 --- a/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js +++ b/packages/php-wasm/web-builds/8-2/asyncify/php_8_2.js @@ -4718,16 +4718,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5085,51 +5076,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5199,21 +5149,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5221,13 +5163,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5239,8 +5178,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5251,33 +5188,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5285,7 +5212,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5294,15 +5220,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5311,43 +5228,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8139,56 +8050,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -8200,8 +8087,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8217,13 +8102,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8233,7 +8114,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8241,9 +8121,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8258,12 +8138,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8273,17 +8152,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js b/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js index e05f04e34ef..34178e5d5ad 100644 --- a/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js +++ b/packages/php-wasm/web-builds/8-2/jspi/php_8_2.js @@ -4675,16 +4675,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5042,51 +5033,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5156,21 +5106,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5178,13 +5120,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5196,8 +5135,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5208,33 +5145,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5242,7 +5169,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5251,15 +5177,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5268,43 +5185,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7901,64 +7812,39 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -7970,8 +7856,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7987,13 +7871,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8003,7 +7883,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8011,9 +7890,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8028,12 +7907,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8043,17 +7921,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js b/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js index 3d10bfbf806..cad692c54b1 100644 --- a/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js +++ b/packages/php-wasm/web-builds/8-3/asyncify/php_8_3.js @@ -4718,16 +4718,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5085,51 +5076,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5199,21 +5149,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5221,13 +5163,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5239,8 +5178,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5251,33 +5188,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5285,7 +5212,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5294,15 +5220,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5311,43 +5228,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8139,56 +8050,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -8200,8 +8087,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8217,13 +8102,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8233,7 +8114,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8241,9 +8121,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8258,12 +8138,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8273,17 +8152,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js b/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js index 6a2907151cb..61c5088a711 100644 --- a/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js +++ b/packages/php-wasm/web-builds/8-3/jspi/php_8_3.js @@ -4675,16 +4675,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5042,51 +5033,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5156,21 +5106,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5178,13 +5120,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5196,8 +5135,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5208,33 +5145,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5242,7 +5169,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5251,15 +5177,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5268,43 +5185,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7901,64 +7812,39 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -7970,8 +7856,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7987,13 +7871,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8003,7 +7883,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8011,9 +7890,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8028,12 +7907,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8043,17 +7921,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js b/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js index f2f81fe245e..fc9efd207eb 100644 --- a/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js +++ b/packages/php-wasm/web-builds/8-4/asyncify/php_8_4.js @@ -4718,16 +4718,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5085,51 +5076,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5199,21 +5149,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5221,13 +5163,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5239,8 +5178,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5251,33 +5188,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5285,7 +5212,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5294,15 +5220,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5311,43 +5228,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8139,56 +8050,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -8200,8 +8087,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8217,13 +8102,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8233,7 +8114,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8241,9 +8121,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8258,12 +8138,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8273,17 +8152,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js b/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js index 8f1e8d66d58..778b38fa412 100644 --- a/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js +++ b/packages/php-wasm/web-builds/8-4/jspi/php_8_4.js @@ -4675,16 +4675,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5042,51 +5033,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5156,21 +5106,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5178,13 +5120,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5196,8 +5135,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5208,33 +5145,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5242,7 +5169,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5251,15 +5177,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5268,43 +5185,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7901,64 +7812,39 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -7970,8 +7856,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7987,13 +7871,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8003,7 +7883,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8011,9 +7890,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8028,12 +7907,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8043,17 +7921,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); diff --git a/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js b/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js index c0964a344f0..f43b98f7219 100644 --- a/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js +++ b/packages/php-wasm/web-builds/8-5/asyncify/php_8_5.js @@ -4718,16 +4718,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5085,51 +5076,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5199,21 +5149,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5221,13 +5163,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5239,8 +5178,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5251,33 +5188,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5285,7 +5212,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5294,15 +5220,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5311,43 +5228,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -8140,56 +8051,32 @@ export function init(RuntimeName, PHPLoader) { const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -8201,8 +8088,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -8218,13 +8103,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8234,7 +8115,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8242,9 +8122,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8259,12 +8139,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8274,17 +8153,33 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); } diff --git a/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js b/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js index ca59945a1cd..9f297d34f29 100644 --- a/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js +++ b/packages/php-wasm/web-builds/8-5/jspi/php_8_5.js @@ -4675,16 +4675,7 @@ export function init(RuntimeName, PHPLoader) { POLLHUP: 16, SETFL_MASK: 3072, socketTimeouts: new Map(), - pendingNetworkWaits: new Set(), - networkingExited: false, init: function () { - Module['cancelNetworkWaits'] = (code = 0) => { - PHPWASM.networkingExited = true; - for (const wait of PHPWASM.pendingNetworkWaits) { - wait.cancel(code); - } - PHPWASM.socketTimeouts.clear(); - }; if (PHPLoader.bindUserSpace) { addOnInit(() => { if (typeof PHPLoader.processId !== 'number') { @@ -5042,51 +5033,10 @@ export function init(RuntimeName, PHPLoader) { }); const cancel = () => { ws.removeListener(event, listener); + setTimeout(resolve); }; return [promise, cancel]; }, - createNetworkWait: function (wakeUp, cleanup, abort) { - const wait = { - active: !PHPWASM.networkingExited, - finish(result) { - if (!wait.active) { - return; - } - stop(); - wakeUp(result); - }, - cancel(code) { - if (!wait.active) { - return; - } - stop(); - abort?.(new ExitStatus(code)); - }, - }; - function stop() { - wait.active = false; - PHPWASM.pendingNetworkWaits.delete(wait); - cleanup(); - } - if (wait.active) { - PHPWASM.pendingNetworkWaits.add(wait); - } - return wait; - }, - awaitNetworkOperation: function (start) { - if (typeof Asyncify.makeAsyncFunction === 'function') { - const operation = Asyncify.handleAsync( - () => - new Promise((resolve, reject) => start(resolve, reject)) - ); - // Some syscall shims ignore the returned promise. Mark it handled - // so cancelling them isn't an unhandled rejection. JSPI still - // receives the original rejection and unwinds the suspended stack. - operation.catch(PHPWASM.noop); - return operation; - } - return Asyncify.handleSleep(start); - }, noop: function () {}, parseSocketTimeout: function (optionValuePtr, optionLen) { if (!optionValuePtr || optionLen < 8) { @@ -5156,21 +5106,13 @@ export function init(RuntimeName, PHPLoader) { }, }; function _wasm_connect(sockfd, addr, addrlen) { - /** - * Use a synchronous connect() call when Asyncify is used. - * - * The async version was originally introduced to support the Memcached and Redis extensions, - * and both are only available with JSPI. Asyncify is too difficult to maintain and - * it's not getting that upgrade. - */ if (!('Suspending' in WebAssembly)) { var sock = getSocketFromFD(sockfd); var info = getSocketAddress(addr, addrlen); sock.sock_ops.connect(sock, info.addr, info.port); return 0; } - return PHPWASM.awaitNetworkOperation((wakeUp, abort) => { - // Get the socket + return Asyncify.handleSleep((wakeUp) => { let sock; try { sock = getSocketFromFD(sockfd); @@ -5178,13 +5120,10 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-ERRNO_CODES.EBADF); return; } - if (!sock) { wakeUp(-ERRNO_CODES.EBADF); return; } - - // Parse the address let info; try { info = getSocketAddress(addr, addrlen); @@ -5196,8 +5135,6 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Perform the connect (this creates the WebSocket but doesn't wait) try { sock.sock_ops.connect(sock, info.addr, info.port); } catch (e) { @@ -5208,33 +5145,23 @@ export function init(RuntimeName, PHPLoader) { wakeUp(-e.errno); return; } - - // Get all websockets for this socket const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - // No WebSocket yet, this shouldn't happen after connect wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - const ws = webSockets[0]; - - // If already connected, return success if (ws.readyState === ws.OPEN) { wakeUp(0); return; } - - // If already closed or closing, return error if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED) { wakeUp(-ERRNO_CODES.ECONNREFUSED); return; } - - // Wait for the connection to be established. A zero timeval - // disables the timeout, matching SO_SNDTIMEO semantics. const sendTimeout = PHPWASM.socketTimeouts.get(sockfd)?.send; - const timeout = sendTimeout ?? 30000; + const timeout = sendTimeout ?? 3e4; + let resolved = false; let timeoutId; let handleOpen; let handleError; @@ -5242,7 +5169,6 @@ export function init(RuntimeName, PHPLoader) { const peer = PHPWASM.getAllPeers(sock).find( (candidate) => candidate.socket === ws ); - const cleanupConnectListeners = () => { if (typeof timeoutId !== 'undefined') { clearTimeout(timeoutId); @@ -5251,15 +5177,6 @@ export function init(RuntimeName, PHPLoader) { ws.removeEventListener('error', handleError); ws.removeEventListener('close', handleClose); }; - - const wait = PHPWASM.createNetworkWait( - wakeUp, - cleanupConnectListeners, - abort - ); - if (!wait.active) { - return; - } const cleanupFailedConnect = (errno) => { try { if ( @@ -5268,43 +5185,37 @@ export function init(RuntimeName, PHPLoader) { ) { ws.close(); } - } catch (e) { - // Ignore close errors on an already-failed connect. - } + } catch (e) {} if (peer) { SOCKFS.websocket_sock_ops.removePeer(sock, peer); } sock.connecting = false; sock.error = errno; }; - const finishConnect = (result) => { - if (wait.active) { + if (!resolved) { + resolved = true; + cleanupConnectListeners(); if (result < 0) { cleanupFailedConnect(-result); } - wait.finish(result); + wakeUp(result); } }; - if (timeout > 0) { timeoutId = setTimeout(() => { finishConnect(-ERRNO_CODES.ETIMEDOUT); }, timeout); } - handleOpen = () => { finishConnect(0); }; - handleError = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - handleClose = () => { finishConnect(-ERRNO_CODES.ECONNREFUSED); }; - ws.addEventListener('open', handleOpen); ws.addEventListener('error', handleError); ws.addEventListener('close', handleClose); @@ -7902,64 +7813,39 @@ export function init(RuntimeName, PHPLoader) { __asyncjs__js_popen_to_file.sig = 'iiii'; function __asyncjs__wasm_poll_socket(socketd, events, timeout) { return Asyncify.handleAsync(async () => { - const returnCallback = (resolver) => - new Promise((resolve, reject) => resolver(resolve, reject)); + const returnCallback = (resolver) => new Promise(resolver); const POLLIN = 1; const POLLPRI = 2; const POLLOUT = 4; const POLLERR = 8; const POLLHUP = 16; const POLLNVAL = 32; - return returnCallback((wakeUp, abort) => { + return returnCallback((wakeUp) => { const polls = []; - let timeoutId; - const wait = PHPWASM.createNetworkWait( - wakeUp, - () => { - clearTimeout(timeoutId); - polls.forEach(([, cancel]) => cancel()); - }, - abort - ); - if (!wait.active) { - return; - } - /** - * Special semantics for polling sockets. - * - * @TODO: Remove this code branch entirely and poll sockets using the second if/else - * branch below. The only reason this wasn't done yet is that the original PR - * was focusing on removing child process-related special casing and did not - * want to increase the risk of breaking other code, especially around listening - * network sockets. - */ const stream = FS.getStream(socketd); if (FS.isSocket(stream?.node.mode)) { - // This is, most likely, a websocket. Let's make sure. const sock = getSocketFromFD(socketd); if (!sock) { - wait.finish(0); + wakeUp(0); return; } const lookingFor = new Set(); - if (events & POLLIN || events & POLLPRI) { if (sock.server) { for (const client of sock.pending) { if ((client.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } } else if ((sock.recv_queue || []).length > 0) { - wait.finish(1); + wakeUp(1); return; } } - const webSockets = PHPWASM.getAllWebSockets(sock); if (!webSockets.length) { - wait.finish(0); + wakeUp(0); return; } for (const ws of webSockets) { @@ -7971,8 +7857,6 @@ export function init(RuntimeName, PHPLoader) { polls.push(PHPWASM.awaitConnection(ws)); lookingFor.add('POLLOUT'); } - // Notify the user the socket is now closed even if the only requested - // in or out events. if ( events & POLLHUP || events & POLLIN || @@ -7988,13 +7872,9 @@ export function init(RuntimeName, PHPLoader) { } } } else if (stream?.stream_ops?.poll) { - // Poll the stream for data. - // @TODO: Consider reusing the polling implementation in js_fd_read(). let interrupted = false; - let pollTimeoutId; async function poll() { try { - // Inlined ___syscall_poll with added await support: while (true) { var mask = POLLNVAL; mask = SYSCALLS.DEFAULT_POLLMASK; @@ -8004,7 +7884,6 @@ export function init(RuntimeName, PHPLoader) { if (stream.stream_ops?.poll) { mask = stream.stream_ops.poll(stream, -1); } - mask &= events | POLLERR | POLLHUP; if (mask) { return mask; @@ -8012,9 +7891,9 @@ export function init(RuntimeName, PHPLoader) { if (interrupted) { return ERRNO_CODES.ETIMEDOUT; } - await new Promise((resolve) => { - pollTimeoutId = setTimeout(resolve, 10); - }); + await new Promise((resolve) => + setTimeout(resolve, 10) + ); } } catch (e) { if ( @@ -8029,12 +7908,11 @@ export function init(RuntimeName, PHPLoader) { poll(), () => { interrupted = true; - clearTimeout(pollTimeoutId); }, ]); } else { - timeoutId = setTimeout(function () { - wait.finish(1); + setTimeout(function () { + wakeUp(1); }, timeout); return; } @@ -8044,17 +7922,34 @@ export function init(RuntimeName, PHPLoader) { events + ', defaulting to setTimeout().' ); - timeoutId = setTimeout(function () { - wait.finish(0); + setTimeout(function () { + wakeUp(0); }, timeout); return; } - - Promise.race(polls.map(([promise]) => promise)).then(() => - wait.finish(1) - ); + const promises = polls.map(([promise]) => promise); + const clearPolling = () => + polls.forEach(([, clear]) => clear()); + let awaken = false; + let timeoutId; + Promise.race(promises).then(function (results) { + if (!awaken) { + awaken = true; + wakeUp(1); + if (timeoutId) { + clearTimeout(timeoutId); + } + clearPolling(); + } + }); if (timeout !== -1) { - timeoutId = setTimeout(() => wait.finish(0), timeout); + timeoutId = setTimeout(function () { + if (!awaken) { + awaken = true; + wakeUp(0); + clearPolling(); + } + }, timeout); } }); }); From 0995bd5a47225fe39259fd91e7d4d716d6d96a94 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sun, 8 Nov 2026 22:31:31 -0500 Subject: [PATCH 34/34] [ php-wasm ] Make the exit guard tests fail without the guard The spy on net.createConnection never saw tcp-socket.ts's calls, which go through a namespace import, and the PHP test checked for a late connection before it could arrive. Spy on the socket's connect(), check that no TCP socket exists, and wait a bounded time for a late connection. The PHP test no longer sets a read timeout or requires PHP to resume. Document that PHP waiting on a socket may resume and finish its script after exit, and explain why the server guard throws. Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/php-wasm/node/README.md | 5 ++- .../src/lib/networking/with-networking.ts | 3 ++ .../test/networking-port-allocation.spec.ts | 5 ++- .../node/src/test/php-networking.spec.ts | 35 +++++++++++-------- 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/packages/php-wasm/node/README.md b/packages/php-wasm/node/README.md index ac1df92c82c..1e335d600b6 100644 --- a/packages/php-wasm/node/README.md +++ b/packages/php-wasm/node/README.md @@ -29,7 +29,10 @@ console.log(await output.stdoutText); On runtime exit, listening sockets close and TCP sockets have up to 30 seconds to drain queued writes. The exited runtime cannot open new network connections. As on previous runtimes, `php.exit()` does not provide general cancellation of -PHP code that was already executing. +PHP code that was already executing. PHP waiting on a socket when the runtime +exits may resume and finish its script, including writes to mounted files, but +it can't open network connections. A `stream_socket_server()` call after exit +fails the request. ## Loading PHP extensions diff --git a/packages/php-wasm/node/src/lib/networking/with-networking.ts b/packages/php-wasm/node/src/lib/networking/with-networking.ts index 98032728c76..f5f27f3dfc1 100644 --- a/packages/php-wasm/node/src/lib/networking/with-networking.ts +++ b/packages/php-wasm/node/src/lib/networking/with-networking.ts @@ -40,6 +40,9 @@ export async function withNetworking( class RuntimeTcpServer extends TcpServer { constructor(options: TcpServerOptions) { + // Unlike a failed connection, PHP has no way to see a failed listen, + // so stop the request instead: stream_socket_server() after exit + // rejects php.run() with this error. if (closed) { throw new Error('The PHP runtime has exited'); } diff --git a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts index 2c5d80c14f1..5db2027efc9 100644 --- a/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts +++ b/packages/php-wasm/node/src/test/networking-port-allocation.spec.ts @@ -35,7 +35,9 @@ describe('networking port allocation', () => { const emscriptenOptions = await withNetworking({}); const OutboundSocket = emscriptenOptions['websocket'].decorator(); const Server = emscriptenOptions['websocket'].serverDecorator(); - const connectSpy = vi.spyOn(net, 'createConnection'); + // tcp-socket.ts calls createConnection() through a namespace import, + // which a spy on it can't see, so spy on the socket's connect(). + const connectSpy = vi.spyOn(net.Socket.prototype, 'connect'); const listenSpy = vi.spyOn(net.Server.prototype, 'listen'); emscriptenOptions.closeNetworkConnections!(); @@ -46,6 +48,7 @@ describe('networking port allocation', () => { expect(() => new Server({ host: '127.0.0.1', port: 0 })).toThrow( 'The PHP runtime has exited' ); + expect(socket._socket).toBeUndefined(); expect(connectSpy).not.toHaveBeenCalled(); expect(listenSpy).not.toHaveBeenCalled(); }); diff --git a/packages/php-wasm/node/src/test/php-networking.spec.ts b/packages/php-wasm/node/src/test/php-networking.spec.ts index 0c9d5e489a6..95d2033e2a1 100644 --- a/packages/php-wasm/node/src/test/php-networking.spec.ts +++ b/packages/php-wasm/node/src/test/php-networking.spec.ts @@ -418,14 +418,21 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { }); describe('Runtime exit', () => { - it('should reject new connections after a blocked read returns during exit', async () => { + it('should not open connections after the runtime exits', async () => { const connections: net.Socket[] = []; let notifyWaiting: () => void; const waiting = new Promise( (resolve) => (notifyWaiting = resolve) ); + let notifyLateConnection: () => void; + const lateConnection = new Promise( + (resolve) => (notifyLateConnection = resolve) + ); const tcpServer = net.createServer((socket) => { connections.push(socket); + if (connections.length > 1) { + notifyLateConnection(); + } socket.once('data', () => notifyWaiting()); }); await new Promise((resolve) => @@ -435,28 +442,28 @@ describe.each(phpVersions)('PHP %s', (phpVersion) => { let php: PHP | undefined; try { php = new PHP(await loadNodeRuntime(phpVersion, options)); + // Closing the socket at exit can wake PHP waiting in fread(), and + // PHP then runs the rest of its script. const request = php.run({ code: ` {}); await waiting; - const connectSpy = vi.spyOn(net, 'createConnection'); - try { - php.exit(); - // Preserve trunk's read completion behavior, without allowing - // the resumed script to open a connection after cleanup. - expect((await request).text).toBe('read returned'); - expect(connectSpy).not.toHaveBeenCalled(); - expect(connections).toHaveLength(1); - } finally { - connectSpy.mockRestore(); - } + php.exit(); + // Without the guard, the late connection arrives within a few + // hundred milliseconds, and after the request settles. + await Promise.race([ + lateConnection, + new Promise((resolve) => setTimeout(resolve, 1000)), + ]); + + expect(connections).toHaveLength(1); } finally { php?.exit(); connections.forEach((socket) => socket.destroy());