forked from kenjiuno/Npgsql
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPoolTests.cs
More file actions
562 lines (487 loc) · 20.7 KB
/
PoolTests.cs
File metadata and controls
562 lines (487 loc) · 20.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using static Npgsql.Tests.TestUtil;
namespace Npgsql.Tests
{
[NonParallelizable]
class PoolTests : TestBase
{
[Test]
public void MinPoolSizeEqualsMaxPoolSize()
{
using var conn = CreateConnection(new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(MinPoolSizeEqualsMaxPoolSize),
MinPoolSize = 30,
MaxPoolSize = 30
}.ToString());
conn.Open();
}
[Test]
public void MinPoolSizeLargerThanMaxPoolSize()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(MinPoolSizeLargerThanMaxPoolSize),
MinPoolSize = 2,
MaxPoolSize = 1
}.ToString();
Assert.That(() => CreateConnection(connString), Throws.Exception.TypeOf<ArgumentException>());
}
[Test]
public void ReuseConnectorBeforeCreatingNew()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ReuseConnectorBeforeCreatingNew),
}.ToString();
using var conn = CreateConnection(connString);
conn.Open();
var backendId = conn.Connector!.BackendProcessId;
conn.Close();
conn.Open();
Assert.That(conn.Connector.BackendProcessId, Is.EqualTo(backendId));
}
[Test, Timeout(10000)]
public void GetConnectorFromExhaustedPool()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(GetConnectorFromExhaustedPool),
MaxPoolSize = 1,
Timeout = 0
}.ToString();
using var conn1 = CreateConnection(connString);
conn1.Open();
// Pool is exhausted
using var conn2 = CreateConnection(connString);
new Timer(o => conn1.Close(), null, 1000, Timeout.Infinite);
conn2.Open();
}
//[Test, Explicit, Timeout(10000)]
public async Task GetConnectorFromExhaustedPoolAsync()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(GetConnectorFromExhaustedPoolAsync),
MaxPoolSize = 1,
Timeout = 0
}.ToString();
using var conn1 = CreateConnection(connString);
await conn1.OpenAsync();
// Pool is exhausted
using var conn2 = CreateConnection(connString);
using (new Timer(o => conn1.Close(), null, 1000, Timeout.Infinite))
await conn2.OpenAsync();
}
[Test]
public async Task TimeoutGettingConnectorFromExhaustedPool([Values(true, false)] bool async)
{
var csb = new NpgsqlConnectionStringBuilder(ConnectionString)
{
MaxPoolSize = 1,
Timeout = 2
};
using var _ = CreateTempPool(csb, out var connString);
using (var conn1 = CreateConnection(connString))
{
await conn1.OpenAsync();
// Pool is now exhausted
await using var conn2 = CreateConnection(connString);
var e = async
? Assert.ThrowsAsync<NpgsqlException>(async () => await conn2.OpenAsync())!
: Assert.Throws<NpgsqlException>(() => conn2.Open())!;
Assert.That(e.InnerException, Is.TypeOf<TimeoutException>());
}
// conn1 should now be back in the pool as idle
using (var conn3 = CreateConnection(connString))
conn3.Open();
}
[Test]
public async Task TimeoutGettingConnectorFromExhaustedPoolAsync()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(TimeoutGettingConnectorFromExhaustedPoolAsync),
MaxPoolSize = 1,
Timeout = 2
}.ToString();
using (var conn1 = CreateConnection(connString))
{
await conn1.OpenAsync();
// Pool is exhausted
using (var conn2 = CreateConnection(connString))
Assert.That(async () => await conn2.OpenAsync(), Throws.Exception.TypeOf<NpgsqlException>());
}
// conn1 should now be back in the pool as idle
using (var conn3 = CreateConnection(connString))
conn3.Open();
}
[Test, Timeout(10000)]
[Explicit("Timing-based")]
public async Task CancelOpenAsync()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(CancelOpenAsync),
MaxPoolSize = 1,
}.ToString();
using var conn1 = CreateConnection(connString);
await conn1.OpenAsync();
Assert.True(PoolManager.TryGetValue(connString, out var pool));
AssertPoolState(pool, open: 1, idle: 0);
// Pool is exhausted
using (var conn2 = CreateConnection(connString))
{
var cts = new CancellationTokenSource(1000);
var openTask = conn2.OpenAsync(cts.Token);
AssertPoolState(pool, open: 1, idle: 0);
Assert.That(async () => await openTask, Throws.Exception.TypeOf<OperationCanceledException>());
}
AssertPoolState(pool, open: 1, idle: 0);
using (var conn2 = CreateConnection(connString))
using (new Timer(o => conn1.Close(), null, 1000, Timeout.Infinite))
{
await conn2.OpenAsync();
AssertPoolState(pool, open: 1, idle: 0);
}
AssertPoolState(pool, open: 1, idle: 1);
}
[Test, Description("Makes sure that when a pooled connection is closed it's properly reset, and that parameter settings aren't leaked")]
public void ResetOnClose()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ResetOnClose),
SearchPath = "public"
}.ToString();
using var conn = CreateConnection(connString);
conn.Open();
Assert.That(conn.ExecuteScalar("SHOW search_path"), Is.Not.Contains("pg_temp"));
var backendId = conn.Connector!.BackendProcessId;
conn.ExecuteNonQuery("SET search_path=pg_temp");
conn.Close();
conn.Open();
Assert.That(conn.Connector.BackendProcessId, Is.EqualTo(backendId));
Assert.That(conn.ExecuteScalar("SHOW search_path"), Is.EqualTo("public"));
}
[Test]
public void ArgumentExceptionOnZeroPruningInterval()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ArgumentExceptionOnZeroPruningInterval),
ConnectionPruningInterval = 0
}.ToString();
Assert.Throws<ArgumentException>(() => OpenConnection(connString));
}
[Test]
public void ArgumentExceptionOnPruningIntervalLargerThanIdleLifetime()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ArgumentExceptionOnPruningIntervalLargerThanIdleLifetime),
ConnectionIdleLifetime = 1,
ConnectionPruningInterval = 2
}.ToString();
Assert.Throws<ArgumentException>(() => OpenConnection(connString));
}
[Theory, Explicit("Slow, and flaky under pressure, based on timing")]
[TestCase(0, 2, 1, 2)] // min pool size 0, sample twice
[TestCase(1, 2, 1, 2)] // min pool size 1, sample twice
[TestCase(2, 2, 1, 2)] // min pool size 2, sample twice
[TestCase(2, 3, 2, 2)] // test rounding up, should sample twice.
[TestCase(2, 1, 1, 1)] // test sample once.
[TestCase(2, 20, 3, 7)] // test high samples.
public void PruneIdleConnectors(int minPoolSize, int connectionIdleLifeTime, int connectionPruningInterval, int samples)
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(PruneIdleConnectors),
MinPoolSize = minPoolSize,
ConnectionIdleLifetime = connectionIdleLifeTime,
ConnectionPruningInterval = connectionPruningInterval
}.ToString();
var connectionPruningIntervalMs = connectionPruningInterval * 1000;
using var conn1 = OpenConnection(connString);
using var conn2 = OpenConnection(connString);
using var conn3 = OpenConnection(connString);
Assert.True(PoolManager.TryGetValue(connString, out var pool));
conn1.Close();
conn2.Close();
AssertPoolState(pool!, open: 3, idle: 2);
var paddingMs = 100; // 100ms
var sleepInterval = connectionPruningIntervalMs + paddingMs;
var total = 0;
for (var i = 0; i < samples - 1; i++)
{
total += sleepInterval;
Thread.Sleep(sleepInterval);
// ConnectionIdleLifetime not yet reached.
AssertPoolState(pool, open: 3, idle: 2);
}
// final cycle to do pruning.
Thread.Sleep(Math.Max(sleepInterval, (connectionIdleLifeTime * 1000) - total));
// ConnectionIdleLifetime reached, we still have one connection open minimum,
// and as a result we have minPoolSize - 1 idle connections.
AssertPoolState(pool, open: Math.Max(1, minPoolSize), idle: Math.Max(0, minPoolSize - 1));
}
[Test, Description("Makes sure that when a waiting async open is is given a connection, the continuation is executed in the TP rather than on the closing thread")]
public void CloseReleasesWaiterOnAnotherThread()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(CloseReleasesWaiterOnAnotherThread),
MaxPoolSize = 1
}.ToString();
var conn1 = CreateConnection(connString);
try
{
conn1.Open(); // Pool is now exhausted
Assert.True(PoolManager.TryGetValue(connString, out var pool));
AssertPoolState(pool, open: 1, idle: 0);
Func<Task<int>> asyncOpener = async () =>
{
using (var conn2 = CreateConnection(connString))
{
await conn2.OpenAsync();
AssertPoolState(pool, open: 1, idle: 0);
}
AssertPoolState(pool, open: 1, idle: 1);
return Thread.CurrentThread.ManagedThreadId;
};
// Start an async open which will not complete as the pool is exhausted.
var asyncOpenerTask = asyncOpener();
conn1.Close(); // Complete the async open by closing conn1
var asyncOpenerThreadId = asyncOpenerTask.GetAwaiter().GetResult();
AssertPoolState(pool, open: 1, idle: 1);
Assert.That(asyncOpenerThreadId, Is.Not.EqualTo(Thread.CurrentThread.ManagedThreadId));
}
finally
{
conn1.Close();
NpgsqlConnection.ClearPool(conn1);
}
}
[Test]
public void ReleaseWaiterOnConnectionFailure()
{
var connectionString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ReleaseWaiterOnConnectionFailure),
Port = 9999,
MaxPoolSize = 1
}.ToString();
try
{
var tasks = Enumerable.Range(0, 2).Select(i => Task.Run(async () =>
{
using var conn = CreateConnection(connectionString);
await conn.OpenAsync();
})).ToArray();
try
{
Task.WaitAll(tasks);
}
catch (AggregateException e)
{
foreach (var inner in e.InnerExceptions)
Assert.That(inner, Is.TypeOf<NpgsqlException>());
return;
}
Assert.Fail();
}
finally
{
NpgsqlConnection.ClearPool(CreateConnection(connectionString));
}
}
[Test]
[TestCase(1)]
[TestCase(2)]
public void ClearPool(int iterations)
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ClearPool)
}.ToString();
NpgsqlConnection conn;
for (var i = 0; i < iterations; i++)
{
using (conn = OpenConnection(connString)) { }
// Now have one connection in the pool
Assert.True(PoolManager.TryGetValue(connString, out var pool));
AssertPoolState(pool, open: 1, idle: 1);
NpgsqlConnection.ClearPool(conn);
AssertPoolState(pool, open: 0, idle: 0);
}
}
[Test]
public void ClearWithBusy()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ClearWithBusy)
}.ToString();
ConnectorSource? pool;
using (var conn = OpenConnection(connString))
{
NpgsqlConnection.ClearPool(conn);
// conn is still busy but should get closed when returned to the pool
Assert.True(PoolManager.TryGetValue(connString, out pool));
AssertPoolState(pool, open: 1, idle: 0);
}
AssertPoolState(pool, open: 0, idle: 0);
}
[Test]
public void ClearWithNoPool()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ClearWithNoPool)
}.ToString();
using var conn = CreateConnection(connString);
NpgsqlConnection.ClearPool(conn);
}
[Test, Description("https://github.com/npgsql/npgsql/commit/45e33ecef21f75f51a625c7b919a50da3ed8e920#r28239653")]
public void PhysicalOpenFailure()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(PhysicalOpenFailure),
Port = 44444,
MaxPoolSize = 1
}.ToString();
using var conn = CreateConnection(connString);
for (var i = 0; i < 1; i++)
Assert.That(() => conn.Open(), Throws.Exception
.TypeOf<NpgsqlException>()
.With.InnerException.TypeOf<SocketException>());
Assert.True(PoolManager.TryGetValue(connString, out var pool));
AssertPoolState(pool, open: 0, idle: 0);
}
//[Test, Explicit]
//[TestCase(10, 10, 30, true)]
//[TestCase(10, 10, 30, false)]
//[TestCase(10, 20, 30, true)]
//[TestCase(10, 20, 30, false)]
public void ExercisePool(int maxPoolSize, int numTasks, int seconds, bool async)
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ApplicationName = nameof(ExercisePool),
MaxPoolSize = maxPoolSize
}.ToString();
Console.WriteLine($"Spinning up {numTasks} parallel tasks for {seconds} seconds (MaxPoolSize={maxPoolSize})...");
StopFlag = 0;
var tasks = Enumerable.Range(0, numTasks).Select(i => Task.Run(async () =>
{
while (StopFlag == 0)
{
using var conn = CreateConnection(connString);
if (async)
await conn.OpenAsync();
else
conn.Open();
}
})).ToArray();
Thread.Sleep(seconds * 1000);
Interlocked.Exchange(ref StopFlag, 1);
Console.WriteLine("Stopped. Waiting for all tasks to stop...");
Task.WaitAll(tasks);
Console.WriteLine("Done");
}
[Test]
public async Task ConnectionLifetime()
{
var builder = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ConnectionLifetime = 1
};
using var _ = CreateTempPool(builder, out var connectionString);
await using var conn = new NpgsqlConnection(connectionString);
await conn.OpenAsync();
var processId = conn.ProcessID;
await conn.CloseAsync();
await Task.Delay(2000);
await conn.OpenAsync();
Assert.That(conn.ProcessID, Is.Not.EqualTo(processId));
}
#region Support
volatile int StopFlag;
void AssertPoolState(ConnectorSource? pool, int open, int idle)
{
if (pool == null)
throw new ArgumentNullException(nameof(pool));
var (openState, idleState, _) = pool.Statistics;
Assert.That(openState, Is.EqualTo(open), $"Open should be {open} but is {openState}");
Assert.That(idleState, Is.EqualTo(idle), $"Idle should be {idle} but is {idleState}");
}
// With MaxPoolSize=1, opens many connections in parallel and executes a simple SELECT. Since there's only one
// physical connection, all operations will be completely serialized
[Test]
public Task OnePhysicalConnectionManyCommands()
{
const int numParallelCommands = 10000;
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
MaxPoolSize = 1,
MaxAutoPrepare = 5,
AutoPrepareMinUsages = 5,
Timeout = 0
}.ToString();
return Task.WhenAll(Enumerable.Range(0, numParallelCommands)
.Select(async i =>
{
using var conn = new NpgsqlConnection(connString);
await conn.OpenAsync();
using var cmd = new NpgsqlCommand("SELECT " + i, conn);
var result = await cmd.ExecuteScalarAsync();
Assert.That(result, Is.EqualTo(i));
}));
}
// When multiplexing, and the pool is totally saturated (at Max Pool Size and 0 idle connectors), we select
// the connector with the least commands in flight and execute on it. We must never select a connector with
// a pending transaction on it.
// TODO: Test not tested
[Test]
[Ignore("Multiplexing: fails")]
public void MultiplexedCommandDoesntGetExecutedOnTransactionedConnector()
{
var connString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
MaxPoolSize = 1,
Timeout = 1
}.ToString();
using var connWithTx = OpenConnection(connString);
using var tx = connWithTx.BeginTransaction();
// connWithTx should now be bound with the only physical connector available.
// Any commands execute should timeout
using var conn2 = OpenConnection(connString);
using var cmd = new NpgsqlCommand("SELECT 1", conn2);
Assert.ThrowsAsync<NpgsqlException>(() => cmd.ExecuteScalarAsync());
}
protected override NpgsqlConnection CreateConnection(string? connectionString = null)
{
var conn = base.CreateConnection(connectionString);
_cleanup.Add(conn);
return conn;
}
readonly List<NpgsqlConnection> _cleanup = new();
[TearDown]
public void Cleanup()
{
foreach (var c in _cleanup)
{
NpgsqlConnection.ClearPool(c);
}
_cleanup.Clear();
}
#endregion
}
}