Skip to content

Commit 2a55160

Browse files
committed
Dummy but perf better
1 parent acac7d4 commit 2a55160

File tree

7 files changed

+115
-86
lines changed

7 files changed

+115
-86
lines changed

dotnet/src/webdriver/BiDi/Communication/Broker.cs

Lines changed: 86 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
using OpenQA.Selenium.BiDi.Communication.Json;
2121
using OpenQA.Selenium.BiDi.Communication.Json.Converters;
22+
using OpenQA.Selenium.BiDi.Communication.Json.Internal;
2223
using OpenQA.Selenium.BiDi.Communication.Transport;
2324
using OpenQA.Selenium.Internal.Logging;
2425
using System;
@@ -39,7 +40,7 @@ public class Broker : IAsyncDisposable
3940
private readonly BiDi _bidi;
4041
private readonly ITransport _transport;
4142

42-
private readonly ConcurrentDictionary<int, TaskCompletionSource<JsonElement>> _pendingCommands = new();
43+
private readonly ConcurrentDictionary<int, (Command, TaskCompletionSource<object>)> _pendingCommands = new();
4344
private readonly BlockingCollection<MessageEvent> _pendingEvents = [];
4445

4546
private readonly ConcurrentDictionary<string, List<EventHandler>> _eventHandlers = new();
@@ -89,7 +90,6 @@ internal Broker(BiDi bidi, Uri url)
8990
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
9091

9192
// https://github.com/dotnet/runtime/issues/72604
92-
new Json.Converters.Polymorphic.MessageConverter(),
9393
new Json.Converters.Polymorphic.EvaluateResultConverter(),
9494
new Json.Converters.Polymorphic.RemoteValueConverter(),
9595
new Json.Converters.Polymorphic.RealmInfoConverter(),
@@ -122,24 +122,72 @@ private async Task ReceiveMessagesAsync(CancellationToken cancellationToken)
122122
{
123123
while (!cancellationToken.IsCancellationRequested)
124124
{
125-
var data = await _transport.ReceiveAsync(cancellationToken).ConfigureAwait(false);
125+
try
126+
{
127+
var data = await _transport.ReceiveAsync(cancellationToken).ConfigureAwait(false);
128+
129+
Utf8JsonReader utfJsonReader = new(new ReadOnlySpan<byte>(data));
130+
utfJsonReader.Read();
131+
var messageType = utfJsonReader.GetDiscriminator("type");
132+
133+
//var message = JsonSerializer.Deserialize(new ReadOnlySpan<byte>(data), _jsonSerializerContext.Message);
134+
135+
switch (messageType)
136+
{
137+
case "success":
138+
var successId = int.Parse(utfJsonReader.GetDiscriminator("id"));
139+
var successCommand = _pendingCommands[successId];
140+
var messageSuccess = JsonSerializer.Deserialize(ref utfJsonReader, successCommand.Item1.ResultType, _jsonSerializerContext);
141+
142+
successCommand.Item2.SetResult(messageSuccess);
143+
break;
144+
145+
case "event":
146+
utfJsonReader.Read();
147+
utfJsonReader.Read();
148+
var method = utfJsonReader.GetString();
126149

127-
var message = JsonSerializer.Deserialize(new ReadOnlySpan<byte>(data), _jsonSerializerContext.Message);
150+
utfJsonReader.Read();
128151

129-
switch (message)
152+
EventArgs eventArgs = null;
153+
154+
switch (method)
155+
{
156+
case "network.beforeRequestSent":
157+
eventArgs = JsonSerializer.Deserialize(ref utfJsonReader, _jsonSerializerContext.BeforeRequestSentEventArgs);
158+
break;
159+
}
160+
161+
var messageEvent = new MessageEvent(method, eventArgs);
162+
_pendingEvents.Add(messageEvent);
163+
break;
164+
165+
case "error":
166+
var messageError = JsonSerializer.Deserialize(ref utfJsonReader, _jsonSerializerContext.MessageError);
167+
var errorCommand = _pendingCommands[messageError.Id];
168+
errorCommand.Item2.SetException(new BiDiException($"{messageError.Error}: {messageError.Message}"));
169+
break;
170+
}
171+
}
172+
catch (Exception ex)
130173
{
131-
case MessageSuccess messageSuccess:
132-
_pendingCommands[messageSuccess.Id].SetResult(messageSuccess.Result);
133-
_pendingCommands.TryRemove(messageSuccess.Id, out _);
134-
break;
135-
case MessageEvent messageEvent:
136-
_pendingEvents.Add(messageEvent);
137-
break;
138-
case MessageError mesageError:
139-
_pendingCommands[mesageError.Id].SetException(new BiDiException($"{mesageError.Error}: {mesageError.Message}"));
140-
_pendingCommands.TryRemove(mesageError.Id, out _);
141-
break;
174+
_logger.Error($"Couldn't process received message: {ex}");
142175
}
176+
177+
//switch (message)
178+
//{
179+
// case MessageSuccess messageSuccess:
180+
// _pendingCommands[messageSuccess.Id].SetResult(messageSuccess.Result);
181+
// _pendingCommands.TryRemove(messageSuccess.Id, out _);
182+
// break;
183+
// case MessageEvent messageEvent:
184+
// _pendingEvents.Add(messageEvent);
185+
// break;
186+
// case MessageError mesageError:
187+
// _pendingCommands[mesageError.Id].SetException(new BiDiException($"{mesageError.Error}: {mesageError.Message}"));
188+
// _pendingCommands.TryRemove(mesageError.Id, out _);
189+
// break;
190+
//}
143191
}
144192
}
145193

@@ -155,7 +203,7 @@ private async Task ProcessEventsAwaiterAsync()
155203
{
156204
foreach (var handler in eventHandlers.ToArray()) // copy handlers avoiding modified collection while iterating
157205
{
158-
var args = (EventArgs)result.Params.Deserialize(handler.EventArgsType, _jsonSerializerContext)!;
206+
var args = result.Params;
159207

160208
args.BiDi = _bidi;
161209

@@ -183,40 +231,51 @@ private async Task ProcessEventsAwaiterAsync()
183231
}
184232
}
185233

186-
public async Task<TResult> ExecuteCommandAsync<TCommand, TResult>(TCommand command, CommandOptions? options)
234+
public async Task ExecuteCommandAsync<TCommand>(TCommand command, CommandOptions? options)
187235
where TCommand : Command
188236
{
189-
var jsonElement = await ExecuteCommandCoreAsync(command, options).ConfigureAwait(false);
190-
191-
return (TResult)jsonElement.Deserialize(typeof(TResult), _jsonSerializerContext)!;
237+
await ExecuteCommandCoreAsync(command, options).ConfigureAwait(false);
192238
}
193239

194-
public async Task ExecuteCommandAsync<TCommand>(TCommand command, CommandOptions? options)
240+
public async Task<TResult> ExecuteCommandAsync<TCommand, TResult>(TCommand command, CommandOptions? options)
195241
where TCommand : Command
196242
{
197-
await ExecuteCommandCoreAsync(command, options).ConfigureAwait(false);
243+
//var jsonElement = await ExecuteCommandCoreAsync(command, options).ConfigureAwait(false);
244+
245+
//return (TResult)jsonElement.Deserialize(typeof(TResult), _jsonSerializerContext)!;
246+
247+
var result = await ExecuteCommandCoreAsync(command, options).ConfigureAwait(false);
248+
249+
return ((MessageSuccess<TResult>)result).Result;
198250
}
199251

200-
private async Task<JsonElement> ExecuteCommandCoreAsync<TCommand>(TCommand command, CommandOptions? options)
252+
private async Task<object> ExecuteCommandCoreAsync<TCommand>(TCommand command, CommandOptions? options)
201253
where TCommand : Command
202254
{
203255
command.Id = Interlocked.Increment(ref _currentCommandId);
204256

205-
var tcs = new TaskCompletionSource<JsonElement>(TaskCreationOptions.RunContinuationsAsynchronously);
257+
var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
258+
259+
//var cancellationToken = new CancellationToken();
260+
261+
//using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
206262

207263
var timeout = options?.Timeout ?? TimeSpan.FromSeconds(30);
208264

265+
//cts.CancelAfter(timeout);
266+
267+
209268
using var cts = new CancellationTokenSource(timeout);
210269

211270
cts.Token.Register(() => tcs.TrySetCanceled(cts.Token));
212271

213-
_pendingCommands[command.Id] = tcs;
272+
_pendingCommands[command.Id] = (command, tcs);
214273

215274
var data = JsonSerializer.SerializeToUtf8Bytes(command, typeof(TCommand), _jsonSerializerContext);
216275

217276
await _transport.SendAsync(data, cts.Token).ConfigureAwait(false);
218277

219-
return await tcs.Task.ConfigureAwait(false);
278+
return await tcs.Task;
220279
}
221280

222281
public async Task<Subscription> SubscribeAsync<TEventArgs>(string eventName, Action<TEventArgs> action, SubscriptionOptions? options = null)

dotnet/src/webdriver/BiDi/Communication/Command.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,30 @@
1717
// under the License.
1818
// </copyright>
1919

20+
using System;
2021
using System.Text.Json.Serialization;
2122

2223
namespace OpenQA.Selenium.BiDi.Communication;
2324

2425
public abstract class Command
2526
{
26-
protected Command(string method)
27+
protected Command(string method, Type resultType)
2728
{
2829
Method = method;
30+
ResultType = resultType;
2931
}
3032

3133
[JsonPropertyOrder(1)]
3234
public string Method { get; }
3335

3436
[JsonPropertyOrder(0)]
3537
public int Id { get; internal set; }
38+
39+
[JsonIgnore]
40+
public Type ResultType { get; }
3641
}
3742

38-
internal abstract class Command<TCommandParameters, TCommandResult>(TCommandParameters @params, string method) : Command(method)
43+
internal abstract class Command<TCommandParameters, TCommandResult>(TCommandParameters @params, string method) : Command(method, typeof(MessageSuccess<TCommandResult>))
3944
where TCommandParameters : CommandParameters
4045
where TCommandResult : EmptyResult
4146
{

dotnet/src/webdriver/BiDi/Communication/Json/BiDiJsonSerializerContext.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323
namespace OpenQA.Selenium.BiDi.Communication.Json;
2424

2525
#region https://github.com/dotnet/runtime/issues/72604
26-
[JsonSerializable(typeof(MessageSuccess))]
26+
//[JsonSerializable(typeof(MessageSuccess))]
27+
[JsonSerializable(typeof(MessageSuccess<EmptyResult>))]
2728
[JsonSerializable(typeof(MessageError))]
2829
[JsonSerializable(typeof(MessageEvent))]
2930

@@ -79,7 +80,7 @@ namespace OpenQA.Selenium.BiDi.Communication.Json;
7980
[JsonSerializable(typeof(Modules.Session.NewResult))]
8081
[JsonSerializable(typeof(Modules.Session.EndCommand))]
8182
[JsonSerializable(typeof(Modules.Session.SubscribeCommand))]
82-
[JsonSerializable(typeof(Modules.Session.SubscribeResult))]
83+
[JsonSerializable(typeof(MessageSuccess<Modules.Session.SubscribeResult>))]
8384
[JsonSerializable(typeof(Modules.Session.UnsubscribeByIdCommand))]
8485
[JsonSerializable(typeof(Modules.Session.UnsubscribeByAttributesCommand))]
8586

@@ -97,17 +98,17 @@ namespace OpenQA.Selenium.BiDi.Communication.Json;
9798

9899
[JsonSerializable(typeof(Modules.BrowsingContext.ActivateCommand))]
99100
[JsonSerializable(typeof(Modules.BrowsingContext.CaptureScreenshotCommand))]
100-
[JsonSerializable(typeof(Modules.BrowsingContext.CaptureScreenshotResult))]
101+
[JsonSerializable(typeof(MessageSuccess<Modules.BrowsingContext.CaptureScreenshotResult>))]
101102
[JsonSerializable(typeof(Modules.BrowsingContext.CloseCommand), TypeInfoPropertyName = "BrowsingContext_CloseCommand")]
102103
[JsonSerializable(typeof(Modules.BrowsingContext.CreateCommand))]
103104
[JsonSerializable(typeof(Modules.BrowsingContext.CreateResult))]
104105
[JsonSerializable(typeof(Modules.BrowsingContext.GetTreeCommand))]
105-
[JsonSerializable(typeof(Modules.BrowsingContext.GetTreeResult))]
106+
[JsonSerializable(typeof(MessageSuccess<Modules.BrowsingContext.GetTreeResult>))]
106107
[JsonSerializable(typeof(Modules.BrowsingContext.HandleUserPromptCommand))]
107108
[JsonSerializable(typeof(Modules.BrowsingContext.LocateNodesCommand))]
108-
[JsonSerializable(typeof(Modules.BrowsingContext.LocateNodesResult))]
109+
[JsonSerializable(typeof(MessageSuccess<Modules.BrowsingContext.LocateNodesResult>))]
109110
[JsonSerializable(typeof(Modules.BrowsingContext.NavigateCommand))]
110-
[JsonSerializable(typeof(Modules.BrowsingContext.NavigateResult))]
111+
[JsonSerializable(typeof(MessageSuccess<Modules.BrowsingContext.NavigateResult>))]
111112
[JsonSerializable(typeof(Modules.BrowsingContext.PrintCommand))]
112113
[JsonSerializable(typeof(Modules.BrowsingContext.PrintResult))]
113114
[JsonSerializable(typeof(Modules.BrowsingContext.ReloadCommand))]
@@ -141,7 +142,7 @@ namespace OpenQA.Selenium.BiDi.Communication.Json;
141142
[JsonSerializable(typeof(Modules.Script.DisownCommand))]
142143
[JsonSerializable(typeof(Modules.Script.CallFunctionCommand))]
143144
[JsonSerializable(typeof(Modules.Script.EvaluateCommand))]
144-
[JsonSerializable(typeof(Modules.Script.EvaluateResult))]
145+
[JsonSerializable(typeof(MessageSuccess<Modules.Script.EvaluateResult>))]
145146
[JsonSerializable(typeof(Modules.Script.GetRealmsCommand))]
146147
[JsonSerializable(typeof(Modules.Script.GetRealmsResult))]
147148
[JsonSerializable(typeof(Modules.Script.RemovePreloadScriptCommand))]

dotnet/src/webdriver/BiDi/Communication/Json/Converters/Polymorphic/MessageConverter.cs

Lines changed: 0 additions & 45 deletions
This file was deleted.

dotnet/src/webdriver/BiDi/Communication/Json/Internal/JsonExtensions.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,15 @@ public static string GetDiscriminator(this ref Utf8JsonReader reader, string nam
4040

4141
if (propertyName == name)
4242
{
43-
discriminator = readerClone.GetString();
43+
if (readerClone.TokenType == JsonTokenType.Number)
44+
{
45+
discriminator = readerClone.GetInt64().ToString();
46+
}
47+
else
48+
{
49+
discriminator = readerClone.GetString();
50+
}
51+
4452
break;
4553
}
4654

dotnet/src/webdriver/BiDi/Communication/Message.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
// under the License.
1818
// </copyright>
1919

20-
using System.Text.Json;
20+
using System;
2121

2222
namespace OpenQA.Selenium.BiDi.Communication;
2323

@@ -28,7 +28,7 @@ namespace OpenQA.Selenium.BiDi.Communication;
2828
//[JsonDerivedType(typeof(MessageEvent), "event")]
2929
internal abstract record Message;
3030

31-
internal record MessageSuccess(int Id, JsonElement Result) : Message;
31+
internal record MessageSuccess<T>(int Id, T Result) : Message;
3232

3333
internal record MessageError(int Id) : Message
3434
{
@@ -37,4 +37,5 @@ internal record MessageError(int Id) : Message
3737
public string? Message { get; set; }
3838
}
3939

40-
internal record MessageEvent(string Method, JsonElement Params) : Message;
40+
internal record MessageEvent(string Method, EventArgs Params) : Message;
41+

dotnet/src/webdriver/WebDriver.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<TargetFrameworks>netstandard2.0;net8.0;</TargetFrameworks>
55
<AssemblyName>WebDriver</AssemblyName>
66
<RootNamespace>OpenQA.Selenium</RootNamespace>
7-
<LangVersion>12.0</LangVersion>
7+
<LangVersion>13.0</LangVersion>
88
<Nullable>enable</Nullable>
99
</PropertyGroup>
1010

0 commit comments

Comments
 (0)