Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
2de2bd2
Base commit for the multiple hosts feature
vonzshik Mar 20, 2021
a8a861c
FIxed mock not being await of a failover check query
vonzshik Mar 20, 2021
5c061ca
Attempt to fix replication tests
vonzshik Mar 20, 2021
888bff5
Yet another attempt to fix tests
vonzshik Mar 20, 2021
a35337a
Final fix for the replication tests
vonzshik Mar 20, 2021
be27ea9
Fixed rent for non-prefered connection
vonzshik Mar 20, 2021
7d63ea2
First round of change proposals
roji Mar 20, 2021
9f2a513
Small nit on documentation
vonzshik Mar 21, 2021
858be14
Changed exception messages + moved clusterValidator check
vonzshik Mar 21, 2021
f7afc2b
Got rid of flags
vonzshik Mar 21, 2021
e7cd892
Removed unnecessary todo
vonzshik Mar 21, 2021
ed54317
Fallback now also returns preferred
vonzshik Mar 21, 2021
adf2319
Small nit
vonzshik Mar 21, 2021
0fd50d6
Tiny tweaks
roji Mar 21, 2021
4ebb8d9
Renamed TargetServerType to TargetSessionAttributes (like libpq)
vonzshik Mar 21, 2021
c7f1e9f
Fixed compilation
vonzshik Mar 21, 2021
fa23b9f
Connection's Host, Port and DataSource return null (or empty string) …
vonzshik Mar 21, 2021
2ac88fe
Fixed some tests
vonzshik Mar 21, 2021
94b26a1
Fixed DataSource for multiplexing
vonzshik Mar 21, 2021
4a143ec
Added an exception if no suitable host has been found
vonzshik Mar 21, 2021
ccdb4e2
Added a basic test, fixed getting the pool by canonical string
vonzshik Mar 21, 2021
d6c8252
Added a check for the pool count
vonzshik Mar 21, 2021
a8ec69b
Added assert for multi host wrapper is not added as a new pool
vonzshik Mar 21, 2021
3b91fe3
MultiHostConnectorPoolWrapper now works correctly for enlisted connec…
vonzshik Mar 21, 2021
a4fd761
Fixed compilation
vonzshik Mar 21, 2021
040790b
Fixed a very theoretical problem of concurrent update with different …
vonzshik Mar 21, 2021
31a4f1c
Changed the ordering of timestamp
vonzshik Mar 21, 2021
4bf31d5
Added a connection string param to control the cluster state expiration
vonzshik Mar 23, 2021
4bf4f43
Added a list of critical failure codes
vonzshik Mar 23, 2021
3f2a870
Fixed test
vonzshik Mar 23, 2021
0faa240
Also consider the clusted offline if we've timed out
vonzshik Mar 24, 2021
0bcfbb8
Designate server as offline on IOException
vonzshik Mar 24, 2021
81568c2
Made TargetSessionAttributes start from 0
vonzshik Mar 24, 2021
71018b2
Removed admin shutdown from critial errors
vonzshik Mar 24, 2021
569d031
ClusterRecheckSeconds -> HostRecheckSeconds
vonzshik Mar 24, 2021
b6aaa48
NpgsqlConnection.Port is again non-nullable
vonzshik Mar 24, 2021
b35f33e
Only update the cluster state for the MultiHostPool
vonzshik Mar 24, 2021
84351b4
Fixed tests
vonzshik Mar 24, 2021
932259a
Yet another test fix
vonzshik Mar 24, 2021
637c9f6
Only throw aggregate exception if there are any exceptions
vonzshik Mar 25, 2021
43b39e6
Small rewrite of no suitable host exception
vonzshik Mar 25, 2021
402927a
Added a support for the host:pool do the default pool (and unpool con…
vonzshik Mar 25, 2021
90e4def
Throw exception if there is anything but TargetSessionAttributes.Any …
vonzshik Mar 25, 2021
f02e21d
Fixed UnixDomainSockets for windows
vonzshik Mar 25, 2021
cdf001d
Moved error handling to PostgresErrorCodes + changed to StartsWith
vonzshik Mar 26, 2021
f0707e1
Fix for state update while reading notifications
vonzshik Mar 27, 2021
2b64d10
Added a support for the ReadWrite and ReadOnly connections
vonzshik Mar 27, 2021
28e8e60
Missed
vonzshik Mar 27, 2021
2a86836
Some very first testing
roji Mar 25, 2021
ea1a90f
Fixed changing the connection's state whenever the physical connectio…
vonzshik Mar 28, 2021
b110252
Do not update the query state, if pool.Get opens a new connection
vonzshik Mar 28, 2021
ec1b2be
UpdateClusterState returns the state after update
vonzshik Mar 29, 2021
bb7d0fd
MultiHostPool now only re-checks the cluster's state if it was uknown…
vonzshik Mar 29, 2021
2997707
Wrapper references MultiHostConnectorPool directly
vonzshik Mar 29, 2021
8a426e7
Added a few missing sealed
vonzshik Mar 29, 2021
ca52b78
Yet another few missing sealed
vonzshik Mar 29, 2021
1c64a6e
Missed sealed, missed PrimaryReadOnly for fallback, simplified get logic
vonzshik Mar 30, 2021
8ead171
MultipleHostPool now checks for the cluster's state while enlisting i…
vonzshik Mar 30, 2021
bc1c2cb
Added a test for the cluster state cache
vonzshik Mar 30, 2021
258e97a
Small nit
vonzshik Mar 30, 2021
2989610
Spelling
vonzshik Mar 30, 2021
363df79
Removed unnecessary sealed keyword
vonzshik Mar 30, 2021
94937b9
Made TargetSessionAttributes a string
vonzshik Mar 30, 2021
0af2ab3
Made MultiHostConnectorPool.Get pretty
vonzshik Mar 30, 2021
67d8673
After rebase fix
vonzshik Mar 30, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions src/Npgsql/ClusterStateCache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using Npgsql.Util;
using System;
using System.Collections.Concurrent;

namespace Npgsql
{
static class ClusterStateCache
{
static readonly ConcurrentDictionary<ClusterIdentifier, ClusterInfo> Clusters = new();

internal static ClusterState GetClusterState(string host, int port, bool ignoreExpiration)
=> Clusters.TryGetValue(new(host, port), out var cs) && (ignoreExpiration || !cs.Timeout.HasExpired)
? cs.State
: ClusterState.Unknown;

#if NETSTANDARD2_0
internal static ClusterState UpdateClusterState(string host, int port, ClusterState state, DateTime timeStamp, TimeSpan stateExpiration)
=> Clusters.AddOrUpdate(
new ClusterIdentifier(host, port),
new ClusterInfo(state, new NpgsqlTimeout(stateExpiration), timeStamp),
(_, oldInfo) => oldInfo.TimeStamp >= timeStamp ? oldInfo : new ClusterInfo(state, new NpgsqlTimeout(stateExpiration), timeStamp)).State;
#else
internal static ClusterState UpdateClusterState(string host, int port, ClusterState state, DateTime timeStamp, TimeSpan stateExpiration)
=> Clusters.AddOrUpdate(
new ClusterIdentifier(host, port),
(_, newInfo) => newInfo,
(_, oldInfo, newInfo) => oldInfo.TimeStamp >= newInfo.TimeStamp ? oldInfo : newInfo,
new ClusterInfo(state, new NpgsqlTimeout(stateExpiration), timeStamp)).State;
#endif

readonly struct ClusterIdentifier : IEquatable<ClusterIdentifier>
{
readonly string _host;
readonly int _port;

public ClusterIdentifier(string host, int port) => (_host, _port) = (host, port);
public override bool Equals(object? obj) => obj is ClusterIdentifier other && Equals(other);
public bool Equals(ClusterIdentifier other) => _port == other._port && _host == other._host;
public override int GetHashCode() => HashCode.Combine(_host, _port);
}

readonly struct ClusterInfo
{
internal readonly ClusterState State;
internal readonly NpgsqlTimeout Timeout;
// While the TimeStamp is not strictly required, it does lower the risk of overwriting the current state with an old value
internal readonly DateTime TimeStamp;

public ClusterInfo(ClusterState state, NpgsqlTimeout timeout, DateTime timeStamp)
=> (State, Timeout, TimeStamp) = (state, timeout, timeStamp);
}
}

enum ClusterState : byte
{
Unknown = 0,
Comment thread
vonzshik marked this conversation as resolved.
Resolved
Offline = 1,
PrimaryReadWrite = 2,
PrimaryReadOnly = 3,
Standby = 4
}
}
99 changes: 27 additions & 72 deletions src/Npgsql/ConnectorPool.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
Expand All @@ -9,29 +8,19 @@
using System.Transactions;
using Npgsql.Logging;
using Npgsql.Util;
using static Npgsql.Util.Statics;

namespace Npgsql
{
sealed partial class ConnectorPool
sealed partial class ConnectorPool : ConnectorSource
{
#region Fields and properties

static readonly NpgsqlLogger Log = NpgsqlLogManager.CreateLogger(nameof(ConnectorPool));

internal NpgsqlConnectionStringBuilder Settings { get; }

/// <summary>
/// Contains the connection string returned to the user from <see cref="NpgsqlConnection.ConnectionString"/>
/// after the connection has been opened. Does not contain the password unless Persist Security Info=true.
/// </summary>
internal string UserFacingConnectionString { get; }

readonly int _max;
readonly int _min;
readonly bool _autoPrepare;
readonly TimeSpan _connectionLifetime;
volatile int _numConnectors;

public bool IsBootstrapped
{
Expand All @@ -41,8 +30,14 @@ public bool IsBootstrapped

volatile bool _isBootstrapped;

volatile int _numConnectors;

internal int NumConnectors => _numConnectors;

volatile int _idleCount;

internal int IdleCount => _idleCount;

/// <summary>
/// Tracks all connectors currently managed by this pool, whether idle or busy.
/// Only updated rarely - when physical connections are opened/closed - but is read in perf-sensitive contexts.
Expand All @@ -51,6 +46,8 @@ public bool IsBootstrapped

readonly bool _multiplexing;

readonly MultiHostConnectorPool? _parentPool;

/// <summary>
/// Reader side for the idle connector channel. Contains nulls in order to release waiting attempts after
/// a connector has been physically closed/broken.
Expand All @@ -74,19 +71,14 @@ public bool IsBootstrapped
volatile bool _pruningTimerEnabled;
int _pruningSampleIndex;

// Note that while the dictionary is protected by locking, we assume that the lists it contains don't need to be
// (i.e. access to connectors of a specific transaction won't be concurrent)
readonly Dictionary<Transaction, List<NpgsqlConnector>> _pendingEnlistedConnectors
= new();

static readonly SingleThreadSynchronizationContext SingleThreadSynchronizationContext = new("NpgsqlRemainingAsyncSendWorker");

// TODO: Make this configurable
const int MultiexingCommandChannelBound = 4096;

#endregion

internal (int Total, int Idle, int Busy) Statistics
internal override (int Total, int Idle, int Busy) Statistics
{
get
{
Expand All @@ -96,11 +88,14 @@ readonly Dictionary<Transaction, List<NpgsqlConnector>> _pendingEnlistedConnecto
}
}

internal ConnectorPool(NpgsqlConnectionStringBuilder settings, string connString)
internal ConnectorPool(NpgsqlConnectionStringBuilder settings, string connString, MultiHostConnectorPool? parentPool = null)
: base(settings, connString)
{
if (settings.MaxPoolSize < settings.MinPoolSize)
throw new ArgumentException($"Connection can't have 'Max Pool Size' {settings.MaxPoolSize} under 'Min Pool Size' {settings.MinPoolSize}");

_parentPool = parentPool;

// We enforce Max Pool Size, so no need to to create a bounded channel (which is less efficient)
// On the consuming side, we have the multiplexing write loop but also non-multiplexing Rents
// On the producing side, we have connections being released back into the pool (both multiplexing and not)
Expand All @@ -111,12 +106,6 @@ internal ConnectorPool(NpgsqlConnectionStringBuilder settings, string connString
_max = settings.MaxPoolSize;
_min = settings.MinPoolSize;

UserFacingConnectionString = settings.PersistSecurityInfo
? connString
: settings.ToStringWithoutPassword();

Settings = settings;

if (settings.ConnectionPruningInterval == 0)
throw new ArgumentException("ConnectionPruningInterval can't be 0.");
var connectionIdleLifetime = TimeSpan.FromSeconds(settings.ConnectionIdleLifetime);
Expand Down Expand Up @@ -171,7 +160,7 @@ internal ConnectorPool(NpgsqlConnectionStringBuilder settings, string connString
}
}

internal ValueTask<NpgsqlConnector> Rent(
internal override ValueTask<NpgsqlConnector> Get(
NpgsqlConnection conn, NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
return TryGetIdleConnector(out var connector)
Expand Down Expand Up @@ -254,7 +243,7 @@ static NpgsqlConnector AssignConnection(NpgsqlConnection connection, NpgsqlConne
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
bool TryGetIdleConnector([NotNullWhen(true)] out NpgsqlConnector? connector)
internal bool TryGetIdleConnector([NotNullWhen(true)] out NpgsqlConnector? connector)
{
while (_idleConnectorReader.TryRead(out var nullableConnector))
{
Expand Down Expand Up @@ -305,7 +294,7 @@ bool CheckIdleConnector([NotNullWhen(true)] NpgsqlConnector? connector)
return true;
}

async ValueTask<NpgsqlConnector?> OpenNewConnector(
internal async ValueTask<NpgsqlConnector?> OpenNewConnector(
NpgsqlConnection conn, NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
// As long as we're under max capacity, attempt to increase the connector count and open a new connection.
Expand All @@ -318,8 +307,9 @@ bool CheckIdleConnector([NotNullWhen(true)] NpgsqlConnector? connector)
try
{
// We've managed to increase the open counter, open a physical connections.
var connector = new NpgsqlConnector(conn) { ClearCounter = _clearCounter };
await connector.Open(timeout, async, cancellationToken);
var connector = new NpgsqlConnector(conn, this) { ClearCounter = _clearCounter };
var queryClusterState = _parentPool is not null && Settings.ReplicationMode == ReplicationMode.Off;
await connector.Open(timeout, async, queryClusterState, cancellationToken);

var i = 0;
for (; i < _max; i++)
Expand Down Expand Up @@ -353,7 +343,7 @@ bool CheckIdleConnector([NotNullWhen(true)] NpgsqlConnector? connector)
return null;
}

internal void Return(NpgsqlConnector connector)
internal override void Return(NpgsqlConnector connector)
{
Debug.Assert(!connector.InTransaction);
Debug.Assert(connector.MultiplexAsyncWritingLock == 0 || connector.IsBroken || connector.IsClosed,
Expand All @@ -374,7 +364,7 @@ internal void Return(NpgsqlConnector connector)
Debug.Assert(written);
}

internal void Clear()
internal override void Clear()
{
Interlocked.Increment(ref _clearCounter);

Expand Down Expand Up @@ -420,49 +410,14 @@ void CloseConnector(NpgsqlConnector connector)
DisablePruning();
}

#region Pending Enlisted Connections

internal void AddPendingEnlistedConnector(NpgsqlConnector connector, Transaction transaction)
{
lock (_pendingEnlistedConnectors)
{
if (!_pendingEnlistedConnectors.TryGetValue(transaction, out var list))
list = _pendingEnlistedConnectors[transaction] = new List<NpgsqlConnector>();
list.Add(connector);
}
}

internal void TryRemovePendingEnlistedConnector(NpgsqlConnector connector, Transaction transaction)
{
lock (_pendingEnlistedConnectors)
{
if (!_pendingEnlistedConnectors.TryGetValue(transaction, out var list))
return;
list.Remove(connector);
if (list.Count == 0)
_pendingEnlistedConnectors.Remove(transaction);
}
}

internal bool TryRentEnlistedPending(Transaction transaction, [NotNullWhen(true)] out NpgsqlConnector? connector)
internal override void TryRemovePendingEnlistedConnector(NpgsqlConnector connector, Transaction transaction)
{
lock (_pendingEnlistedConnectors)
{
if (!_pendingEnlistedConnectors.TryGetValue(transaction, out var list))
{
connector = null;
return false;
}
connector = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
if (list.Count == 0)
_pendingEnlistedConnectors.Remove(transaction);
return true;
}
if (_parentPool is null)
base.TryRemovePendingEnlistedConnector(connector, transaction);
else
_parentPool.TryRemovePendingEnlistedConnector(connector, transaction);
}

#endregion

#region Pruning

// Manual reactivation of timer happens in callback
Expand Down
87 changes: 87 additions & 0 deletions src/Npgsql/ConnectorSource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using Npgsql.Util;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;

namespace Npgsql
{
abstract class ConnectorSource
{
internal NpgsqlConnectionStringBuilder Settings { get; }

/// <summary>
/// Contains the connection string returned to the user from <see cref="NpgsqlConnection.ConnectionString"/>
/// after the connection has been opened. Does not contain the password unless Persist Security Info=true.
/// </summary>
internal string UserFacingConnectionString { get; }

// Note that while the dictionary is protected by locking, we assume that the lists it contains don't need to be
// (i.e. access to connectors of a specific transaction won't be concurrent)
protected readonly Dictionary<Transaction, List<NpgsqlConnector>> _pendingEnlistedConnectors
= new();

internal abstract (int Total, int Idle, int Busy) Statistics { get; }

internal ConnectorSource(NpgsqlConnectionStringBuilder settings, string connString)
{
Settings = settings;

UserFacingConnectionString = settings.PersistSecurityInfo
? connString
: settings.ToStringWithoutPassword();
}

internal abstract ValueTask<NpgsqlConnector> Get(
NpgsqlConnection conn, NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken);

internal abstract void Return(NpgsqlConnector connector);

internal abstract void Clear();

#region Pending Enlisted Connections

internal virtual void AddPendingEnlistedConnector(NpgsqlConnector connector, Transaction transaction)
{
lock (_pendingEnlistedConnectors)
{
if (!_pendingEnlistedConnectors.TryGetValue(transaction, out var list))
list = _pendingEnlistedConnectors[transaction] = new List<NpgsqlConnector>();
list.Add(connector);
}
}

internal virtual void TryRemovePendingEnlistedConnector(NpgsqlConnector connector, Transaction transaction)
{
lock (_pendingEnlistedConnectors)
{
if (!_pendingEnlistedConnectors.TryGetValue(transaction, out var list))
return;
list.Remove(connector);
if (list.Count == 0)
_pendingEnlistedConnectors.Remove(transaction);
}
}

internal virtual bool TryRentEnlistedPending(Transaction transaction, NpgsqlConnection connection,
[NotNullWhen(true)] out NpgsqlConnector? connector)
{
lock (_pendingEnlistedConnectors)
{
if (!_pendingEnlistedConnectors.TryGetValue(transaction, out var list))
{
connector = null;
return false;
}
connector = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
if (list.Count == 0)
_pendingEnlistedConnectors.Remove(transaction);
return true;
}
}

#endregion
}
}
Loading