1919
2020using OpenQA . Selenium . BiDi . Communication . Json ;
2121using OpenQA . Selenium . BiDi . Communication . Json . Converters ;
22+ using OpenQA . Selenium . BiDi . Communication . Json . Internal ;
2223using OpenQA . Selenium . BiDi . Communication . Transport ;
2324using OpenQA . Selenium . Internal . Logging ;
2425using 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 )
0 commit comments