Out with MagicOnion, in with LiteNetLib

Removed MagicOnion
Added LiteNetLib
Created client and server abstractions
Fixed serialization bugs
This commit is contained in:
hyperion51 2020-03-24 14:36:22 +00:00
commit e96146b7bb
869 changed files with 59401 additions and 16812 deletions

View file

@ -0,0 +1,587 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net.Clustering
{
/// <summary>
/// Represents a pooled connection to a RethinkDB cluster.
/// </summary>
public class ConnectionPool : IConnection
{
private string user;
private string password;
private string dbname;
private Seed[] seeds;
private bool discover;
private IPoolingStrategy poolingStrategy;
private TimeSpan? initialTimeout;
private SslContext sslContext;
/// <summary>
/// The default database used by queries.
/// </summary>
public string Db => this.dbname;
#region REQL AST RUNNERS
Task<dynamic> IConnection.RunAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
if( this.shutdownSignal.IsCancellationRequested )
{
throw new ReqlDriverError("HostPool is shutdown.");
}
return poolingStrategy.RunAsync<T>(term, globalOpts, cancelToken);
}
Task<Cursor<T>> IConnection.RunCursorAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
if( this.shutdownSignal.IsCancellationRequested )
{
throw new ReqlDriverError("HostPool is shutdown.");
}
return poolingStrategy.RunCursorAsync<T>(term, globalOpts, cancelToken);
}
Task<T> IConnection.RunAtomAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
if( this.shutdownSignal.IsCancellationRequested )
{
throw new ReqlDriverError("HostPool is shutdown.");
}
return poolingStrategy.RunAtomAsync<T>(term, globalOpts, cancelToken);
}
Task<T> IConnection.RunResultAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
if( this.shutdownSignal.IsCancellationRequested )
{
throw new ReqlDriverError("HostPool is shutdown.");
}
return poolingStrategy.RunResultAsync<T>(term, globalOpts, cancelToken);
}
void IConnection.RunNoReply(ReqlAst term, object globalOpts)
{
if( this.shutdownSignal.IsCancellationRequested )
{
throw new ReqlDriverError("HostPool is shutdown.");
}
poolingStrategy.RunNoReply(term, globalOpts);
}
Task<Response> IConnection.RunUnsafeAsync(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
if (this.shutdownSignal.IsCancellationRequested)
{
throw new ReqlDriverError("HostPool is shutdown.");
}
return poolingStrategy.RunUnsafeAsync(term, globalOpts, cancelToken);
}
#endregion
internal ConnectionPool(Builder builder)
{
user = builder.user ?? "admin";
password = builder.password ?? builder.authKey ?? "";
dbname = builder.dbname;
seeds = builder.seeds;
discover = builder.discover;
poolingStrategy = builder.hostpool;
initialTimeout = builder.initialTimeout;
sslContext = builder.sslContext;
}
/// <summary>
/// Shutdown the connection pool.
/// </summary>
public void Shutdown()
{
shutdownSignal?.Cancel();
poolingStrategy?.Shutdown();
if( poolingStrategy != null )
{
//shutdown all connections.
foreach( var h in poolingStrategy.HostList )
{
var conn = h.conn as Connection;
conn.Close(false);
h.MarkFailed();
}
}
}
/// <summary>
/// Used to determine if a node is currently available in the host pool
/// to receive queries. The boolean value should be considered a "rough" estimate
/// of the availability of a node in the pool. This indicator may lag behind
/// as it does not check the exact state of every node's TCP socket.
/// </summary>
public bool AnyOpen => this.poolingStrategy.HostList.Any(h => !h.Dead);
private CancellationTokenSource shutdownSignal;
private TaskCompletionSource<ConnectionPool> poolReady;
/// <summary>
/// Starts the connection pool.
/// </summary>
protected virtual void StartPool()
{
shutdownSignal = new CancellationTokenSource();
poolReady = new TaskCompletionSource<ConnectionPool>();
if( poolingStrategy == null )
{
throw new ArgumentNullException(nameof(poolingStrategy),
$"You must specify a pooling strategy '{nameof(Builder.PoolingStrategy)}' when building the connection pool.");
}
var initialSeeds = this.seeds.Select(seed =>
{
var conn = NewPoolConnection(seed.IpAddress, seed.Port);
return new {conn, EndPointId = EndpointIdentifier(seed.IpAddress, seed.Port) };
});
foreach( var conn in initialSeeds )
{
this.poolingStrategy.AddHost(conn.EndPointId, conn.conn);
}
Task.Factory.StartNew(Supervisor, TaskCreationOptions.LongRunning);
if( discover )
{
Task.Factory.StartNew(Discoverer, TaskCreationOptions.LongRunning);
}
}
/// <summary>
/// This thread is in charge of discovering new hosts via rethinkdb system
/// table change feed. If a new host is found it is added to the host pool.
/// </summary>
private void Discoverer()
{
var r = RethinkDB.R;
var changeFeed = r.Db("rethinkdb").Table("server_status").Changes()[new {include_initial = true}];
while( true )
{
if( shutdownSignal.IsCancellationRequested )
{
Log.Debug($"{nameof(Discoverer)}: Shutdown Signal Received");
break;
}
try
{
poolReady.Task.Wait();
}
catch
{
Log.Trace($"{nameof(Discoverer)}: Pool is not ready to discover new hosts.");
Thread.Sleep(1000);
}
try
{
var cursor = changeFeed.RunChanges<Server>(this);
foreach( var change in cursor )
{
if( change.NewValue != null )
{
MaybeAddNewHost(change.NewValue);
}
}
}
catch
{
Log.Trace($"{nameof(Discoverer)}: Discover change feed broke.");
Thread.Sleep(1000);
}
}
}
/// <summary>
/// Called by the discoverer thread when a new server has been added (or comes back
/// online). This method will determine if AddHost is needed. We only have monotonically
/// increasing hosts to prevent unnecessary locking on the host list array.
/// </summary>
private void MaybeAddNewHost(Server server)
{
//Ok, could be initial or new host.
//either way, see if we need to add
//the connection if it has not been
//discovered.
var port = server.Network.ReqlPort;
var realAddresses = server.Network.CanonicalAddress
.Where(s => // no localhost and no ipv6. for now.
!s.Host.StartsWith("127.0.0.1") &&
!s.Host.Contains(":"))
.Select(c => c.Host);
//now do any of the real
//addresses match the ones already in
//the host list?
var hlist = poolingStrategy.HostList;
//has it been discovered?
if( !realAddresses.Any(ip => hlist.Any(s => s.Host.Contains(ip))) )
{
//the host IP is not found, so, see if we can connect?
foreach( var ip in realAddresses )
{
//can we connect to this IP?
var test = new TcpClient();
try
{
test.Connect(ip, port);
}
catch
{
try
{
test.Shutdown();
}
catch
{
}
continue;
}
if( test.Connected )
{
test.Shutdown();
//good chance we can connect to it.
var conn = NewPoolConnection(ip, port);
var endPointId = EndpointIdentifier(ip, port);
this.poolingStrategy.AddHost(endPointId, conn);
Log.Trace($"{nameof(Discoverer)}: Server '{server.Name}' ({endPointId}) was added to the host pool. The supervisor will bring up the connection later.");
break; //stop checking IPs, one is enough.
}
}
}
else
{
Log.Trace(
$"{nameof(Discoverer)}: Server '{server.Name}' is back, but doesn't need to be added to the pool. The supervisor will re-establish the connection later.");
}
}
private string EndpointIdentifier(string ip, int port)
{
return $"{ip}:{port}";
}
/// <summary>
/// This thread is mainly in charge of supervising the connections.
/// The supervisor will kick off a worker to try to reconnect
/// connections that are due for reconnecting. It also scans though
/// the host list looking for connections that are not dead but have errors
/// and attempts to reset them.
/// </summary>
private void Supervisor()
{
var restartWorkers = new List<Task>();
while( true )
{
if( shutdownSignal.IsCancellationRequested )
{
Log.Debug($"{nameof(Supervisor)}: Shutdown Signal Received");
break;
}
var hlist = poolingStrategy.HostList;
for( int i = 0; i < hlist.Length; i++ )
{
var he = hlist[i];
var conn = he.conn as Connection;
if( he.NeedsRetry() )
{
var worker = Task.Run(() =>
{
try
{
conn.Reconnect();
}
catch( Exception e )
{
Log.Debug($"{nameof(Supervisor)}: EXCEPTION: '{he.Host}' -- {e.Message}.");
}
if( conn.Open )
{
Log.Debug($"{nameof(Supervisor)}: RETRY: Server '{he.Host}' is UP.");
he.Dead = false;
poolReady.TrySetResult(this);
}
else
{
Log.Debug($"{nameof(Supervisor)}: RETRY: Server '{he.Host}' is DOWN.");
he.RetryFailed();
}
});
restartWorkers.Add(worker);
}
}
if( restartWorkers.Any() )
{
try
{
Task.WaitAll(restartWorkers.ToArray());
}
catch{}
restartWorkers.Clear();
}
else
{
Thread.Sleep(1000);
}
}
}
/// <summary>
/// Called to create a new connection to a RethinkDB server.
/// </summary>
protected virtual Connection NewPoolConnection(string hostname, int port)
{
var connNew = new Connection(new Connection.Builder()
{
user = user,
password = password,
dbname = dbname,
hostname = hostname,
port = port,
sslContext = sslContext,
});
connNew.ConnectionError += OnConnectionError;
return connNew;
}
private void OnConnectionError(object sender, Exception e)
{
var connError = sender as Connection;
var hlist = this.poolingStrategy.HostList;
var he = hlist.FirstOrDefault(h => h.conn == connError);
he?.MarkFailed();
}
internal static Builder Build()
{
return new Builder();
}
/// <summary>
/// Disposes / shuts down the connection pool.
/// </summary>
public void Dispose()
{
this.Shutdown();
}
/// <summary>
/// The connection pool builder.
/// </summary>
public class Builder : IConnectionBuilder<Builder>
{
internal bool discover;
internal Seed[] seeds;
internal string dbname;
internal string authKey;
internal string user;
internal string password;
internal IPoolingStrategy hostpool;
internal TimeSpan? initialTimeout;
internal SslContext sslContext;
/// <summary>
/// Seed the driver with the following endpoints. Should be strings of the form "Host:Port".
/// </summary>
/// <param name="seeds">Strings of the form "Host:Port"</param>
public Builder Seed(params string[] seeds)
{
var initalSeeds = seeds.Select(s =>
{
var parts = s.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
var host = parts[0];
IPAddress.Parse(host); //make sure it's an IP address.
var port = parts.Length == 2 ? int.Parse(parts[1]) : RethinkDBConstants.DefaultPort;
return new Seed(host, port);
});
return Seed(initalSeeds);
}
/// <summary>
/// Seed the driver with the following endpoints. Should be strings of the form "Host:Port".
/// </summary>
/// <param name="seeds">Strings of the form "Host:Port"</param>
public Builder Seed(IEnumerable<string> seeds)
{
return Seed(seeds.ToArray());
}
/// <summary>
/// Seed the driver with the following endpoints.
/// </summary>
public Builder Seed(IEnumerable<Seed> seeds)
{
this.seeds = seeds.ToArray();
return this;
}
/// <summary>
/// Seed the driver with the following endpoints.
/// </summary>
public Builder Seed(params Seed[] seeds)
{
this.seeds = seeds.ToArray();
return this;
}
/// <summary>
/// Sets the initial timeout (in seconds) for connecting.
/// If a connection cannot be made within the specified time span
/// to any server, an exception is thrown. If no timeout is set,
/// the call to Connect() will block until at least one connection
/// is made.
/// </summary>
public Builder InitialTimeout(int timeout)
{
this.initialTimeout = TimeSpan.FromSeconds(timeout);
return this;
}
/// <summary>
/// discover() is used to enable host discovery, when true the driver
/// will attempt to discover any new nodes added to the cluster and then
/// start sending queries to the newly added cluster nodes.
/// </summary>
public Builder Discover(bool discoverNewHosts)
{
this.discover = discoverNewHosts;
return this;
}
/// <summary>
/// The default DB for queries.
/// </summary>
public virtual Builder Db(string val)
{
this.dbname = val;
return this;
}
/// <summary>
/// The authorization key to the cluster.
/// </summary>
public virtual Builder AuthKey(string val)
{
this.authKey = val;
return this;
}
/// <summary>
/// The user account and password to connect as (default "admin", "").
/// </summary>
public Builder User(string user, string password)
{
this.user = user;
this.password = password;
return this;
}
/// <summary>
/// The selection strategy to for selecting a connection. IE: RoundRobin, HeartBeat, or EpsilonGreedy.
/// </summary>
public Builder PoolingStrategy(IPoolingStrategy hostPool)
{
this.hostpool = hostPool;
return this;
}
/// <summary>
/// Creates and establishes the connection pool using the specified settings.
/// </summary>
/// <returns>The returned connect pool is ready to be used. At least one host will be ready to accept a query.</returns>
public virtual ConnectionPool Connect()
{
var conn = new ConnectionPool(this);
conn.StartPool();
if( initialTimeout.HasValue )
{
if( !conn.poolReady.Task.Wait(initialTimeout.Value) )
{
conn.Shutdown();
throw new ReqlDriverError("Connection timed out.");
}
}
else
{
conn.poolReady.Task.Wait();
}
return conn;
}
/// <summary>
/// Asynchronously creates and establishes the connection pool using the specified settings.
/// </summary>
/// <returns>The returned connect pool is ready to be used. At least one host will be ready to accept a query.</returns>
public virtual async Task<ConnectionPool> ConnectAsync(CancellationToken cancellationToken = default)
{
var conn = new ConnectionPool(this);
conn.StartPool();
var timeout = initialTimeout ?? TimeSpan.FromMilliseconds(-1);
var taskCompleted = await conn.poolReady.Task.WaitOrTimeout(timeout, cancellationToken)
.ConfigureAwait(false);
if (!taskCompleted)
{
conn.Shutdown();
throw new ReqlDriverError("Connection timed out.");
}
return conn;
}
/// <summary>
/// Enables SSL over the driver port
/// </summary>
/// <param name="context">Context settings for the SSL stream.</param>
public virtual Builder EnableSsl(SslContext context, string licenseTo, string licenseKey)
{
this.sslContext = context;
#if !DEBUG
if( !LicenseVerifier.VerifyLicense(licenseTo, licenseKey) )
{
throw new ReqlDriverError("The SSL/TLS usage license is invalid. Please check your license that you copied all the characters in your license. If you still have trouble, please contact support@bitarmory.com.");
}
#endif
return this;
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 95bdb149200e9f642b4d607825ed0c73
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,416 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using RethinkDb.Driver.Ast;
using Random = System.Random;
namespace RethinkDb.Driver.Net.Clustering
{
/// <summary>
/// Epsilon Greedy is an algorithm that allows HostPool not only to track failure state,
/// but also to learn about "better" options in terms of speed, and to pick from available hosts
/// based on how well they perform. This gives a weighted request rate to better
/// performing hosts, while still distributing requests to all hosts (proportionate to their performance).
///
/// A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132
///
/// To compute the weighting scores, we perform a weighted average of recent response times, over the course of
/// `decayDuration`. decayDuration may be set to null to use the default value of 5 minutes
/// We then use the supplied EpsilonValueCalculator to calculate a score from that weighted average response time.
/// </summary>
public class EpsilonGreedyHostPool : RoundRobinHostPool
{
static readonly TimeSpan DefaultDecayDuration = TimeSpan.FromMinutes(5);
/// <summary>
/// Initial epsilon value.
/// </summary>
public const double InitialEpsilon = 0.3;
/// <summary>
/// The steady state percentage of time to explore
/// </summary>
public const double MinEpsilon = 0.01; // explore one percent of the time
/// <summary>
/// The decay exploration rate.
/// </summary>
public const double EpsilonDecay = 0.90; // decay the exploration rate
/// <summary>
/// Number of bucket slot measurements
/// </summary>
public const int EpsilonBuckets = 120; //measurement slots
/// <summary>
/// Epsilon threshold that controls exploration. If a random double is
/// less than &lt; (or below) epsilon, then an round-robin exploration is performed.
/// IE: Higher the epsilon, the more chances for exploration of other hosts.
/// In the long run, epsilon will EpsilonDecay on each exploration until reaching MinEpsilon.
/// Additionally, in the long run, exploration will only take place MinEpsilon % of the time.
/// </summary>
private double epsilon;
private TimeSpan decayDuration;
private EpsilonValueCalculator calc;
private float[] weights = null;
private Timer timer;
/// <summary>
/// Random value generator.
/// </summary>
public static Random Random { get; set; }
static EpsilonGreedyHostPool()
{
Random = new Random();
}
/// <summary>
/// Construct an Epsilon Greedy HostPool
///
/// Epsilon Greedy is an algorithm that allows HostPool not only to track failure state,
/// but also to learn about "better" options in terms of speed, and to pick from available hosts
/// based on how well they perform. This gives a weighted request rate to better
/// performing hosts, while still distributing requests to all hosts (proportionate to their performance).
///
/// A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132
///
/// To compute the weighting scores, we perform a weighted average of recent response times, over the course of
/// `decayDuration`. decayDuration may be set to null to use the default value of 5 minutes
/// We then use the supplied EpsilonValueCalculator to calculate a score from that weighted average response time.
/// </summary>
/// <param name="retryDelayInitial">The initial retry delay when a host goes down. Default, null, is 30 seconds.</param>
/// <param name="retryDelayMax">The maximum retry delay when a host goes down. Default, null, is 15 minutes.</param>
/// <param name="decayDuration">The amount of time to cycle through all EpsilonBuckets (0...120).
/// This decay duration is divided by EpsilonBuckets (default: 5 min / 120 buckets = 2.5 seconds per bucket).
/// IE: The average will be taken every decayDuration/EpsilonBuckets seconds.</param>
/// <param name="calc">Given the weighted average among EpsilonBuckets slot measurements, calculate the host's EpsilonValue using EpsilonCalculators.Linear/Logarithmic/Polynomial(exponent)</param>
/// <param name="autoStartDecayTimer">Automatically starts the decay timer. If false, you need to call StartDecayTimer manually for epsilon values to be calculated correctly.</param>
public EpsilonGreedyHostPool(
TimeSpan? retryDelayInitial,
TimeSpan? retryDelayMax,
TimeSpan? decayDuration,
EpsilonValueCalculator calc,
bool autoStartDecayTimer = true)
: base(retryDelayInitial, retryDelayMax)
{
this.decayDuration = decayDuration ?? DefaultDecayDuration;
this.calc = calc;
this.epsilon = InitialEpsilon;
this.weights = Enumerable.Range(1, EpsilonBuckets)
.Select(i => i / Convert.ToSingle(EpsilonBuckets))
.ToArray();
if( autoStartDecayTimer )
{
StartDecayTimer();
}
}
/// <summary>
/// Construct an Epsilon Greedy HostPool
///
/// Epsilon Greedy is an algorithm that allows HostPool not only to track failure state,
/// but also to learn about "better" options in terms of speed, and to pick from available hosts
/// based on how well they perform. This gives a weighted request rate to better
/// performing hosts, while still distributing requests to all hosts (proportionate to their performance).
///
/// A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132
///
/// To compute the weighting scores, we perform a weighted average of recent response times, over the course of
/// `decayDuration`. decayDuration may be set to null to use the default value of 5 minutes
/// We then use the supplied EpsilonValueCalculator to calculate a score from that weighted average response time.
/// </summary>
/// <param name="decayDuration">The amount of time to cycle though all EpsilonBuckets (0...120).
/// This decay duration is divided by EpsilonBuckets (default: 5 min / 120 buckets = 2.5 seconds per bucket).
/// IE: The average will be taken every decayDuration/EpsilonBuckets seconds.</param>
/// <param name="calc">Given the weighted average among EpsilonBuckets slot measurements, calculate the host's EpsilonValue using EpsilonCalculators.Linear/Logarithmic/Polynomial(exponent)</param>
/// <param name="autoStartDecayTimer">Automatically starts the decay timer. If false, you need to call StartDecayTimer manually for epsilon values to be calculated correctly.</param>
public EpsilonGreedyHostPool(TimeSpan? decayDuration,
EpsilonValueCalculator calc,
bool autoStartDecayTimer = true) :
this(null, null, decayDuration, calc, autoStartDecayTimer)
{
}
/// <summary>
/// Epsilon threshold that controls exploration. If a random double is
/// less than &lt; (or below) epsilon, then an round-robin exploration is performed.
/// IE: Higher the epsilon, the more chances for exploration of other hosts.
/// In the long run, epsilon will EpsilonDecay on each exploration to MinEpsilon.
/// </summary>
public void SetEpsilon(float epsilon)
{
this.epsilon = epsilon;
}
/// <summary>
/// If the autoStartDecayTimer was false, you need to start
/// the decay timer manually using this method.
/// </summary>
public void StartDecayTimer()
{
var durationPerBucket = TimeSpan.FromTicks(decayDuration.Ticks / EpsilonBuckets);
this.timer = new Timer(PerformEpsilonGreedyDecay, null, Timeout.Infinite, Timeout.Infinite);
//fire now.
this.timer.Change(TimeSpan.Zero, durationPerBucket);
}
internal void PerformEpsilonGreedyDecay(object state)
{
lock( hostLock )
{
if( shuttingDown )
{
this.timer.Change(Timeout.Infinite, Timeout.Infinite);
this.timer.Dispose();
return;
}
}
//Parallel.For()
//basically advance the index
var hlist = this.hostList;
foreach( var h in hlist )
{
var nextIndex = (h.EpsilonIndex + 1) % EpsilonBuckets;
h.EpsilonCounts[nextIndex] = 0; //write ahead, before other threads
h.EpsilonValues[nextIndex] = 0; //before they see the next index
h.EpsilonAvg[nextIndex] = 0;
//advance the index, so all threads begin writing
//and recording their speed results to the new bucket
var currentIndex = Interlocked.Increment(ref h.EpsilonIndex);
//not done yet....
//now calculate the new average for the previous index now
//that threads have advanced to the new epsilon index bucket
var prevIndex = (currentIndex - 1) % EpsilonBuckets;
var averages = h.EpsilonAvg;
if( h.EpsilonCounts[prevIndex] > 0 )
{
averages[prevIndex] = h.EpsilonValues[prevIndex] / Convert.ToSingle(h.EpsilonCounts[prevIndex]);
}
}
//finally, update percentages
Update();
}
internal virtual HostEntry GetEpsilonGreedy()
{
HostEntry hostToUse = null;
//this is our exploration phase
var rand = Random.NextDouble();
if( rand < this.epsilon )
{
this.epsilon = this.epsilon * EpsilonDecay;
if( this.epsilon < MinEpsilon )
{
this.epsilon = MinEpsilon;
}
return this.GetRoundRobin();
}
var hlist = this.hostList;
var ceiling = 0.0d;
//find best.
for( var i = 0; i < hlist.Length; i++ )
{
var h = hlist[i];
if( !h.Dead && h.EpsilonWeightAverage > 0 )
{
ceiling += h.EpsilonPercentage;
if( rand <= ceiling )
{
hostToUse = h;
break;
}
}
}
if( hostToUse == null || hostToUse.Dead )
{
return this.GetRoundRobin();
}
return hostToUse;
}
private void SetWeightedAverageResponseTime(HostEntry h)
{
var value = 0f;
var lastValue = 0f;
var prevIndex = (h.EpsilonIndex - 1) % EpsilonBuckets; //capture the current index
//start from 2, skipping the current epsilon index
for( var i = 2; i <= EpsilonBuckets; i++ )
{
var pos = (prevIndex + i) % EpsilonBuckets;
var counts = h.EpsilonCounts[pos];
// Changing the line below to what I think it should be to get the weights right
var weight = weights[i - 1];
if( counts > 0 )
{
//the average
//var currentValue = h.EpsilonValues[pos] / Convert.ToSingle(counts);
var currentValue = h.EpsilonAvg[pos];
value += currentValue * weight;
lastValue = currentValue;
}
else
{
value += lastValue * weight;
}
}
h.EpsilonWeightAverage = value;
}
private void SetEpsilonValue(HostEntry h)
{
h.EpsilonValue = this.calc.CalcValueFromAvgResponseTime(h.EpsilonWeightAverage);
}
internal void MarkSuccess(HostEntry h, long start, long end)
{
var duration = TimeSpan.FromTicks(end - start);
var index = h.EpsilonIndex % EpsilonBuckets;
var counts = h.EpsilonCounts;
var values = h.EpsilonValues;
Interlocked.Increment(ref counts[index]);
Interlocked.Add(ref values[index], Convert.ToInt64(duration.TotalMilliseconds));
}
internal void Update()
{
var hlist = this.hostList;
var sumValues = 0f;
// calculate values for each host in the 0..1 range (but not normalized)
for( int i = 0; i < hlist.Length; i++ )
{
var h = hlist[i];
SetWeightedAverageResponseTime(h);
SetEpsilonValue(h);
if( !h.Dead && h.EpsilonWeightAverage > 0 )
{
sumValues += h.EpsilonValue;
}
}
//now normalize the 0..1 range to get percentage
//need to know the sum before normalizing
for( int i = 0; i < hlist.Length; i++ )
{
var h = hlist[i];
if( !h.Dead && h.EpsilonWeightAverage > 0 )
{
h.EpsilonPercentage = h.EpsilonValue / sumValues;
}
}
}
#region CONNECTION RUNNERS
public override async Task<dynamic> RunAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetEpsilonGreedy();
try
{
var start = DateTime.Now.Ticks;
var result = await host.conn.RunAsync<T>(term, globalOpts, cancelToken).ConfigureAwait(false);
var end = DateTime.Now.Ticks;
MarkSuccess(host, start, end);
return result;
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override async Task<T> RunAtomAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetEpsilonGreedy();
try
{
var start = DateTime.Now.Ticks;
var result = await host.conn.RunAtomAsync<T>(term, globalOpts, cancelToken).ConfigureAwait(false);
var end = DateTime.Now.Ticks;
MarkSuccess(host, start, end);
return result;
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override async Task<T> RunResultAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetEpsilonGreedy();
try
{
var start = DateTime.Now.Ticks;
var result = await host.conn.RunResultAsync<T>(term, globalOpts, cancelToken).ConfigureAwait(false);
var end = DateTime.Now.Ticks;
MarkSuccess(host, start, end);
return result;
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override void RunNoReply(ReqlAst term, object globalOpts)
{
HostEntry host = GetEpsilonGreedy();
try
{
var start = DateTime.Now.Ticks;
host.conn.RunNoReply(term, globalOpts);
var end = DateTime.Now.Ticks;
MarkSuccess(host, start, end);
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override async Task<Cursor<T>> RunCursorAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetEpsilonGreedy();
try
{
var start = DateTime.Now.Ticks;
var result = await host.conn.RunCursorAsync<T>(term, globalOpts, cancelToken).ConfigureAwait(false);
var end = DateTime.Now.Ticks;
MarkSuccess(host, start, end);
return result;
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
#endregion
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bfa125f7245dba7489e49fd0962d8918
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,144 @@
using System;
namespace RethinkDb.Driver.Net.Clustering
{
/// <summary>
/// Classes implementing this interface are used to convert the average response time for a host
/// into a score that can be used to weight hosts in the epsilon greedy hostpool. Lower response
/// times should yield higher scores (we want to select the faster hosts more often) The default
/// LinearEpsilonValueCalculator just uses the reciprocal of the response time. In practice, any
/// decreasing function from the positive reals to the positive reals should work.
/// </summary>
public abstract class EpsilonValueCalculator
{
/// <summary>
/// The implementation of the value calculation.
/// </summary>
public abstract float CalcValueFromAvgResponseTime(float v);
/// <summary>
/// Linear value calculation
/// </summary>
public static float LinearEpsilonValueCalculator(float v)
{
return 1.0f / v;
}
/// <summary>
/// Logarithmic value calculation
/// </summary>
public static float LogEpsilonValueCalculator(float v)
{
return LinearEpsilonValueCalculator(Convert.ToSingle(Math.Log(v + 1.0d)));
}
/// <summary>
/// Polynomial value calculation
/// </summary>
public static float PolynomialEpsilonValueCalculator(float v, float exp)
{
return LinearEpsilonValueCalculator(Convert.ToSingle(Math.Pow(v, exp)));
}
}
/// <summary>
/// Linear epsilon value calculation
/// </summary>
public class LinearEpsilonValueCalculator : EpsilonValueCalculator
{
/// <summary>
/// The implementation of the value calculation.
/// </summary>
public override float CalcValueFromAvgResponseTime(float v)
{
return LinearEpsilonValueCalculator(v);
}
}
/// <summary>
/// Logarithmic epsilon value calculation
/// </summary>
public class LogEpsilonValueCalculator : EpsilonValueCalculator
{
/// <summary>
/// The implementation of the value calculation.
/// </summary>
public override float CalcValueFromAvgResponseTime(float v)
{
return LogEpsilonValueCalculator(v);
}
}
/// <summary>
/// Polynomial epsilon value calculation
/// </summary>
public class PolynomialEpsilonValueCalculator : EpsilonValueCalculator
{
private readonly float exponent;
/// <summary>
/// Constructor with exponent
/// </summary>
public PolynomialEpsilonValueCalculator(float exponent)
{
this.exponent = exponent;
}
/// <summary>
/// The implementation of the value calculation.
/// </summary>
public override float CalcValueFromAvgResponseTime(float v)
{
return PolynomialEpsilonValueCalculator(v, exponent);
}
}
/// <summary>
/// Classes implementing this interface are used to convert the average response time for a host
/// into a score that can be used to weight hosts in the epsilon greedy hostpool. Lower response
/// times should yield higher scores (we want to select the faster hosts more often) The default
/// LinearEpsilonValueCalculator just uses the reciprocal of the response time. In practice, any
/// decreasing function from the positive reals to the positive reals should work.
/// </summary>
public static class EpsilonCalculator
{
/// <summary>
/// Linear calculator to convert the average response time for a host
/// into a score that can be used to weight hosts in the epsilon greedy hostpool. Lower response
/// times should yield higher scores (we want to select the faster hosts more often) The default
/// LinearEpsilonValueCalculator just uses the reciprocal of the response time. In practice, any
/// decreasing function from the positive reals to the positive reals should work.
/// </summary>
public static EpsilonValueCalculator Linear()
{
return new LinearEpsilonValueCalculator();
}
/// <summary>
/// Logarithmic calculator to convert the average response time for a host
/// into a score that can be used to weight hosts in the epsilon greedy hostpool. Lower response
/// times should yield higher scores (we want to select the faster hosts more often) The default
/// LinearEpsilonValueCalculator just uses the reciprocal of the response time. In practice, any
/// decreasing function from the positive reals to the positive reals should work.
/// </summary>
public static EpsilonValueCalculator Logarithmic()
{
return new LogEpsilonValueCalculator();
}
/// <summary>
/// Polynomial calculator to convert the average response time for a host
/// into a score that can be used to weight hosts in the epsilon greedy hostpool. Lower response
/// times should yield higher scores (we want to select the faster hosts more often) The default
/// LinearEpsilonValueCalculator just uses the reciprocal of the response time. In practice, any
/// decreasing function from the positive reals to the positive reals should work.
/// </summary>
public static EpsilonValueCalculator Polynomial(float exponent)
{
return new PolynomialEpsilonValueCalculator(exponent);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 63ab95c482267104fbb6a5b3a58e50ec
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,13 @@
using System;
using System.IO;
namespace RethinkDb.Driver.Net.Clustering
{
internal static class ExceptionIs
{
public static bool NetworkError(Exception e)
{
return e is IOException || e is ObjectDisposedException;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f5eda98bde10c2f4983fe9cad7dd69eb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,65 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
namespace RethinkDb.Driver.Net.Clustering
{
public class HostEntry
{
public TimeSpan RetryDelayInitial { get; set; }
public TimeSpan RetryDelayMax { get; set; }
public HostEntry(string host)
{
this.Host = host;
this.EpsilonValues = new long[EpsilonGreedyHostPool.EpsilonBuckets];
this.EpsilonCounts = new long[EpsilonGreedyHostPool.EpsilonBuckets];
this.EpsilonAvg = new float[EpsilonGreedyHostPool.EpsilonBuckets];
}
public IConnection conn;
public string Host { get; set; }
public bool Dead { get; set; }
public object Tag { get; set; }
public DateTime NextRetry { get; set; }
public int RetryCount { get; set; }
public TimeSpan RetryDelay { get; set; }
public long[] EpsilonCounts { get; set; }
public long[] EpsilonValues { get; set; }
public float[] EpsilonAvg { get; set; }
public int EpsilonIndex;
public float EpsilonValue;
public float EpsilonPercentage;
public float EpsilonWeightAverage;
public virtual void RetryFailed()
{
this.RetryCount += 1;
//double the retry delay
var newDelay = this.RetryDelay.Add(this.RetryDelay);
this.RetryDelay = newDelay < this.RetryDelayMax ? newDelay : this.RetryDelayMax;
this.NextRetry = DateTime.Now + this.RetryDelay;
}
public virtual bool NeedsRetry()
{
return this.Dead && this.NextRetry < DateTime.Now;
}
public virtual void MarkFailed()
{
if( !this.Dead )
{
this.RetryCount = 0;
this.RetryDelay = this.RetryDelayInitial;
this.NextRetry = DateTime.Now.Add(this.RetryDelay);
this.Dead = true;
Log.Trace($"Host {this.Host} is DOWN.");
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8f471588c77848547b0f43c050114615
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,82 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using System.Threading;
using System.Threading.Tasks;
using RethinkDb.Driver.Ast;
namespace RethinkDb.Driver.Net.Clustering
{
public abstract class HostPool : IPoolingStrategy
{
protected TimeSpan RetryDelayInitial;
protected TimeSpan RetryDelayMax;
//this array should be monotonically increasing, to avoid
//unnecessary thread locking and synch problems when iterating
//over the length of the list.
protected HostEntry[] hostList;
public HostPool(TimeSpan? retryDelayInitial, TimeSpan? retryDelayMax)
{
this.RetryDelayInitial = retryDelayInitial ?? TimeSpan.FromSeconds(30);
this.RetryDelayMax = retryDelayMax ?? TimeSpan.FromSeconds(900);
if( this.RetryDelayInitial < TimeSpan.FromSeconds(30)
|| this.RetryDelayMax < TimeSpan.FromSeconds(30) )
{
throw new ArgumentOutOfRangeException(
$"{nameof(retryDelayInitial)} and {nameof(retryDelayMax)} must both be greater than 30 seconds. Anything less can cause threads to pile up on each other because the default socket timeout for windows is about 20 seconds.");
}
hostList = new HostEntry[0];
}
protected object hostLock = new object();
public HostEntry[] HostList => hostList;
public virtual void AddHost(string host, Connection conn)
{
lock( hostLock )
{
if( shuttingDown ) return;
var oldHostList = this.hostList;
var nextHostList = new HostEntry[oldHostList.Length + 1];
Array.Copy(oldHostList, nextHostList, oldHostList.Length);
//add new host to the end of the array. Initially, start off as a dead
//host.
var he = new HostEntry(host)
{
conn = conn,
Dead = true,
RetryDelayInitial = RetryDelayInitial,
RetryDelayMax = RetryDelayMax
};
nextHostList[nextHostList.Length - 1] = he;
this.hostList = nextHostList;
}
}
protected bool shuttingDown = false;
public virtual void Shutdown()
{
lock( hostLock )
{
shuttingDown = true;
}
}
public abstract Task<dynamic> RunAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
public abstract Task<Cursor<T>> RunCursorAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
public abstract Task<T> RunAtomAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
public abstract Task<T> RunResultAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
public abstract void RunNoReply(ReqlAst term, object globalOpts);
public abstract Task<Response> RunUnsafeAsync(ReqlAst term, object globalOpts, CancellationToken cancelToken);
public abstract void Dispose();
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 332dbbb1c21dbd04cb399be38f4b4826
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,12 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace RethinkDb.Driver.Net.Clustering
{
public interface IPoolingStrategy : IConnection
{
HostEntry[] HostList { get; }
void AddHost(string host, Connection conn);
void Shutdown();
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c3e0292e136b7784ab49c98d00f844b9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,158 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using System.Threading;
using System.Threading.Tasks;
using RethinkDb.Driver.Ast;
namespace RethinkDb.Driver.Net.Clustering
{
/// <summary>
/// Create a new RoundRobin host pool. Each host is used in a round robin
/// strategy when processing each query.
/// </summary>
public class RoundRobinHostPool : HostPool
{
protected int nextHostIndex = -1;
/// <summary>
/// Create a new RoundRobin host pool. Each host is used in a round robin
/// strategy when processing each query. When a host goes down, the supervisor will
/// wait retryDelayInitial timespan before trying again. If the reconnect fails, the
/// retry delay is doubled. Doubling of the retry is stopped at once the retry delay
/// is greater than retryDelayMax; thereafter, every subsequent retry is retryDelayMax.
/// The retryDelayInitial is 30 seconds, and retryDelayMax is 15 minutes.
/// </summary>
/// <param name="retryDelayInitial">The initial retry delay when a host goes down. Default, null, is 30 seconds.</param>
/// <param name="retryDelayMax">The maximum retry delay when a host goes down. Default, null, is 15 minutes.</param>
public RoundRobinHostPool(TimeSpan? retryDelayInitial, TimeSpan? retryDelayMax)
: base(retryDelayInitial, retryDelayMax)
{
}
/// <summary>
/// Create a new RoundRobin host pool. Each host is used in a round robin
/// strategy when processing each query. When a host goes down, the supervisor will
/// wait retryDelayInitial timespan before trying again. If the reconnect fails, the
/// retry delay is doubled. Doubling of the retry is stopped at once the retry delay
/// is greater than retryDelayMax; thereafter, every subsequent retry is retryDelayMax.
/// The retryDelayInitial is 30 seconds, and retryDelayMax is 15 minutes.
/// </summary>
public RoundRobinHostPool() : this(null, null)
{
}
public virtual HostEntry GetRoundRobin()
{
var hostCount = this.hostList.Length; //thread capture
for( var i = 0; i < hostCount; i++ )
{
var next = Interlocked.Increment(ref nextHostIndex);
var currentIndex = next % hostCount;
var h = hostList[currentIndex];
if( !h.Dead )
{
return h;
}
}
return hostList[0];
}
#region CONNECTION RUNNERS
public override async Task<dynamic> RunAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetRoundRobin();
try
{
return await host.conn.RunAsync<T>(term, globalOpts, cancelToken).ConfigureAwait(false);
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override async Task<Cursor<T>> RunCursorAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetRoundRobin();
try
{
return await host.conn.RunCursorAsync<T>(term, globalOpts, cancelToken).ConfigureAwait(false);
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override async Task<T> RunAtomAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetRoundRobin();
try
{
return await host.conn.RunAtomAsync<T>(term, globalOpts, cancelToken).ConfigureAwait(false);
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override async Task<T> RunResultAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetRoundRobin();
try
{
return await host.conn.RunResultAsync<T>(term, globalOpts, cancelToken).ConfigureAwait(false);
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override void RunNoReply(ReqlAst term, object globalOpts)
{
HostEntry host = GetRoundRobin();
try
{
host.conn.RunNoReply(term, globalOpts);
}
catch( Exception e ) when( ExceptionIs.NetworkError(e) )
{
host.MarkFailed();
throw;
}
}
public override async Task<Response> RunUnsafeAsync(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
HostEntry host = GetRoundRobin();
try
{
return await host.conn.RunUnsafeAsync(term, globalOpts, cancelToken).ConfigureAwait(false);
}
catch (Exception e) when (ExceptionIs.NetworkError(e))
{
host.MarkFailed();
throw;
}
}
#endregion
public override void Dispose()
{
//nothing to do i guess.
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1f397cf9ab2a33e448b9238d8b44ec45
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,30 @@
using System.Net;
namespace RethinkDb.Driver.Net.Clustering
{
/// <summary>
/// Represents a RethinkDB server endpoint.
/// </summary>
public class Seed
{
/// <summary>
/// Create a new RethinkDB seed endpoint.
/// </summary>
public Seed(string ipAddress, int port = RethinkDBConstants.DefaultPort)
{
IPAddress.Parse(ipAddress);
this.IpAddress = ipAddress;
this.Port = port;
}
/// <summary>
/// RethinkDB hostname
/// </summary>
public string IpAddress { get; }
/// <summary>
/// RethinkDB port
/// </summary>
public int Port { get; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0dfbd40010e2cbb4893c7c950f799ab8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,28 @@
using Newtonsoft.Json;
namespace RethinkDb.Driver.Net.Clustering
{
internal class Server
{
public string Id { get; set; }
public string Name { get; set; }
public Network Network { get; set; }
}
internal class Network
{
[JsonProperty("canonical_addresses")]
public CanonicalAddress[] CanonicalAddress { get; set; }
public string Hostname { get; set; }
[JsonProperty("reql_port")]
public int ReqlPort { get; set; }
}
internal class CanonicalAddress
{
public string Host { get; set; }
public int Port { get; set; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f90f93b757fa5f54aa1a52e6a9db6a3c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: