-
Notifications
You must be signed in to change notification settings - Fork 1
/
BrowserHttpHandler.cs
674 lines (581 loc) · 27.9 KB
/
BrowserHttpHandler.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
#nullable enable
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using JSObject = System.Runtime.InteropServices.JavaScript.JSObject;
using JSException = System.Runtime.InteropServices.JavaScript.JSException;
using HostObject = System.Runtime.InteropServices.JavaScript.HostObject;
using Uint8Array = System.Runtime.InteropServices.JavaScript.Uint8Array;
using Function = System.Runtime.InteropServices.JavaScript.Function;
using System.Buffers;
namespace Client
{
// **Note** on `Task.ConfigureAwait(continueOnCapturedContext: true)` for the WebAssembly Browser.
// The current implementation of WebAssembly for the Browser does not have a SynchronizationContext nor a Scheduler
// thus forcing the callbacks to run on the main browser thread. When threading is eventually implemented using
// emscripten's threading model of remote worker threads, via SharedArrayBuffer, any API calls will have to be
// remoted back to the main thread. Most APIs only work on the main browser thread.
// During discussions the concensus has been that it will not matter right now which value is used for ConfigureAwait
// we should put this in place now.
internal sealed class BrowserHttpHandler
{
// This partial implementation contains members common to Browser WebAssembly running on .NET Core.
private static readonly JSObject? s_fetch = (JSObject)System.Runtime.InteropServices.JavaScript.Runtime.GetGlobalObject("fetch");
private static readonly JSObject? s_window = (JSObject)System.Runtime.InteropServices.JavaScript.Runtime.GetGlobalObject("window");
internal static readonly HttpRequestOptionsKey<bool> EnableStreamingRequest = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingRequest");
internal static readonly HttpRequestOptionsKey<bool> EnableStreamingResponse = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse");
private static readonly HttpRequestOptionsKey<IDictionary<string, object>> FetchOptions = new HttpRequestOptionsKey<IDictionary<string, object>>("WebAssemblyFetchOptions");
private bool _allowAutoRedirect = false;
// flag to determine if the _allowAutoRedirect was explicitly set or not.
private bool _isAllowAutoRedirectTouched;
/// <summary>
/// Gets whether the current Browser supports streaming requests
/// </summary>
private static bool StreamingRequestSupported { get; } = GetIsStreamingRequestSupported();
private static bool GetIsStreamingRequestSupported()
{
using (var streamingRequestSupported = new Function("return typeof Request !== 'undefined' && 'body' in Request.prototype && typeof ReadableStream === 'function' && !new Request('', { body: new ReadableStream(), method: 'POST' }).headers.has('Content-Type')"))
return (bool)streamingRequestSupported.Call();
}
/// <summary>
/// Gets whether the current Browser supports streaming responses
/// </summary>
private static bool StreamingSupported { get; } = GetIsStreamingSupported();
private static bool GetIsStreamingSupported()
{
using (var streamingSupported = new Function("return typeof Response !== 'undefined' && 'body' in Response.prototype && typeof ReadableStream === 'function'"))
return (bool)streamingSupported.Call();
}
public bool UseCookies
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public CookieContainer CookieContainer
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public DecompressionMethods AutomaticDecompression
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public bool UseProxy
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public IWebProxy? Proxy
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public ICredentials? DefaultProxyCredentials
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public bool PreAuthenticate
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public ICredentials? Credentials
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public bool AllowAutoRedirect
{
get => _allowAutoRedirect;
set
{
_allowAutoRedirect = value;
_isAllowAutoRedirectTouched = true;
}
}
public int MaxAutomaticRedirections
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public int MaxConnectionsPerServer
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public int MaxResponseHeadersLength
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public SslClientAuthenticationOptions SslOptions
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}
public const bool SupportsAutomaticDecompression = false;
public const bool SupportsProxy = false;
public const bool SupportsRedirectConfiguration = true;
private Dictionary<string, object?>? _properties;
public IDictionary<string, object?> Properties => _properties ??= new Dictionary<string, object?>();
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
try
{
var requestObject = new JSObject();
if (request.Options.TryGetValue(FetchOptions, out IDictionary<string, object>? fetchOptions))
{
foreach (KeyValuePair<string, object> item in fetchOptions)
{
requestObject.SetObjectProperty(item.Key, item.Value);
}
}
requestObject.SetObjectProperty("method", request.Method.Method);
// Only set if property was specifically modified and is not default value
if (_isAllowAutoRedirectTouched)
{
// Allowing or Disallowing redirects.
// Here we will set redirect to `manual` instead of error if AllowAutoRedirect is
// false so there is no exception thrown
//
// https://developer.mozilla.org/en-US/docs/Web/API/Response/type
//
// other issues from whatwg/fetch:
//
// https://github.com/whatwg/fetch/issues/763
// https://github.com/whatwg/fetch/issues/601
requestObject.SetObjectProperty("redirect", AllowAutoRedirect ? "follow" : "manual");
}
CancellationTokenSource abortCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
WasmRequestReadableStream? wasmRequestReadableStream = null;
// We need to check for body content
if (request.Content != null)
{
bool streamingRequestEnabled = false;
if (StreamingRequestSupported)
{
request.Options.TryGetValue(EnableStreamingRequest, out streamingRequestEnabled);
}
if (streamingRequestEnabled)
{
wasmRequestReadableStream = new WasmRequestReadableStream(request, abortCts);
using (JSObject obj = new JSObject())
{
obj.SetObjectProperty("pull", (Func<JSObject, Task>)wasmRequestReadableStream.Pull);
using (var readableStream = new HostObject("ReadableStream", obj))
{
requestObject.SetObjectProperty("body", readableStream);
}
}
}
else if (request.Content is StringContent)
{
requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true));
}
else
{
using (Uint8Array uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true)))
{
requestObject.SetObjectProperty("body", uint8Buffer);
}
}
}
// Process headers
// Cors has its own restrictions on headers.
// https://developer.mozilla.org/en-US/docs/Web/API/Headers
using (HostObject jsHeaders = new HostObject("Headers"))
{
foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers)
{
foreach (string value in header.Value)
{
jsHeaders.Invoke("append", header.Key, value);
}
}
if (request.Content != null)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in request.Content.Headers)
{
foreach (string value in header.Value)
{
jsHeaders.Invoke("append", header.Key, value);
}
}
}
requestObject.SetObjectProperty("headers", jsHeaders);
}
WasmHttpReadStream? wasmHttpReadStream = null;
JSObject abortController = new HostObject("AbortController");
JSObject signal = (JSObject)abortController.GetObjectProperty("signal");
requestObject.SetObjectProperty("signal", signal);
signal.Dispose();
CancellationTokenRegistration abortRegistration = abortCts.Token.Register((Action)(() =>
{
if (abortController.JSHandle != -1)
{
abortController.Invoke("abort");
abortController.Dispose();
}
wasmRequestReadableStream?.Dispose();
wasmHttpReadStream?.Dispose();
abortCts.Dispose();
}));
var args = new System.Runtime.InteropServices.JavaScript.Array();
if (request.RequestUri != null)
{
args.Push(request.RequestUri.ToString());
args.Push(requestObject);
}
requestObject.Dispose();
var response = s_fetch?.Invoke("apply", s_window, args) as Task<object>;
args.Dispose();
if (response == null)
throw new Exception();
JSObject t = (JSObject)await response.ConfigureAwait(continueOnCapturedContext: true);
var status = new WasmFetchResponse(t, abortController, wasmRequestReadableStream, abortCts, abortRegistration);
HttpResponseMessage httpResponse = new HttpResponseMessage((HttpStatusCode)status.Status);
httpResponse.RequestMessage = request;
// Here we will set the ReasonPhrase so that it can be evaluated later.
// We do not have a status code but this will signal some type of what happened
// after interrogating the status code for success or not i.e. IsSuccessStatusCode
//
// https://developer.mozilla.org/en-US/docs/Web/API/Response/type
// opaqueredirect: The fetch request was made with redirect: "manual".
// The Response's status is 0, headers are empty, body is null and trailer is empty.
if (status.ResponseType == "opaqueredirect")
{
//httpResponse.SetReasonPhraseWithoutValidation(status.ResponseType);
}
bool streamingEnabled = false;
if (StreamingSupported)
{
request.Options.TryGetValue(EnableStreamingResponse, out streamingEnabled);
}
httpResponse.Content = streamingEnabled
? new StreamContent(wasmHttpReadStream = new WasmHttpReadStream(status))
: (HttpContent)new BrowserHttpContent(status);
// Fill the response headers
// CORS will only allow access to certain headers.
// If a request is made for a resource on another origin which returns the CORs headers, then the type is cors.
// cors and basic responses are almost identical except that a cors response restricts the headers you can view to
// `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`.
// View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
//
// Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation
using (JSObject respHeaders = status.Headers)
{
if (respHeaders != null)
{
using (var entriesIterator = (JSObject)respHeaders.Invoke("entries"))
{
JSObject? nextResult = null;
try
{
nextResult = (JSObject)entriesIterator.Invoke("next");
while (!(bool)nextResult.GetObjectProperty("done"))
{
using (var resultValue = (System.Runtime.InteropServices.JavaScript.Array)nextResult.GetObjectProperty("value"))
{
var name = (string)resultValue[0];
var value = (string)resultValue[1];
if (!httpResponse.Headers.TryAddWithoutValidation(name, value))
httpResponse.Content.Headers.TryAddWithoutValidation(name, value);
}
nextResult?.Dispose();
nextResult = (JSObject)entriesIterator.Invoke("next");
}
}
finally
{
nextResult?.Dispose();
}
}
}
}
return httpResponse;
}
catch (JSException jsExc)
{
throw new System.Net.Http.HttpRequestException(jsExc.Message);
}
}
private sealed class WasmRequestReadableStream : IDisposable
{
private const int BufferSize = 1024 * 1024;
private readonly HttpRequestMessage _request;
private readonly CancellationTokenSource _abortCts;
private byte[]? _requestBuffer;
private Stream? _requestStream;
private bool _isDisposed;
public WasmRequestReadableStream(HttpRequestMessage request, CancellationTokenSource abortCts)
{
_request = request;
_abortCts = abortCts;
}
public async Task Pull(JSObject controller)
{
try
{
using (controller)
{
if (_requestBuffer == null)
{
_requestBuffer = ArrayPool<byte>.Shared.Rent(BufferSize);
}
if (_requestStream == null)
{
_requestStream = await _request.Content!.ReadAsStreamAsync(_abortCts.Token).ConfigureAwait(continueOnCapturedContext: true);
}
int count = await _requestStream.ReadAsync(new Memory<byte>(_requestBuffer), _abortCts.Token).ConfigureAwait(continueOnCapturedContext: true);
if (count > 0)
{
using (Uint8Array uint8Buffer = Uint8Array.From(_requestBuffer.AsSpan(0, count)))
{
controller.Invoke("enqueue", uint8Buffer);
}
}
else
{
controller.Invoke("close");
}
}
}
catch
{
if (!_abortCts.IsCancellationRequested)
{
_abortCts.Cancel();
}
}
}
public void Dispose()
{
if (_isDisposed)
return;
_isDisposed = true;
if (_requestBuffer != null)
{
ArrayPool<byte>.Shared.Return(_requestBuffer);
_requestBuffer = null;
}
_requestStream?.Dispose();
}
}
private sealed class WasmFetchResponse : IDisposable
{
private readonly JSObject _fetchResponse;
private readonly JSObject _abortController;
private readonly WasmRequestReadableStream _requestStream;
private readonly CancellationTokenSource _abortCts;
private readonly CancellationTokenRegistration _abortRegistration;
private bool _isDisposed;
public WasmFetchResponse(JSObject fetchResponse, JSObject abortController, WasmRequestReadableStream requestStream, CancellationTokenSource abortCts, CancellationTokenRegistration abortRegistration)
{
_fetchResponse = fetchResponse ?? throw new ArgumentNullException(nameof(fetchResponse));
_abortController = abortController ?? throw new ArgumentNullException(nameof(abortController));
_requestStream = requestStream;
_abortCts = abortCts;
_abortRegistration = abortRegistration;
}
public bool IsOK => (bool)_fetchResponse.GetObjectProperty("ok");
public bool IsRedirected => (bool)_fetchResponse.GetObjectProperty("redirected");
public int Status => (int)_fetchResponse.GetObjectProperty("status");
public string StatusText => (string)_fetchResponse.GetObjectProperty("statusText");
public string ResponseType => (string)_fetchResponse.GetObjectProperty("type");
public string Url => (string)_fetchResponse.GetObjectProperty("url");
public bool IsBodyUsed => (bool)_fetchResponse.GetObjectProperty("bodyUsed");
public JSObject Headers => (JSObject)_fetchResponse.GetObjectProperty("headers");
public JSObject Body => (JSObject)_fetchResponse.GetObjectProperty("body");
public Task<object> ArrayBuffer() => (Task<object>)_fetchResponse.Invoke("arrayBuffer");
public Task<object> Text() => (Task<object>)_fetchResponse.Invoke("text");
public Task<object> JSON() => (Task<object>)_fetchResponse.Invoke("json");
public void Dispose()
{
if (_isDisposed)
return;
_isDisposed = true;
_abortCts.Dispose();
_abortRegistration.Dispose();
_requestStream?.Dispose();
_fetchResponse?.Dispose();
_abortController?.Dispose();
}
}
private sealed class BrowserHttpContent : HttpContent
{
private byte[]? _data;
private readonly WasmFetchResponse _status;
public BrowserHttpContent(WasmFetchResponse status)
{
_status = status ?? throw new ArgumentNullException(nameof(status));
}
private async Task<byte[]> GetResponseData()
{
if (_data != null)
{
return _data;
}
using (System.Runtime.InteropServices.JavaScript.ArrayBuffer dataBuffer = (System.Runtime.InteropServices.JavaScript.ArrayBuffer)await _status.ArrayBuffer().ConfigureAwait(continueOnCapturedContext: true))
{
using (Uint8Array dataBinView = new Uint8Array(dataBuffer))
{
_data = dataBinView.ToArray();
_status.Dispose();
}
}
return _data;
}
protected override async Task<Stream> CreateContentReadStreamAsync()
{
byte[] data = await GetResponseData().ConfigureAwait(continueOnCapturedContext: true);
return new MemoryStream(data, writable: false);
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) =>
SerializeToStreamAsync(stream, context, CancellationToken.None);
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken)
{
byte[] data = await GetResponseData().ConfigureAwait(continueOnCapturedContext: true);
await stream.WriteAsync(data, cancellationToken).ConfigureAwait(continueOnCapturedContext: true);
}
protected override bool TryComputeLength(out long length)
{
if (_data != null)
{
length = _data.Length;
return true;
}
length = 0;
return false;
}
protected override void Dispose(bool disposing)
{
_status?.Dispose();
base.Dispose(disposing);
}
}
private sealed class WasmHttpReadStream : Stream
{
private WasmFetchResponse? _status;
private JSObject? _reader;
private byte[]? _bufferedBytes;
private int _position;
public WasmHttpReadStream(WasmFetchResponse status)
{
_status = status;
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
//ValidateBufferArguments(buffer, offset, count);
return ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
}
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
{
if (_reader == null)
{
// If we've read everything, then _reader and _status will be null
if (_status == null)
{
return 0;
}
try
{
using (JSObject body = _status.Body)
{
_reader = (JSObject)body.Invoke("getReader");
}
}
catch (JSException)
{
cancellationToken.ThrowIfCancellationRequested();
throw;
}
}
if (_bufferedBytes != null && _position < _bufferedBytes.Length)
{
return ReadBuffered();
}
try
{
var t = (Task<object>)_reader.Invoke("read");
using (var read = (JSObject)await t.ConfigureAwait(continueOnCapturedContext: true))
{
if ((bool)read.GetObjectProperty("done"))
{
_reader.Dispose();
_reader = null;
_status?.Dispose();
_status = null;
return 0;
}
_position = 0;
// value for fetch streams is a Uint8Array
using (Uint8Array binValue = (Uint8Array)read.GetObjectProperty("value"))
_bufferedBytes = binValue.ToArray();
}
}
catch (JSException)
{
cancellationToken.ThrowIfCancellationRequested();
throw;
}
return ReadBuffered();
int ReadBuffered()
{
int n = Math.Min(_bufferedBytes.Length - _position, buffer.Length);
if (n <= 0)
{
return 0;
}
_bufferedBytes.AsSpan(_position, n).CopyTo(buffer.Span);
_position += n;
return n;
}
}
protected override void Dispose(bool disposing)
{
_reader?.Dispose();
_status?.Dispose();
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}
}