forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPgPostmasterMock.cs
More file actions
288 lines (246 loc) · 10.7 KB
/
PgPostmasterMock.cs
File metadata and controls
288 lines (246 loc) · 10.7 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using Npgsql.Internal;
namespace Npgsql.Tests.Support;
class PgPostmasterMock : IAsyncDisposable
{
const int ReadBufferSize = 8192;
const int WriteBufferSize = 8192;
const int CancelRequestCode = 1234 << 16 | 5678;
const int SslRequest = 80877103;
const int GssRequest = 80877104;
static readonly Encoding Encoding = NpgsqlWriteBuffer.UTF8Encoding;
static readonly Encoding RelaxedEncoding = NpgsqlWriteBuffer.RelaxedUTF8Encoding;
readonly Socket _socket;
readonly List<PgServerMock> _allServers = [];
bool _acceptingClients;
Task? _acceptClientsTask;
int _processIdCounter;
readonly bool _completeCancellationImmediately;
readonly string? _startupErrorCode;
readonly bool _breakOnGssEncryptionRequest;
ChannelWriter<Task<ServerOrCancellationRequest>> _pendingRequestsWriter { get; }
ChannelReader<Task<ServerOrCancellationRequest>> _pendingRequestsReader { get; }
internal string ConnectionString { get; }
internal string Host { get; }
internal int Port { get; }
volatile MockState _state;
internal MockState State
{
get => _state;
set => _state = value;
}
internal static PgPostmasterMock Start(
string? connectionString = null,
bool completeCancellationImmediately = true,
MockState state = MockState.MultipleHostsDisabled,
string? startupErrorCode = null,
bool breakOnGssEncryptionRequest = false)
{
var mock = new PgPostmasterMock(connectionString, completeCancellationImmediately, state, startupErrorCode, breakOnGssEncryptionRequest);
mock.AcceptClients();
return mock;
}
internal PgPostmasterMock(
string? connectionString = null,
bool completeCancellationImmediately = true,
MockState state = MockState.MultipleHostsDisabled,
string? startupErrorCode = null,
bool breakOnGssEncryptionRequest = false)
{
var pendingRequestsChannel = Channel.CreateUnbounded<Task<ServerOrCancellationRequest>>();
_pendingRequestsReader = pendingRequestsChannel.Reader;
_pendingRequestsWriter = pendingRequestsChannel.Writer;
var connectionStringBuilder = new NpgsqlConnectionStringBuilder(connectionString);
_completeCancellationImmediately = completeCancellationImmediately;
State = state;
_startupErrorCode = startupErrorCode;
_breakOnGssEncryptionRequest = breakOnGssEncryptionRequest;
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var endpoint = new IPEndPoint(IPAddress.Loopback, 0);
_socket.Bind(endpoint);
var localEndPoint = (IPEndPoint)_socket.LocalEndPoint!;
Host = localEndPoint.Address.ToString();
Port = localEndPoint.Port;
connectionStringBuilder.Host = Host;
connectionStringBuilder.Port = Port;
#pragma warning disable CS0618 // Type or member is obsolete
connectionStringBuilder.ServerCompatibilityMode = ServerCompatibilityMode.NoTypeLoading;
#pragma warning restore CS0618 // Type or member is obsolete
ConnectionString = connectionStringBuilder.ConnectionString;
_socket.Listen(5);
}
public NpgsqlDataSource CreateDataSource(Action<NpgsqlDataSourceBuilder>? configure = null)
{
var builder = new NpgsqlDataSourceBuilder(ConnectionString);
configure?.Invoke(builder);
return builder.Build();
}
void AcceptClients()
{
_acceptingClients = true;
_acceptClientsTask = DoAcceptClients();
async Task DoAcceptClients()
{
while (true)
{
var serverOrCancellationRequest = await Accept(_completeCancellationImmediately);
if (serverOrCancellationRequest.Server is { } server)
{
// Hand off the new server to the client test only once startup is complete, to avoid reading/writing in parallel
// during startup. Don't wait for all this to complete - continue to accept other connections in case that's needed.
if (string.IsNullOrEmpty(_startupErrorCode))
{
// We may be accepting (and starting up) multiple connections in parallel, but some tests assume we return
// server connections in FIFO. As a result, we enqueue immediately into the _pendingRequestsWriter channel,
// but we enqueue a Task which represents the Startup completing.
await _pendingRequestsWriter.WriteAsync(Task.Run(async () =>
{
await server.Startup(State);
return serverOrCancellationRequest;
}));
}
else
_ = server.FailedStartup(_startupErrorCode);
}
else
{
await _pendingRequestsWriter.WriteAsync(Task.FromResult(serverOrCancellationRequest));
}
}
// ReSharper disable once FunctionNeverReturns
}
}
async Task<ServerOrCancellationRequest> Accept(bool completeCancellationImmediately)
{
var clientSocket = await _socket.AcceptAsync();
var stream = new NetworkStream(clientSocket, true);
var readBuffer = new NpgsqlReadBuffer(null!, stream, clientSocket, ReadBufferSize, Encoding,
RelaxedEncoding);
var writeBuffer = new NpgsqlWriteBuffer(null!, stream, clientSocket, WriteBufferSize, Encoding);
writeBuffer.MessageLengthValidation = false;
await readBuffer.EnsureAsync(4);
var len = readBuffer.ReadInt32();
await readBuffer.EnsureAsync(len - 4);
var request = readBuffer.ReadInt32();
if (request == GssRequest)
{
if (_breakOnGssEncryptionRequest)
{
readBuffer.Dispose();
writeBuffer.Dispose();
await stream.DisposeAsync();
return default;
}
writeBuffer.WriteByte((byte)'N');
await writeBuffer.Flush(async: true);
await readBuffer.EnsureAsync(4);
len = readBuffer.ReadInt32();
await readBuffer.EnsureAsync(len - 4);
request = readBuffer.ReadInt32();
}
if (request == SslRequest)
{
writeBuffer.WriteByte((byte)'N');
await writeBuffer.Flush(async: true);
await readBuffer.EnsureAsync(4);
len = readBuffer.ReadInt32();
await readBuffer.EnsureAsync(len - 4);
request = readBuffer.ReadInt32();
}
if (request == CancelRequestCode)
{
var cancellationRequest = new PgCancellationRequest(readBuffer, writeBuffer, stream, readBuffer.ReadInt32(), readBuffer.ReadInt32());
if (completeCancellationImmediately)
{
cancellationRequest.Complete();
}
return new ServerOrCancellationRequest(cancellationRequest);
}
// This is not a cancellation, "spawn" a new server
readBuffer.ReadPosition -= 8;
var server = new PgServerMock(stream, readBuffer, writeBuffer, ++_processIdCounter);
_allServers.Add(server);
return new ServerOrCancellationRequest(server);
}
internal async Task<PgServerMock> AcceptServer(bool completeCancellationImmediately = true)
{
if (_acceptingClients)
throw new InvalidOperationException($"Already accepting clients via {nameof(AcceptClients)}");
var serverOrCancellationRequest = await Accept(completeCancellationImmediately);
if (serverOrCancellationRequest.Server is null)
throw new InvalidOperationException("Expected a server connection but got a cancellation request instead");
return serverOrCancellationRequest.Server;
}
internal async Task<PgCancellationRequest> AcceptCancellationRequest()
{
if (_acceptingClients)
throw new InvalidOperationException($"Already accepting clients via {nameof(AcceptClients)}");
var serverOrCancellationRequest = await Accept(completeCancellationImmediately: true);
if (serverOrCancellationRequest.CancellationRequest is null)
throw new InvalidOperationException("Expected a cancellation request but got a server connection instead");
return serverOrCancellationRequest.CancellationRequest;
}
internal async ValueTask<PgServerMock> WaitForServerConnection()
{
var serverOrCancellationRequest = await await _pendingRequestsReader.ReadAsync();
if (serverOrCancellationRequest.Server is null)
throw new InvalidOperationException("Expected a server connection but got a cancellation request instead");
return serverOrCancellationRequest.Server;
}
internal async ValueTask<PgCancellationRequest> WaitForCancellationRequest()
{
var serverOrCancellationRequest = await await _pendingRequestsReader.ReadAsync();
if (serverOrCancellationRequest.CancellationRequest is null)
throw new InvalidOperationException("Expected cancellation request but got a server connection instead");
return serverOrCancellationRequest.CancellationRequest;
}
public async ValueTask DisposeAsync()
{
var endpoint = _socket.LocalEndPoint as IPEndPoint;
Debug.Assert(endpoint is not null);
// Stop accepting new connections
_socket.Dispose();
try
{
var acceptTask = _acceptClientsTask;
if (acceptTask != null)
await acceptTask;
}
catch
{
// Swallow all exceptions
}
// Destroy all servers created by this postmaster
foreach (var server in _allServers)
server.Dispose();
}
internal readonly struct ServerOrCancellationRequest
{
public ServerOrCancellationRequest(PgServerMock server)
{
Server = server;
CancellationRequest = null;
}
public ServerOrCancellationRequest(PgCancellationRequest cancellationRequest)
{
Server = null;
CancellationRequest = cancellationRequest;
}
internal PgServerMock? Server { get; }
internal PgCancellationRequest? CancellationRequest { get; }
}
}
public enum MockState
{
MultipleHostsDisabled = 0,
Primary = 1,
PrimaryReadOnly = 2,
Standby = 3
}