-
Notifications
You must be signed in to change notification settings - Fork 48
/
BodyWrapperStreamBase.cs
666 lines (571 loc) · 16.6 KB
/
BodyWrapperStreamBase.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
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AdvancedStringBuilder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using WebMarkupMin.AspNet.Common;
using WebMarkupMin.AspNet.Common.Compressors;
#if ASPNETCORE1
#if NET451
using WebMarkupMin.AspNetCore1.Helpers;
#endif
#elif ASPNETCORE2
using WebMarkupMin.AspNetCore2.Helpers;
#elif ASPNETCORE3
using WebMarkupMin.AspNetCore3.Helpers;
#elif ASPNETCORE5
using WebMarkupMin.AspNetCore5.Helpers;
#elif ASPNETCORE6
using WebMarkupMin.AspNetCore6.Helpers;
#elif ASPNETCORE7
using WebMarkupMin.AspNetCore7.Helpers;
#else
#error No implementation for this target
#endif
using WebMarkupMin.Core;
using WebMarkupMin.Core.Utilities;
using AspNetCommonStrings = WebMarkupMin.AspNet.Common.Resources.Strings;
#if ASPNETCORE1
namespace WebMarkupMin.AspNetCore1
#elif ASPNETCORE2
namespace WebMarkupMin.AspNetCore2
#elif ASPNETCORE3
namespace WebMarkupMin.AspNetCore3
#elif ASPNETCORE5
namespace WebMarkupMin.AspNetCore5
#elif ASPNETCORE6
namespace WebMarkupMin.AspNetCore6
#elif ASPNETCORE7
namespace WebMarkupMin.AspNetCore7
#else
#error No implementation for this target
#endif
{
/// <summary>
/// Base class of stream wrapper that apply a markup minification and compression only if necessary
/// </summary>
internal abstract class BodyWrapperStreamBase : Stream
{
/// <summary>
/// HTTP context
/// </summary>
protected readonly HttpContext _context;
/// <summary>
/// Original stream
/// </summary>
private readonly Stream _originalStream;
/// <summary>
/// Stream that original content is read into
/// </summary>
private MemoryStream _cachedStream;
/// <summary>
/// Compression stream
/// </summary>
private Stream _compressionStream;
/// <summary>
/// Flag for whether to do automatically flush the compression stream
/// </summary>
protected bool _autoFlushCompressionStream = false;
/// <summary>
/// WebMarkupMin configuration
/// </summary>
private readonly WebMarkupMinOptions _options;
/// <summary>
/// List of markup minification managers
/// </summary>
private readonly IList<IMarkupMinificationManager> _minificationManagers;
/// <summary>
/// HTTP compression manager
/// </summary>
private readonly IHttpCompressionManager _compressionManager;
/// <summary>
/// Flag indicating whether the stream wrapper is initialized
/// </summary>
private StatedFlag _wrapperInitializedFlag = new StatedFlag();
/// <summary>
/// Flag indicating whether a markup minification is enabled
/// </summary>
protected bool _minificationEnabled = false;
/// <summary>
/// Flag indicating whether a HTTP compression is enabled
/// </summary>
protected bool _compressionEnabled = false;
/// <summary>
/// Current URL
/// </summary>
private string _currentUrl;
/// <summary>
/// Text encoding
/// </summary>
private Encoding _encoding;
/// <summary>
/// Current markup minification manager
/// </summary>
private IMarkupMinificationManager _currentMinificationManager;
/// <summary>
/// Current HTTP compressor
/// </summary>
protected ICompressor _currentCompressor;
/// <summary>
/// Flag indicating whether the current HTTP compressor is initialized
/// </summary>
private StatedFlag _currentCompressorInitializedFlag = new StatedFlag();
/// <summary>
/// Flag that indicates if the HTTP headers is modified for compression
/// </summary>
private StatedFlag _httpHeadersModifiedForCompressionFlag = new StatedFlag();
/// <summary>
/// Flag that the stream wrapper is destroyed
/// </summary>
private StatedFlag _disposedFlag = new StatedFlag();
/// <summary>
/// Constructs an instance of the stream wrapper
/// </summary>
/// <param name="context">HTTP context</param>
/// <param name="originalStream">Original stream</param>
/// <param name="options">WebMarkupMin configuration</param>
/// <param name="minificationManagers">List of markup minification managers</param>
/// <param name="compressionManager">HTTP compression manager</param>
protected BodyWrapperStreamBase(HttpContext context, Stream originalStream,
WebMarkupMinOptions options, IList<IMarkupMinificationManager> minificationManagers,
IHttpCompressionManager compressionManager)
{
_context = context;
_originalStream = originalStream;
_options = options;
_minificationManagers = minificationManagers;
_compressionManager = compressionManager;
}
protected void Initialize()
{
if (_wrapperInitializedFlag.Set())
{
HttpRequest request = _context.Request;
HttpResponse response = _context.Response;
int httpStatusCode = response.StatusCode;
string httpMethod = request.Method;
string contentType = response.ContentType;
string mediaType = null;
Encoding encoding = null;
if (contentType != null)
{
MediaTypeHeaderValue mediaTypeHeader;
if (MediaTypeHeaderValue.TryParse(contentType, out mediaTypeHeader))
{
mediaType = mediaTypeHeader.MediaType
#if NETSTANDARD2_0 || NETCOREAPP3_1_OR_GREATER
.Value
#endif
.ToLowerInvariant()
;
encoding = mediaTypeHeader.Encoding;
}
}
string currentUrl = GetCurrentUrl(request);
IHeaderDictionary responseHeaders = response.Headers;
bool isEncodedContent = responseHeaders.IsEncodedContent();
int minificationManagerCount = _minificationManagers.Count;
if (minificationManagerCount > 0)
{
for (int managerIndex = 0; managerIndex < minificationManagerCount; managerIndex++)
{
IMarkupMinificationManager minificationManager = _minificationManagers[managerIndex];
if (minificationManager.IsSupportedHttpStatusCode(httpStatusCode)
&& minificationManager.IsSupportedHttpMethod(httpMethod)
&& mediaType != null && minificationManager.IsSupportedMediaType(mediaType)
&& minificationManager.IsProcessablePage(currentUrl))
{
if (isEncodedContent)
{
throw new InvalidOperationException(
string.Format(
AspNetCommonStrings.MarkupMinificationIsNotApplicableToEncodedContent,
responseHeaders[HeaderNames.ContentEncoding]
)
);
}
_currentMinificationManager = minificationManager;
_cachedStream = new MemoryStream();
_minificationEnabled = true;
break;
}
}
}
if (_compressionManager != null && !isEncodedContent
&& _compressionManager.IsSupportedHttpStatusCode(httpStatusCode)
&& _compressionManager.IsSupportedHttpMethod(httpMethod)
&& _compressionManager.IsSupportedMediaType(mediaType)
&& _compressionManager.IsProcessablePage(currentUrl))
{
string acceptEncoding = request.Headers[HeaderNames.AcceptEncoding];
InitializeCurrentCompressor(acceptEncoding);
if (_currentCompressor != null)
{
if (!_minificationEnabled)
{
// If markup minification is disabled, then initialize the compression stream.
// Otherwise, initialize the compression stream after minification.
_compressionStream = _currentCompressor.Compress(_originalStream);
}
_compressionEnabled = true;
}
}
_currentUrl = currentUrl;
_encoding = encoding;
}
}
private static string GetCurrentUrl(HttpRequest request)
{
PathString pathBase = request.PathBase;
PathString path = request.Path;
QueryString queryString = request.QueryString;
if (!queryString.HasValue)
{
if (pathBase.HasValue && !path.HasValue)
{
return pathBase.Value;
}
if (!pathBase.HasValue && path.HasValue)
{
return path.Value;
}
}
var stringBuilderPool = StringBuilderPool.Shared;
StringBuilder urlBuilder = stringBuilderPool.Rent();
if (pathBase.HasValue)
{
urlBuilder.Append(pathBase.Value);
}
if (path.HasValue)
{
urlBuilder.Append(path.Value);
}
if (urlBuilder.Length > 0 && queryString.HasValue)
{
urlBuilder.Append(queryString.Value);
}
string currentUrl = urlBuilder.ToString();
stringBuilderPool.Return(urlBuilder);
return currentUrl;
}
protected void InitializeCurrentCompressor(string acceptEncoding)
{
if (_currentCompressorInitializedFlag.Set())
{
_compressionManager?.TryCreateCompressor(acceptEncoding, out _currentCompressor);
}
}
private void ModifyHttpHeadersForCompressionOnce()
{
if (_httpHeadersModifiedForCompressionFlag.Set())
{
IHeaderDictionary responseHeaders = _context.Response.Headers;
_currentCompressor.AppendHttpHeaders((key, value) =>
{
responseHeaders.Append(key, new StringValues(value));
});
#if NET6_0_OR_GREATER
responseHeaders.ContentMD5 = default;
responseHeaders.ContentLength = default;
#else
responseHeaders.Remove(HeaderNames.ContentMD5);
responseHeaders.Remove(HeaderNames.ContentLength);
#endif
}
}
protected async Task InternalFinishAsync()
{
if (_minificationEnabled)
{
bool isMinified = false;
int cachedByteCount = (int)_cachedStream.Length;
IHeaderDictionary responseHeaders = _context.Response.Headers;
Action<string, string> appendHttpHeader = (key, value) =>
{
responseHeaders.Append(key, new StringValues(value));
};
if (cachedByteCount > 0 && _options.IsAllowableResponseSize(cachedByteCount))
{
Encoding encoding = _encoding ?? _options.DefaultEncoding;
#if NETSTANDARD1_3
byte[] cachedBytes = _cachedStream.ToArray();
string content = encoding.GetString(cachedBytes);
#else
byte[] cachedBytes = _cachedStream.GetBuffer();
string content = encoding.GetString(cachedBytes, 0, cachedByteCount);
#endif
IMarkupMinifier minifier = _currentMinificationManager.CreateMinifier();
MarkupMinificationResult minificationResult;
try
{
minificationResult = minifier.Minify(content, _currentUrl,
_encoding, _currentMinificationManager.GenerateStatistics);
}
catch
{
// Disable a HTTP compression when an exception occurs
_compressionEnabled = false;
_currentCompressor = null;
throw;
}
if (minificationResult.Errors.Count == 0)
{
if (_options.IsPoweredByHttpHeadersEnabled())
{
_currentMinificationManager.AppendPoweredByHttpHeader(appendHttpHeader);
}
#if NET6_0_OR_GREATER
responseHeaders.ContentMD5 = default;
#else
responseHeaders.Remove(HeaderNames.ContentMD5);
#endif
string processedContent = minificationResult.MinifiedContent;
var byteArrayPool = ArrayPool<byte>.Shared;
int processedByteCount = encoding.GetByteCount(processedContent);
byte[] processedBytes = byteArrayPool.Rent(processedByteCount);
try
{
encoding.GetBytes(processedContent, 0, processedContent.Length, processedBytes, 0);
if (_compressionEnabled)
{
_compressionStream = _currentCompressor.Compress(_originalStream);
_currentCompressor.AppendHttpHeaders(appendHttpHeader);
#if NET6_0_OR_GREATER
responseHeaders.ContentLength = default;
#else
responseHeaders.Remove(HeaderNames.ContentLength);
#endif
await _compressionStream.WriteAsync(processedBytes, 0, processedByteCount);
}
else
{
responseHeaders[HeaderNames.ContentLength] = processedByteCount.ToString();
await _originalStream.WriteAsync(processedBytes, 0, processedByteCount);
}
}
finally
{
byteArrayPool.Return(processedBytes);
}
isMinified = true;
}
}
if (!isMinified)
{
Stream outputStream;
if (_compressionEnabled)
{
_compressionStream = _currentCompressor.Compress(_originalStream);
_currentCompressor.AppendHttpHeaders(appendHttpHeader);
outputStream = _compressionStream;
}
else
{
outputStream = _originalStream;
}
_cachedStream.Seek(0, SeekOrigin.Begin);
await _cachedStream.CopyToAsync(outputStream);
}
_cachedStream.Clear();
}
}
public virtual async Task FinishAsync()
{
await Task.Run(() => throw new NotImplementedException());
}
#region Stream overrides
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override bool CanWrite
{
get { return _originalStream.CanWrite; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanRead
{
get { return false; }
}
#if NET451 || NETSTANDARD2_0 || NETCOREAPP3_1_OR_GREATER
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback,
object state)
{
return TaskToApmHelpers.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
TaskToApmHelpers.End(asyncResult);
}
#endif
public override void Flush()
{
Initialize();
if (_minificationEnabled)
{
_cachedStream.Flush();
}
else if (_compressionEnabled)
{
_compressionStream.Flush();
}
else
{
_originalStream.Flush();
}
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
Initialize();
if (_minificationEnabled)
{
return _cachedStream.FlushAsync(cancellationToken);
}
else if (_compressionEnabled)
{
return _compressionStream.FlushAsync(cancellationToken);
}
return _originalStream.FlushAsync(cancellationToken);
}
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)
{
Initialize();
if (_minificationEnabled)
{
_cachedStream.Write(buffer, offset, count);
}
else if (_compressionEnabled)
{
ModifyHttpHeadersForCompressionOnce();
_compressionStream.Write(buffer, offset, count);
if (_autoFlushCompressionStream)
{
_compressionStream.Flush();
}
}
else
{
_originalStream.Write(buffer, offset, count);
}
}
public override async Task WriteAsync(byte[] buffer, int offset, int count,
CancellationToken cancellationToken)
{
#if NET6_0_OR_GREATER
await WriteAsync(buffer.AsMemory(offset, count), cancellationToken);
#else
Initialize();
if (_minificationEnabled)
{
await _cachedStream.WriteAsync(buffer, offset, count, cancellationToken);
}
else if (_compressionEnabled)
{
ModifyHttpHeadersForCompressionOnce();
await _compressionStream.WriteAsync(buffer, offset, count, cancellationToken);
if (_autoFlushCompressionStream)
{
await _compressionStream.FlushAsync(cancellationToken);
}
}
else
{
await _originalStream.WriteAsync(buffer, offset, count, cancellationToken);
}
#endif
}
#if NET6_0_OR_GREATER
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
Initialize();
if (_minificationEnabled)
{
await _cachedStream.WriteAsync(buffer, cancellationToken);
}
else if (_compressionEnabled)
{
ModifyHttpHeadersForCompressionOnce();
await _compressionStream.WriteAsync(buffer, cancellationToken);
if (_autoFlushCompressionStream)
{
await _compressionStream.FlushAsync(cancellationToken);
}
}
else
{
await _originalStream.WriteAsync(buffer, cancellationToken);
}
}
#endif
protected override void Dispose(bool disposing)
{
if (_disposedFlag.Set())
{
if (disposing)
{
if (_compressionStream != null)
{
_compressionStream.Dispose();
_compressionStream = null;
}
_currentCompressor = null;
if (_cachedStream != null)
{
_cachedStream.Dispose();
_cachedStream = null;
}
_currentMinificationManager = null;
}
base.Dispose(disposing);
}
}
#if NETCOREAPP3_1_OR_GREATER
public override async ValueTask DisposeAsync()
{
if (_disposedFlag.Set())
{
if (_compressionStream != null)
{
await _compressionStream.DisposeAsync();
_compressionStream = null;
}
_currentCompressor = null;
if (_cachedStream != null)
{
await _cachedStream.DisposeAsync();
_cachedStream = null;
}
_currentMinificationManager = null;
await base.DisposeAsync();
}
}
#endif
#endregion
}
}