forked from MasterDevs/ChromeDevTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChromeSession.cs
256 lines (233 loc) · 8.73 KB
/
ChromeSession.cs
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
#if !NETSTANDARD1_5
using MasterDevs.ChromeDevTools.Serialization;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WebSocket4Net;
namespace MasterDevs.ChromeDevTools
{
public class ChromeSession : IChromeSession
{
private readonly string _endpoint;
private readonly ConcurrentDictionary<string, ConcurrentBag<Action<object>>> _handlers = new ConcurrentDictionary<string, ConcurrentBag<Action<object>>>();
private ICommandFactory _commandFactory;
private IEventFactory _eventFactory;
private ManualResetEvent _openEvent = new ManualResetEvent(false);
private ManualResetEvent _publishEvent = new ManualResetEvent(false);
private ConcurrentDictionary<long, ManualResetEventSlim> _requestWaitHandles = new ConcurrentDictionary<long, ManualResetEventSlim>();
private ICommandResponseFactory _responseFactory;
private ConcurrentDictionary<long, ICommandResponse> _responses = new ConcurrentDictionary<long, ICommandResponse>();
private WebSocket _webSocket;
private static object _Lock = new object();
public ChromeSession(string endpoint, ICommandFactory commandFactory, ICommandResponseFactory responseFactory, IEventFactory eventFactory)
{
_endpoint = endpoint;
_commandFactory = commandFactory;
_responseFactory = responseFactory;
_eventFactory = eventFactory;
}
public void Dispose()
{
if (null == _webSocket) return;
if (_webSocket.State == WebSocketState.Open)
{
_webSocket.Close();
}
_webSocket.Dispose();
}
private void EnsureInit()
{
if (null == _webSocket)
{
lock (_Lock)
{
if (null == _webSocket)
{
Init().Wait();
}
}
}
}
private Task Init()
{
_openEvent.Reset();
_webSocket = new WebSocket(_endpoint);
_webSocket.EnableAutoSendPing = false;
_webSocket.Opened += WebSocket_Opened;
_webSocket.MessageReceived += WebSocket_MessageReceived;
_webSocket.Error += WebSocket_Error;
_webSocket.Closed += WebSocket_Closed;
_webSocket.DataReceived += WebSocket_DataReceived;
_webSocket.Open();
return Task.Run(() =>
{
_openEvent.WaitOne();
});
}
public Task<ICommandResponse> SendAsync<T>(CancellationToken cancellationToken)
{
var command = _commandFactory.Create<T>();
return SendCommand(command, cancellationToken);
}
public Task<ICommandResponse> SendAsync<T>(T parameter, CancellationToken cancellationToken)
{
var command = _commandFactory.Create(parameter);
return SendCommand(command, cancellationToken);
}
public void Subscribe<T>(Action<T> handler) where T : class
{
var handlerType = typeof(T);
var handlerForBag = new Action<object>(obj => handler((T)obj));
_handlers.AddOrUpdate(handlerType.FullName,
(m) => new ConcurrentBag<Action<object>>(new [] { handlerForBag }),
(m, currentBag) =>
{
currentBag.Add(handlerForBag);
return currentBag;
});
}
private void HandleEvent(IEvent evnt)
{
if (null == evnt
|| null == evnt)
{
return;
}
var type = evnt.GetType().GetGenericArguments().FirstOrDefault();
if (null == type)
{
return;
}
var handlerKey = type.FullName;
ConcurrentBag<Action<object>> handlers = null;
if (_handlers.TryGetValue(handlerKey, out handlers))
{
var localHandlers = handlers.ToArray();
foreach (var handler in localHandlers)
{
ExecuteHandler(handler, evnt);
}
}
}
private void ExecuteHandler(Action<object> handler, dynamic evnt)
{
if (evnt.GetType().GetGenericTypeDefinition() == typeof(Event<>))
{
handler(evnt.Params);
} else
{
handler(evnt);
}
}
private void HandleResponse(ICommandResponse response)
{
if (null == response) return;
ManualResetEventSlim requestMre;
if (_requestWaitHandles.TryGetValue(response.Id, out requestMre))
{
_responses.AddOrUpdate(response.Id, id => response, (key, value) => response);
requestMre.Set();
}
else
{
// in the case of an error, we don't always get the request Id back :(
// if there is only one pending requests, we know what to do ... otherwise
if (1 == _requestWaitHandles.Count)
{
var requestId = _requestWaitHandles.Keys.First();
_requestWaitHandles.TryGetValue(requestId, out requestMre);
_responses.AddOrUpdate(requestId, id => response, (key, value) => response);
requestMre.Set();
}
}
}
private Task<ICommandResponse> SendCommand(Command command, CancellationToken cancellationToken)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new MessageContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
};
var requestString = JsonConvert.SerializeObject(command, settings);
var requestResetEvent = new ManualResetEventSlim(false);
_requestWaitHandles.AddOrUpdate(command.Id, requestResetEvent, (id, r) => requestResetEvent);
return Task.Run(() =>
{
EnsureInit();
_webSocket.Send(requestString);
requestResetEvent.Wait(cancellationToken);
ICommandResponse response = null;
_responses.TryRemove(command.Id, out response);
_requestWaitHandles.TryRemove(command.Id, out requestResetEvent);
return response;
});
}
private bool TryGetCommandResponse(byte[] data, out ICommandResponse response)
{
response = _responseFactory.Create(data);
return null != response;
}
private bool TryGetCommandResponse(string message, out ICommandResponse response)
{
response = _responseFactory.Create(message);
return null != response;
}
private bool TryGetEvent(byte[] data, out IEvent evnt)
{
evnt = _eventFactory.Create(data);
return null != evnt;
}
private bool TryGetEvent(string message, out IEvent evnt)
{
evnt = _eventFactory.Create(message);
return null != evnt;
}
private void WebSocket_Closed(object sender, EventArgs e)
{
}
private void WebSocket_DataReceived(object sender, DataReceivedEventArgs e)
{
ICommandResponse response;
if (TryGetCommandResponse(e.Data, out response))
{
HandleResponse(response);
return;
}
IEvent evnt;
if (TryGetEvent(e.Data, out evnt))
{
HandleEvent(evnt);
return;
}
throw new Exception("Don't know what to do with response: " + e.Data);
}
private void WebSocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
{
throw e.Exception;
}
private void WebSocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
ICommandResponse response;
if (TryGetCommandResponse(e.Message, out response))
{
HandleResponse(response);
return;
}
IEvent evnt;
if (TryGetEvent(e.Message, out evnt))
{
HandleEvent(evnt);
return;
}
throw new Exception("Don't know what to do with response: " + e.Message);
}
private void WebSocket_Opened(object sender, EventArgs e)
{
_openEvent.Set();
}
}
}
#endif