-
Notifications
You must be signed in to change notification settings - Fork 832
Expand file tree
/
Copy pathHttpContextStreamWriter.cs
More file actions
155 lines (132 loc) · 5.37 KB
/
HttpContextStreamWriter.cs
File metadata and controls
155 lines (132 loc) · 5.37 KB
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
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Diagnostics;
using System.IO.Pipelines;
using Grpc.Core;
using Grpc.Shared;
using Microsoft.AspNetCore.Http.Features;
namespace Grpc.AspNetCore.Server.Internal;
[DebuggerDisplay("{DebuggerToString(),nq}")]
[DebuggerTypeProxy(typeof(HttpContextStreamWriter<>.HttpContextStreamWriterDebugView))]
internal class HttpContextStreamWriter<TResponse> : IServerStreamWriter<TResponse>
where TResponse : class
{
private readonly HttpContextServerCallContext _context;
private readonly Action<TResponse, SerializationContext> _serializer;
private readonly PipeWriter _bodyWriter;
private readonly IHttpRequestLifetimeFeature _requestLifetimeFeature;
private readonly Lock _writeLock;
private Task? _writeTask;
private bool _completed;
private long _writeCount;
public HttpContextStreamWriter(HttpContextServerCallContext context, Action<TResponse, SerializationContext> serializer)
{
_context = context;
_serializer = serializer;
_writeLock = new Lock();
// Copy HttpContext values.
// This is done to avoid a race condition when reading them from HttpContext later when running in a separate thread.
_bodyWriter = context.HttpContext.Response.BodyWriter;
// Copy lifetime feature because HttpContext.RequestAborted on .NET 6 doesn't return the real cancellation token.
_requestLifetimeFeature = GrpcProtocolHelpers.GetRequestLifetimeFeature(context.HttpContext);
}
public WriteOptions? WriteOptions
{
get => _context.WriteOptions;
set => _context.WriteOptions = value;
}
public Task WriteAsync(TResponse message)
{
return WriteCoreAsync(message, CancellationToken.None);
}
#if NET5_0_OR_GREATER
// Explicit implementation because this WriteAsync has a default interface implementation.
Task IAsyncStreamWriter<TResponse>.WriteAsync(TResponse message, CancellationToken cancellationToken)
{
return WriteCoreAsync(message, cancellationToken);
}
#endif
private async Task WriteCoreAsync(TResponse message, CancellationToken cancellationToken)
{
ArgumentNullThrowHelper.ThrowIfNull(message);
// Register cancellation token early to ensure request is canceled if cancellation is requested.
CancellationTokenRegistration? registration = null;
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(
static (state) => ((HttpContextServerCallContext)state!).CancelRequest(),
_context);
}
try
{
cancellationToken.ThrowIfCancellationRequested();
if (_completed || _requestLifetimeFeature.RequestAborted.IsCancellationRequested)
{
throw new InvalidOperationException("Can't write the message because the request is complete.");
}
_writeLock.Enter();
try
{
// Pending writes need to be awaited first
if (IsWriteInProgressUnsynchronized)
{
throw new InvalidOperationException("Can't write the message because the previous write is in progress.");
}
// Save write task to track whether it is complete. Must be set inside lock.
_writeTask = _bodyWriter.WriteStreamedMessageAsync(message, _context, _serializer, cancellationToken);
}
finally
{
_writeLock.Exit();
}
await _writeTask;
Interlocked.Increment(ref _writeCount);
}
finally
{
registration?.Dispose();
}
}
public void Complete()
{
_completed = true;
}
/// <summary>
/// A value indicating whether there is an async write already in progress.
/// Should only check this property when holding the write lock.
/// </summary>
private bool IsWriteInProgressUnsynchronized
{
get
{
var writeTask = _writeTask;
return writeTask != null && !writeTask.IsCompleted;
}
}
private string DebuggerToString() => $"WriteCount = {_writeCount}, WriterCompleted = {(_completed ? "true" : "false")}";
private sealed class HttpContextStreamWriterDebugView
{
private readonly HttpContextStreamWriter<TResponse> _writer;
public HttpContextStreamWriterDebugView(HttpContextStreamWriter<TResponse> writer)
{
_writer = writer;
}
public ServerCallContext ServerCallContext => _writer._context;
public bool WriterCompleted => _writer._completed;
public long WriteCount => _writer._writeCount;
public WriteOptions? WriteOptions => _writer.WriteOptions;
}
}