-
-
Notifications
You must be signed in to change notification settings - Fork 484
Expand file tree
/
Copy pathChromeTargetManager.cs
More file actions
414 lines (350 loc) · 15.6 KB
/
ChromeTargetManager.cs
File metadata and controls
414 lines (350 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using PuppeteerSharp.Cdp.Messaging;
using PuppeteerSharp.Helpers;
using PuppeteerSharp.Helpers.Json;
namespace PuppeteerSharp.Cdp
{
internal class ChromeTargetManager : ITargetManager
{
private readonly List<string> _ignoredTargets = new();
private readonly Connection _connection;
private readonly Func<TargetInfo, CDPSession, CDPSession, CdpTarget> _targetFactoryFunc;
private readonly Func<Target, bool> _targetFilterFunc;
private readonly ILogger<ChromeTargetManager> _logger;
private readonly AsyncDictionaryHelper<string, CdpTarget> _attachedTargetsByTargetId = new("Target {0} not found");
private readonly ConcurrentDictionary<string, CdpTarget> _attachedTargetsBySessionId = new();
private readonly ConcurrentDictionary<string, TargetInfo> _discoveredTargetsByTargetId = new();
private readonly ConcurrentSet<string> _targetsIdsForInit = [];
private readonly TaskCompletionSource<bool> _initializeCompletionSource = new();
private readonly Browser _browser;
// Needed for .NET only to prevent race conditions between StoreExistingTargetsForInit and OnAttachedToTarget
private readonly int _targetDiscoveryTimeout;
private readonly TaskCompletionSource<bool> _targetDiscoveryCompletionSource = new();
public ChromeTargetManager(
Connection connection,
Func<TargetInfo, CDPSession, CDPSession, CdpTarget> targetFactoryFunc,
Func<Target, bool> targetFilterFunc,
Browser browser,
int targetDiscoveryTimeout = 0)
{
_connection = connection;
_targetFilterFunc = targetFilterFunc;
_targetFactoryFunc = targetFactoryFunc;
_logger = _connection.LoggerFactory.CreateLogger<ChromeTargetManager>();
_connection.MessageReceived += OnMessageReceived;
_connection.SessionDetached += Connection_SessionDetached;
_targetDiscoveryTimeout = targetDiscoveryTimeout;
_browser = browser;
}
public event EventHandler<TargetChangedArgs> TargetAvailable;
public event EventHandler<TargetChangedArgs> TargetGone;
public event EventHandler<TargetChangedArgs> TargetChanged;
public event EventHandler<TargetChangedArgs> TargetDiscovered;
public AsyncDictionaryHelper<string, CdpTarget> GetAvailableTargets() => _attachedTargetsByTargetId;
public async Task InitializeAsync()
{
try
{
await _connection.SendAsync("Target.setDiscoverTargets", new TargetSetDiscoverTargetsRequest
{
Discover = true,
Filter =
[
new TargetSetDiscoverTargetsRequest.DiscoverFilter() { Type = "tab", Exclude = true, },
new TargetSetDiscoverTargetsRequest.DiscoverFilter()
],
}).ConfigureAwait(false);
}
finally
{
_targetDiscoveryCompletionSource.SetResult(true);
}
StoreExistingTargetsForInit();
await _connection.SendAsync(
"Target.setAutoAttach",
new TargetSetAutoAttachRequest()
{
WaitForDebuggerOnStart = true,
Flatten = true,
AutoAttach = true,
}).ConfigureAwait(false);
FinishInitializationIfReady();
await _initializeCompletionSource.Task.ConfigureAwait(false);
}
public IEnumerable<ITarget> GetChildTargets(ITarget target) => target.ChildTargets;
private void StoreExistingTargetsForInit()
{
foreach (var kv in _discoveredTargetsByTargetId)
{
var targetForFilter = new CdpTarget(
kv.Value,
null,
null,
this,
null,
_browser.ScreenshotTaskQueue);
// Only wait for pages and frames (except those from extensions)
// to auto-attach.
var isPageOrFrame = kv.Value.Type is TargetType.Page or TargetType.IFrame;
var isExtension = kv.Value.Url.StartsWith("chrome-extension://", StringComparison.OrdinalIgnoreCase);
if (isPageOrFrame && !isExtension && (_targetFilterFunc == null || _targetFilterFunc(targetForFilter)))
{
_targetsIdsForInit.Add(kv.Key);
}
}
}
private async Task EnsureTargetsIdsForInitAsync()
{
if (_targetDiscoveryTimeout > 0)
{
await _targetDiscoveryCompletionSource.Task.WithTimeout(_targetDiscoveryTimeout).ConfigureAwait(false);
}
else
{
await _targetDiscoveryCompletionSource.Task.ConfigureAwait(false);
}
}
private void OnMessageReceived(object sender, MessageEventArgs e)
{
try
{
switch (e.MessageID)
{
case "Target.attachedToTarget":
_ = OnAttachedToTargetHandlingExceptionsAsync(sender, e.MessageID, e.MessageData.ToObject<TargetAttachedToTargetResponse>());
return;
case "Target.detachedFromTarget":
OnDetachedFromTarget(sender, e.MessageData.ToObject<TargetDetachedFromTargetResponse>());
return;
case "Target.targetCreated":
OnTargetCreated(e.MessageData.ToObject<TargetCreatedResponse>());
return;
case "Target.targetDestroyed":
_ = OnTargetDestroyedAsync(e.MessageID, e.MessageData.ToObject<TargetDestroyedResponse>());
return;
case "Target.targetInfoChanged":
OnTargetInfoChanged(e.MessageData.ToObject<TargetCreatedResponse>());
return;
}
}
catch (Exception ex)
{
HandleExceptionOnMessageReceived(e.MessageID, ex);
}
}
private void Connection_SessionDetached(object sender, SessionEventArgs e)
{
e.Session.MessageReceived -= OnMessageReceived;
}
private void OnTargetCreated(TargetCreatedResponse e)
{
_discoveredTargetsByTargetId[e.TargetInfo.TargetId] = e.TargetInfo;
TargetDiscovered?.Invoke(this, new TargetChangedArgs { TargetInfo = e.TargetInfo });
if (e.TargetInfo.Type == TargetType.Browser && e.TargetInfo.Attached)
{
if (_attachedTargetsByTargetId.ContainsKey(e.TargetInfo.TargetId))
{
return;
}
var target = _targetFactoryFunc(e.TargetInfo, null, null);
target.Initialize();
_attachedTargetsByTargetId.AddItem(e.TargetInfo.TargetId, target);
}
}
private async Task OnTargetDestroyedAsync(string messageId, TargetDestroyedResponse e)
{
try
{
_discoveredTargetsByTargetId.TryRemove(e.TargetId, out var targetInfo);
await EnsureTargetsIdsForInitAsync().ConfigureAwait(false);
FinishInitializationIfReady(e.TargetId);
if (targetInfo?.Type == TargetType.ServiceWorker)
{
// Special case for service workers: report TargetGone event when
// the worker is destroyed.
if (_attachedTargetsByTargetId.TryRemove(e.TargetId, out var target))
{
TargetGone?.Invoke(this, new TargetChangedArgs { Target = target, TargetInfo = targetInfo });
}
}
}
catch (Exception ex)
{
HandleExceptionOnMessageReceived(messageId, ex);
}
}
private void OnTargetInfoChanged(TargetCreatedResponse e)
{
_discoveredTargetsByTargetId[e.TargetInfo.TargetId] = e.TargetInfo;
if (_ignoredTargets.Contains(e.TargetInfo.TargetId) ||
!_attachedTargetsByTargetId.TryGetValue(e.TargetInfo.TargetId, out var target) ||
!e.TargetInfo.Attached)
{
return;
}
var previousURL = target.Url;
var wasInitialized = target.IsInitialized;
if (IsPageTargetBecomingPrimary(target, e.TargetInfo))
{
var session = target.Session;
session.ParentSession?.OnSwapped(session);
}
target.TargetInfoChanged(e.TargetInfo);
if (wasInitialized && previousURL != target.Url)
{
TargetChanged?.Invoke(this, new TargetChangedArgs
{
Target = target,
TargetInfo = e.TargetInfo,
});
}
}
private bool IsPageTargetBecomingPrimary(Target target, TargetInfo newTargetInfo)
=> !string.IsNullOrEmpty(target.TargetInfo.Subtype) && string.IsNullOrEmpty(newTargetInfo.Subtype);
private async Task SilentDetachAsync(CDPSession session, ICDPConnection parentConnection)
{
try
{
await session.SendAsync("Runtime.runIfWaitingForDebugger").ConfigureAwait(false);
// We don't use session.Detach() because that dispatches all commands on
// the connection instead of the parent session.
await parentConnection.SendAsync(
"Target.detachFromTarget",
new TargetDetachFromTargetRequest
{
SessionId = session.Id,
}).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "silentDetach failed.");
}
}
private CdpTarget GetParentTarget(ICDPConnection parentConnection)
=> parentConnection is CdpCDPSession parentSession ? parentSession.Target as CdpTarget : null;
private async Task OnAttachedToTargetAsync(object sender, TargetAttachedToTargetResponse e)
{
var parentConnection = sender as ICDPConnection;
var parentSession = sender as CDPSession;
var targetInfo = e.TargetInfo;
var session = _connection.GetSession(e.SessionId) ?? throw new PuppeteerException($"Session {e.SessionId} was not created.");
if (!_connection.IsAutoAttached(targetInfo.TargetId))
{
return;
}
if (targetInfo.Type == TargetType.ServiceWorker)
{
await EnsureTargetsIdsForInitAsync().ConfigureAwait(false);
FinishInitializationIfReady(targetInfo.TargetId);
await SilentDetachAsync(session, parentConnection).ConfigureAwait(false);
if (_attachedTargetsByTargetId.ContainsKey(targetInfo.TargetId))
{
return;
}
var workerTarget = _targetFactoryFunc(targetInfo, null, null);
workerTarget.Initialize();
_attachedTargetsByTargetId.AddItem(targetInfo.TargetId, workerTarget);
TargetAvailable?.Invoke(this, new TargetChangedArgs { Target = workerTarget });
return;
}
var isExistingTarget = _attachedTargetsByTargetId.TryGetValue(targetInfo.TargetId, out var target);
if (!isExistingTarget)
{
target = _targetFactoryFunc(targetInfo, session, parentSession);
}
var parentTarget = GetParentTarget(parentConnection);
if (_targetFilterFunc?.Invoke(target) == false)
{
_ignoredTargets.Add(targetInfo.TargetId);
await EnsureTargetsIdsForInitAsync().ConfigureAwait(false);
if (parentTarget?.TargetInfo.Type == TargetType.Tab)
{
FinishInitializationIfReady(parentTarget.TargetId);
}
await SilentDetachAsync(session, parentConnection).ConfigureAwait(false);
return;
}
session.MessageReceived += OnMessageReceived;
if (isExistingTarget)
{
session.Target = target;
_attachedTargetsBySessionId.TryAdd(session.Id, target);
}
else
{
target.Initialize();
_attachedTargetsByTargetId.AddItem(targetInfo.TargetId, target);
_attachedTargetsBySessionId.TryAdd(session.Id, target);
}
parentTarget?.AddChildTarget(target);
(parentSession ?? parentConnection as CDPSession)?.OnSessionReady(session);
await EnsureTargetsIdsForInitAsync().ConfigureAwait(false);
_targetsIdsForInit.Remove(target.TargetId);
if (!isExistingTarget)
{
TargetAvailable?.Invoke(this, new TargetChangedArgs { Target = target });
}
FinishInitializationIfReady();
try
{
await Task.WhenAll(
session.SendAsync("Target.setAutoAttach", new TargetSetAutoAttachRequest
{
WaitForDebuggerOnStart = true,
Flatten = true,
AutoAttach = true,
}),
session.SendAsync("Runtime.runIfWaitingForDebugger")).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to call setAutoAttach and runIfWaitingForDebugger");
}
}
private async Task OnAttachedToTargetHandlingExceptionsAsync(object sender, string messageId, TargetAttachedToTargetResponse e)
{
try
{
await OnAttachedToTargetAsync(sender, e).ConfigureAwait(false);
}
catch (Exception ex)
{
HandleExceptionOnMessageReceived(messageId, ex);
}
}
private void HandleExceptionOnMessageReceived(string messageId, Exception ex)
{
var message = $"Browser failed to process {messageId}. {ex.Message}. {ex.StackTrace}";
_logger.LogError(ex, message);
_connection.Close(message);
}
private void FinishInitializationIfReady(string targetId = null)
{
if (targetId != null)
{
_targetsIdsForInit.Remove(targetId);
}
if (_targetsIdsForInit.Count == 0)
{
_initializeCompletionSource.TrySetResult(true);
}
}
private void OnDetachedFromTarget(object sender, TargetDetachedFromTargetResponse e)
{
if (!_attachedTargetsBySessionId.TryRemove(e.SessionId, out var target))
{
return;
}
if (sender is CdpCDPSession parentSession)
{
parentSession.Target.RemoveChildTarget(target);
}
_attachedTargetsByTargetId.TryRemove(target.TargetId, out _);
TargetGone?.Invoke(this, new TargetChangedArgs { Target = target });
}
}
}