aboutsummaryrefslogtreecommitdiff
path: root/Plugins.Essentials/src/Extensions/EssentialHttpEventExtensions.cs
blob: 9458487ed8ee20ed8e692804c61d1c25daeeb6c4 (plain)
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
/*
* Copyright (c) 2022 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials
* File: EssentialHttpEventExtensions.cs 
*
* EssentialHttpEventExtensions.cs is part of VNLib.Plugins.Essentials which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Essentials is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

using VNLib.Net.Http;
using VNLib.Hashing;
using VNLib.Utils;
using VNLib.Utils.Extensions;
using VNLib.Utils.Memory.Caching;
using static VNLib.Plugins.Essentials.Statics;

#nullable enable

namespace VNLib.Plugins.Essentials.Extensions
{

    /// <summary>
    /// Provides extension methods for manipulating <see cref="HttpEvent"/>s
    /// </summary>
    public static class EssentialHttpEventExtensions
    {      
        public const string BEARER_STRING = "Bearer";
        private static readonly int BEARER_LEN = BEARER_STRING.Length;

        /*
         * Pooled/tlocal serializers
         */
        private static ThreadLocal<Utf8JsonWriter> LocalSerializer { get; } = new(() => new(Stream.Null));
        private static IObjectRental<JsonResponse> ResponsePool { get; } = ObjectRental.Create(ResponseCtor);
        private static JsonResponse ResponseCtor() => new(ResponsePool);

        #region Response Configuring

        /// <summary>
        /// Attempts to serialize the JSON object (with default SR_OPTIONS) to binary and configure the response for a JSON message body
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ev"></param>
        /// <param name="code">The <see cref="HttpStatusCode"/> result of the connection</param>
        /// <param name="response">The JSON object to serialzie and send as response body</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponseJson<T>(this IHttpEvent ev, HttpStatusCode code, T response) => CloseResponseJson(ev, code, response, SR_OPTIONS);

        /// <summary>
        /// Attempts to serialize the JSON object to binary and configure the response for a JSON message body
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ev"></param>
        /// <param name="code">The <see cref="HttpStatusCode"/> result of the connection</param>
        /// <param name="response">The JSON object to serialzie and send as response body</param>
        /// <param name="options"><see cref="JsonSerializerOptions"/> to use during serialization</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponseJson<T>(this IHttpEvent ev, HttpStatusCode code, T response, JsonSerializerOptions? options)
        {
            JsonResponse rbuf = ResponsePool.Rent();
            try
            {
                //Serialze the object on the thread local serializer
                LocalSerializer.Value!.Serialize(rbuf, response, options);

                //Set the response as the buffer, 
                ev.CloseResponse(code, ContentType.Json, rbuf);
            }
            catch
            {
                //Return back to pool on error
                ResponsePool.Return(rbuf);
                throw;
            }
        }

        /// <summary>
        /// Attempts to serialize the JSON object to binary and configure the response for a JSON message body
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">The <see cref="HttpStatusCode"/> result of the connection</param>
        /// <param name="response">The JSON object to serialzie and send as response body</param>
        /// <param name="type">The type to use during de-serialization</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponseJson(this IHttpEvent ev, HttpStatusCode code, object response, Type type) => CloseResponseJson(ev, code, response, type, SR_OPTIONS);
        
        /// <summary>
        /// Attempts to serialize the JSON object to binary and configure the response for a JSON message body
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">The <see cref="HttpStatusCode"/> result of the connection</param>
        /// <param name="response">The JSON object to serialzie and send as response body</param>
        /// <param name="type">The type to use during de-serialization</param>
        /// <param name="options"><see cref="JsonSerializerOptions"/> to use during serialization</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponseJson(this IHttpEvent ev, HttpStatusCode code, object response, Type type, JsonSerializerOptions? options)
        {
            JsonResponse rbuf = ResponsePool.Rent();
            try
            {
                //Serialze the object on the thread local serializer
                LocalSerializer.Value!.Serialize(rbuf, response, type, options);

                //Set the response as the buffer, 
                ev.CloseResponse(code, ContentType.Json, rbuf);
            }
            catch
            {
                //Return back to pool on error
                ResponsePool.Return(rbuf);
                throw;
            }
        }

        /// <summary>
        /// Writes the <see cref="JsonDocument"/> data to a temporary buffer and sets it as the response
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">The <see cref="HttpStatusCode"/> result of the connection</param>
        /// <param name="data">The <see cref="JsonDocument"/> data to send to client</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponseJson(this IHttpEvent ev, HttpStatusCode code, JsonDocument data)
        {
            if(data == null)
            {
                ev.CloseResponse(code);
                return;
            }

            JsonResponse rbuf = ResponsePool.Rent();
            try
            {
                //Serialze the object on the thread local serializer
                LocalSerializer.Value!.Serialize(rbuf, data);

                //Set the response as the buffer, 
                ev.CloseResponse(code, ContentType.Json, rbuf);
            }
            catch
            {
                //Return back to pool on error
                ResponsePool.Return(rbuf);
                throw;
            }
        }

        /// <summary>
        /// Close as response to a client with an <see cref="HttpStatusCode.OK"/> and serializes a <see cref="WebMessage"/> as the message response
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="webm">The <see cref="WebMessage"/> to serialize and response to client with</param>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponse<T>(this IHttpEvent ev, T webm) where T:WebMessage
        {
            if (webm == null)
            {
                ev.CloseResponse(HttpStatusCode.OK);
            }
            else
            {
                //Respond with json data
                ev.CloseResponseJson(HttpStatusCode.OK, webm);
            }
        }

        /// <summary>
        /// Close a response to a connection with a file as an attachment (set content dispostion)
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">Status code</param>
        /// <param name="file">The <see cref="FileInfo"/> of the desired file to attach</param>
        /// <exception cref="IOException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        /// <exception cref="System.Security.SecurityException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponseAttachment(this IHttpEvent ev, HttpStatusCode code, FileInfo file)
        {
            //Close with file
            ev.CloseResponse(code, file);
            //Set content dispostion as attachment (only if successfull)
            ev.Server.Headers["Content-Disposition"] = $"attachment; filename=\"{file.Name}\"";
        }
        
        /// <summary>
        /// Close a response to a connection with a file as an attachment (set content dispostion)
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">Status code</param>
        /// <param name="file">The <see cref="FileStream"/> of the desired file to attach</param>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponseAttachment(this IHttpEvent ev, HttpStatusCode code, FileStream file)
        {
            //Close with file
            ev.CloseResponse(code, file);
            //Set content dispostion as attachment (only if successfull)
            ev.Server.Headers["Content-Disposition"] = $"attachment; filename=\"{file.Name}\"";
        }
       
        /// <summary>
        /// Close a response to a connection with a file as an attachment (set content dispostion)
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">Status code</param>
        /// <param name="data">The data to straem to the client as an attatcment</param>
        /// <param name="ct">The <see cref="ContentType"/> that represents the file</param>
        /// <param name="fileName">The name of the file to attach</param>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponseAttachment(this IHttpEvent ev, HttpStatusCode code, ContentType ct, Stream data, string fileName)
        {
            //Close with file
            ev.CloseResponse(code, ct, data);
            //Set content dispostion as attachment (only if successfull)
            ev.Server.Headers["Content-Disposition"] = $"attachment; filename=\"{fileName}\"";
        }

        /// <summary>
        /// Close a response to a connection with a file as the entire response body (not attachment)
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">Status code</param>
        /// <param name="file">The <see cref="FileInfo"/> of the desired file to attach</param>
        /// <exception cref="IOException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        /// <exception cref="System.Security.SecurityException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponse(this IHttpEvent ev, HttpStatusCode code, FileInfo file)
        {
            //Open filestream for file
            FileStream fs = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
            try
            {
                //Set the input as a stream
                ev.CloseResponse(code, fs);
                //Set last modified time only if successfull
                ev.Server.Headers[HttpResponseHeader.LastModified] = file.LastWriteTimeUtc.ToString("R");
            }
            catch 
            {
                //If their is an exception close the stream and re-throw
                fs.Dispose();
                throw;
            }
        }
        
        /// <summary>
        /// Close a response to a connection with a <see cref="FileStream"/>  as the entire response body (not attachment)
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">Status code</param>
        /// <param name="file">The <see cref="FileStream"/> of the desired file to attach</param>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponse(this IHttpEvent ev, HttpStatusCode code, FileStream file)
        {
            //Get content type from filename
            ContentType ct = HttpHelpers.GetContentTypeFromFile(file.Name);            
            //Set the input as a stream
            ev.CloseResponse(code, ct, file);
        }
        
        /// <summary>
        /// Close a response to a connection with a character buffer using the server wide
        /// <see cref="ConnectionInfo.Encoding"/> encoding
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">The response status code</param>
        /// <param name="type">The <see cref="ContentType"/> the data represents</param>
        /// <param name="data">The character buffer to send</param>
        /// <remarks>This method will store an encoded copy as a memory stream, so be careful with large buffers</remarks>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponse(this IHttpEvent ev, HttpStatusCode code, ContentType type, in ReadOnlySpan<char> data)
        {
            //Get a memory stream using UTF8 encoding
            CloseResponse(ev, code, type, in data, ev.Server.Encoding);
        }
        
        /// <summary>
        /// Close a response to a connection with a character buffer using the specified encoding type
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">The response status code</param>
        /// <param name="type">The <see cref="ContentType"/> the data represents</param>
        /// <param name="data">The character buffer to send</param>
        /// <param name="encoding">The encoding type to use when converting the buffer</param>
        /// <remarks>This method will store an encoded copy as a memory stream, so be careful with large buffers</remarks>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponse(this IHttpEvent ev, HttpStatusCode code, ContentType type, in ReadOnlySpan<char> data, Encoding encoding)
        {
            if (data.IsEmpty)
            {
                ev.CloseResponse(code);
                return;
            }

            //Validate encoding
            _ = encoding ?? throw new ArgumentNullException(nameof(encoding));
            
            //Get new simple memory response
            IMemoryResponseReader reader = new SimpleMemoryResponse(data, encoding);
            ev.CloseResponse(code, type, reader);
        }
        
        /// <summary>
        /// Close a response to a connection by copying the speciifed binary buffer
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="code">The response status code</param>
        /// <param name="type">The <see cref="ContentType"/> the data represents</param>
        /// <param name="data">The binary buffer to send</param>
        /// <remarks>The data paramter is copied into an internal <see cref="IMemoryResponseReader"/></remarks>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void CloseResponse(this IHttpEvent ev, HttpStatusCode code, ContentType type, ReadOnlySpan<byte> data)
        {
            if (data.IsEmpty)
            {
                ev.CloseResponse(code);
                return;
            }

            //Get new simple memory response
            IMemoryResponseReader reader = new SimpleMemoryResponse(data);
            ev.CloseResponse(code, type, reader);
        }

        /// <summary>
        /// Close a response to a connection with a relative file within the current root's directory
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="code">The status code to set the response as</param>
        /// <param name="filePath">The path of the relative file to send</param>
        /// <returns>True if the file was found, false if the file does not exist or cannot be accessed</returns>
        /// <exception cref="IOException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool CloseWithRelativeFile(this HttpEntity entity, HttpStatusCode code, string filePath)
        {
            //See if file exists and is within the root's directory
            if (entity.RequestedRoot.FindResourceInRoot(filePath, out string realPath))
            {
                //get file-info
                FileInfo realFile = new(realPath);
                //Close the response with the file stream
                entity.CloseResponse(code, realFile);
                return true;
            }
            return false;
        }

        /// <summary>
        /// Redirects a client using the specified <see cref="RedirectType"/>
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="type">The <see cref="RedirectType"/> redirection type</param>
        /// <param name="location">Location to direct client to, sets the "Location" header</param>
        /// <remarks>Sets required headers for redirection, disables cache control, and returns the status code to the client</remarks>
        /// <exception cref="UriFormatException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void Redirect(this IHttpEvent ev, RedirectType type, string location)
        {
            Redirect(ev, type, new Uri(location, UriKind.RelativeOrAbsolute));
        }
        
        /// <summary>
        /// Redirects a client using the specified <see cref="RedirectType"/>
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="type">The <see cref="RedirectType"/> redirection type</param>
        /// <param name="location">Location to direct client to, sets the "Location" header</param>
        /// <remarks>Sets required headers for redirection, disables cache control, and returns the status code to the client</remarks>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void Redirect(this IHttpEvent ev, RedirectType type, Uri location)
        {
            //Encode the string for propery http url formatting and set the location header
            ev.Server.Headers[HttpResponseHeader.Location] = location.ToString();
            ev.Server.SetNoCache();
            //Set redirect the ressponse redirect code type
            ev.CloseResponse((HttpStatusCode)type);
        }

        #endregion

        /// <summary>
        /// Attempts to read and deserialize a JSON object from the reqeust body (form data or urlencoded)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ev"></param>
        /// <param name="key">Request argument key (name)</param>
        /// <param name="obj"></param>
        /// <returns>true if the argument was found and successfully converted to json</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidJsonRequestException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool TryGetJsonFromArg<T>(this IHttpEvent ev, string key, out T? obj) => TryGetJsonFromArg(ev, key, SR_OPTIONS, out obj);
        
        /// <summary>
        /// Attempts to read and deserialize a JSON object from the reqeust body (form data or urlencoded)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ev"></param>
        /// <param name="key">Request argument key (name)</param>
        /// <param name="options"><see cref="JsonSerializerOptions"/> to use during deserialization </param>
        /// <param name="obj"></param>
        /// <returns>true if the argument was found and successfully converted to json</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidJsonRequestException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool TryGetJsonFromArg<T>(this IHttpEvent ev, string key, JsonSerializerOptions options, out T? obj)
        {
            //Check for key in argument
            if (ev.RequestArgs.TryGetNonEmptyValue(key, out string? value))
            {
                try
                {
                    //Deserialize and return the object
                    obj = value.AsJsonObject<T>(options);
                    return true;
                }
                catch(JsonException je)
                {
                    throw new InvalidJsonRequestException(je);
                }
            }
            obj = default;
            return false;
        }
        
        /// <summary>
        /// Reads the value stored at the key location in the request body arguments, into a <see cref="JsonDocument"/>
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="key">Request argument key (name)</param>
        /// <param name="options"><see cref="JsonDocumentOptions"/> to use during parsing</param>
        /// <returns>A new <see cref="JsonDocument"/> if the key is found, null otherwise</returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="InvalidJsonRequestException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static JsonDocument? GetJsonFromArg(this IHttpEvent ev, string key, in JsonDocumentOptions options = default)
        {
            try
            {
                //Check for key in argument
                return ev.RequestArgs.TryGetNonEmptyValue(key, out string? value) ? JsonDocument.Parse(value, options) : null;
            }
            catch (JsonException je)
            {
                throw new InvalidJsonRequestException(je);
            }
        }

        /// <summary>
        /// If there are file attachements (form data files or content body) and the file is <see cref="ContentType.Json"/>
        /// file. It will be deserialzied to the specified object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ev"></param>
        /// <param name="uploadIndex">The index within <see cref="HttpEntity.Files"/></param> list of the file to read
        /// <param name="options"><see cref="JsonSerializerOptions"/> to use during deserialization </param>
        /// <returns>Returns the deserialized object if found, default otherwise</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidJsonRequestException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static T? GetJsonFromFile<T>(this IHttpEvent ev, JsonSerializerOptions? options = null, int uploadIndex = 0)
        {
            if (ev.Files.Count <= uploadIndex)
            {
                return default;
            }

            FileUpload file = ev.Files[uploadIndex];
            //Make sure the file is a json file
            if (file.ContentType != ContentType.Json)
            {
                return default;
            }
            try
            {
                //Beware this will buffer the entire file object before it attmepts to de-serialize it
                return VnEncoding.JSONDeserializeFromBinary<T>(file.FileData, options);
            }
            catch (JsonException je)
            {
                throw new InvalidJsonRequestException(je);
            }
        }
        
        /// <summary>
        /// If there are file attachements (form data files or content body) and the file is <see cref="ContentType.Json"/>
        /// file. It will be parsed into a new <see cref="JsonDocument"/>
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="uploadIndex">The index within <see cref="HttpEntity.Files"/></param> list of the file to read
        /// <returns>Returns the parsed <see cref="JsonDocument"/>if found, default otherwise</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidJsonRequestException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static JsonDocument? GetJsonFromFile(this IHttpEvent ev, int uploadIndex = 0)
        {
            if (ev.Files.Count <= uploadIndex)
            {
                return default;
            }
            FileUpload file = ev.Files[uploadIndex];
            //Make sure the file is a json file
            if (file.ContentType != ContentType.Json)
            {
                return default;
            }
            try
            {
                return JsonDocument.Parse(file.FileData);
            }
            catch(JsonException je)
            {
                throw new InvalidJsonRequestException(je);
            }
        }
        
        /// <summary>
        /// If there are file attachements (form data files or content body) and the file is <see cref="ContentType.Json"/>
        /// file. It will be deserialzied to the specified object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ev"></param>
        /// <param name="uploadIndex">The index within <see cref="HttpEntity.Files"/></param> list of the file to read
        /// <param name="options"><see cref="JsonSerializerOptions"/> to use during deserialization </param>
        /// <returns>The deserialized object if found, default otherwise</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="IndexOutOfRangeException"></exception>
        /// <exception cref="InvalidJsonRequestException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ValueTask<T?> GetJsonFromFileAsync<T>(this HttpEntity ev, JsonSerializerOptions? options = null, int uploadIndex = 0)
        {
            if (ev.Files.Count <= uploadIndex)
            {
                return ValueTask.FromResult<T?>(default);
            }
            FileUpload file = ev.Files[uploadIndex];
            //Make sure the file is a json file
            if (file.ContentType != ContentType.Json)
            {
                return ValueTask.FromResult<T?>(default);
            }
            //avoid copying the ev struct, so return deserialze task
            static async ValueTask<T?> Deserialze(Stream data, JsonSerializerOptions? options, CancellationToken token)
            {
                try
                {
                    //Beware this will buffer the entire file object before it attmepts to de-serialize it
                    return await VnEncoding.JSONDeserializeFromBinaryAsync<T?>(data, options, token);
                }
                catch (JsonException je)
                {
                    throw new InvalidJsonRequestException(je);
                }
            }
            return Deserialze(file.FileData, options, ev.EventCancellation);
        }
        
        static readonly Task<JsonDocument?> DocTaskDefault = Task.FromResult<JsonDocument?>(null);
        
        /// <summary>
        /// If there are file attachements (form data files or content body) and the file is <see cref="ContentType.Json"/>
        /// file. It will be parsed into a new <see cref="JsonDocument"/>
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="uploadIndex">The index within <see cref="HttpEntity.Files"/></param> list of the file to read
        /// <returns>Returns the parsed <see cref="JsonDocument"/>if found, default otherwise</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="IndexOutOfRangeException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Task<JsonDocument?> GetJsonFromFileAsync(this HttpEntity ev, int uploadIndex = 0)
        {
            if (ev.Files.Count <= uploadIndex)
            {
                return DocTaskDefault;
            }
            FileUpload file = ev.Files[uploadIndex];
            //Make sure the file is a json file
            if (file.ContentType != ContentType.Json)
            {
                return DocTaskDefault;
            }
            static async Task<JsonDocument?> Deserialze(Stream data, CancellationToken token)
            {
                try
                {
                    //Beware this will buffer the entire file object before it attmepts to de-serialize it
                    return await JsonDocument.ParseAsync(data, cancellationToken: token);
                }
                catch (JsonException je)
                {
                    throw new InvalidJsonRequestException(je);
                }
            }
            return Deserialze(file.FileData, ev.EventCancellation);
        }
        
        /// <summary>
        /// If there are file attachements (form data files or content body) the specified parser will be called to parse the 
        /// content body asynchronously into a .net object or its default if no attachments are included
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="parser">A function to asynchronously parse the entity body into its object representation</param>
        /// <param name="uploadIndex">The index within <see cref="HttpEntity.Files"/></param> list of the file to read
        /// <returns>Returns the parsed <typeparamref name="T"/> if found, default otherwise</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="IndexOutOfRangeException"></exception>
        public static Task<T?> ParseFileAsAsync<T>(this IHttpEvent ev, Func<Stream, Task<T?>> parser, int uploadIndex = 0)
        {
            if (ev.Files.Count <= uploadIndex)
            {
                return Task.FromResult<T?>(default);
            }
            //Get the file
            FileUpload file = ev.Files[uploadIndex];
            return parser(file.FileData);
        }
        
        /// <summary>
        /// If there are file attachements (form data files or content body) the specified parser will be called to parse the 
        /// content body asynchronously into a .net object or its default if no attachments are included
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="parser">A function to asynchronously parse the entity body into its object representation</param>
        /// <param name="uploadIndex">The index within <see cref="HttpEntity.Files"/></param> list of the file to read
        /// <returns>Returns the parsed <typeparamref name="T"/> if found, default otherwise</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="IndexOutOfRangeException"></exception>
        public static Task<T?> ParseFileAsAsync<T>(this IHttpEvent ev, Func<Stream, string, Task<T?>> parser, int uploadIndex = 0)
        {
            if (ev.Files.Count <= uploadIndex)
            {
                return Task.FromResult<T?>(default);
            }
            //Get the file
            FileUpload file = ev.Files[uploadIndex];
            //Parse the file using the specified parser
            return parser(file.FileData, file.ContentTypeString());
        }
        
        /// <summary>
        /// If there are file attachements (form data files or content body) the specified parser will be called to parse the 
        /// content body asynchronously into a .net object or its default if no attachments are included
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="parser">A function to asynchronously parse the entity body into its object representation</param>
        /// <param name="uploadIndex">The index within <see cref="HttpEntity.Files"/></param> list of the file to read
        /// <returns>Returns the parsed <typeparamref name="T"/> if found, default otherwise</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="IndexOutOfRangeException"></exception>
        public static ValueTask<T?> ParseFileAsAsync<T>(this IHttpEvent ev, Func<Stream, ValueTask<T?>> parser, int uploadIndex = 0)
        {
            if (ev.Files.Count <= uploadIndex)
            {
                return ValueTask.FromResult<T?>(default);
            }
            //Get the file
            FileUpload file = ev.Files[uploadIndex];
            return parser(file.FileData);
        }
        
        /// <summary>
        /// If there are file attachements (form data files or content body) the specified parser will be called to parse the 
        /// content body asynchronously into a .net object or its default if no attachments are included
        /// </summary>
        /// <param name="ev"></param>
        /// <param name="parser">A function to asynchronously parse the entity body into its object representation</param>
        /// <param name="uploadIndex">The index within <see cref="HttpEntity.Files"/></param> list of the file to read
        /// <returns>Returns the parsed <typeparamref name="T"/> if found, default otherwise</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="IndexOutOfRangeException"></exception>
        public static ValueTask<T?> ParseFileAsAsync<T>(this IHttpEvent ev, Func<Stream, string, ValueTask<T?>> parser, int uploadIndex = 0)
        {
            if (ev.Files.Count <= uploadIndex)
            {
                return ValueTask.FromResult<T?>(default);
            }
            //Get the file
            FileUpload file = ev.Files[uploadIndex];
            //Parse the file using the specified parser
            return parser(file.FileData, file.ContentTypeString());
        }

        /// <summary>
        /// Gets the bearer token from an authorization header
        /// </summary>
        /// <param name="ci"></param>
        /// <param name="token">The token stored in the user's authorization header</param>
        /// <returns>True if the authorization header was set, has a Bearer token value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool HasAuthorization(this IConnectionInfo ci, [NotNullWhen(true)] out string? token)
        {
            //Get auth header value
            string? authorization = ci.Headers[HttpRequestHeader.Authorization];
            //Check if its set
            if (!string.IsNullOrWhiteSpace(authorization))
            {
                int bearerIndex = authorization.IndexOf(BEARER_STRING, StringComparison.OrdinalIgnoreCase);
                //Calc token offset, get token, and trim any whitespace
                token = authorization[(bearerIndex + BEARER_LEN)..].Trim();
                return true;
            }
            token = null;
            return false;
        }
        
        /// <summary>
        /// Get a <see cref="DirectoryInfo"/> instance that points to the current sites filesystem root.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="PathTooLongException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static DirectoryInfo GetRootDir(this HttpEntity ev) => new(ev.RequestedRoot.Directory);
        
        /// <summary>
        /// Returns the MIME string representation of the content type of the uploaded file.
        /// </summary>
        /// <param name="upload"></param>
        /// <returns>The MIME string representation of the content type of the uploaded file.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static string ContentTypeString(this in FileUpload upload) => HttpHelpers.GetContentTypeString(upload.ContentType);

      
        /// <summary>
        /// Attemts to upgrade the connection to a websocket, if the setup fails, it sets up the response to the client accordingly.
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="socketOpenedcallback">A delegate that will be invoked when the websocket has been opened by the framework</param>
        /// <param name="subProtocol">The sub-protocol to use on the current websocket</param>
        /// <param name="userState">An object to store in the <see cref="WebSocketSession.UserState"/> property when the websocket has been accepted</param>
        /// <returns>True if operation succeeds.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        public static bool AcceptWebSocket(this IHttpEvent entity, WebsocketAcceptedCallback socketOpenedcallback, object? userState, string? subProtocol = null)
        {
            //Make sure this is a websocket request
            if (!entity.Server.IsWebSocketRequest)
            {
                throw new InvalidOperationException("Connection is not a websocket request");
            }

            //Must define an accept callback
            _ = socketOpenedcallback ?? throw new ArgumentNullException(nameof(socketOpenedcallback));

            string? version = entity.Server.Headers["Sec-WebSocket-Version"];

            //rfc6455:4.2, version must equal 13
            if (!string.IsNullOrWhiteSpace(version) && version.Contains("13", StringComparison.OrdinalIgnoreCase))
            {
                //Get socket key
                string? key = entity.Server.Headers["Sec-WebSocket-Key"];
                if (!string.IsNullOrWhiteSpace(key) && key.Length < 25)
                {
                    //Set headers for acceptance
                    entity.Server.Headers[HttpResponseHeader.Upgrade] = "websocket";
                    entity.Server.Headers[HttpResponseHeader.Connection] = "Upgrade";

                    //Hash accept string
                    entity.Server.Headers["Sec-WebSocket-Accept"] = ManagedHash.ComputeBase64Hash($"{key.Trim()}{HttpHelpers.WebsocketRFC4122Guid}", HashAlg.SHA1);

                    //Protocol if user specified it
                    if (!string.IsNullOrWhiteSpace(subProtocol))
                    {
                        entity.Server.Headers["Sec-WebSocket-Protocol"] = subProtocol;
                    }

                    //Setup a new websocket session with a new session id
                    entity.DangerousChangeProtocol(new WebSocketSession(subProtocol, socketOpenedcallback)
                    {
                        IsSecure = entity.Server.IsSecure(),
                        UserState = userState
                    });

                    return true;
                }
            }
            //Set the client up for a bad request response, nod a valid websocket request
            entity.CloseResponse(HttpStatusCode.BadRequest);
            return false;
        }
    }
}