-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathNpgsqlWriteBuffer.cs
More file actions
566 lines (474 loc) · 17.9 KB
/
NpgsqlWriteBuffer.cs
File metadata and controls
566 lines (474 loc) · 17.9 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
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
using System;
using System.Buffers.Binary;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Npgsql.Util;
using static System.Threading.Timeout;
namespace Npgsql.Internal;
/// <summary>
/// A buffer used by Npgsql to write data to the socket efficiently.
/// Provides methods which encode different values types and tracks the current position.
/// </summary>
sealed class NpgsqlWriteBuffer : IDisposable
{
#region Fields and Properties
internal static readonly UTF8Encoding UTF8Encoding = new ThrowingUTF8Encoding();
internal static readonly UTF8Encoding RelaxedUTF8Encoding = Encoding.UTF8 as UTF8Encoding ?? new(false, throwOnInvalidBytes: false);
sealed class ThrowingUTF8Encoding() : UTF8Encoding(false, throwOnInvalidBytes: true);
internal readonly NpgsqlConnector Connector;
internal Stream Underlying { private get; set; }
readonly Socket? _underlyingSocket;
internal bool MessageLengthValidation { get; set; } = true;
readonly ResettableCancellationTokenSource _timeoutCts;
readonly MetricsReporter? _metricsReporter;
/// <summary>
/// Timeout for sync and async writes
/// </summary>
internal TimeSpan Timeout
{
get => _timeoutCts.Timeout;
set
{
if (_timeoutCts.Timeout != value)
{
Debug.Assert(_underlyingSocket != null);
if (value > TimeSpan.Zero)
{
_underlyingSocket.SendTimeout = (int)value.TotalMilliseconds;
_timeoutCts.Timeout = value;
}
else
{
_underlyingSocket.SendTimeout = -1;
_timeoutCts.Timeout = InfiniteTimeSpan;
}
}
}
}
/// <summary>
/// The total byte length of the buffer.
/// </summary>
internal int Size { get; private set; }
bool _copyMode;
internal Encoding TextEncoding { get; }
public int WriteSpaceLeft => Size - WritePosition;
// (Re)init to make sure we'll refetch from the write buffer.
internal PgWriter GetWriter(NpgsqlDatabaseInfo typeCatalog, FlushMode flushMode = FlushMode.None)
=> _pgWriter.Init(typeCatalog, flushMode);
internal readonly byte[] Buffer;
readonly Encoder _textEncoder;
internal int WritePosition;
int _messageBytesFlushed;
int? _messageLength;
bool _disposed;
readonly PgWriter _pgWriter;
Span<byte> Span => Buffer.AsSpan(WritePosition, WriteSpaceLeft);
/// <summary>
/// The minimum buffer size possible.
/// </summary>
internal const int MinimumSize = 4096;
internal const int DefaultSize = 8192;
#endregion
#region Constructors
internal NpgsqlWriteBuffer(
NpgsqlConnector? connector,
Stream stream,
Socket? socket,
int size,
Encoding textEncoding)
{
ArgumentOutOfRangeException.ThrowIfLessThan(size, MinimumSize);
Connector = connector!; // TODO: Clean this up; only null when used from PregeneratedMessages, where we don't care.
Underlying = stream;
_underlyingSocket = socket;
_metricsReporter = connector?.DataSource.MetricsReporter!;
_timeoutCts = new ResettableCancellationTokenSource();
Buffer = new byte[size];
Size = size;
TextEncoding = textEncoding;
_textEncoder = TextEncoding.GetEncoder();
_pgWriter = new PgWriter(new NpgsqlBufferWriter(this));
}
#endregion
#region I/O
public async Task Flush(bool async, CancellationToken cancellationToken = default)
{
if (_copyMode)
{
// In copy mode, we write CopyData messages. The message code has already been
// written to the beginning of the buffer, but we need to go back and write the
// length.
if (WritePosition == 1)
return;
var pos = WritePosition;
WritePosition = 1;
WriteInt32(pos - 1);
WritePosition = pos;
} else if (WritePosition == 0)
return;
else
AdvanceMessageBytesFlushed(WritePosition);
var finalCt = async && Timeout > TimeSpan.Zero
? _timeoutCts.Start(cancellationToken)
: cancellationToken;
try
{
if (async)
{
await Underlying.WriteAsync(Buffer, 0, WritePosition, finalCt).ConfigureAwait(false);
await Underlying.FlushAsync(finalCt).ConfigureAwait(false);
if (Timeout > TimeSpan.Zero)
_timeoutCts.Stop();
}
else
{
Underlying.Write(Buffer, 0, WritePosition);
Underlying.Flush();
}
}
catch (Exception ex)
{
// Stopping twice (in case the previous Stop() call succeeded) doesn't hurt.
// Not stopping will cause an assertion failure in debug mode when we call Start() the next time.
// We can't stop in a finally block because Connector.Break() will dispose the buffer and the contained
// _timeoutCts
_timeoutCts.Stop();
switch (ex)
{
// User requested the cancellation
case OperationCanceledException when cancellationToken.IsCancellationRequested:
throw Connector.Break(ex);
// Read timeout
case OperationCanceledException:
case IOException { InnerException: SocketException { SocketErrorCode: SocketError.TimedOut } }:
Debug.Assert(ex is OperationCanceledException ? async : !async);
throw Connector.Break(new NpgsqlException("Exception while writing to stream", new TimeoutException("Timeout during writing attempt")));
}
throw Connector.Break(new NpgsqlException("Exception while writing to stream", ex));
}
NpgsqlEventSource.Log.BytesWritten(WritePosition);
_metricsReporter?.ReportBytesWritten(WritePosition);
WritePosition = 0;
if (_copyMode)
WriteCopyDataHeader();
}
internal void Flush() => Flush(false).GetAwaiter().GetResult();
#endregion
#region Direct write
internal void DirectWrite(ReadOnlySpan<byte> buffer)
{
Flush();
if (_copyMode)
{
// Flush has already written the CopyData header for us, but write the CopyData
// header to the socket with the write length before we can start writing the data directly.
Debug.Assert(WritePosition == 5);
WritePosition = 1;
WriteInt32(checked(buffer.Length + 4));
WritePosition = 5;
_copyMode = false;
StartMessage(5);
Flush();
_copyMode = true;
WriteCopyDataHeader(); // And ready the buffer after the direct write completes
}
else
{
Debug.Assert(WritePosition == 0);
AdvanceMessageBytesFlushed(buffer.Length);
}
try
{
Underlying.Write(buffer);
}
catch (Exception e)
{
throw Connector.Break(new NpgsqlException("Exception while writing to stream", e));
}
}
internal async Task DirectWrite(ReadOnlyMemory<byte> memory, bool async, CancellationToken cancellationToken = default)
{
await Flush(async, cancellationToken).ConfigureAwait(false);
if (_copyMode)
{
// Flush has already written the CopyData header for us, but write the CopyData
// header to the socket with the write length before we can start writing the data directly.
Debug.Assert(WritePosition == 5);
WritePosition = 1;
WriteInt32(checked(memory.Length + 4));
WritePosition = 5;
_copyMode = false;
StartMessage(5);
await Flush(async, cancellationToken).ConfigureAwait(false);
_copyMode = true;
WriteCopyDataHeader(); // And ready the buffer after the direct write completes
}
else
{
Debug.Assert(WritePosition == 0);
AdvanceMessageBytesFlushed(memory.Length);
}
try
{
if (async)
await Underlying.WriteAsync(memory, cancellationToken).ConfigureAwait(false);
else
Underlying.Write(memory.Span);
}
catch (Exception e)
{
throw Connector.Break(new NpgsqlException("Exception while writing to stream", e));
}
}
#endregion Direct write
#region Write Simple
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteByte(byte value)
{
CheckBounds<byte>();
Buffer[WritePosition] = value;
WritePosition += sizeof(byte);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt16(short value)
{
CheckBounds<short>();
Unsafe.WriteUnaligned(ref Buffer[WritePosition], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value);
WritePosition += sizeof(short);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt16(ushort value)
{
CheckBounds<ushort>();
Unsafe.WriteUnaligned(ref Buffer[WritePosition], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value);
WritePosition += sizeof(ushort);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt32(int value)
{
CheckBounds<int>();
Unsafe.WriteUnaligned(ref Buffer[WritePosition], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value);
WritePosition += sizeof(int);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt32(uint value)
{
CheckBounds<uint>();
Unsafe.WriteUnaligned(ref Buffer[WritePosition], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value);
WritePosition += sizeof(uint);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt64(long value)
{
CheckBounds<long>();
Unsafe.WriteUnaligned(ref Buffer[WritePosition], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value);
WritePosition += sizeof(long);
}
[Conditional("DEBUG")]
unsafe void CheckBounds<T>() where T : unmanaged
{
if (sizeof(T) > WriteSpaceLeft)
ThrowNotSpaceLeft();
}
static void ThrowNotSpaceLeft()
=> ThrowHelper.ThrowInvalidOperationException("There is not enough space left in the buffer.");
public Task WriteString(string s, int byteLen, bool async, CancellationToken cancellationToken = default)
{
if (byteLen <= WriteSpaceLeft)
{
WriteString(s);
return Task.CompletedTask;
}
return WriteStringLong(this, async, s, byteLen, cancellationToken);
static async Task WriteStringLong(NpgsqlWriteBuffer buffer, bool async, string s, int byteLen, CancellationToken cancellationToken)
{
Debug.Assert(byteLen > buffer.WriteSpaceLeft);
if (byteLen <= buffer.Size)
{
// String can fit entirely in an empty buffer. Flush and retry rather than
// going into the partial writing flow below
await buffer.Flush(async, cancellationToken).ConfigureAwait(false);
buffer.WriteString(s);
}
else
{
var encoder = buffer._textEncoder;
encoder.Reset();
var data = s.AsMemory();
var minBufferSize = buffer.TextEncoding.GetMaxByteCount(1);
bool completed;
do
{
if (buffer.WriteSpaceLeft < minBufferSize)
await buffer.Flush(async, cancellationToken).ConfigureAwait(false);
encoder.Convert(data.Span, buffer.Span, flush: true, out var charsUsed, out var bytesUsed, out completed);
data = data.Slice(charsUsed);
buffer.WritePosition += bytesUsed;
} while (!completed);
}
}
}
public void WriteString(string s)
{
Debug.Assert(TextEncoding.GetByteCount(s) <= WriteSpaceLeft);
WritePosition += TextEncoding.GetBytes(s, 0, s.Length, Buffer, WritePosition);
}
public void WriteBytes(ReadOnlySpan<byte> buf)
{
Debug.Assert(buf.Length <= WriteSpaceLeft);
buf.CopyTo(new Span<byte>(Buffer, WritePosition, Buffer.Length - WritePosition));
WritePosition += buf.Length;
}
public void WriteBytes(ReadOnlyMemory<byte> buf)
=> WriteBytes(buf.Span);
public void WriteBytes(byte[] buf) => WriteBytes(buf.AsSpan());
public void WriteBytes(byte[] buf, int offset, int count)
=> WriteBytes(new ReadOnlySpan<byte>(buf, offset, count));
public Task WriteBytesRaw(ReadOnlyMemory<byte> bytes, bool async, CancellationToken cancellationToken = default)
{
if (bytes.Length <= WriteSpaceLeft)
{
WriteBytes(bytes);
return Task.CompletedTask;
}
return WriteBytesLong(this, async, bytes, cancellationToken);
static async Task WriteBytesLong(NpgsqlWriteBuffer buffer, bool async, ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken)
{
if (bytes.Length <= buffer.Size)
{
// value can fit entirely in an empty buffer. Flush and retry rather than
// going into the partial writing flow below
await buffer.Flush(async, cancellationToken).ConfigureAwait(false);
buffer.WriteBytes(bytes);
}
else
{
var remaining = bytes.Length;
do
{
if (buffer.WriteSpaceLeft == 0)
await buffer.Flush(async, cancellationToken).ConfigureAwait(false);
var writeLen = Math.Min(remaining, buffer.WriteSpaceLeft);
var offset = bytes.Length - remaining;
buffer.WriteBytes(bytes.Slice(offset, writeLen));
remaining -= writeLen;
}
while (remaining > 0);
}
}
}
public void WriteNullTerminatedString(string s)
{
AssertASCIIOnly(s);
Debug.Assert(WriteSpaceLeft >= s.Length + 1);
WritePosition += Encoding.ASCII.GetBytes(s, 0, s.Length, Buffer, WritePosition);
WriteByte(0);
}
public void WriteNullTerminatedString(byte[] s)
{
AssertASCIIOnly(s);
Debug.Assert(WriteSpaceLeft >= s.Length + 1);
WriteBytes(s);
WriteByte(0);
}
#endregion
#region Copy
internal void StartCopyMode()
{
_copyMode = true;
Size -= 5;
WriteCopyDataHeader();
}
internal void EndCopyMode()
{
// EndCopyMode is usually called after a Flush which ended the last CopyData message.
// That Flush also wrote the header for another CopyData which we clear here.
_copyMode = false;
Size += 5;
Clear();
}
void WriteCopyDataHeader()
{
Debug.Assert(_copyMode);
Debug.Assert(WritePosition == 0);
WriteByte(FrontendMessageCode.CopyData);
// Leave space for the message length
WriteInt32(0);
}
#endregion
#region Dispose
public void Dispose()
{
if (_disposed)
return;
_timeoutCts.Dispose();
_disposed = true;
}
#endregion
#region Misc
internal void StartMessage(int messageLength)
{
if (!MessageLengthValidation)
return;
if (_messageLength is not null && _messageBytesFlushed != _messageLength && WritePosition != -_messageBytesFlushed + _messageLength)
Throw();
// Add negative WritePosition to compensate for previous message(s) written without flushing.
_messageBytesFlushed = -WritePosition;
_messageLength = messageLength;
void Throw()
{
throw Connector.Break(new OverflowException("Did not write the amount of bytes the message length specified"));
}
}
void AdvanceMessageBytesFlushed(int count)
{
if (!MessageLengthValidation)
return;
if (count < 0 || _messageLength is null || (long)_messageBytesFlushed + count > _messageLength)
Throw();
_messageBytesFlushed += count;
void Throw()
{
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (_messageLength is null)
throw Connector.Break(new InvalidOperationException("No message was started"));
if ((long)_messageBytesFlushed + count > _messageLength)
throw Connector.Break(new OverflowException("Tried to write more bytes than the message length specified"));
}
}
internal void Clear()
{
WritePosition = 0;
_messageLength = null;
}
/// <summary>
/// Returns all contents currently written to the buffer (but not flushed).
/// Useful for pre-generating messages.
/// </summary>
internal byte[] GetContents()
{
var buf = new byte[WritePosition];
Array.Copy(Buffer, buf, WritePosition);
return buf;
}
[Conditional("DEBUG")]
internal static void AssertASCIIOnly(string s)
{
foreach (var c in s)
if (c >= 128)
Debug.Fail("Method only supports ASCII strings");
}
[Conditional("DEBUG")]
internal static void AssertASCIIOnly(byte[] s)
{
foreach (var c in s)
if (c >= 128)
Debug.Fail("Method only supports ASCII strings");
}
#endregion
}