Skip to content

Commit a1b71ab

Browse files
committed
수정: 마지막 브라우저 세션 종료 시 이벤트 구독 해제
NodeCdpTransport가 활성 세션과 진행 중 연결이 있을 때만 connection 구독을 유지한다. 사용자 브라우저의 중복 연결·종료 구현을 공통 수명 주기로 통합하고 실패·재연결도 정리한다. 검증: 누수 재현 RED 후 npm test 13/13, 설치 MCP 양쪽 25/25, Chrome 제어 82/82. 검증: 반복 자원 정리 20/20, 사용자 브라우저 Edge·Chrome 37/37 통과.
1 parent 576339c commit a1b71ab

5 files changed

Lines changed: 111 additions & 46 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ happen only on an explicit maintainer decision; the Unreleased section accumulat
7272

7373
### Fixed
7474

75+
- Closing the last browser session now releases its transport event subscription. Failed attachment, concurrent
76+
attachment, external target closure, and later reconnection preserve the same cleanup boundary.
7577
- A page that moves on to another page of the permission, or whose frame navigates, keeps delivering its events: a
7678
main frame that commits inside the permission is verified by the URL it committed, and a child frame's navigation no
7779
longer suspends the page. A download started behind a "your download will begin" page, or on a page with a

‎scripts/browserControl/nodeCdpTransport.js‎

Lines changed: 47 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ export class NodeCdpTransport {
77
this._sessions = new Map();
88
this._children = new Map();
99
this._listeners = new Map();
10-
this._unsubscribe = connection.subscribe((event) => this._receiveEvent(event));
10+
this._unsubscribe = null;
11+
this._pendingAttaches = 0;
1112
}
1213

1314
async listTargets() {
@@ -30,20 +31,30 @@ export class NodeCdpTransport {
3031
}
3132

3233
async attach(targetId) {
33-
const { sessionId } = await this._connection.send("Target.attachToTarget", { targetId, flatten: true });
34-
const session = Object.freeze({ id: sessionId, targetId: String(targetId) });
34+
this._unsubscribe ||= this._connection.subscribe((event) => this._receiveEvent(event));
35+
this._pendingAttaches += 1;
36+
let sessionId;
3537
try {
38+
({ sessionId } = await this._attachTarget(targetId));
39+
const session = Object.freeze({ id: sessionId, targetId: String(targetId) });
40+
this._sessions.set(sessionId, session);
3641
// Same-origin navigation도 opaque locator document epoch을 바꿔야 한다. Page domain은
3742
// transport 운영 이벤트용으로 내부 활성화하며 raw command permission에는 추가하지 않는다.
3843
await this._connection.send("Page.enable", {}, session.id);
39-
this._sessions.set(sessionId, session);
4044
if (!this._guard) await this._autoAttach(session.id);
45+
if (!this._sessions.has(sessionId)) throw new Error("browser target detached during attach");
4146
return session;
4247
} catch (error) {
43-
await Promise.allSettled([
44-
this._connection.send("Target.detachFromTarget", { sessionId }),
45-
]);
48+
if (sessionId) {
49+
await Promise.allSettled([
50+
this._detachSession(sessionId),
51+
]);
52+
this._removeSession(sessionId);
53+
}
4654
throw error;
55+
} finally {
56+
this._pendingAttaches -= 1;
57+
this._releaseSubscription();
4758
}
4859
}
4960

@@ -110,22 +121,40 @@ export class NodeCdpTransport {
110121

111122
async detach(session) {
112123
if (!this._sessions.has(session.id)) return;
113-
try { await this._connection.send("Target.detachFromTarget", { sessionId: session.id }); }
114-
finally {
115-
this._sessions.delete(session.id);
116-
this._removeChildren(session.id);
117-
this._listeners.delete(session.id);
118-
}
124+
try { await this._detachSession(session.id); }
125+
finally { this._removeSession(session.id); }
119126
}
120127

121128
async close() {
122129
this._sessions.clear();
123130
this._children.clear();
124131
this._listeners.clear();
125-
this._unsubscribe();
132+
this._unsubscribe?.();
133+
this._unsubscribe = null;
126134
this._connection.close();
127135
}
128136

137+
_releaseSubscription() {
138+
if (this._sessions.size || this._pendingAttaches) return;
139+
this._unsubscribe?.();
140+
this._unsubscribe = null;
141+
}
142+
143+
_attachTarget(targetId) {
144+
return this._connection.send("Target.attachToTarget", { targetId, flatten: true });
145+
}
146+
147+
_detachSession(sessionId) {
148+
return this._connection.send("Target.detachFromTarget", { sessionId });
149+
}
150+
151+
_removeSession(sessionId) {
152+
this._sessions.delete(sessionId);
153+
this._removeChildren(sessionId);
154+
this._listeners.delete(sessionId);
155+
this._releaseSubscription();
156+
}
157+
129158
_autoAttach(sessionId) {
130159
return this._connection.send("Target.setAutoAttach", {
131160
autoAttach: true, waitForDebuggerOnStart: false, flatten: true,
@@ -179,8 +208,10 @@ export class NodeCdpTransport {
179208
if (this._sessions.has(event.params?.sessionId)) {
180209
this._sessions.delete(event.params.sessionId);
181210
this._removeChildren(event.params.sessionId);
182-
this._emit(event.params.sessionId, { method: "Transport.detached",
183-
params: { reason: event.params.reason || "target_closed" } });
211+
try {
212+
this._emit(event.params.sessionId, { method: "Transport.detached",
213+
params: { reason: event.params.reason || "target_closed" } });
214+
} finally { this._removeSession(event.params.sessionId); }
184215
}
185216
return;
186217
}

‎scripts/browserControl/userBrowser/userBrowserTransport.js‎

Lines changed: 7 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,12 @@ export class UserBrowserTransport extends NodeCdpTransport {
2323
return this._connection.send("PyprocUserBrowser.activateTab", { targetId: String(targetId) });
2424
}
2525

26-
async attach(targetId) {
27-
const { sessionId } = await this._connection.send("PyprocUserBrowser.attachTab", { targetId: String(targetId) });
28-
const session = Object.freeze({ id: sessionId, targetId: String(targetId) });
29-
try {
30-
// Same-origin navigation must replace the opaque locator epoch, as on a native CDP session.
31-
await this._connection.send("Page.enable", {}, session.id);
32-
this._sessions.set(sessionId, session);
33-
await this._autoAttach(session.id);
34-
return session;
35-
} catch (error) {
36-
await Promise.allSettled([this._connection.send("PyprocUserBrowser.detachSession", { sessionId })]);
37-
throw error;
38-
}
26+
_attachTarget(targetId) {
27+
return this._connection.send("PyprocUserBrowser.attachTab", { targetId: String(targetId) });
28+
}
29+
30+
_detachSession(sessionId) {
31+
return this._connection.send("PyprocUserBrowser.detachSession", { sessionId });
3932
}
4033

4134
async describe(session) {
@@ -80,13 +73,7 @@ export class UserBrowserTransport extends NodeCdpTransport {
8073

8174
_receiveEvent(event) {
8275
if (event.method === "PyprocUserBrowser.detached") {
83-
const rootId = event.params?.sessionId;
84-
if (!this._sessions.has(rootId)) return;
85-
this._sessions.delete(rootId);
86-
this._removeChildren(rootId);
87-
this._emit(rootId, { method: "Transport.detached",
88-
params: { reason: event.params.reason || "target_closed" } });
89-
return;
76+
return super._receiveEvent({ ...event, method: "Target.detachedFromTarget" });
9077
}
9178
super._receiveEvent(event);
9279
}
@@ -95,16 +82,6 @@ export class UserBrowserTransport extends NodeCdpTransport {
9582
return Object.freeze({ ...super.inspect(), provider: "userBrowser" });
9683
}
9784

98-
async detach(session) {
99-
if (!this._sessions.has(session.id)) return;
100-
try { await this._connection.send("PyprocUserBrowser.detachSession", { sessionId: session.id }); }
101-
finally {
102-
this._sessions.delete(session.id);
103-
this._removeChildren(session.id);
104-
this._listeners.delete(session.id);
105-
}
106-
}
107-
10885
async close() {
10986
// Ending the task is the extension's job too (it ends it when this connection goes), so a pipe already gone is
11087
// not an error here.

‎tests/contracts/browserControl.mjs‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
connectNodeBrowserControl,
88
} from "../../scripts/browserControl/browserControlBroker.mjs";
99
import { CdpConnection } from "../../scripts/browserControl/cdpConnection.mjs";
10+
import { NodeCdpTransport } from "../../scripts/browserControl/nodeCdpTransport.js";
1011
import {
1112
BrowserControlPort,
1213
BROWSER_CONTROL_ERROR_CODES,
@@ -188,6 +189,57 @@ function browserGuestFactory() {
188189
}
189190

190191
export async function assertBrowserControlContract() {
192+
// 마지막 세션을 닫은 제품은 재사용 가능해야 하며 connection 구독을 남기지 않는다.
193+
const connectionListeners = new Set();
194+
let failCommand = "";
195+
let finishAttach;
196+
const connection = {
197+
subscribe(listener) {
198+
connectionListeners.add(listener);
199+
return () => connectionListeners.delete(listener);
200+
},
201+
async send(method, params) {
202+
if (method === failCommand) throw new Error(`failed ${method}`);
203+
if (method === "Target.attachToTarget") {
204+
if (params.targetId === "pending") await new Promise((resolve) => { finishAttach = resolve; });
205+
return { sessionId: `raw:${params.targetId}` };
206+
}
207+
return {};
208+
},
209+
close() {},
210+
};
211+
const nativeTransport = new NodeCdpTransport(connection);
212+
assert(connectionListeners.size === 0, "사용하지 않는 transport가 connection을 구독한다");
213+
for (const command of ["Target.attachToTarget", "Page.enable", "Target.setAutoAttach"]) {
214+
failCommand = command;
215+
const error = await errorOf(() => nativeTransport.attach("failed"));
216+
assert(error && connectionListeners.size === 0 && nativeTransport.inspect().sessions === 0,
217+
`실패한 attach가 세션이나 구독을 남긴다: ${command}`);
218+
}
219+
failCommand = "";
220+
const firstNativeSession = await nativeTransport.attach("first");
221+
const pendingNativeSession = nativeTransport.attach("pending");
222+
await nativeTransport.detach(firstNativeSession);
223+
assert(connectionListeners.size === 1, "진행 중인 attach의 구독을 먼저 해제했다");
224+
finishAttach();
225+
const secondNativeSession = await pendingNativeSession;
226+
const thirdNativeSession = await nativeTransport.attach("third");
227+
await nativeTransport.detach(secondNativeSession);
228+
assert(connectionListeners.size === 1, "다른 세션의 구독을 해제했다");
229+
const detachedEvents = [];
230+
nativeTransport.subscribe(thirdNativeSession, (event) => detachedEvents.push(event));
231+
for (const listener of [...connectionListeners]) listener({ method: "Target.detachedFromTarget",
232+
params: { sessionId: thirdNativeSession.id } });
233+
assert(detachedEvents[0]?.method === "Transport.detached" && connectionListeners.size === 0
234+
&& nativeTransport.inspect().sessions === 0, "외부 세션 종료가 구독을 정리하지 않았다");
235+
const finalNativeSession = await nativeTransport.attach("again");
236+
assert(connectionListeners.size === 1, "재연결이 이벤트 구독을 복구하지 않았다");
237+
failCommand = "Target.detachFromTarget";
238+
await errorOf(() => nativeTransport.detach(finalNativeSession));
239+
assert(connectionListeners.size === 0 && nativeTransport.inspect().sessions === 0,
240+
"detach 실패가 구독을 남긴다");
241+
await nativeTransport.close();
242+
191243
const defaultBrowserArgs = headlessArgs("contract-profile");
192244
assert(defaultBrowserArgs.includes("--disable-extensions"), "공용 browser harness 기본 extension 차단이 열렸다");
193245
assert(!defaultBrowserArgs.some((arg) => arg.startsWith("--remote-debugging")),

‎tests/contracts/userBrowser.mjs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,9 @@ export async function assertUserBrowserContract() {
137137
unsubscribe();
138138
assert.deepEqual(seen, ["Transport.frameAttached", "Transport.frameDetached",
139139
"Page.frameNavigated", "Transport.detached"]);
140+
assert.equal(connection.listeners.size, 0, "external detach leaves no connection subscription");
141+
await transport.detach(await transport.attach("7"));
142+
assert.equal(connection.listeners.size, 0, "explicit detach leaves no connection subscription after reattach");
140143
const targets = userBrowserTargets(connection);
141144
assert.equal(await targets.create("about:blank"), undefined);
142145
assert.equal(connection.sent.at(-1).method, "PyprocUserBrowser.openTab");

0 commit comments

Comments
 (0)