-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathPipelinesBased.cs
225 lines (190 loc) · 7.95 KB
/
PipelinesBased.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
using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Pipeline
{
public class PipelinesBased
{
public PipelinesBased(PipeReader pipeReader)
{
_pipeReader = pipeReader;
_contentLengthData = "Content-Length".Select(x => (byte) x).ToArray();
_headersBuffer = new Memory<byte>(new byte[HeadersFinishedLength]);
_contentLengthBuffer = new Memory<byte>(new byte[ContentLengthLength]);
_contentLengthValueBuffer = new byte[20]; // Max string length of the long value
_contentLengthValueMemory =
new Memory<byte>(_contentLengthValueBuffer); // Max string length of the long value
}
public static readonly byte[] HeadersFinished =
new[] { (byte) '\r', (byte) '\n', (byte) '\r', (byte) '\n' }.ToArray();
public const int HeadersFinishedLength = 4;
public static readonly char[] HeaderKeys = { '\r', '\n', ':' };
public const short MinBuffer = 21; // Minimum size of the buffer "Content-Length: X\r\n\r\n"
public static readonly byte[] ContentLength = "Content-Length".Select(x => (byte) x).ToArray();
public static readonly int ContentLengthLength = 14;
private readonly PipeReader _pipeReader;
private readonly Memory<byte> _headersBuffer;
private readonly Memory<byte> _contentLengthBuffer;
private readonly byte[] _contentLengthValueBuffer;
private readonly Memory<byte> _contentLengthValueMemory;
private byte[] _contentLengthData;
private bool TryParseHeaders(ref ReadOnlySequence<byte> buffer, out ReadOnlySequence<byte> line)
{
// TODO: This might be simplified with SequenceReader...
// Not sure we can move to purely .netstandard 2.1
if (buffer.Length < MinBuffer || buffer.Length < HeadersFinishedLength)
{
line = default;
return false;
}
var rentedSpan = _headersBuffer.Span;
var start = buffer.PositionOf((byte) '\r');
do
{
if (!start.HasValue)
{
line = default;
return false;
}
var next = buffer.Slice(start.Value, buffer.GetPosition(4, start.Value));
next.CopyTo(rentedSpan);
if (IsEqual(rentedSpan, HeadersFinished))
{
line = buffer.Slice(0, next.End);
buffer = buffer.Slice(next.End);
return true;
}
start = buffer.Slice(buffer.GetPosition(HeadersFinishedLength, start.Value)).PositionOf((byte) '\r');
} while (start.HasValue && buffer.Length > MinBuffer);
line = default;
return false;
}
private static bool IsEqual(in Span<byte> headers, in byte[] bytes)
{
var isEqual = true;
var len = bytes.Length;
for (var i = 0; i < len; i++)
{
if (bytes[i] == headers[i]) continue;
isEqual = false;
break;
}
return isEqual;
}
private bool TryParseBodyString(
in long length, ref ReadOnlySequence<byte> buffer,
out ReadOnlySequence<byte> line
)
{
if (buffer.Length < length)
{
line = default;
return false;
}
line = buffer.Slice(0, length);
buffer = buffer.Slice(length);
return true;
}
private bool TryParseContentLength(ref ReadOnlySequence<byte> buffer, out long length)
{
do
{
var colon = buffer.PositionOf((byte) ':');
if (!colon.HasValue)
{
length = -1;
return false;
}
var slice = buffer.Slice(0, colon.Value);
slice.CopyTo(_contentLengthBuffer.Span);
if (IsEqual(_contentLengthBuffer.Span, ContentLength))
{
var position = buffer.GetPosition(1, colon.Value);
var offset = 1;
while (buffer.TryGet(ref position, out var memory) && !memory.Span.IsEmpty)
{
foreach (var t in memory.Span)
{
if (t == (byte) ' ')
{
offset++;
continue;
}
break;
}
}
var lengthSlice = buffer.Slice(
buffer.GetPosition(offset, colon.Value),
buffer.PositionOf((byte) '\r') ?? buffer.End
);
var whitespacePosition = lengthSlice.PositionOf((byte) ' ');
if (whitespacePosition.HasValue)
{
lengthSlice = lengthSlice.Slice(0, whitespacePosition.Value);
}
lengthSlice.CopyTo(_contentLengthValueMemory.Span);
if (long.TryParse(Encoding.ASCII.GetString(_contentLengthValueBuffer), out length))
{
// Reset the array otherwise smaller numbers will be inflated;
for (var i = 0; i < lengthSlice.Length; i++) _contentLengthValueMemory.Span[i] = 0;
return true;
}
// Reset the array otherwise smaller numbers will be inflated;
for (var i = 0; i < lengthSlice.Length; i++) _contentLengthValueMemory.Span[i] = 0;
// _logger.LogError("Unable to get length from content length header...");
return false;
}
buffer = buffer.Slice(buffer.GetPosition(1, buffer.PositionOf((byte) '\n') ?? buffer.End));
} while (true);
}
internal async Task ProcessInputStream(CancellationToken cancellationToken)
{
// some time to attach a debugger
// System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
var headersParsed = false;
long length = 0;
while (!cancellationToken.IsCancellationRequested)
{
var result = await _pipeReader.ReadAsync(cancellationToken);
var buffer = result.Buffer;
if (!headersParsed)
{
if (TryParseHeaders(ref buffer, out var line))
{
if (TryParseContentLength(ref line, out length))
{
headersParsed = true;
}
}
}
if (headersParsed && length == 0)
{
HandleRequest(new ReadOnlySequence<byte>(Array.Empty<byte>()));
headersParsed = false;
}
if (headersParsed)
{
if (TryParseBodyString(length, ref buffer, out var line))
{
headersParsed = false;
length = 0;
HandleRequest(line);
}
}
_pipeReader.AdvanceTo(buffer.Start, buffer.End);
// Stop reading if there's no more data coming.
if (result.IsCompleted && buffer.GetPosition(0, buffer.Start).Equals(buffer.GetPosition(0, buffer.End)))
{
break;
}
}
}
private void HandleRequest(in ReadOnlySequence<byte> request)
{
}
}
}