/
JsonHubProtocol.cs
812 lines (710 loc) · 34.6 KB
/
JsonHubProtocol.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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Internal;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.SignalR.Protocol
{
/// <summary>
/// Implements the SignalR Hub Protocol using System.Text.Json.
/// </summary>
public sealed class JsonHubProtocol : IHubProtocol
{
private const string ResultPropertyName = "result";
private static readonly JsonEncodedText ResultPropertyNameBytes = JsonEncodedText.Encode(ResultPropertyName);
private const string ItemPropertyName = "item";
private static readonly JsonEncodedText ItemPropertyNameBytes = JsonEncodedText.Encode(ItemPropertyName);
private const string InvocationIdPropertyName = "invocationId";
private static readonly JsonEncodedText InvocationIdPropertyNameBytes = JsonEncodedText.Encode(InvocationIdPropertyName);
private const string StreamIdsPropertyName = "streamIds";
private static readonly JsonEncodedText StreamIdsPropertyNameBytes = JsonEncodedText.Encode(StreamIdsPropertyName);
private const string TypePropertyName = "type";
private static readonly JsonEncodedText TypePropertyNameBytes = JsonEncodedText.Encode(TypePropertyName);
private const string ErrorPropertyName = "error";
private static readonly JsonEncodedText ErrorPropertyNameBytes = JsonEncodedText.Encode(ErrorPropertyName);
private const string AllowReconnectPropertyName = "allowReconnect";
private static readonly JsonEncodedText AllowReconnectPropertyNameBytes = JsonEncodedText.Encode(AllowReconnectPropertyName);
private const string TargetPropertyName = "target";
private static readonly JsonEncodedText TargetPropertyNameBytes = JsonEncodedText.Encode(TargetPropertyName);
private const string ArgumentsPropertyName = "arguments";
private static readonly JsonEncodedText ArgumentsPropertyNameBytes = JsonEncodedText.Encode(ArgumentsPropertyName);
private const string HeadersPropertyName = "headers";
private static readonly JsonEncodedText HeadersPropertyNameBytes = JsonEncodedText.Encode(HeadersPropertyName);
private const string ProtocolName = "json";
private const int ProtocolVersion = 1;
/// <summary>
/// Gets the serializer used to serialize invocation arguments and return values.
/// </summary>
private readonly JsonSerializerOptions _payloadSerializerOptions;
/// <summary>
/// Initializes a new instance of the <see cref="JsonHubProtocol"/> class.
/// </summary>
public JsonHubProtocol() : this(Options.Create(new JsonHubProtocolOptions()))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonHubProtocol"/> class.
/// </summary>
/// <param name="options">The options used to initialize the protocol.</param>
public JsonHubProtocol(IOptions<JsonHubProtocolOptions> options)
{
_payloadSerializerOptions = options.Value.PayloadSerializerOptions;
}
/// <inheritdoc />
public string Name => ProtocolName;
/// <inheritdoc />
public int Version => ProtocolVersion;
/// <inheritdoc />
public TransferFormat TransferFormat => TransferFormat.Text;
/// <inheritdoc />
public bool IsVersionSupported(int version)
{
return version == Version;
}
/// <inheritdoc />
public bool TryParseMessage(ref ReadOnlySequence<byte> input, IInvocationBinder binder, [NotNullWhen(true)] out HubMessage? message)
{
if (!TextMessageParser.TryParseMessage(ref input, out var payload))
{
message = null;
return false;
}
message = ParseMessage(payload, binder);
return message != null;
}
/// <inheritdoc />
public void WriteMessage(HubMessage message, IBufferWriter<byte> output)
{
WriteMessageCore(message, output);
TextMessageFormatter.WriteRecordSeparator(output);
}
/// <inheritdoc />
public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message)
{
return HubProtocolExtensions.GetMessageBytes(this, message);
}
private HubMessage? ParseMessage(ReadOnlySequence<byte> input, IInvocationBinder binder)
{
try
{
// We parse using the Utf8JsonReader directly but this has a problem. Some of our properties are dependent on other properties
// and since reading the json might be unordered, we need to store the parsed content as JsonDocument to re-parse when true types are known.
// if we're lucky and the state we need to directly parse is available, then we'll use it.
int? type = null;
string? invocationId = null;
string? target = null;
string? error = null;
var hasItem = false;
object? item = null;
var hasResult = false;
object? result = null;
var hasArguments = false;
object?[]? arguments = null;
string[]? streamIds = null;
bool hasArgumentsToken = false;
Utf8JsonReader argumentsToken = default;
bool hasItemsToken = false;
Utf8JsonReader itemsToken = default;
bool hasResultToken = false;
Utf8JsonReader resultToken = default;
ExceptionDispatchInfo? argumentBindingException = null;
Dictionary<string, string>? headers = null;
var completed = false;
var allowReconnect = false;
var reader = new Utf8JsonReader(input, isFinalBlock: true, state: default);
reader.CheckRead();
// We're always parsing a JSON object
reader.EnsureObjectStart();
do
{
switch (reader.TokenType)
{
case JsonTokenType.PropertyName:
if (reader.ValueTextEquals(TypePropertyNameBytes.EncodedUtf8Bytes))
{
type = reader.ReadAsInt32(TypePropertyName);
if (type == null)
{
throw new InvalidDataException($"Expected '{TypePropertyName}' to be of type {JsonTokenType.Number}.");
}
}
else if (reader.ValueTextEquals(InvocationIdPropertyNameBytes.EncodedUtf8Bytes))
{
invocationId = reader.ReadAsString(InvocationIdPropertyName);
}
else if (reader.ValueTextEquals(StreamIdsPropertyNameBytes.EncodedUtf8Bytes))
{
reader.CheckRead();
if (reader.TokenType != JsonTokenType.StartArray)
{
throw new InvalidDataException(
$"Expected '{StreamIdsPropertyName}' to be of type {SystemTextJsonExtensions.GetTokenString(JsonTokenType.StartArray)}.");
}
var newStreamIds = new List<string>();
reader.Read();
while (reader.TokenType != JsonTokenType.EndArray)
{
newStreamIds.Add(reader.GetString() ?? throw new InvalidDataException($"Null value for '{StreamIdsPropertyName}' is not valid."));
reader.Read();
}
streamIds = newStreamIds.ToArray();
}
else if (reader.ValueTextEquals(TargetPropertyNameBytes.EncodedUtf8Bytes))
{
target = reader.ReadAsString(TargetPropertyName);
}
else if (reader.ValueTextEquals(ErrorPropertyNameBytes.EncodedUtf8Bytes))
{
error = reader.ReadAsString(ErrorPropertyName);
}
else if (reader.ValueTextEquals(AllowReconnectPropertyNameBytes.EncodedUtf8Bytes))
{
allowReconnect = reader.ReadAsBoolean(AllowReconnectPropertyName);
}
else if (reader.ValueTextEquals(ResultPropertyNameBytes.EncodedUtf8Bytes))
{
hasResult = true;
reader.CheckRead();
if (string.IsNullOrEmpty(invocationId))
{
// If we don't have an invocation id then we need to value copy the reader so we can parse it later
hasResultToken = true;
resultToken = reader;
reader.Skip();
}
else
{
// If we have an invocation id already we can parse the end result
var returnType = binder.GetReturnType(invocationId);
result = BindType(ref reader, returnType);
}
}
else if (reader.ValueTextEquals(ItemPropertyNameBytes.EncodedUtf8Bytes))
{
reader.CheckRead();
hasItem = true;
string? id = null;
if (!string.IsNullOrEmpty(invocationId))
{
id = invocationId;
}
else
{
// If we don't have an id yet then we need to value copy the reader so we can parse it later
hasItemsToken = true;
itemsToken = reader;
reader.Skip();
continue;
}
try
{
var itemType = binder.GetStreamItemType(id);
item = BindType(ref reader, itemType);
}
catch (Exception ex)
{
return new StreamBindingFailureMessage(id, ExceptionDispatchInfo.Capture(ex));
}
}
else if (reader.ValueTextEquals(ArgumentsPropertyNameBytes.EncodedUtf8Bytes))
{
reader.CheckRead();
int initialDepth = reader.CurrentDepth;
if (reader.TokenType != JsonTokenType.StartArray)
{
throw new InvalidDataException($"Expected '{ArgumentsPropertyName}' to be of type {SystemTextJsonExtensions.GetTokenString(JsonTokenType.StartArray)}.");
}
hasArguments = true;
if (string.IsNullOrEmpty(target))
{
// We don't know the method name yet so just value copy the reader so we can parse it later
hasArgumentsToken = true;
argumentsToken = reader;
reader.Skip();
}
else
{
try
{
var paramTypes = binder.GetParameterTypes(target);
arguments = BindTypes(ref reader, paramTypes);
}
catch (Exception ex)
{
argumentBindingException = ExceptionDispatchInfo.Capture(ex);
// Could be at any point in argument array JSON when an error is thrown
// Read until the end of the argument JSON array
while (reader.CurrentDepth == initialDepth && reader.TokenType == JsonTokenType.StartArray ||
reader.CurrentDepth > initialDepth)
{
reader.CheckRead();
}
}
}
}
else if (reader.ValueTextEquals(HeadersPropertyNameBytes.EncodedUtf8Bytes))
{
reader.CheckRead();
headers = ReadHeaders(ref reader);
}
else
{
reader.CheckRead();
reader.Skip();
}
break;
case JsonTokenType.EndObject:
completed = true;
break;
}
}
while (!completed && reader.CheckRead());
HubMessage message;
switch (type)
{
case HubProtocolConstants.InvocationMessageType:
{
if (target is null)
{
throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
}
if (hasArgumentsToken)
{
// We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything.
try
{
var paramTypes = binder.GetParameterTypes(target);
arguments = BindTypes(ref argumentsToken, paramTypes);
}
catch (Exception ex)
{
argumentBindingException = ExceptionDispatchInfo.Capture(ex);
}
}
message = argumentBindingException != null
? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException)
: BindInvocationMessage(invocationId, target, arguments, hasArguments, streamIds);
}
break;
case HubProtocolConstants.StreamInvocationMessageType:
{
if (target is null)
{
throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
}
if (hasArgumentsToken)
{
// We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything.
try
{
var paramTypes = binder.GetParameterTypes(target);
arguments = BindTypes(ref argumentsToken, paramTypes);
}
catch (Exception ex)
{
argumentBindingException = ExceptionDispatchInfo.Capture(ex);
}
}
message = argumentBindingException != null
? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException)
: BindStreamInvocationMessage(invocationId, target, arguments, hasArguments, streamIds);
}
break;
case HubProtocolConstants.StreamItemMessageType:
if (invocationId is null)
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (hasItemsToken)
{
try
{
var returnType = binder.GetStreamItemType(invocationId);
item = BindType(ref itemsToken, returnType);
}
catch (JsonException ex)
{
message = new StreamBindingFailureMessage(invocationId, ExceptionDispatchInfo.Capture(ex));
break;
}
}
message = BindStreamItemMessage(invocationId, item, hasItem, binder);
break;
case HubProtocolConstants.CompletionMessageType:
if (invocationId is null)
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (hasResultToken)
{
var returnType = binder.GetReturnType(invocationId);
result = BindType(ref resultToken, returnType);
}
message = BindCompletionMessage(invocationId, error, result, hasResult, binder);
break;
case HubProtocolConstants.CancelInvocationMessageType:
message = BindCancelInvocationMessage(invocationId);
break;
case HubProtocolConstants.PingMessageType:
return PingMessage.Instance;
case HubProtocolConstants.CloseMessageType:
return BindCloseMessage(error, allowReconnect);
case null:
throw new InvalidDataException($"Missing required property '{TypePropertyName}'.");
default:
// Future protocol changes can add message types, old clients can ignore them
return null;
}
return ApplyHeaders(message, headers);
}
catch (JsonException jrex)
{
throw new InvalidDataException("Error reading JSON.", jrex);
}
}
private static Dictionary<string, string> ReadHeaders(ref Utf8JsonReader reader)
{
var headers = new Dictionary<string, string>(StringComparer.Ordinal);
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new InvalidDataException($"Expected '{HeadersPropertyName}' to be of type {JsonTokenType.StartObject}.");
}
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonTokenType.PropertyName:
var propertyName = reader.GetString()!;
reader.CheckRead();
if (reader.TokenType != JsonTokenType.String)
{
throw new InvalidDataException($"Expected header '{propertyName}' to be of type {JsonTokenType.String}.");
}
headers[propertyName] = reader.GetString()!;
break;
case JsonTokenType.Comment:
break;
case JsonTokenType.EndObject:
return headers;
}
}
throw new InvalidDataException("Unexpected end when reading message headers");
}
private void WriteMessageCore(HubMessage message, IBufferWriter<byte> stream)
{
var reusableWriter = ReusableUtf8JsonWriter.Get(stream);
try
{
var writer = reusableWriter.GetJsonWriter();
writer.WriteStartObject();
switch (message)
{
case InvocationMessage m:
WriteMessageType(writer, HubProtocolConstants.InvocationMessageType);
WriteHeaders(writer, m);
WriteInvocationMessage(m, writer);
break;
case StreamInvocationMessage m:
WriteMessageType(writer, HubProtocolConstants.StreamInvocationMessageType);
WriteHeaders(writer, m);
WriteStreamInvocationMessage(m, writer);
break;
case StreamItemMessage m:
WriteMessageType(writer, HubProtocolConstants.StreamItemMessageType);
WriteHeaders(writer, m);
WriteStreamItemMessage(m, writer);
break;
case CompletionMessage m:
WriteMessageType(writer, HubProtocolConstants.CompletionMessageType);
WriteHeaders(writer, m);
WriteCompletionMessage(m, writer);
break;
case CancelInvocationMessage m:
WriteMessageType(writer, HubProtocolConstants.CancelInvocationMessageType);
WriteHeaders(writer, m);
WriteCancelInvocationMessage(m, writer);
break;
case PingMessage _:
WriteMessageType(writer, HubProtocolConstants.PingMessageType);
break;
case CloseMessage m:
WriteMessageType(writer, HubProtocolConstants.CloseMessageType);
WriteCloseMessage(m, writer);
break;
default:
throw new InvalidOperationException($"Unsupported message type: {message.GetType().FullName}");
}
writer.WriteEndObject();
writer.Flush();
Debug.Assert(writer.CurrentDepth == 0);
}
finally
{
ReusableUtf8JsonWriter.Return(reusableWriter);
}
}
private static void WriteHeaders(Utf8JsonWriter writer, HubInvocationMessage message)
{
if (message.Headers != null && message.Headers.Count > 0)
{
writer.WriteStartObject(HeadersPropertyNameBytes);
foreach (var value in message.Headers)
{
writer.WriteString(value.Key, value.Value);
}
writer.WriteEndObject();
}
}
private void WriteCompletionMessage(CompletionMessage message, Utf8JsonWriter writer)
{
WriteInvocationId(message, writer);
if (!string.IsNullOrEmpty(message.Error))
{
writer.WriteString(ErrorPropertyNameBytes, message.Error);
}
else if (message.HasResult)
{
writer.WritePropertyName(ResultPropertyNameBytes);
if (message.Result == null)
{
writer.WriteNullValue();
}
else
{
JsonSerializer.Serialize(writer, message.Result, message.Result.GetType(), _payloadSerializerOptions);
}
}
}
private static void WriteCancelInvocationMessage(CancelInvocationMessage message, Utf8JsonWriter writer)
{
WriteInvocationId(message, writer);
}
private void WriteStreamItemMessage(StreamItemMessage message, Utf8JsonWriter writer)
{
WriteInvocationId(message, writer);
writer.WritePropertyName(ItemPropertyNameBytes);
if (message.Item == null)
{
writer.WriteNullValue();
}
else
{
JsonSerializer.Serialize(writer, message.Item, message.Item.GetType(), _payloadSerializerOptions);
}
}
private void WriteInvocationMessage(InvocationMessage message, Utf8JsonWriter writer)
{
WriteInvocationId(message, writer);
writer.WriteString(TargetPropertyNameBytes, message.Target);
WriteArguments(message.Arguments, writer);
WriteStreamIds(message.StreamIds, writer);
}
private void WriteStreamInvocationMessage(StreamInvocationMessage message, Utf8JsonWriter writer)
{
WriteInvocationId(message, writer);
writer.WriteString(TargetPropertyNameBytes, message.Target);
WriteArguments(message.Arguments, writer);
WriteStreamIds(message.StreamIds, writer);
}
private static void WriteCloseMessage(CloseMessage message, Utf8JsonWriter writer)
{
if (message.Error != null)
{
writer.WriteString(ErrorPropertyNameBytes, message.Error);
}
if (message.AllowReconnect)
{
writer.WriteBoolean(AllowReconnectPropertyNameBytes, true);
}
}
private void WriteArguments(object?[] arguments, Utf8JsonWriter writer)
{
writer.WriteStartArray(ArgumentsPropertyNameBytes);
foreach (var argument in arguments)
{
if (argument == null)
{
writer.WriteNullValue();
}
else
{
JsonSerializer.Serialize(writer, argument, argument.GetType(), _payloadSerializerOptions);
}
}
writer.WriteEndArray();
}
private static void WriteStreamIds(string[]? streamIds, Utf8JsonWriter writer)
{
if (streamIds == null)
{
return;
}
writer.WriteStartArray(StreamIdsPropertyNameBytes);
foreach (var streamId in streamIds)
{
writer.WriteStringValue(streamId);
}
writer.WriteEndArray();
}
private static void WriteInvocationId(HubInvocationMessage message, Utf8JsonWriter writer)
{
if (!string.IsNullOrEmpty(message.InvocationId))
{
writer.WriteString(InvocationIdPropertyNameBytes, message.InvocationId);
}
}
private static void WriteMessageType(Utf8JsonWriter writer, int type)
{
writer.WriteNumber(TypePropertyNameBytes, type);
}
private static HubMessage BindCancelInvocationMessage(string? invocationId)
{
if (string.IsNullOrEmpty(invocationId))
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
return new CancelInvocationMessage(invocationId);
}
private static HubMessage BindCompletionMessage(string invocationId, string? error, object? result, bool hasResult, IInvocationBinder binder)
{
if (string.IsNullOrEmpty(invocationId))
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (error != null && hasResult)
{
throw new InvalidDataException("The 'error' and 'result' properties are mutually exclusive.");
}
if (hasResult)
{
return new CompletionMessage(invocationId, error, result, hasResult: true);
}
return new CompletionMessage(invocationId, error, result: null, hasResult: false);
}
private static HubMessage BindStreamItemMessage(string invocationId, object? item, bool hasItem, IInvocationBinder binder)
{
if (string.IsNullOrEmpty(invocationId))
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (!hasItem)
{
throw new InvalidDataException($"Missing required property '{ItemPropertyName}'.");
}
return new StreamItemMessage(invocationId, item);
}
private static HubMessage BindStreamInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds)
{
if (string.IsNullOrEmpty(invocationId))
{
throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
}
if (!hasArguments)
{
throw new InvalidDataException($"Missing required property '{ArgumentsPropertyName}'.");
}
if (string.IsNullOrEmpty(target))
{
throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
}
Debug.Assert(arguments != null);
return new StreamInvocationMessage(invocationId, target, arguments, streamIds);
}
private static HubMessage BindInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds)
{
if (string.IsNullOrEmpty(target))
{
throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
}
if (!hasArguments)
{
throw new InvalidDataException($"Missing required property '{ArgumentsPropertyName}'.");
}
Debug.Assert(arguments != null);
return new InvocationMessage(invocationId, target, arguments, streamIds);
}
private object? BindType(ref Utf8JsonReader reader, Type type)
{
return JsonSerializer.Deserialize(ref reader, type, _payloadSerializerOptions);
}
private object?[] BindTypes(ref Utf8JsonReader reader, IReadOnlyList<Type> paramTypes)
{
object?[]? arguments = null;
var paramIndex = 0;
var paramCount = paramTypes.Count;
var depth = reader.CurrentDepth;
reader.CheckRead();
while (reader.TokenType != JsonTokenType.EndArray && reader.CurrentDepth > depth)
{
if (paramIndex < paramCount)
{
arguments ??= new object?[paramCount];
try
{
arguments[paramIndex] = BindType(ref reader, paramTypes[paramIndex]);
}
catch (Exception ex)
{
throw new InvalidDataException("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex);
}
}
else
{
// Skip extra arguments and throw error after reading them all
reader.Skip();
}
reader.CheckRead();
paramIndex++;
}
if (paramIndex != paramCount)
{
throw new InvalidDataException($"Invocation provides {paramIndex} argument(s) but target expects {paramCount}.");
}
return arguments ?? Array.Empty<object>();
}
private static CloseMessage BindCloseMessage(string? error, bool allowReconnect)
{
// An empty string is still an error
if (error == null && !allowReconnect)
{
return CloseMessage.Empty;
}
return new CloseMessage(error, allowReconnect);
}
private static HubMessage ApplyHeaders(HubMessage message, Dictionary<string, string>? headers)
{
if (headers != null && message is HubInvocationMessage invocationMessage)
{
invocationMessage.Headers = headers;
}
return message;
}
internal static JsonSerializerOptions CreateDefaultSerializerSettings()
{
return new JsonSerializerOptions()
{
WriteIndented = false,
ReadCommentHandling = JsonCommentHandling.Disallow,
AllowTrailingCommas = false,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
IgnoreReadOnlyProperties = false,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
MaxDepth = 64,
DictionaryKeyPolicy = null,
DefaultBufferSize = 16 * 1024,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
}
}
}