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,12 @@
using System.Threading;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net
{
internal class Awaiter : CancellableTask
{
public Awaiter(CancellationToken cancelToken) : base(cancelToken)
{
}
}
}

View file

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

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ec7c030a04a13c94aad551c1f2dede7d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

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:

View file

@ -0,0 +1,726 @@
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Model;
using RethinkDb.Driver.Proto;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net
{
/// <summary>
/// Represents a single connection to a RethinkDB Server.
/// </summary>
public class Connection : IConnection
{
private long nextToken = 0;
private string dbname;
private readonly TimeSpan? connectTimeout;
private readonly Handshake handshake;
internal SocketWrapper Socket { get; private set; }
private readonly ConcurrentDictionary<long, ICursor> cursorCache = new ConcurrentDictionary<long, ICursor>();
private SslContext sslContext;
/// <summary>
/// Raised when the underlying network connection has thrown an exception.
/// </summary>
public event EventHandler<Exception> ConnectionError;
internal Connection(Builder builder)
{
dbname = builder.dbname;
if( builder.authKey.IsNotNullOrEmpty() && builder.user.IsNotNullOrEmpty() )
{
throw new ReqlDriverError("Either `authKey` or `user` can be used, but not both.");
}
var user = builder.user ?? "admin";
var password = builder.password ?? builder.authKey ?? "";
this.handshake = new Handshake(user, password);
this.Hostname = builder.hostname ?? "localhost";
this.Port = builder.port ?? RethinkDBConstants.DefaultPort;
connectTimeout = builder.timeout;
this.sslContext = builder.sslContext;
}
/// <summary>
/// Hostname assigned to the connection.
/// </summary>
public string Hostname { get; }
/// <summary>
/// TCP port number assigned to the connection.
/// </summary>
public int Port { get; }
/// <summary>
/// Current default database for queries on the connection. To change default database, <see cref="Use"/>
/// </summary>
public virtual string Db => dbname;
/// <summary>
/// Changes the default database on the connection.
/// </summary>
public virtual void Use(string db)
{
dbname = db;
}
/// <summary>
/// Returns the connection timeout setting.
/// </summary>
public virtual TimeSpan? Timeout => connectTimeout;
/// <summary>
/// Reconnects the underlying connection to the server.
/// </summary>
/// <param name="noreplyWait"><see cref="NoReplyWait"/></param>
/// <param name="timeout">The timeout value before throwing exception</param>
public virtual void Reconnect(bool noreplyWait = false, TimeSpan? timeout = null)
{
ReconnectAsync(noreplyWait, timeout).WaitSync();
}
/// <summary>
/// Asynchronously reconnects the underlying connection to the server.
/// </summary>
/// <param name="noreplyWait"><see cref="NoReplyWait"/></param>
/// <param name="timeout">The timeout value before throwing exception</param>
public virtual async Task ReconnectAsync(bool noreplyWait = false, TimeSpan? timeout = null)
{
Close(noreplyWait);
this.Socket = new SocketWrapper(this.Hostname, this.Port, timeout ?? connectTimeout, this.sslContext, OnSocketErrorCallback);
await this.Socket.ConnectAsync(handshake).ConfigureAwait(false);
}
/// <summary>
/// Gets the connection state of the Socket. This property will return the latest
/// known state of the Socket. When it returns false, the Socket was either never connected
/// or it is not connected anymore. When it returns true, though, there's no guarantee that the Socket
/// is still connected, but only that it was connected at the time of the last IO operation.
/// </summary>
public virtual bool Open => this.Socket?.Open ?? false;
/// <summary>
/// Retrieves the client-side local endpoint used to connect to the RethinkDB server.
/// </summary>
public virtual IPEndPoint ClientEndPoint => this.Socket?.ClientEndPoint;
/// <summary>
/// Retrieves the server-side endpoint of the connection to the RethinkDB server.
/// </summary>
public virtual IPEndPoint RemoteEndPoint => this.Socket?.RemoteEndPoint;
/// <summary>
/// Flag to check if the underlying socket has some kind of error.
/// </summary>
public virtual bool HasError => this.Socket?.HasError ?? false;
/// <summary>
/// An exception throwing method to check the state of the
/// underlying socket.
/// </summary>
/// <exception cref="ReqlDriverError">Throws when the underlying socket is closed.</exception>
public virtual void CheckOpen()
{
if( !this.Socket?.Open ?? true )
{
throw new ReqlDriverError("Connection is closed.");
}
}
/// <summary>
/// Called when the underlying <see cref="SocketWrapper"/> encounters an error.
/// </summary>
protected void OnSocketErrorCallback(Exception e)
{
CleanUpCursorCache(e.Message);
//raise event defensively. in case anyone else is subscribed
//we don't stop processing the rest of the subscribers.
this.ConnectionError.FireEvent(this, e);
}
/// <summary>
/// Called when cleanup is needed. Usually when the connection was closed
/// and can no longer be used. The <see cref="Connection"/> is in a state
/// where it must be "reconnected" before it can be used again.
/// </summary>
protected void CleanUpCursorCache(string message)
{
foreach( var cursor in this.cursorCache.Values )
{
cursor.SetError(message);
}
cursorCache.Clear();
}
/// <summary>
/// Closes the connection.
/// </summary>
public void Dispose()
{
this.Close(false);
}
/// <summary>
/// Closes the connection.
/// </summary>
/// <param name="shouldNoReplyWait"><see cref="NoReplyWait"/></param>
public virtual void Close(bool shouldNoReplyWait = true)
{
if( this.Socket != null )
{
try
{
if( shouldNoReplyWait )
{
NoReplyWait();
}
}
finally
{
nextToken = 0;
this.Socket.Close();
this.Socket = null;
}
}
CleanUpCursorCache("The connection is closed.");
}
/// <summary>
/// Ensure that previous queries executed with NoReplyWait have been processed
/// by the server. Note that this guarantee only apples to queries run on the
/// same connection.
/// </summary>
public virtual void NoReplyWait()
{
NoReplyWaitAsync().WaitSync();
}
/// <summary>
/// Asynchronously ensures that previous queries executed with NoReplyWait have
/// been processed by the server. Note that this guarantee only apples to queries
/// run on the same connection.
/// </summary>
public virtual Task NoReplyWaitAsync(CancellationToken cancelToken = default)
{
return RunQueryWaitAsync(Query.NoReplyWait(NewToken()), cancelToken);
}
/// <summary>
/// Return the server name and server UUID being used by a connection.
/// </summary>
public virtual async Task<Server> ServerAsync(CancellationToken cancelToken = default)
{
var response = await SendQuery(Query.ServerInfo(NewToken()), cancelToken, awaitResponse: true).ConfigureAwait(false);
if( response.Type == ResponseType.SERVER_INFO )
{
return response.Data[0].ToObject<Server>(Converter.Serializer);
}
throw new ReqlDriverError("Did not receive a SERVER_INFO response.");
}
/// <summary>
/// Return the server name and server UUID being used by a connection.
/// </summary>
public virtual Server Server()
{
return ServerAsync().WaitSync();
}
private long NewToken()
{
return Interlocked.Increment(ref nextToken);
}
Task<Response> SendQueryReply(Query query)
{
return SendQuery(query, CancellationToken.None, awaitResponse: true);
}
void SendQueryNoReply(Query query)
{
SendQuery(query, CancellationToken.None, awaitResponse: false);
}
/// <summary>
/// Fast SUCCESS_SEQUENCE or SUCCESS_PARTIAL conversion without DLR dynamic.
/// </summary>
protected virtual async Task<Cursor<T>> RunQueryCursorAsync<T>(Query query, CancellationToken cancelToken)
{
var res = await SendQuery(query, cancelToken, awaitResponse: true).ConfigureAwait(false);
if( res.IsPartial || res.IsSequence )
{
return new Cursor<T>(this, query, res);
}
if (res.IsError)
{
throw res.MakeError(query);
}
throw new ReqlDriverError(
$"The query response cannot be converted to a Cursor<T>. The run helper " +
$"works with SUCCESS_SEQUENCE or SUCCESS_PARTIAL results. The server " +
$"response was {res.Type}. If the server response can be handled by " +
$"this run method check T. Otherwise, if the server response cannot " +
$"be handled by this run helper use `.RunAtom<T>` or `.RunResult<T>`.");
}
/// <summary>
/// Fast SUCCESS_ATOM conversion without the DLR dynamic
/// </summary>
protected virtual async Task<T> RunQueryAtomAsync<T>(Query query, CancellationToken cancelToken)
{
var res = await SendQuery(query, cancelToken, awaitResponse: true).ConfigureAwait(false);
if( res.IsAtom )
{
try
{
if( typeof(T).IsJToken() )
{
if( res.Data[0].Type == JTokenType.Null ) return (T)(object)null;
var fmt = FormatOptions.FromOptArgs(query.GlobalOptions);
Converter.ConvertPseudoTypes(res.Data[0], fmt);
return (T)(object)res.Data[0]; //ugh ugly. find a better way to do this.
//return res.Data[0].ToObject<T>();
}
return res.Data[0].ToObject<T>(Converter.Serializer);
}
catch( IndexOutOfRangeException ex )
{
throw new ReqlDriverError("Atom response was empty!", ex);
}
}
if( res.IsError )
{
throw res.MakeError(query);
}
throw new ReqlDriverError(
$"The query response cannot be converted to an object of T or List<T>. This run helper works with SUCCESS_ATOM results. The server response was {res.Type}. If the server response can be handled by this run method try converting to T or List<T>. Otherwise, if the server response cannot be handled by this run helper use another run helper like `.RunCursor` or `.RunResult<T>`.");
}
/// <summary>
/// Fast SUCCESS_ATOM or SUCCESS_SEQUENCE conversion without the DLR dynamic
/// </summary>
private async Task<T> RunQueryResultAsync<T>(Query query, CancellationToken cancelToken)
{
var res = await SendQuery(query, cancelToken, awaitResponse: true).ConfigureAwait(false);
if( res.IsAtom )
{
try
{
if( typeof(T).IsJToken() )
{
if( res.Data[0].Type == JTokenType.Null ) return (T)(object)null;
var fmt = FormatOptions.FromOptArgs(query.GlobalOptions);
Converter.ConvertPseudoTypes(res.Data[0], fmt);
return (T)(object)res.Data[0]; //ugh ugly. find a better way to do this.
}
return res.Data[0].ToObject<T>(Converter.Serializer);
}
catch ( IndexOutOfRangeException ex )
{
throw new ReqlDriverError("Atom response was empty!", ex);
}
}
if( res.IsSequence )
{
if( typeof(T).IsJToken() )
{
var fmt = FormatOptions.FromOptArgs(query.GlobalOptions);
Converter.ConvertPseudoTypes(res.Data, fmt);
return (T)(object)res.Data; //ugh ugly. find a better way to do this.
}
return res.Data.ToObject<T>(Converter.Serializer);
}
if (res.IsError)
{
throw res.MakeError(query);
}
throw new ReqlDriverError(
$"The query response cannot be converted to an object of T or List<T> " +
$"because the server response was {res.Type}. The `.RunResult<T>` helper " +
$"only works with SUCCESS_ATOM or SUCCESS_SEQUENCE responses. When the query " +
$"response grows larger (over 100K), the response type from the server " +
$"can change from SUCCESS_SEQUENCE to SUCCESS_PARTIAL; in which case, you'll " +
$"need to use `.RunCursor` that handles both SUCCESS_SEQUENCE and SUCCESS_PARTIAL " +
$"response types. The `.RunResult` run helper is only meant to be a " +
$"convenience method for relatively quick and smaller responses.");
}
/// <summary>
/// Asynchronously ensures that previous queries executed with NoReplyWait have
/// been processed by the server. Note that this guarantee only apples to queries
/// run on the same connection.
/// </summary>
protected virtual async Task RunQueryWaitAsync(Query query, CancellationToken cancelToken)
{
var res = await SendQuery(query, cancelToken, awaitResponse: true).ConfigureAwait(false);
if( res.IsWaitComplete )
{
return;
}
if (res.IsError)
{
throw res.MakeError(query);
}
throw new ReqlDriverError(
$"The query response is not WAIT_COMPLETE. The returned query is {res.Type}. You need to call the appropriate run method that handles the response type for your query.");
}
/// <summary>
/// Run the query but it's return type is standard dynamic.
/// </summary>
protected async Task<dynamic> RunQueryAsync<T>(Query query, CancellationToken cancelToken)
{
//If you need to continue after an await, **while inside the driver**,
//as a library writer, you must use ConfigureAwait(false) on *your*
//await to tell the compiler NOT to resume
//on synchronization context (if one is present).
//
//The top most await (your user) will capture the correct synchronization context
//(if any) when they await on a query's run.
//
// https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Async-library-methods-should-consider-using-Task-ConfigureAwait-false-
// http://blogs.msdn.com/b/lucian/archive/2013/11/23/talk-mvp-summit-async-best-practices.aspx
//
var res = await SendQuery(query, cancelToken, awaitResponse: true).ConfigureAwait(false);
if( res.IsAtom )
{
try
{
if( typeof(T).IsJToken() )
{
if( res.Data[0].Type == JTokenType.Null ) return null;
var fmt = FormatOptions.FromOptArgs(query.GlobalOptions);
Converter.ConvertPseudoTypes(res.Data[0], fmt);
return res.Data[0];
}
return res.Data[0].ToObject(typeof(T), Converter.Serializer);
}
catch ( IndexOutOfRangeException ex )
{
throw new ReqlDriverError("Atom response was empty!", ex);
}
}
else if( res.IsPartial || res.IsSequence )
{
return new Cursor<T>(this, query, res);
}
else if( res.IsWaitComplete )
{
return null;
}
else
{
throw res.MakeError(query);
}
}
/// <summary>
/// Sends the query over to the underlying socket for sending.
/// </summary>
protected Task<Response> SendQuery(Query query, CancellationToken cancelToken, bool awaitResponse)
{
if( this.Socket == null ) throw new ReqlDriverError("No socket open.");
return this.Socket.SendQuery(query.Token, query.Serialize(), awaitResponse, cancelToken);
}
/// <summary>
/// Prepares the query by setting the default DB if it doesn't exist.
/// </summary>
protected Query PrepareQuery(ReqlAst term, OptArgs globalOpts)
{
SetDefaultDb(globalOpts);
Query q = Query.Start(NewToken(), term, globalOpts);
if( globalOpts?.ContainsKey("noreply") == true )
{
throw new ReqlDriverError("Don't provide the noreply option as an optarg. Use `.RunNoReply` instead of `.Run`");
}
return q;
}
/// <summary>
/// Sets the database if it's not already set.
/// </summary>
protected void SetDefaultDb(OptArgs globalOpts)
{
if( globalOpts?.ContainsKey("db") == false && this.dbname != null )
{
// Only override the db global arg if the user hasn't
// specified one already and one is specified on the connection
globalOpts.With("db", this.dbname);
}
if( globalOpts?.ContainsKey("db") == true )
{
// The db arg must be wrapped in a db ast object
globalOpts.With("db", new Db(Arguments.Make(globalOpts["db"])));
}
}
#region REQL AST RUNNERS
//Typically called by the surface API of ReqlAst.
Task<dynamic> IConnection.RunAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
Query q = PrepareQuery(term, OptArgs.FromAnonType(globalOpts));
return RunQueryAsync<T>(q, cancelToken);
}
Task<Cursor<T>> IConnection.RunCursorAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
Query q = PrepareQuery(term, OptArgs.FromAnonType(globalOpts));
return RunQueryCursorAsync<T>(q, cancelToken);
}
Task<T> IConnection.RunAtomAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
Query q = PrepareQuery(term, OptArgs.FromAnonType(globalOpts));
return RunQueryAtomAsync<T>(q, cancelToken);
}
Task<T> IConnection.RunResultAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
Query q = PrepareQuery(term, OptArgs.FromAnonType(globalOpts));
return RunQueryResultAsync<T>(q, cancelToken);
}
void IConnection.RunNoReply(ReqlAst term, object globalOpts)
{
var opts = OptArgs.FromAnonType(globalOpts);
SetDefaultDb(opts);
opts.With("noreply", true);
SendQueryNoReply(Query.Start(NewToken(), term, opts));
}
Task<Response> IConnection.RunUnsafeAsync(ReqlAst term, object globalOpts, CancellationToken cancelToken)
{
Query q = PrepareQuery(term, OptArgs.FromAnonType(globalOpts));
return SendQuery(q, cancelToken, awaitResponse: true);
}
#endregion
#region CURSOR SUPPORT
internal virtual Task<Response> Continue(ICursor cursor)
{
return SendQueryReply(Query.Continue(cursor.Token));
}
internal virtual void Stop(ICursor cursor)
{
/*
neumino: The END query itself doesn't come back with a response
cowboy: ..... a Query[token,STOP], is like sending a very last CONTINUE, r:[] would contain the last bits of the finished seq
neumino: Yes a STOP is like a very last CONTINUE
neumino: If you have a pending CONTINUE, and send a STOP, you should get back two SUCCESS_SEQUENCE
*/
//this.Socket?.CancelAwaiter(cursor.Token);
SendQueryNoReply(Query.Stop(cursor.Token));
}
internal void AddToCache(long token, ICursor cursor)
{
if( this.Socket == null )
throw new ReqlDriverError("Can't add to cache when not connected.");
cursorCache[token] = cursor;
}
internal void RemoveFromCache(long token)
{
ICursor removed;
if( !cursorCache.TryRemove(token, out removed) )
{
Log.Trace($"Could not remove cursor token {token} from cursorCache.");
}
}
#endregion
internal static Builder Build()
{
return new Builder();
}
/// <summary>
/// The Connection builder.
/// </summary>
public class Builder : IConnectionBuilder<Builder>
{
internal string hostname = null;
internal int? port = null;
internal string dbname = null;
internal TimeSpan? timeout = null;
internal string authKey = null;
internal string user = null;
internal string password = null;
internal SslContext sslContext = null;
/// <summary>
/// The hostname or IP address of the server.
/// </summary>
/// <param name="hostnameOrIp">Hostname or IP address</param>
public virtual Builder Hostname(string hostnameOrIp)
{
this.hostname = hostnameOrIp;
return this;
}
/// <summary>
/// The TCP port to connect with.
/// </summary>
public virtual Builder Port(int driverPort)
{
this.port = driverPort;
return this;
}
/// <summary>
/// The default DB for queries.
/// </summary>
public virtual Builder Db(string database)
{
this.dbname = database;
return this;
}
/// <summary>
/// The authorization key to the server.
/// </summary>
public virtual Builder AuthKey(string key)
{
this.authKey = key;
return this;
}
/// <summary>
/// The user account and password to connect as (default "admin", "").
/// </summary>
public virtual Builder User(string user, string password)
{
this.user = user;
this.password = password;
return this;
}
/// <summary>
/// Note: Timeout is not used when using connectAsync();
/// </summary>
/// <param name="seconds"></param>
/// <returns></returns>
public virtual Builder Timeout(int seconds)
{
this.timeout = TimeSpan.FromSeconds(seconds);
return this;
}
/// <summary>
/// Creates and establishes the connection using the specified settings.
/// </summary>
public virtual Connection Connect()
{
return ConnectAsync().WaitSync();
}
/// <summary>
/// Asynchronously creates and establishes the connection using the specified settings.
/// </summary>
public virtual async Task<Connection> ConnectAsync()
{
var conn = new Connection(this);
await conn.ReconnectAsync().ConfigureAwait(false);
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;
}
}
}
internal sealed class LicenseVerifier
{
public static bool VerifyLicense(string licenseTo, string licenseKey)
{
AssertKeyIsNotBanned(licenseKey);
const string modulusString =
"tccosXHxEfxzsO1NgsAbGT0X+WuQMUYcj7r2UJCHDqqq3TbR7UoAgzjm3MV1k/eJxRnURypw2wj98eafyajeprk3lK6BnWa5tG8S7p3QU5kkUo7TnmTj8rRkTk9RwArIGGjKfCVZToE06UQudsJmw1UK3mku1qF0/hD909cSiCM=";
const string exponentString = "AQAB";
var data = Encoding.UTF8.GetBytes(licenseTo);
var rsaParameters = new RSAParameters
{
Modulus = Convert.FromBase64String(modulusString),
Exponent = Convert.FromBase64String(exponentString)
};
#if STANDARD
using( var rsa = System.Security.Cryptography.RSA.Create() )
#else
using( var rsa = new System.Security.Cryptography.RSACryptoServiceProvider() )
#endif
{
var licenseData = Convert.FromBase64String(licenseKey);
rsa.ImportParameters(rsaParameters);
bool verified = false;
#if STANDARD
verified = rsa.VerifyData(data, licenseData, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
#else
verified = rsa.VerifyData(data, CryptoConfig.MapNameToOID("SHA256"), licenseData);
#endif
return verified;
}
}
internal static void AssertKeyIsNotBanned(string licenseKey)
{
var isBanned =
licenseKey.StartsWith(
"fuIIq8Pre2NzXVi0otn54PCx22NNAbNReAsk/ylDIV/ZrWeC60B+C76oj3/Ptb8b02vxPYdN6nR2nz3IgYG/O6Zy5TKoYl2UnR2aNq8sKxjv9siwsjMS82EZB8pxs0UwPoz+xmrKY40sqiIz+thDI2EH1MlGoZd+KfJImJp7fvI=")
||
licenseKey.StartsWith(
"tE4z+qpOuKWP4XfmAbnyepzI6m/qx2DaI+aDkMes94ujERmA7O6bb0100+LiClLymVLXYXNvkRBg7ot6NGlfyli/8x1h3IgL+HD8gFoWdTAN4oG8wE8ZyrFugnqmAHUDAy4h/KrOqB8VUXwGQh8Y/0ZxOBQb0KOaZJC/MUMbve8=");
if( isBanned ) throw new UnauthorizedAccessException("The license key has expired.");
}
}
}

View file

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

View file

@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RethinkDb.Driver.Net.JsonConverters;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net
{
/// <summary>
/// Configuration for RethinkDB's JSON serializer
/// </summary>
public static class Converter
{
static Converter()
{
InitializeDefault();
}
/// <summary>
/// Initializes default serializer settings. There is no need to call this manually
/// as it is already initialized in the static constructor.
/// </summary>
public static void InitializeDefault()
{
Converters = new JsonConverter[]
{
DateTimeConverter = new ReqlDateTimeConverter(),
BinaryConverter = new ReqlBinaryConverter(),
GroupingConverter = new ReqlGroupingConverter(),
PocoExprConverter = new PocoExprConverter(),
};
var settings = new JsonSerializerSettings()
{
Converters = Converters
};
Serializer = JsonSerializer.CreateDefault(settings);
}
/// <summary>
/// An array of the JSON converters in this static class.
/// </summary>
public static JsonConverter[] Converters { get; set; }
/// <summary>
/// The JSON serializer used for ser/deser.
/// </summary>
public static JsonSerializer Serializer { get; set; }
/// <summary>
/// DateTime converter to/from ReQL pseudo types
/// </summary>
public static ReqlDateTimeConverter DateTimeConverter { get; set; }
/// <summary>
/// Binary converter to/from ReQL pseudo types
/// </summary>
public static ReqlBinaryConverter BinaryConverter { get; set; }
/// <summary>
/// DateTime converter from ReQL grouping types
/// </summary>
public static ReqlGroupingConverter GroupingConverter { get; set; }
/// <summary>
/// Allows anonymous types to be composed with ReQL expressions like R.Now()
/// </summary>
public static PocoExprConverter PocoExprConverter { get; set; }
/// <summary>
/// The pseudo type key
/// </summary>
public const string PseudoTypeKey = "$reql_type$";
/// <summary>
/// Discriminator for TIME types.
/// </summary>
public const string Time = "TIME";
/// <summary>
/// Discriminator for GROUPED_DATA types.
/// </summary>
public const string GroupedData = "GROUPED_DATA";
/// <summary>
/// Discriminator for GEOMETRY types.
/// </summary>
public const string Geometry = "GEOMETRY";
/// <summary>
/// Discriminator for BINARY types.
/// </summary>
public const string Binary = "BINARY";
/// <summary>
/// Method for converting pseudo types in JToken (JObjects)
/// </summary>
public static void ConvertPseudoTypes(JToken data, FormatOptions fmt)
{
var reqlTypes = data.SelectTokens("$..$reql_type$").ToList();
foreach (var typeToken in reqlTypes)
{
var reqlType = typeToken.Value<string>();
//JObject -> JProerty -> JVaule:$reql_type$, go backup the chain.
var pesudoObject = typeToken.Parent.Parent as JObject;
JToken convertedValue = null;
if (reqlType == Time)
{
if (fmt.RawTime)
continue;
convertedValue = new JValue(GetTime(pesudoObject));
}
else if (reqlType == GroupedData)
{
if (fmt.RawGroups)
continue;
convertedValue = GetGrouped(pesudoObject);
}
else if (reqlType == Binary)
{
if (fmt.RawBinary)
continue;
convertedValue = new JValue(GetBinary(pesudoObject));
}
else if (reqlType == Geometry)
{
// Nothing specific here
continue;
}
else
{
// Just leave unknown pseudo-types alone
continue;
}
pesudoObject.Replace(convertedValue);
}
}
private static object GetTime(JObject value)
{
double epoch_time = value["epoch_time"].ToObject<double>();
string timezone = value["timezone"].ToString();
if (Serializer.DateParseHandling == DateParseHandling.DateTime)
{
return ReqlDateTimeConverter.ConvertDateTime(epoch_time, timezone, Serializer.DateTimeZoneHandling);
}
else
{
return ReqlDateTimeConverter.ConvertDateTimeOffset(epoch_time, timezone);
}
}
private static byte[] GetBinary(JObject value)
{
var base64 = value["data"].Value<string>();
return Convert.FromBase64String(base64);
}
private static JToken GetGrouped(JObject value)
{
return value["data"];
}
}
}

View file

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

View file

@ -0,0 +1,114 @@
using System;
using System.Security.Cryptography;
using System.Text;
namespace RethinkDb.Driver.Net
{
internal class Crypto
{
private static readonly SecureRandom SecureRandom = new SecureRandom();
private const int NonceBytes = 18;
public const int Pbkdf2Iterations = 4096;
public static byte[] Sha256(byte[] clientKey)
{
using( var sha = new IncrementalSHA256() )
{
sha.AppendData(clientKey);
return sha.GetHashAndReset();
}
}
public static byte[] Hmac(byte[] key, string str)
{
using( var mac = new HMACSHA256(key) )
{
return mac.ComputeHash(Encoding.UTF8.GetBytes(str));
}
}
public static byte[] Pbkdf2(byte[] password, byte[] salt, int iterations = Pbkdf2Iterations)
{
/*
// Algorithm Credits to https://github.com/vexocide
//
// Implements PBKDF2WithHmacSHA256 in Java. Beautifully Amazing.
using (var mac = new HMACSHA256(password))
{
mac.TransformBlock(salt, 0, salt.Length, salt, 0);
byte[] i = { 0, 0, 0, 1 };
mac.TransformFinalBlock(i, 0, i.Length);
byte[] t = mac.Hash;
mac.Initialize();
byte[] u = t;
for (uint c = 2; c <= iterations; c++)
{
t = mac.ComputeHash(t);
for (int j = 0; j < mac.HashSize / 8; j++)
{
u[j] ^= t[j];
}
}
return u;
}
*/
#if STANDARD
using( var macSalt = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, password) )
#endif
using ( var mac = new HMACSHA256(password) )
{
#if STANDARD
macSalt.AppendData(salt);
#else
mac.TransformBlock(salt, 0, salt.Length, salt, 0);
#endif
byte[] i = {0, 0, 0, 1};
#if STANDARD
macSalt.AppendData(i);
#else
mac.TransformFinalBlock(i, 0, i.Length);
#endif
#if STANDARD
byte[] t = macSalt.GetHashAndReset();
#else
byte[] t = mac.Hash;
mac.Initialize();
#endif
byte[] u = t;
for( uint c = 2; c <= iterations; c++ )
{
t = mac.ComputeHash(t);
for( int j = 0; j < mac.HashSize / 8; j++ )
{
u[j] ^= t[j];
}
}
return u;
}
}
public static string MakeNonce()
{
byte[] rawNonce = new byte[NonceBytes];
SecureRandom.GetBytes(rawNonce);
return Convert.ToBase64String(rawNonce);
}
public static byte[] Xor(byte[] a, byte[] b)
{
byte[] result = new byte[a.Length];
for( var i = 0; i < result.Length; i++ )
result[i] = (byte)(a[i] ^ b[i]);
return result;
}
}
}

View file

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

View file

@ -0,0 +1,340 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Model;
using RethinkDb.Driver.Proto;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net
{
/// <summary>
/// Cursor that handles stream types of responses.
/// </summary>
/// <typeparam name="T">The underlying item being iterated over.</typeparam>
public class Cursor<T> : IEnumerable<T>, IEnumerator<T>, ICursor
{
private readonly Connection conn;
private bool TIsJToken = false;
private Query query;
internal Cursor(Connection conn, Query query, Response firstResponse)
{
this.conn = conn;
this.query = query;
this.IsFeed = firstResponse.IsFeed;
this.Token = query.Token;
this.TIsJToken = typeof(T).IsJToken();
this.fmt = FormatOptions.FromOptArgs(query.GlobalOptions);
this.conn.AddToCache(this.Token, this);
//is the first response all there is?
this.sequenceFinished = firstResponse.Type == ResponseType.SUCCESS_SEQUENCE;
MaybeSendContinue();
ExtendBuffer(firstResponse);
}
/// <summary>
/// The size of the buffered items.
/// </summary>
public int BufferedSize => this.items.Count;
/// <summary>
/// The list of items in the queue. This does not include the Current item.
/// </summary>
public List<T> BufferedItems => items.Select(Convert).ToList();
/// <summary>
/// Whether the Cursor is any kind of feed.
/// </summary>
public bool IsFeed { get; }
/// <summary>
/// A flag to determine if the cursor can still be used.
/// </summary>
public bool IsOpen => this.Error == null;
/// <summary>
/// If any, the error that disabled the cursor.
/// </summary>
public Exception Error { get; private set; }
/// <summary>
/// The token of the query that the cursor represents. This is a unique cursor ID.
/// </summary>
public long Token { get; }
private Task<Response> pendingContinue;
private readonly Queue<JToken> items = new Queue<JToken>();
//we need these to keep track of the run options
//for things like "time_format: 'raw'"
private FormatOptions fmt;
void AdvanceCurrent()
{
var item = items.Dequeue();
this.Current = Convert(item);
}
/// <summary>
/// Advances the cursor to the next item. This is a blocking operation
/// if there are no buffered items to advance on and a response from
/// the server is needed.
/// </summary>
public bool MoveNext()
{
return MoveNextAsync().WaitSync();
}
/// <summary>
/// Asynchronously advances the cursor to the next item.
/// </summary>
///
/// <param name="cancelToken">
/// <para>
/// Used to cancel the advancement of the next item if it takes too long.
/// </para>
/// <para>
/// The <paramref name="cancelToken"/> has no effect if the cursor still
/// has buffered items to draw from. Cancellation pertains to the
/// wait on an outstanding network request that is taking too long.
/// </para>
/// <para>
/// If the <paramref name="cancelToken"/> is canceled before
/// <see cref="MoveNextAsync"/> is called, <see cref="TaskCanceledException"/>
/// is thrown immediately before any operation begins.
/// </para>
/// <para>
/// Additionally, cancellation is a safe operation. When
/// a <see cref="TaskCanceledException"/> is thrown, the exception will
/// not disrupt the ordering of cursor items. Cancellation only pertains to
/// the semantic *wait* on a pending network request. Cancellation will not
/// cancel an already in-progress network request for more items.
/// Therefore, a <see cref="TaskCanceledException"/>
/// will not disrupt the success of future precedent calls
/// to <see cref="MoveNextAsync"/>. Network requests will still arrive
/// in order at some later time.
/// </para>
/// </param>
///
/// <exception cref="TaskCanceledException">
/// <para>
/// Thrown when <paramref name="cancelToken"/> is canceled before
/// <see cref="MoveNextAsync"/> is called.
/// </para>
/// <para>
/// Thrown when there are no buffered items to draw from and operation
/// requires waiting on a response from the server.
/// </para>
/// <para>
/// When <see cref="TaskCanceledException"/> is thrown the exception
/// will not disrupt the ordering of items. Any non-canceled precedent calls to
/// <see cref="MoveNextAsync"/> from an antecedent canceled <see cref="TaskCanceledException"/>
/// will advance the cursor normally and maintain ordering of items.
/// </para>
/// </exception>
public async Task<bool> MoveNextAsync(CancellationToken cancelToken = default)
{
cancelToken.ThrowIfCancellationRequested();
while( items.Count == 0 )
{
if( !this.IsOpen ) return false;
//our buffer is empty, we need to expect the next batch of items.
if( !this.pendingContinue.IsCompleted )
{
//the next batch isn't here yet. so,
//let's await and honor the cancelToken.
//create a task that is controlled by the token.
using( var cancelTask = new CancellableTask(cancelToken) )
{
//now await on either task, pending or the cancellation of the CancellableTask.
await Task.WhenAny(this.pendingContinue, cancelTask.Task).ConfigureAwait(false);
//if it was the cancelTask that triggered the continuation... throw if requested.
cancelToken.ThrowIfCancellationRequested();
//else, no cancellation was requested.
//we can proceed by processing the results we awaited for.
} //ensure the disposal of the cancelToken registration upon exiting scope
}
//if we get here, the next batch should be available.
var newBatch = this.pendingContinue.Result;
this.pendingContinue = null;
MaybeSendContinue();
this.ExtendBuffer(newBatch);
}
//either way, we have something to advance.
AdvanceCurrent();
return true;
}
void MaybeSendContinue()
{
if( this.IsOpen && this.conn.Open && pendingContinue == null && !sequenceFinished )
{
this.pendingContinue = this.conn.Continue(this);
}
}
void ExtendBuffer(Response response)
{
if( this.IsOpen )
{
if( response.IsPartial )
{
//SUCCESS_PARTIAL
foreach( var jToken in response.Data )
{
items.Enqueue(jToken);
}
}
else if( response.IsSequence )
{
//SUCCESS_SEQUENCE
foreach( var jToken in response.Data )
{
items.Enqueue(jToken);
}
this.SequenceFinished();
}
else if ( response.IsError )
{
var ex = response.MakeError(query);
this.Shutdown(ex);
throw ex;
}
else
{
throw new NotSupportedException(
$"Cursor cannot extend the response. The response was not a SUCCESS_PARTIAL or SUCCESS_SEQUENCE. The response type the cursor received was {response.Type}.");
}
}
}
T Convert(JToken token)
{
if( this.TIsJToken )
{
Converter.ConvertPseudoTypes(token, fmt);
return (T)(object)token; //ugh ugly. find a better way to do this.
}
return token.ToObject<T>(Converter.Serializer);
}
bool sequenceFinished;
void SequenceFinished()
{
sequenceFinished = true;
this.Shutdown("The sequence is finished. There are no more items to iterate over.");
}
/// <summary>
/// Disposes the Cursor so it cannot be used anymore.
/// </summary>
public void Dispose()
{
this.Shutdown("The Cursor was disposed. Iteration cannot continue. If the Cursor was used in a LINQ expression LINQ may have called .Dispose() on the Cursor.");
}
/// <summary>
/// Forcibly closes the Cursor so it cannot be used anymore.
/// </summary>
public void Close()
{
this.Shutdown("The Cursor was forcibly closed. Iteration cannot continue.");
}
void Shutdown(Exception ex)
{
if (this.conn.Open && this.IsOpen)
{
conn.RemoveFromCache(this.Token);
if (!sequenceFinished)
{
conn.Stop(this);
}
SetError(ex);
}
else
{
SetError(ex);
}
}
void Shutdown(string reason)
{
Shutdown(new InvalidOperationException(reason));
}
internal void SetError(Exception ex)
{
if (this.Error != null) return;
this.Error = ex;
}
//Some trickery just so we don't expose SetError
//on the public API surface.
internal void SetError(string msg)
{
SetError(new InvalidOperationException(msg));
}
void ICursor.SetError(string msg)
{
SetError(msg);
}
/// <summary>
/// Clears <see cref="BufferedItems"/>. Any advancement after the buffer
/// is cleared will cause a new batch of items to be buffered.
/// </summary>
public void ClearBuffer()
{
this.items.Clear();
}
/// <summary>
/// Throws always. A Cursor cannot be reset. Hidden from public use.
/// </summary>
/// <exception cref="InvalidOperationException">Throws always. A Cursor cannot be reset.</exception>
void IEnumerator.Reset()
{
throw new InvalidOperationException("A Cursor cannot be reset.");
}
/// <summary>
/// The current item in iteration.
/// </summary>
public T Current { get; private set; }
object IEnumerator.Current => this.Current;
/// <summary>
/// The cursor's enumerator
/// </summary>
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}

View file

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

View file

@ -0,0 +1,52 @@
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Model;
namespace RethinkDb.Driver.Net
{
/// <summary>
/// ReQL pseudo type format options for JToken (JObject, JArray) derivatives.
/// </summary>
public class FormatOptions
{
/// <summary>
/// Leave $reql_time$:TIME types as raw
/// </summary>
public bool RawTime { get; set; }
/// <summary>
/// Leave $reql_time$:GROUPED_DATA types as raw
/// </summary>
public bool RawGroups { get; set; }
/// <summary>
/// Leave $reql_time$:BINARY types as raw
/// </summary>
public bool RawBinary { get; set; }
/// <summary>
/// Format options for JToken
/// </summary>
public FormatOptions()
{
}
/// <summary>
/// Factory method for FormatOptions from OptArgs
/// </summary>
public static FormatOptions FromOptArgs(OptArgs args)
{
var fmt = new FormatOptions();
// TODO: find a better way to do this.
ReqlAst datum;
var value = args.TryGetValue("time_format", out datum) ? ((Datum)datum).datum : new Datum("native").datum;
fmt.RawTime = value.Equals("raw");
value = args.TryGetValue("binary_format", out datum) ? ((Datum)datum).datum : new Datum("native").datum;
fmt.RawBinary = value.Equals("raw");
value = args.TryGetValue("group_format", out datum) ? ((Datum)datum).datum : new Datum("native").datum;
fmt.RawGroups = value.Equals("raw");
return fmt;
}
}
}

View file

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

View file

@ -0,0 +1,305 @@
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace RethinkDb.Driver.Net
{
internal class Handshake
{
const Proto.Version Version = Proto.Version.V1_0;
const long SubProtocolVersion = 0L;
const Proto.Protocol Protocol = Proto.Protocol.JSON;
private const string ClientKey = "Client Key";
private const string ServerKey = "Server Key";
private string username;
private string password;
private IProtocolState state;
private interface IProtocolState
{
IProtocolState NextState(string response);
byte[] ToSend();
bool IsFinished { get; }
}
public Handshake(string username, string password)
{
this.username = username;
this.password = password;
}
class InitialState : IProtocolState
{
private readonly string nonce;
private readonly string username;
private readonly byte[] password;
internal InitialState(string username, string password)
{
this.username = username;
this.password = Encoding.UTF8.GetBytes(password);
this.nonce = Crypto.MakeNonce();
}
public IProtocolState NextState(string response)
{
if( response != null )
{
throw new ReqlDriverError("Unexpected response");
}
// We could use a json serializer, but it's fairly straightforward
var clientFirstMessageBare = new ScramAttributes()
.SetUsername(username)
.SetNonce(nonce);
byte[] jsonBytes = Encoding.UTF8.GetBytes(
"{" +
"\"protocol_version\":" + SubProtocolVersion + "," +
"\"authentication_method\":\"SCRAM-SHA-256\"," +
"\"authentication\":" + "\"n,," + clientFirstMessageBare + "\"" +
"}"
);
byte[] msg;
using (var ms = new MemoryStream())
using (var bw = new BinaryWriter(ms))
{
bw.Write((int)Version);
bw.Write(jsonBytes);
bw.Write('\0');
bw.Flush();
msg = ms.ToArray();
}
return new WaitingForProtocolRange(
nonce, password, clientFirstMessageBare, msg);
}
public byte[] ToSend()
{
return null;
}
public bool IsFinished => false;
}
class WaitingForProtocolRange : IProtocolState
{
private string nonce;
private byte[] message;
private ScramAttributes clientFirstMessageBare;
private byte[] password;
internal WaitingForProtocolRange(
string nonce,
byte[] password,
ScramAttributes clientFirstMessageBare,
byte[] message)
{
this.nonce = nonce;
this.password = password;
this.clientFirstMessageBare = clientFirstMessageBare;
this.message = message;
}
public IProtocolState NextState(string response)
{
var json = JObject.Parse(response);
ThrowIfFailure(json);
long minVersion = json["min_protocol_version"].Value<long>();
long maxVersion = json["max_protocol_version"].Value<long>();
if( SubProtocolVersion < minVersion || SubProtocolVersion > maxVersion )
{
throw new ReqlDriverError(
"Unsupported protocol version " + SubProtocolVersion +
", expected between " + minVersion + " and " + maxVersion);
}
return new WaitingForAuthResponse(nonce, password, clientFirstMessageBare);
}
public byte[] ToSend()
{
return message;
}
public bool IsFinished => false;
}
private class WaitingForAuthResponse : IProtocolState
{
private string nonce;
private byte[] password;
private ScramAttributes clientFirstMessageBare;
public WaitingForAuthResponse(string nonce, byte[] password, ScramAttributes clientFirstMessageBare)
{
this.nonce = nonce;
this.password = password;
this.clientFirstMessageBare = clientFirstMessageBare;
}
public IProtocolState NextState(string response)
{
var json = JObject.Parse(response);
ThrowIfFailure(json);
string serverFirstMessage = json["authentication"].Value<string>();
ScramAttributes serverAuth = ScramAttributes.From(serverFirstMessage);
if( !serverAuth.Nonce.StartsWith(nonce) )
{
throw new ReqlAuthError("Invalid nonce from server");
}
ScramAttributes clientFinalMessageWithoutProof = new ScramAttributes()
.SetHeaderAndChannelBinding("biws")
.SetNonce(serverAuth.Nonce);
// SaltedPassword := Hi(Normalize(password), salt, i)
byte[] saltedPassword = Crypto.Pbkdf2(
password, serverAuth.Salt, serverAuth.IterationCount);
// ClientKey := HMAC(SaltedPassword, "Client Key")
byte[] clientKey = Crypto.Hmac(saltedPassword, ClientKey);
// StoredKey := H(ClientKey)
byte[] storedKey = Crypto.Sha256(clientKey);
// AuthMessage := client-first-message-bare + "," +
// server-first-message + "," +
// client-final-message-without-proof
string authMessage =
clientFirstMessageBare + "," +
serverFirstMessage + "," +
clientFinalMessageWithoutProof;
// ClientSignature := HMAC(StoredKey, AuthMessage)
byte[] clientSignature = Crypto.Hmac(storedKey, authMessage);
// ClientProof := ClientKey XOR ClientSignature
byte[] clientProof = Crypto.Xor(clientKey, clientSignature);
// ServerKey := HMAC(SaltedPassword, "Server Key")
byte[] serverKey = Crypto.Hmac(saltedPassword, ServerKey);
// ServerSignature := HMAC(ServerKey, AuthMessage)
byte[] serverSignature = Crypto.Hmac(serverKey, authMessage);
ScramAttributes auth = clientFinalMessageWithoutProof
.SetClientProof(clientProof);
byte[] authJson = Encoding.UTF8.GetBytes("{\"authentication\":\"" + auth + "\"}");
byte[] message;
using (var ms = new MemoryStream())
using (var bw = new BinaryWriter(ms))
{
bw.Write(authJson);
bw.Write('\0');
bw.Flush();
message = ms.ToArray();
}
return new WaitingForAuthSuccess(serverSignature, message);
}
public byte[] ToSend()
{
return null;
}
public bool IsFinished => false;
}
private class WaitingForAuthSuccess : IProtocolState
{
private byte[] serverSignature;
private byte[] message;
public WaitingForAuthSuccess(byte[] serverSignature, byte[] message)
{
this.serverSignature = serverSignature;
this.message = message;
}
public IProtocolState NextState(string response)
{
var json = JObject.Parse(response);
ThrowIfFailure(json);
ScramAttributes auth = ScramAttributes
.From(json["authentication"].Value<string>());
if( !auth.ServerSignature.SequenceEqual(serverSignature) )
{
throw new ReqlAuthError("Invalid server signature");
}
return new HandshakeSuccess();
}
public byte[] ToSend()
{
return message;
}
public bool IsFinished => false;
}
private class HandshakeSuccess : IProtocolState
{
public IProtocolState NextState(string response)
{
return this;
}
public byte[] ToSend()
{
return null;
}
public bool IsFinished => true;
}
static void ThrowIfFailure(JObject json)
{
if( !json["success"].Value<bool>() )
{
long errorCode = json["error_code"].Value<long>();
if( errorCode >= 10 && errorCode <= 20 )
{
throw new ReqlAuthError(json["error"].Value<string>());
}
else
{
throw new ReqlDriverError(json["error"].Value<string>());
}
}
}
public void Reset()
{
this.state = new InitialState(this.username, this.password);
}
public byte[] NextMessage(string response)
{
this.state = this.state.NextState(response);
return this.state.ToSend();
}
public bool IsFinished => this.state.IsFinished;
}
}

View file

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

View file

@ -0,0 +1,45 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using RethinkDb.Driver.Ast;
namespace RethinkDb.Driver.Net
{
/// <summary>
/// Represents a marker interface for either a Connection or ConnectionPool.
/// This should really only be used for IoC purpose. Do not call methods
/// explicitly from this interface, instead the Run* methods at the end of a query.
/// </summary>
public interface IConnection : IDisposable
{
/// <summary>
/// DO NOT CALL THIS METHOD EXPLICITLY. USE Run*() METHODS AT THE END OF YOUR QUERY.
/// </summary>
Task<dynamic> RunAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
/// <summary>
/// DO NOT CALL THIS METHOD EXPLICITLY. USE Run*() METHODS AT THE END OF YOUR QUERY.
/// </summary>
Task<Cursor<T>> RunCursorAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
/// <summary>
/// DO NOT CALL THIS METHOD EXPLICITLY. USE Run*() METHODS AT THE END OF YOUR QUERY.
/// </summary>
Task<T> RunAtomAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
/// <summary>
/// DO NOT CALL THIS METHOD EXPLICITLY. USE Run*() METHODS AT THE END OF YOUR QUERY.
/// </summary>
Task<T> RunResultAsync<T>(ReqlAst term, object globalOpts, CancellationToken cancelToken);
/// <summary>
/// DO NOT CALL THIS METHOD EXPLICITLY. USE Run*() METHODS AT THE END OF YOUR QUERY.
/// </summary>
void RunNoReply(ReqlAst term, object globalOpts);
/// <summary>
/// DO NOT CALL THIS METHOD EXPLICITLY. USE Run*() METHODS AT THE END OF YOUR QUERY.
/// </summary>
Task<Response> RunUnsafeAsync(ReqlAst term, object globalOpts, CancellationToken cancelToken);
}
}

View file

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

View file

@ -0,0 +1,20 @@
namespace RethinkDb.Driver.Net
{
internal interface IConnectionBuilder<TBuilder>
{
/// <summary>
/// The default DB for queries.
/// </summary>
TBuilder Db(string val);
/// <summary>
/// The authorization key to the server.
/// </summary>
TBuilder AuthKey(string key);
/// <summary>
/// The user account and password to connect as (default "admin", "").
/// </summary>
TBuilder User(string user, string password);
}
}

View file

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

View file

@ -0,0 +1,10 @@
using System.Collections;
namespace RethinkDb.Driver.Net
{
internal interface ICursor : IEnumerable, IEnumerator
{
void SetError(string msg);
long Token { get; }
}
}

View file

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

View file

@ -0,0 +1,71 @@
using System;
using System.Security.Cryptography;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net
{
/// <summary>
/// Cross platform SHA 256 Hasher
/// </summary>
public class IncrementalSHA256 : IDisposable
{
#if STANDARD
private IncrementalHash hasher;
#else
private SHA256 hasher;
#endif
/// <summary>
/// Constructor
/// </summary>
public IncrementalSHA256()
{
#if STANDARD
hasher = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
#else
hasher = SHA256.Create();
#endif
}
/// <summary>
/// Updates the hash value
/// </summary>
public void AppendData(byte[] data)
{
#if STANDARD
hasher.AppendData(data);
#else
hasher.TransformBlock(data, 0, data.Length, null, 0);
#endif
}
/// <summary>
/// Gets the final hash calculation in hex string.
/// </summary>
public string GetHashStringAndReset()
{
return StringHelper.GetHexString(GetHashAndReset());
}
/// <summary>
/// Gets the final hash calculation as byte array.
/// </summary>
public byte[] GetHashAndReset()
{
#if STANDARD
return hasher.GetHashAndReset();
#else
hasher.TransformFinalBlock(new byte[0], 0, 0);
return hasher.Hash;
#endif
}
/// <summary>
/// Disposes the hasher.
/// </summary>
public void Dispose()
{
hasher.Dispose();
}
}
}

View file

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

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ef607916570060e43b43ffe5f2b2b130
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,25 @@
using System;
using Newtonsoft.Json;
namespace RethinkDb.Driver.Net.JsonConverters
{
internal static class ExtensionsForJsonConverters
{
public static void ReadAndAssertProperty(this JsonReader reader, string propertyName)
{
ReadAndAssert(reader);
if( (reader.TokenType != JsonToken.PropertyName) || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase) )
{
throw new JsonSerializationException($"Expected JSON property '{propertyName}'.");
}
}
public static void ReadAndAssert(this JsonReader reader)
{
if( !reader.Read() )
{
throw new JsonSerializationException("Unexpected end.");
}
}
}
}

View file

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

View file

@ -0,0 +1,61 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using Newtonsoft.Json;
namespace RethinkDb.Driver.Net.JsonConverters
{
public class ReqlBinaryConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartObject(); //convert to $reql_type$
writer.WritePropertyName(Converter.PseudoTypeKey);
writer.WriteValue(Converter.Binary);
writer.WritePropertyName("data");
writer.WriteValue(Convert.ToBase64String((byte[])value));
writer.WriteEndObject();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if( reader.TokenType == JsonToken.Null )
{
return null;
}
if( reader.TokenType != JsonToken.StartObject )
{
var msg = string.Join(" ",
$"The JSON representation of binary data (byte[]) when parsing the server response is not a {Converter.PseudoTypeKey}:{Converter.Binary} object.",
$"This happens if your JSON document contains binary data (byte[]) in some other format (like a base64 string only) rather than a native RethinkDB pseudo type {Converter.PseudoTypeKey}:{Converter.Binary} object.",
$"If you are overriding the default Ser/Deserialization process, you need to make sure byte[] is a native {Converter.PseudoTypeKey}:{Converter.Binary} objects before using the built-in {nameof(ReqlBinaryConverter)}.",
"See https://rethinkdb.com/docs/data-types/ for more information about how binary data is represented in RethinkDB.");
throw new JsonSerializationException(msg);
}
reader.ReadAndAssertProperty(Converter.PseudoTypeKey);
var reql_type = reader.ReadAsString();
if( reql_type != Converter.Binary )
{
throw new JsonSerializationException($"Expected {Converter.PseudoTypeKey} should be {Converter.Binary} but got {reql_type}.");
}
reader.ReadAndAssertProperty("data");
var data = reader.ReadAsBytes();
//realign and get out of the pseudo type
//one more post read to align out of { reql_type:BINARY, data:""}
reader.ReadAndAssert();
return data;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(byte[]);
}
}
}

View file

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

View file

@ -0,0 +1,143 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RethinkDb.Driver.Net.JsonConverters
{
public class ReqlDateTimeConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(Converter.PseudoTypeKey);
writer.WriteValue(Converter.Time);
writer.WritePropertyName("epoch_time");
DateTimeOffset dto;
if( value is DateTimeOffset )
{
dto = (DateTimeOffset)value;
}
else //value is DateTime
{
var dt = (DateTime)value;
if( dt == DateTime.MinValue )
{ //Ugh. Make MinValue consistent cross-platform on Windows and Linux.
//See: https://github.com/dotnet/corefx/issues/9019
// https://github.com/bchavez/RethinkDb.Driver/issues/66
//Either way, we shunt the value to MinValue and avoid
//conversion of MinValue.
dto = DateTimeOffset.MinValue;
}
else
{
dto = new DateTimeOffset((DateTime)value);
}
}
writer.WriteValue(ToUnixTime(dto));
writer.WritePropertyName("timezone");
var offset = $"{(dto.Offset < TimeSpan.Zero ? "-" : "+")}{dto.Offset.ToString("hh':'mm")}";
writer.WriteValue(offset);
writer.WriteEndObject();
}
//http://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c
public static double ToUnixTime(DateTimeOffset date)
{
return ToUnixTime(date.UtcTicks);
}
public static double ToUnixTime(long utcTicks)
{
return (utcTicks - 621355968000000000) / 10000000.0;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if( reader.TokenType == JsonToken.Null )
{
return null;
}
if( reader.TokenType != JsonToken.StartObject )
{
var msg = string.Join(" ",
$"The JSON representation of a DateTime/DateTimeOffset when parsing the server response is not a {Converter.PseudoTypeKey}:{Converter.Time} object.",
$"This happens if your JSON document contains DateTime/DateTimeOffsets in some other format (like an ISO8601 string) rather than a native RethinkDB pseudo type {Converter.PseudoTypeKey}:{Converter.Time} object.",
$"If you are overriding the default Ser/Deserialization process, you need to make sure DateTime/DateTimeOffset are native {Converter.PseudoTypeKey}:{Converter.Time} objects before using the built-in {nameof(ReqlDateTimeConverter)}.",
"See https://rethinkdb.com/docs/data-types/ for more information about how Date and Times are represented in RethinkDB.");
throw new JsonSerializationException(msg);
}
reader.ReadAndAssertProperty(Converter.PseudoTypeKey);
var reql_type = reader.ReadAsString();
if( reql_type != Converter.Time )
{
throw new JsonSerializationException($"Expected {Converter.PseudoTypeKey} should be {Converter.Time} but got {reql_type}.");
}
reader.ReadAndAssertProperty("epoch_time");
var epoch_time = reader.ReadAsDouble();
if( epoch_time == null )
{
throw new JsonSerializationException($"The {Converter.PseudoTypeKey}:{Converter.Time} object doesn't have an epoch_time value.");
}
reader.ReadAndAssertProperty("timezone");
var timezone = reader.ReadAsString();
//realign and get out of the pseudo type
//one more post read to align out of { reql_type:TIME, .... }
reader.ReadAndAssert();
if( objectType == typeof(DateTimeOffset) ||
objectType == typeof(DateTimeOffset?) )
{
return ConvertDateTimeOffset(epoch_time.Value, timezone);
}
else
{
return ConvertDateTime(epoch_time.Value, timezone, serializer.DateTimeZoneHandling);
}
}
public static DateTimeOffset ConvertDateTimeOffset(double epoch_time, string timezone)
{
var tz = TimeSpan.Parse(timezone.Substring(1));
if (!timezone.StartsWith("+"))
tz = -tz;
var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
var dt = epoch + TimeSpan.FromSeconds(epoch_time);
return dt.ToOffset(tz);
}
public static DateTime ConvertDateTime(double epoch_time, string timezone, DateTimeZoneHandling tzHandle)
{
var dto = ConvertDateTimeOffset(epoch_time, timezone);
switch (tzHandle)
{
case DateTimeZoneHandling.Local:
return dto.LocalDateTime;
case DateTimeZoneHandling.Utc:
return dto.UtcDateTime;
case DateTimeZoneHandling.Unspecified:
return dto.DateTime;
case DateTimeZoneHandling.RoundtripKind:
return dto.Offset == TimeSpan.Zero ? dto.UtcDateTime : dto.LocalDateTime;
default:
throw new JsonSerializationException("Invalid date time handling value.");
}
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime) ||
objectType == typeof(DateTimeOffset) ||
objectType == typeof(DateTime?) ||
objectType == typeof(DateTimeOffset?);
}
}
}

View file

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

View file

@ -0,0 +1,33 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net.JsonConverters
{
public class PocoExprConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var ast = value as ReqlExpr;
var expr = ast.Build() as JToken;
writer.WriteRawValue(expr.ToString(Formatting.None, Converter.Converters));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead => false;
public override bool CanConvert(Type objectType)
{
return objectType.IsASubclassOf(typeof(ReqlExpr));
}
}
}

View file

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

View file

@ -0,0 +1,97 @@
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RethinkDb.Driver.Model;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net.JsonConverters
{
public class ReqlGroupingConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new JsonSerializationException($"{nameof(ReqlGroupingConverter)} can't be used to serialize grouping results.");
}
//EXAMPLE:
// "r": [
// {
// "$reql_type$": "GROUPED_DATA",
// "data": [
// [
// "Alice",
// [
// { "id": 5, "player": "Alice", "points": 7, "type": "free"},
// { "id": 12, "player": "Alice", "points": 2, "type": "free" }
// ]
// ],
// [
// "Bob",
// [
// { "id": 2, "player": "Bob", "points": 15, "type": "ranked" },
// { "id": 11, "player": "Bob", "points": 10, "type": "free" }
// ]
// ]
// ]
// }
// ]
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
reader.ReadAndAssertProperty(Converter.PseudoTypeKey);
var reql_type = reader.ReadAsString();
if( reql_type != Converter.GroupedData )
{
throw new JsonSerializationException($"Expected {Converter.PseudoTypeKey} should be {Converter.GroupedData} but got {reql_type}.");
}
reader.ReadAndAssertProperty("data");
//move reader to property value
reader.ReadAndAssert();
//... probably find a better way to do this.
var genType = objectType.GetGenericTypeDefinition();
IList list;
if( genType == typeof(GroupedResultSet<,>) )
{
list = (IList)Activator.CreateInstance(objectType);
objectType = objectType.BaseType().GenericTypeArguments[0];
}
else
{
var listType = typeof(List<>).MakeGenericType(objectType);
list = (IList)Activator.CreateInstance(listType);
}
var data = serializer.Deserialize<List<JArray>>(reader);
foreach( var group in data )
{
var key = group[0]; //key, group value in common
var items = group[1]; //the grouped items
var grouping = Activator.CreateInstance(objectType, key, items);
list.Add(grouping);
}
//.Select(arr => Activator.CreateInstance(objectType, arr) ).ToList();
return list;
}
public override bool CanWrite => false;
public override bool CanConvert(Type objectType)
{
if( objectType.IsGenericType() )
{
var genType = objectType.GetGenericTypeDefinition();
return genType == typeof(GroupedResult<,>) ||
genType == typeof(GroupedResultSet<,>);
}
return false;
}
}
}

View file

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

View file

@ -0,0 +1,138 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Model;
using RethinkDb.Driver.Proto;
namespace RethinkDb.Driver.Net
{
/// <summary>
/// Response from the server.
/// </summary>
public class Response
{
private const string TypeKey = "t";
private const string NotesKey = "n";
private const string ErrorKey = "e";
private const string ProfileKey = "p";
private const string BacktraceKey = "b";
private const string DataKey = "r";
/// <summary>
/// The token ID associated with the query.
/// </summary>
public long Token { get; }
/// <summary>
/// The response type <see cref="ResponseType"/>.
/// </summary>
public ResponseType Type { get; }
/// <summary>
/// Notes about the response <see cref="ResponseNote"/>
/// </summary>
public List<ResponseNote> Notes { get; private set; }
/// <summary>
/// The data payload.
/// </summary>
public JArray Data { get; private set; }
/// <summary>
/// Profile information about the query
/// </summary>
public Profile Profile { get; private set; }
/// <summary>
/// Backtrace information about a failed query.
/// </summary>
public Backtrace Backtrace { get; private set; }
/// <summary>
/// The error type, if any.
/// </summary>
public ErrorType? ErrorType { get; private set; }
private Response(long token, ResponseType responseType)
{
this.Token = token;
this.Type = responseType;
}
/// <summary>
/// Parses a Response from a raw JSON string
/// </summary>
public static Response ParseFrom(long token, string buf)
{
//we check here because it's possibly very expensive to ship this buf around in the call stack
if( Log.IsTraceEnabled ) Log.Trace($"JSON Recv: Token: {token}, JSON: {buf}");
var jsonResp = ParseJson(buf);
var responseType = jsonResp[TypeKey].ToObject<ResponseType>();
var responseNotes = jsonResp[NotesKey]?.ToObject<List<ResponseNote>>() ?? new List<ResponseNote>();
ErrorType? et = jsonResp[ErrorKey]?.ToObject<ErrorType>();
var profile = Profile.FromJsonArray((JArray)jsonResp[ProfileKey]);
var backtrace = Backtrace.FromJsonArray((JArray)jsonResp[BacktraceKey]);
var res = new Response(token, responseType)
{
ErrorType = et,
Profile = profile,
Backtrace = backtrace,
Data = (JArray)jsonResp[DataKey] ?? new JArray(),
Notes = responseNotes
};
return res;
}
private static JObject ParseJson(string buf)
{
using( var reader = new JsonTextReader(new StringReader(buf)) )
{
return Converter.Serializer.Deserialize<JObject>(reader);
}
}
public virtual bool IsWaitComplete => this.Type == ResponseType.WAIT_COMPLETE;
/* Whether the response is any kind of feed */
public virtual bool IsFeed => this.Notes.Any(rn => rn.IsFeed());
/* Whether the response is any kind of error */
public virtual bool IsError => this.Type.IsError();
/* What type of success the response contains */
public virtual bool IsAtom => this.Type == ResponseType.SUCCESS_ATOM;
public virtual bool IsSequence => this.Type == ResponseType.SUCCESS_SEQUENCE;
public virtual bool IsPartial => this.Type == ResponseType.SUCCESS_PARTIAL;
public virtual ReqlError MakeError(Query query)
{
string msg = this.Data.Count > 0 ? (string)Data[0] : "Unknown error message";
return new ErrorBuilder(msg, this.Type)
.SetBacktrace(this.Backtrace)
.SetErrorType(this.ErrorType.GetValueOrDefault())
.SetTerm(query)
.Build();
}
/// <summary>
/// Pretty printing a response for diagnostics.
/// </summary>
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}

View file

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

View file

@ -0,0 +1,153 @@
using System;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net
{
internal class ScramAttributes
{
// Getters
public string AuthIdentity { get; private set; } // a
public string Username { get; private set; } // n
public string Nonce { get; private set; } // r
public string HeaderAndChannelBinding { get; private set; } // c
public byte[] Salt { get; private set; } // s
public int IterationCount { get; private set; } // i
public string ClientProof { get; private set; } // p
public byte[] ServerSignature { get; private set; } // v
public string Error { get; private set; } // e
public string OriginalString = null;
public static ScramAttributes From(ScramAttributes other)
{
var obj = new ScramAttributes
{
AuthIdentity = other.AuthIdentity,
Username = other.Username,
Nonce = other.Nonce,
HeaderAndChannelBinding = other.HeaderAndChannelBinding,
Salt = other.Salt,
IterationCount = other.IterationCount,
ClientProof = other.ClientProof,
ServerSignature = other.ServerSignature,
Error = other.Error
};
return obj;
}
public static ScramAttributes From(string input)
{
var sa = new ScramAttributes
{
OriginalString = input
};
foreach( string section in input.Split(','))
{
string[] keyVal = section.Split(new[] {'='}, 2);
sa.SetAttribute(keyVal[0], keyVal[1]);
}
return sa;
}
private void SetAttribute(string key, string val)
{
switch( key )
{
case "a":
this.AuthIdentity = val;
break;
case "n":
this.Username = val;
break;
case "r":
this.Nonce = val;
break;
case "m":
throw new ReqlAuthError("m field disallowed");
case "c":
this.HeaderAndChannelBinding = val;
break;
case "s":
this.Salt = Convert.FromBase64String(val);
break;
case "i":
this.IterationCount = int.Parse(val);
break;
case "p":
this.ClientProof = val;
break;
case "v":
this.ServerSignature = Convert.FromBase64String(val);
break;
case "e":
this.Error = val;
break;
// Supposed to ignore unexpected fields
}
}
public override string ToString()
{
if( this.OriginalString.IsNotNullOrEmpty() )
{
return OriginalString;
}
string output = "";
if( this.Username.IsNotNullOrEmpty() )
{
output += ",n=" + this.Username;
}
if( this.Nonce.IsNotNullOrEmpty() )
{
output += ",r=" + this.Nonce;
}
if( this.HeaderAndChannelBinding.IsNotNullOrEmpty() )
{
output += ",c=" + this.HeaderAndChannelBinding;
}
if( this.ClientProof.IsNotNullOrEmpty() )
{
output += ",p=" + this.ClientProof;
}
if( output.StartsWith(",") )
{
return output.Substring(1);
}
else
{
return output;
}
}
// Setters with coercion
public ScramAttributes SetUsername(string username)
{
ScramAttributes next = ScramAttributes.From(this);
next.Username = username.Replace("=", "=3D").Replace(",", "=2C");
return next;
}
public ScramAttributes SetNonce(string nonce)
{
ScramAttributes next = ScramAttributes.From(this);
next.Nonce = nonce;
return next;
}
public ScramAttributes SetHeaderAndChannelBinding(string hacb)
{
ScramAttributes next = ScramAttributes.From(this);
next.HeaderAndChannelBinding = hacb;
return next;
}
public ScramAttributes SetClientProof(byte[] clientProof)
{
ScramAttributes next = ScramAttributes.From(this);
next.ClientProof = Convert.ToBase64String(clientProof);
return next;
}
}
}

View file

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

View file

@ -0,0 +1,20 @@
using System;
using System.Security.Cryptography;
namespace RethinkDb.Driver.Net
{
internal class SecureRandom : IDisposable
{
private RandomNumberGenerator random = RandomNumberGenerator.Create();
public void GetBytes(byte[] data)
{
random.GetBytes(data);
}
public void Dispose()
{
random.Dispose();
}
}
}

View file

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

View file

@ -0,0 +1,396 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RethinkDb.Driver.Utils;
namespace RethinkDb.Driver.Net
{
internal class SocketWrapper
{
private Socket socket;
private readonly TimeSpan timeout;
private readonly string hostname;
private readonly int port;
private readonly Action<Exception> errorCallback;
private NetworkStream ns = null;
private BinaryWriter bw = null;
private BinaryReader br = null;
private SslContext sslContext;
private SslStream ssl = null;
public SocketWrapper(string hostname, int port, TimeSpan? timeout, SslContext sslContext, Action<Exception> errorCallback)
{
this.hostname = hostname;
this.port = port;
this.errorCallback = errorCallback;
this.sslContext = sslContext;
this.timeout = timeout ?? TimeSpan.FromSeconds(60);
}
private Exception currentException;
public virtual async Task ConnectAsync(Handshake handshake)
{
try
{
handshake.Reset();
var addresses = await Dns.GetHostAddressesAsync(this.hostname)
.ConfigureAwait(false);
this.socket = await ConnectInternalAsync(addresses, this.port)
.ConfigureAwait(false);
this.ns = new NetworkStream(this.socket);
if (this.sslContext != null)
{
this.ssl = new SslStream(this.ns,
leaveInnerStreamOpen: false,
userCertificateValidationCallback: this.sslContext.ServerCertificateValidationCallback,
userCertificateSelectionCallback: this.sslContext.LocalCertificateSelectionCallback);
await this.ssl.AuthenticateAsClientAsync(this.sslContext.TargetHostOverride ?? this.hostname,
this.sslContext.ClientCertificateCollection,
this.sslContext.EnabledProtocols,
this.sslContext.CheckCertificateRevocation)
.ConfigureAwait(false);
}
this.bw = new BinaryWriter(this.ssl as Stream ?? this.ns);
this.br = new BinaryReader(this.ssl as Stream ?? this.ns);
// execute RethinkDB handshake
ExecuteHandshake(handshake);
//http://blog.i3arnon.com/2015/07/02/task-run-long-running/
//LongRunning creates a new thread and marks it as a background thread
//(ie: does not block application shutdown, when all foreground threads finish)
pump = new CancellationTokenSource();
// GitHub Issue #24 - Set PUMP token first before starting thread.
// If the pump token is set in ResponsePump, and the thread is scheduled
// late, and we return immediately to the caller indicating the connection
// is ready, the caller will immediately SendQuery. However, SendQuery
// is dependent on pump, and will encounter a null reference exception
// because the ResponsePump thread is late setting the token.
//
// So, set the token so that we're *really* ready to begin sending
// queries.
#pragma warning disable 4014 // We know what' we're doing. It's intentional.
Task.Factory.StartNew(ResponsePump, TaskCreationOptions.LongRunning);
#pragma warning restore 4014
}
catch
{
try
{
this.Close();
}
catch
{
// attempt to close, ignored,
// and re-throw the original exception
}
throw;
}
}
private static async Task<Socket> ConnectInternalAsync(IPAddress[] addresses, int port)
{
Exception lastExc = null;
foreach( var address in addresses )
{
var s = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
{
NoDelay = true
};
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
try
{
#if STANDARD
await s.ConnectAsync(address, port).ConfigureAwait(false);
#else
await Task.Factory.FromAsync(
(targetHost, targetPort, callback, state) =>
((Socket)state).BeginConnect(targetHost, targetPort, callback, state),
asyncResult =>
((Socket)asyncResult.AsyncState).EndConnect(asyncResult),
address, port, state: s)
.ConfigureAwait(false);
#endif
return s;
}
catch( Exception exc )
{
lastExc = exc;
s.Dispose();
}
}
if( lastExc != null ) throw lastExc;
throw new ArgumentException("No addresses provided", nameof(addresses));
}
private void ExecuteHandshake(Handshake handshake)
{
// initialize handshake
var toWrite = handshake.NextMessage(null);
// Sit in the handshake until it's completed. Exceptions will be thrown if
// anything goes wrong.
while (!handshake.IsFinished)
{
if (toWrite != null)
{
bw.Write(toWrite);
}
var serverMsg = ReadNullTerminatedString(this.timeout);
toWrite = handshake.NextMessage(serverMsg);
}
}
public virtual void Connect(Handshake handshake)
{
if( !ConnectAsync(handshake).Wait(this.timeout) )
{
try
{
this.Close();
}
catch
{
}
throw new ReqlDriverError("Connection timed out.");
}
}
private string ReadNullTerminatedString(TimeSpan? deadline)
{
var deadlineInstant = deadline.HasValue ? DateTime.Now.Add(deadline.Value) : (DateTime?)null;
var sb = new StringBuilder();
char c;
while( (c = this.br.ReadChar()) != '\0' )
{
if( deadlineInstant.HasValue )
{
if( deadlineInstant <= DateTime.Now )
{
throw new ReqlDriverError("Connection timed out.");
}
}
sb.Append(c);
}
return sb.ToString();
}
private CancellationTokenSource pump = null;
/// <summary>
/// Started just after connect. Do not use or async/await code in this pump
/// because it is a long-running task.
/// http://blog.i3arnon.com/2015/07/02/task-run-long-running/
/// </summary>
private void ResponsePump()
{
while( true )
{
if( pump.IsCancellationRequested )
{
Log.Trace("Response Pump: shutting down. Cancel is requested.");
break;
}
if( this.Closed )
{
Log.Trace("Response Pump: The connected socket is not open. Response Loop exiting.");
break;
}
try
{
//WARN: Do not use or async/await code in this pump; because it is a
//long-running task.
//http://blog.i3arnon.com/2015/07/02/task-run-long-running/
var response = this.Read();
Awaiter awaitingTask;
if( awaiters.TryRemove(response.Token, out awaitingTask) )
{
Task.Run(() =>
{
//regardless of the outcome, clean up any registered
//cancellation tokens with using statement.
using ( awaitingTask )
{
//try setting the result, because it's possible
//the awaiting task was canceled.
if( !awaitingTask.TrySetResult(response) )
{
Log.Debug(
$"Response Pump: The awaiter waiting for response token {response.Token} could not be set. The task was probably canceled.");
}
}
});
}
else
{
//Wow, there's nobody waiting for this response.
Log.Debug(
$"Response Pump: There are no awaiters waiting for {response.Token} token. A cursor was probably closed and this might be a response to a QUERY:STOP. The response will be ignored.");
//I guess we'll ignore for now, perhaps a cursor was killed
}
}
catch( Exception e )
{
currentException = e;
this.errorCallback?.Invoke(currentException);
Log.Trace($"Response Pump: {e.GetType().Name} - {e.Message} The connection can no longer be used. {nameof(ResponsePump)} is preparing to shutdown.");
//shutdown all.
try
{
this.Close();
}
catch
{
}
break;
}
}
Log.Trace($"Cleaning up Response Pump awaiters for {hostname}:{port}");
//clean up.
foreach( var a in awaiters.Values )
{
if( currentException != null )
{
a.TrySetException(currentException);
}
else
{
a.TrySetCanceled();
}
}
awaiters.Clear();
}
/// <summary>
/// Blocking Read by the ResponsePump
/// </summary>
private Response Read()
{
var token = this.br.ReadInt64();
var responseLength = this.br.ReadInt32();
var response = this.br.ReadBytes(responseLength);
return Response.ParseFrom(token, Encoding.UTF8.GetString(response));
}
private ConcurrentDictionary<long, Awaiter> awaiters = new ConcurrentDictionary<long, Awaiter>();
private object writeLock = new object();
public virtual Task<Response> SendQuery(long token, string json, bool awaitResponse, CancellationToken cancelToken)
{
cancelToken.ThrowIfCancellationRequested();
if( this.Closed )
{
throw new ReqlDriverError($"Threads may not {nameof(SendQuery)} because the connection is closed.");
}
if( pump.IsCancellationRequested )
{
throw new ReqlDriverError($"Threads may not {nameof(SendQuery)} because the connection is shutting down.");
}
Awaiter awaiter = null;
if( awaitResponse )
{
//Assign a new awaiter for this token,
//The caller is expecting a response.
awaiter = new Awaiter(cancelToken);
awaiters[token] = awaiter;
}
lock( writeLock )
{
// Everyone can write their query as fast as they can; block if needed.
cancelToken.ThrowIfCancellationRequested();
//We could probably use a semaphore slim as a lock
//and Wait(cancelToken), but using semaphore slim
//is slower and requires more overhead. So, instead
//we just cancel at earliest possible time when the lock
//is free.
try
{
//using bw is fast and convenient
this.bw.Write(token);
var jsonBytes = Encoding.UTF8.GetBytes(json);
this.bw.Write(jsonBytes.Length);
this.bw.Write(jsonBytes);
//we check here because it's possibly very expensive to ship this json around in the call stack
if (Log.IsTraceEnabled) Log.Trace($"JSON Send: Token: {token}, JSON: {json}");
}
catch( Exception e )
{
currentException = e;
this.errorCallback?.Invoke(currentException);
Log.Trace($"Write Query failed for Token {token}. Exception: {e.Message}");
throw;
}
}
return awaiter?.Task ?? TaskHelper.CompletedResponse;
}
public virtual bool Closed => !this.Open;
public virtual bool Open => socket?.Connected ?? false;
public virtual IPEndPoint ClientEndPoint => this.socket.LocalEndPoint as IPEndPoint;
public virtual IPEndPoint RemoteEndPoint => this.socket.RemoteEndPoint as IPEndPoint;
public virtual bool HasError => currentException != null;
public virtual void Close()
{
this.pump?.Cancel();
try
{
this.ssl?.Dispose();
this.ns.Dispose();
}
catch
{
}
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Dispose();
}
catch
{
}
currentException = currentException ?? new EndOfStreamException("The driver connection is closed.");
}
}
}

View file

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

View file

@ -0,0 +1,43 @@
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace RethinkDb.Driver.Net
{
/// <summary>
/// Settings object for SSL/TLS connections with RethinkDB.
/// </summary>
public class SslContext
{
/// <summary>
/// Client certificates.
/// </summary>
public X509CertificateCollection ClientCertificateCollection { get; set; } = new X509Certificate2Collection();
/// <summary>
/// Server-side certificate validation callback.
/// </summary>
public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; }
/// <summary>
/// Client-side certificate validation callback
/// </summary>
public LocalCertificateSelectionCallback LocalCertificateSelectionCallback { get; set; }
/// <summary>
/// The enabled security protocols to use over the socket. Default: TLS, TLS 1.1, TLS 1.2.
/// SSLv2 and SSLv3 are considered insecure.
/// </summary>
public SslProtocols EnabledProtocols { get; set; } =
SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
/// <summary>
/// By default, the connection's hostname is used. This setting can override host verification.
/// </summary>
public string TargetHostOverride { get; set; }
/// <summary>
/// Check for certificate revocation.
/// </summary>
public bool CheckCertificateRevocation { get; set; } = false;
}
}

View file

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