Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions packages/dev-middleware/src/__tests__/InspectorDeviceUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import WebSocket from 'ws';
export class DeviceAgent {
#ws: ?WebSocket;
#readyPromise: Promise<void>;
#lastSessionIdByPageId: Map<string, string> = new Map();

constructor(url: string, signal?: AbortSignal, host?: ?string) {
const ws = new WebSocket(url, {
Expand All @@ -40,7 +41,14 @@ export class DeviceAgent {
});
this.#ws = ws;
ws.on('message', data => {
this.__handle(JSON.parse(data.toString()));
const message: MessageToDevice = JSON.parse(data.toString());
if (message.event === 'connect') {
this.#lastSessionIdByPageId.set(
message.payload.pageId,
message.payload.sessionId,
);
}
this.__handle(message);
});
if (signal != null) {
signal.addEventListener('abort', () => {
Expand Down Expand Up @@ -80,12 +88,20 @@ export class DeviceAgent {
this.#ws = null;
}

sendWrappedEvent(pageId: string, event: JSONSerializable) {
sendWrappedEvent(
pageId: string,
event: JSONSerializable,
sessionId: string = nullthrows(
this.#lastSessionIdByPageId.get(pageId),
`No session connected to page ${pageId}`,
),
) {
this.send({
event: 'wrappedEvent',
payload: {
pageId,
wrappedEvent: JSON.stringify(event),
sessionId,
},
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ describe('inspector proxy React Native reloads', () => {
syntheticPage.webSocketDebuggerUrl,
autoCleanup.signal,
);
await until(() => expect(device1.connect).toBeCalledTimes(1));

device1.sendWrappedEvent('originalPage-initial', {
error: 'Mock error',
Expand Down Expand Up @@ -237,6 +238,7 @@ describe('inspector proxy React Native reloads', () => {
* We can reuse our existing debugger connection to the synthetic page.
* Messages from the updated page will be routed to the debugger.
*/
await until(() => expect(device1.connect).toBeCalledTimes(2));
device1.sendWrappedEvent('originalPage-updated', {
error: 'Another mock error',
});
Expand Down Expand Up @@ -402,51 +404,45 @@ describe('inspector proxy React Native reloads', () => {
}
});

test.each([
['with', true],
['without', false],
])(
"device disconnect event %s session ID closes the debugger connection when target has 'nativePageReloads' capability flag",
async (_, includeSessionId) => {
const {device, debugger_, sessionId} = await createAndConnectTarget(
serverRef,
autoCleanup.signal,
{
app: 'bar-app',
id: 'page1',
title: 'bar-title',
vm: 'bar-vm',
capabilities: {
nativePageReloads: true,
},
test("device disconnect event closes the debugger connection when target has 'nativePageReloads' capability flag", async () => {
const {device, debugger_, sessionId} = await createAndConnectTarget(
serverRef,
autoCleanup.signal,
{
app: 'bar-app',
id: 'page1',
title: 'bar-title',
vm: 'bar-vm',
capabilities: {
nativePageReloads: true,
},
);
const debuggerClosed = new Promise<{code: number, reason: string}>(
resolve =>
debugger_.socket.once('close', (code: number, reason: Buffer) =>
resolve({code, reason: reason.toString()}),
),
);
},
);
const debuggerClosed = new Promise<{code: number, reason: string}>(
resolve =>
debugger_.socket.once('close', (code: number, reason: Buffer) =>
resolve({code, reason: reason.toString()}),
),
);

try {
device.send({
event: 'disconnect',
payload: {
pageId: 'page1',
...(includeSessionId ? {sessionId} : {}),
},
});
expect(await debuggerClosed).toEqual({
code: 1000,
reason: WS_CLOSE_REASON.PAGE_REMOVED,
});
expect(debugger_.handle).not.toBeCalledWith({method: 'reload'});
} finally {
device.close();
debugger_.close();
}
},
);
try {
device.send({
event: 'disconnect',
payload: {
pageId: 'page1',
sessionId,
},
});
expect(await debuggerClosed).toEqual({
code: 1000,
reason: WS_CLOSE_REASON.PAGE_REMOVED,
});
expect(debugger_.handle).not.toBeCalledWith({method: 'reload'});
} finally {
device.close();
debugger_.close();
}
});

test("disabled when target has 'nativePageReloads' capability flag", async () => {
let device1;
Expand Down
74 changes: 17 additions & 57 deletions packages/dev-middleware/src/inspector-proxy/Device.js
Original file line number Diff line number Diff line change
Expand Up @@ -601,71 +601,31 @@ export default class Device {
// TODO(moti): Handle null case explicitly, e.g. swallow disconnect events
// for unknown pages.
const page: ?Page = this.#pages.get(pageId);
const debuggerConnection = this.#debuggerConnections.get(sessionId);

if (page != null && this.#pageHasCapability(page, 'nativePageReloads')) {
for (const [sid, debuggerConnection] of this.#debuggerConnections) {
if (
sessionId != null
? sid === sessionId
: debuggerConnection.pageId === pageId
) {
this.#debuggerConnections.delete(sid);
debuggerConnection.socket.close(
WS_CLOSURE_CODE.NORMAL,
WS_CLOSE_REASON.PAGE_REMOVED,
);
}
if (debuggerConnection != null) {
this.#debuggerConnections.delete(sessionId);
debuggerConnection.socket.close(
WS_CLOSURE_CODE.NORMAL,
WS_CLOSE_REASON.PAGE_REMOVED,
);
}
return;
}

// Find the debugger connection(s) for this page
if (sessionId != null) {
// Disconnect specific session
const debuggerConnection = this.#debuggerConnections.get(sessionId);
if (
debuggerConnection &&
debuggerConnection.socket.readyState === WS.OPEN
) {
if (debuggerConnection.pageId !== REACT_NATIVE_RELOADABLE_PAGE_ID) {
debug(
`Legacy page ${pageId} is reloading (sessionId: ${sessionId}).`,
);
debuggerConnection.socket.send(JSON.stringify({method: 'reload'}));
}
}
} else {
// Legacy mode: send to all connected debuggers for this page
for (const debuggerConnection of this.#debuggerConnections.values()) {
if (
debuggerConnection.pageId !== REACT_NATIVE_RELOADABLE_PAGE_ID &&
debuggerConnection.socket.readyState === WS.OPEN
) {
debug(`Legacy page ${pageId} is reloading.`);
debuggerConnection.socket.send(JSON.stringify({method: 'reload'}));
}
}
if (
debuggerConnection &&
debuggerConnection.socket.readyState === WS.OPEN &&
debuggerConnection.pageId !== REACT_NATIVE_RELOADABLE_PAGE_ID
) {
debug(`Legacy page ${pageId} is reloading (sessionId: ${sessionId}).`);
debuggerConnection.socket.send(JSON.stringify({method: 'reload'}));
}
} else if (message.event === 'wrappedEvent') {
const sessionId = message.payload.sessionId;

// Route message to the correct debugger connection by sessionId
let debuggerConnection: ?DebuggerConnection = null;
if (sessionId != null) {
debuggerConnection = this.#debuggerConnections.get(sessionId);
} else {
// Legacy mode: route to the first (and only) debugger connection
// ASSERT: In legacy mode, there should be at most one debugger connected.
if (this.#debuggerConnections.size > 1) {
debug(
'WARNING: Device sent message without sessionId but multiple debuggers are connected. ' +
'This indicates a device/proxy version mismatch.',
);
}
debuggerConnection =
this.#debuggerConnections.values().next().value ?? null;
}

const debuggerConnection = this.#debuggerConnections.get(
message.payload.sessionId,
);
if (debuggerConnection == null) {
return;
}
Expand Down
13 changes: 6 additions & 7 deletions packages/dev-middleware/src/inspector-proxy/__docs__/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ interface Message {

#### Device → Proxy Messages

| Event | Payload | Description |
| -------------- | -------------------------------------------------------------- | ----------------------------------------------------- |
| `getPages` | `Page[]` | Current list of inspectable pages. |
| `disconnect` | `{ pageId: string, sessionId?: string }` | Notify that page disconnected or rejected connection. |
| `wrappedEvent` | `{ pageId: string, sessionId?: string, wrappedEvent: string }` | Forward CDP message (JSON string) from page. |
| Event | Payload | Description |
| -------------- | ------------------------------------------------------------- | ----------------------------------------------------- |
| `getPages` | `Page[]` | Current list of inspectable pages. |
| `disconnect` | `{ pageId: string, sessionId: string }` | Notify that page disconnected or rejected connection. |
| `wrappedEvent` | `{ pageId: string, sessionId: string, wrappedEvent: string }` | Forward CDP message (JSON string) from page. |

#### Page Object

Expand Down Expand Up @@ -175,8 +175,7 @@ a `disconnect` back to the proxy for that `pageId`. Devices also send a
`disconnect` for each session when a page is removed.

For targets with `nativePageReloads`, the proxy closes the debugger connection
with `[PAGE_REMOVED]` when it receives a `disconnect` for its session (or for
its page, if `sessionId` is omitted).
with `[PAGE_REMOVED]` when it receives a `disconnect` for its session.

### Connection Semantics

Expand Down
6 changes: 3 additions & 3 deletions packages/dev-middleware/src/inspector-proxy/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export type WrappedEventFromDevice = Readonly<{
payload: Readonly<{
pageId: string,
wrappedEvent: string,
sessionId?: string,
sessionId: string,
}>,
}>;

Expand Down Expand Up @@ -87,10 +87,10 @@ export type DisconnectRequest = Readonly<{
}>;

// Event sent from Device to Inspector Proxy when a debugger session ends or is
// rejected. Legacy devices omit the sessionId.
// rejected.
export type DisconnectEventFromDevice = Readonly<{
event: 'disconnect',
payload: Readonly<{pageId: string, sessionId?: string}>,
payload: Readonly<{pageId: string, sessionId: string}>,
}>;

// Request sent from Inspector Proxy to Device to get a list of pages.
Expand Down
Loading