You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Zero/ZeroLevel/Services/Network/Exchange.cs

987 lines
37 KiB

6 years ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
6 years ago
using System.Threading;
using System.Threading.Tasks;
using ZeroLevel.Models;
using ZeroLevel.Network.SDL;
6 years ago
namespace ZeroLevel.Network
6 years ago
{
/// <summary>
6 years ago
/// Provides data exchange between services
6 years ago
/// </summary>
5 years ago
internal sealed class Exchange :
IExchange
6 years ago
{
5 years ago
private readonly ServiceRouteStorage _dicovery_aliases = new ServiceRouteStorage();
private readonly ServiceRouteStorage _user_aliases = new ServiceRouteStorage();
private readonly ExClientServerCachee _cachee = new ExClientServerCachee();
6 years ago
5 years ago
public IServiceRoutesStorage RoutesStorage => _user_aliases;
5 years ago
public IServiceRoutesStorage DiscoveryStorage => _dicovery_aliases;
5 years ago
private readonly IZeroService _owner;
#region Ctor
5 years ago
public Exchange(IZeroService owner)
6 years ago
{
5 years ago
_owner = owner;
6 years ago
}
#endregion Ctor
6 years ago
#region IMultiClient
5 years ago
public bool Peek(string alias, string inbox)
{
return CallService(alias, (transport) => transport.Send(inbox));
}
6 years ago
/// <summary>
/// Sending a message to the service
6 years ago
/// </summary>
/// <param name="alias">Service key or url</param>
/// <param name="data">Message</param>
/// <returns></returns>
public bool Send<T>(string alias, T data)
6 years ago
{
5 years ago
return CallService(alias, (transport) => transport.Send<T>(BaseSocket.DEFAULT_MESSAGE_INBOX, data));
6 years ago
}
/// <summary>
/// Sending a message to the service
/// </summary>
/// <param name="alias">Service key or url</param>
/// <param name="inbox">Inbox name</param>
/// <param name="data">Message</param>
/// <returns></returns>
public bool Send<T>(string alias, string inbox, T data)
6 years ago
{
5 years ago
return CallService(alias, (transport) => transport.Send<T>(inbox, data));
6 years ago
}
/// <summary>
/// Sending a message to all services with the specified key, to the default handler
6 years ago
/// </summary>
/// <typeparam name="T">Message type</typeparam>
6 years ago
/// <param name="serviceKey">Service key</param>
/// <param name="data">Message</param>
/// <returns>true - on successful submission</returns>
public bool SendBroadcast<T>(string serviceKey, T data) => SendBroadcast(serviceKey, BaseSocket.DEFAULT_MESSAGE_INBOX, data);
/// <summary>
/// Sending a message to all services with the specified key to the specified handler
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="alias">Service key</param>
6 years ago
/// <param name="inbox">Inbox name</param>
/// <param name="data">Message</param>
/// <returns>true - on successful submission</returns>
public bool SendBroadcast<T>(string alias, string inbox, T data)
6 years ago
{
5 years ago
var result = false;
6 years ago
try
{
5 years ago
var clients = GetClientEnumerator(alias).ToArray();
var tasks = new Task[clients.Length];
int index = 0;
foreach (var client in clients)
{
5 years ago
tasks[index++] = Task.Run(() =>
{
try
{
5 years ago
result |= client.Send(inbox, data);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.SendBroadcast] Error broadcast send data to services '{alias}'. Inbox '{inbox}'");
}
});
}
5 years ago
Task.WaitAll(tasks);
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.SendBroadcast] Error broadcast send data in service '{alias}'. Inbox '{inbox}'");
6 years ago
}
5 years ago
return result;
6 years ago
}
/// <summary>
/// Sending a message to all services of a specific type to the specified handler
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="type">Service type</param>
/// <param name="inbox">Inbox name</param>
/// <param name="data">Message</param>
/// <returns>true - on successful submission</returns>
public bool SendBroadcastByType<T>(string type, string inbox, T data)
6 years ago
{
5 years ago
var result = false;
6 years ago
try
{
5 years ago
var clients = GetClientEnumeratorByType(type).ToArray();
var tasks = new Task[clients.Length];
int index = 0;
foreach (var client in clients)
6 years ago
{
5 years ago
tasks[index++] = Task.Run(() =>
{
try
{
5 years ago
result |= client.Send(inbox, data);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.SendBroadcastByType] Error broadcast send data to services with type '{type}'. Inbox '{inbox}'");
}
});
6 years ago
}
5 years ago
Task.WaitAll(tasks);
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.SendBroadcastByType] Error broadcast send data to services with type '{type}'. Inbox '{inbox}'");
6 years ago
}
5 years ago
return result;
6 years ago
}
/// <summary>
/// Sending a message to all services of a particular type, to the default handler
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="type">Service type</param>
/// <param name="data">Message</param>
/// <returns>true - on successful submission</returns>
public bool SendBroadcastByType<T>(string type, T data) =>
SendBroadcastByType(type, BaseSocket.DEFAULT_MESSAGE_INBOX, data);
/// <summary>
/// Sending a message to all services of a specific group to the specified handler
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="group">Service group</param>
/// <param name="inbox">Inbox name</param>
/// <param name="data">Message</param>
/// <returns>true - on successful submission</returns>
public bool SendBroadcastByGroup<T>(string group, string inbox, T data)
6 years ago
{
5 years ago
var result = false;
6 years ago
try
{
5 years ago
var clients = GetClientEnumeratorByGroup(group).ToArray();
var tasks = new Task[clients.Length];
int index = 0;
foreach (var client in clients)
6 years ago
{
5 years ago
tasks[index++] = Task.Run(() =>
{
try
{
5 years ago
result |= client.Send(inbox, data);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.SendBroadcastByGroup] Error broadcast send data to services with type '{group}'. Inbox '{inbox}'");
}
});
6 years ago
}
5 years ago
Task.WaitAll(tasks);
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.SendBroadcastByGroup] Error broadcast send data to services with type '{group}'. Inbox '{inbox}'");
6 years ago
}
5 years ago
return result;
6 years ago
}
/// <summary>
/// Sending a message to all services of a specific group in the default handler
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="serviceGroup">Service group</param>
/// <param name="data">Messsage</param>
/// <returns>true - on successful submission</returns>
public bool SendBroadcastByGroup<T>(string serviceGroup, T data) =>
SendBroadcastByGroup(serviceGroup, BaseSocket.DEFAULT_MESSAGE_INBOX, data);
6 years ago
public bool Request<Tresponse>(string alias, Action<Tresponse> callback) =>
Request(alias, BaseSocket.DEFAULT_REQUEST_WITHOUT_ARGS_INBOX, callback);
public bool Request<Tresponse>(string alias, string inbox, Action<Tresponse> callback)
6 years ago
{
try
{
5 years ago
return CallService(alias, (transport) =>
6 years ago
{
try
{
5 years ago
return transport.Request<Tresponse>(inbox, callback);
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.Request] Error request to service '{alias}'. Inbox '{inbox}'");
6 years ago
}
return false;
5 years ago
});
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.Request] Error request to service '{alias}'. Inbox '{inbox}'");
6 years ago
}
5 years ago
return false;
6 years ago
}
public bool Request<Trequest, Tresponse>(string alias, Trequest request, Action<Tresponse> callback)
=> Request(alias, BaseSocket.DEFAULT_REQUEST_INBOX, callback);
public bool Request<Trequest, Tresponse>(string alias, string inbox, Trequest request, Action<Tresponse> callback)
6 years ago
{
try
{
5 years ago
return CallService(alias, (transport) =>
6 years ago
{
try
{
5 years ago
return transport.Request(inbox, request, callback);
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.Request] Error request to service '{alias}'. Inbox '{inbox}'");
6 years ago
}
return false;
5 years ago
});
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.Request] Error request to service '{alias}'. Inbox '{inbox}'");
6 years ago
}
5 years ago
return false;
6 years ago
}
/// <summary>
/// Broadcast polling of services by key, without message of request, to default handler
/// </summary>
/// <typeparam name="Tresponse">Response message type</typeparam>
/// <param name="alias">Service key</param>
/// <param name="callback">Response handler</param>
/// <returns>true - in case of successful mailing</returns>
public bool RequestBroadcast<Tresponse>(string alias, Action<IEnumerable<Tresponse>> callback) =>
RequestBroadcast(alias, BaseSocket.DEFAULT_REQUEST_WITHOUT_ARGS_INBOX, callback);
6 years ago
/// <summary>
/// Broadcast polling services by key
6 years ago
/// </summary>
/// <typeparam name="Tresponse">Response message type</typeparam>
/// <param name="alias">Service key</param>
6 years ago
/// <param name="inbox">Inbox name</param>
/// <param name="data">Request message</param>
/// <param name="responseHandler">Response handler</param>
/// <returns>true - in case of successful mailing</returns>
public bool RequestBroadcast<Tresponse>(string alias, string inbox, Action<IEnumerable<Tresponse>> callback)
6 years ago
{
try
{
var clients = GetClientEnumerator(alias).ToList();
5 years ago
if (clients.Count > 0)
{
callback(_RequestBroadcast<Tresponse>(clients, inbox));
return true;
}
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.RequestBroadcast] Error broadcast request to service '{alias}'. Inbox '{inbox}'");
6 years ago
}
return false;
}
public bool RequestBroadcast<Trequest, Tresponse>(string alias, Trequest data, Action<IEnumerable<Tresponse>> callback)
=> RequestBroadcast(alias, BaseSocket.DEFAULT_REQUEST_INBOX, data, callback);
public bool RequestBroadcast<Trequest, Tresponse>(string alias, string inbox, Trequest data
, Action<IEnumerable<Tresponse>> callback)
6 years ago
{
try
{
var clients = GetClientEnumerator(alias).ToList();
5 years ago
if (clients.Count > 0)
{
callback(_RequestBroadcast<Trequest, Tresponse>(clients, inbox, data));
return true;
}
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.RequestBroadcast] Error broadcast request to service '{alias}'. Inbox '{inbox}'");
6 years ago
}
return false;
}
public bool RequestBroadcastByGroup<Tresponse>(string serviceGroup, Action<IEnumerable<Tresponse>> callback)
=> RequestBroadcastByGroup(serviceGroup, BaseSocket.DEFAULT_REQUEST_INBOX, callback);
public bool RequestBroadcastByGroup<Tresponse>(string serviceGroup, string inbox, Action<IEnumerable<Tresponse>> callback)
6 years ago
{
try
{
var clients = GetClientEnumeratorByGroup(serviceGroup).ToList();
5 years ago
if (clients.Count > 0)
{
callback(_RequestBroadcast<Tresponse>(clients, inbox));
return true;
}
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange] Error broadcast request to service by group '{serviceGroup}'. Inbox '{inbox}'");
6 years ago
}
return false;
}
public bool RequestBroadcastByGroup<Trequest, Tresponse>(string serviceGroup, Trequest data, Action<IEnumerable<Tresponse>> callback)
=> RequestBroadcastByGroup(serviceGroup, BaseSocket.DEFAULT_REQUEST_INBOX, data, callback);
public bool RequestBroadcastByGroup<Trequest, Tresponse>(string serviceGroup, string inbox, Trequest data
, Action<IEnumerable<Tresponse>> callback)
6 years ago
{
try
{
var clients = GetClientEnumeratorByGroup(serviceGroup).ToList();
5 years ago
if (clients.Count > 0)
{
callback(_RequestBroadcast<Trequest, Tresponse>(clients, inbox, data));
return true;
}
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange] Error broadcast request to service by group '{serviceGroup}'. Inbox '{inbox}'");
6 years ago
}
return false;
6 years ago
}
public bool RequestBroadcastByType<Tresponse>(string serviceType, Action<IEnumerable<Tresponse>> callback)
=> RequestBroadcastByType(serviceType, BaseSocket.DEFAULT_REQUEST_WITHOUT_ARGS_INBOX, callback);
public bool RequestBroadcastByType<Tresponse>(string serviceType, string inbox, Action<IEnumerable<Tresponse>> callback)
6 years ago
{
try
{
var clients = GetClientEnumeratorByType(serviceType).ToList();
5 years ago
if (clients.Count > 0)
{
callback(_RequestBroadcast<Tresponse>(clients, inbox));
return true;
}
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange] Error broadcast request to service by type '{serviceType}'. Inbox '{inbox}'");
6 years ago
}
return false;
6 years ago
}
6 years ago
/// <summary>
/// Broadcast polling services by type of service, to default handler
6 years ago
/// </summary>
6 years ago
/// <typeparam name="Treq">Request message type</typeparam>
/// <typeparam name="Tresp">Response message type</typeparam>
/// <param name="serviceType">Service type</param>
6 years ago
/// <param name="data">Request message</param>
/// <param name="callback">Response handler</param>
6 years ago
/// <returns>true - in case of successful mailing</returns>
public bool RequestBroadcastByType<Trequest, Tresponse>(string serviceType, Trequest data
, Action<IEnumerable<Tresponse>> callback) =>
RequestBroadcastByType(serviceType, BaseSocket.DEFAULT_REQUEST_INBOX, data, callback);
6 years ago
/// <summary>
6 years ago
/// Broadcast polling services by type of service
6 years ago
/// </summary>
6 years ago
/// <typeparam name="Treq">Request message type</typeparam>
/// <typeparam name="Tresp">Response message type</typeparam>
/// <param name="serviceType">Service type</param>
/// <param name="inbox">Inbox name</param>
/// <param name="data">Request message</param>
/// <param name="callback">Response handler</param>
6 years ago
/// <returns>true - in case of successful mailing</returns>
public bool RequestBroadcastByType<Trequest, Tresponse>(string serviceType, string inbox, Trequest data
, Action<IEnumerable<Tresponse>> callback)
6 years ago
{
try
{
var clients = GetClientEnumeratorByType(serviceType).ToList();
5 years ago
if (clients.Count > 0)
{
callback(_RequestBroadcast<Trequest, Tresponse>(clients, inbox, data));
return true;
}
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange] Error broadcast request to service by type '{serviceType}'. Inbox '{inbox}'");
}
return false;
6 years ago
}
#endregion
#region Discovery
private long _update_discovery_table_task = -1;
private long _register_in_discovery_table_task = -1;
private static TimeSpan _update_discovery_table_period = TimeSpan.FromSeconds(15);
private static TimeSpan _register_in_discovery_table_period = TimeSpan.FromSeconds(15);
public void UseDiscovery()
6 years ago
{
try
6 years ago
{
var discoveryEndpoint = Configuration.Default.First("discovery");
5 years ago
_user_aliases.Set(BaseSocket.DISCOVERY_ALIAS, NetUtils.CreateIPEndPoint(discoveryEndpoint));
RestartDiscoveryTasks();
}
catch (Exception ex)
{
Log.Error(ex, "[Exchange.UseDiscovery]");
6 years ago
}
}
public void UseDiscovery(string discoveryEndpoint)
{
try
{
5 years ago
_user_aliases.Set(BaseSocket.DISCOVERY_ALIAS, NetUtils.CreateIPEndPoint(discoveryEndpoint));
RestartDiscoveryTasks();
}
catch (Exception ex)
6 years ago
{
Log.Error(ex, "[Exchange.UseDiscovery]");
6 years ago
}
}
public void UseDiscovery(IPEndPoint discoveryEndpoint)
{
try
{
5 years ago
_user_aliases.Set(BaseSocket.DISCOVERY_ALIAS, discoveryEndpoint);
RestartDiscoveryTasks();
}
catch (Exception ex)
{
Log.Error(ex, "[Exchange.UseDiscovery]");
}
}
private void RestartDiscoveryTasks()
{
if (_update_discovery_table_task != -1)
{
Sheduller.Remove(_update_discovery_table_task);
}
if (_register_in_discovery_table_task != -1)
{
Sheduller.Remove(_register_in_discovery_table_task);
}
5 years ago
UpdateServiceListFromDiscovery();
_register_in_discovery_table_task = Sheduller.RemindEvery(TimeSpan.FromMilliseconds(500), _update_discovery_table_period, RegisterServicesInDiscovery);
_update_discovery_table_task = Sheduller.RemindEvery(TimeSpan.FromMilliseconds(750), _register_in_discovery_table_period, UpdateServiceListFromDiscovery);
}
private void RegisterServicesInDiscovery()
{
5 years ago
var discovery_endpoint = _user_aliases.Get(BaseSocket.DISCOVERY_ALIAS);
if (discovery_endpoint.Success)
{
var discoveryClient = _cachee.GetClient(discovery_endpoint.Value, true);
5 years ago
if (discoveryClient != null)
{
foreach (var service in _cachee.ServerList)
{
var request = discoveryClient.Request<ServiceRegisterInfo, InvokeResult>("register"
, new ServiceRegisterInfo
5 years ago
{
Port = service.LocalEndpoint.Port,
ServiceInfo = _owner.ServiceInfo
5 years ago
}
, r =>
{
if (!r.Success)
{
Log.SystemWarning($"[Exchange.RegisterServicesInDiscovery] Register canceled. {r.Comment}");
}
});
5 years ago
if (request == false)
5 years ago
{
5 years ago
Log.SystemWarning($"[Exchange.RegisterServicesInDiscovery] Register canceled.");
}
}
}
}
}
5 years ago
private void UpdateServiceListFromDiscovery()
{
5 years ago
var discovery_endpoint = _user_aliases.Get(BaseSocket.DISCOVERY_ALIAS);
if (discovery_endpoint.Success)
{
var discoveryClient = _cachee.GetClient(discovery_endpoint.Value, true);
5 years ago
if (discoveryClient != null)
{
5 years ago
try
{
var ir = discoveryClient.Request<IEnumerable<ServiceEndpointInfo>>("services", records =>
{
5 years ago
if (records == null)
{
5 years ago
Log.SystemWarning("[Exchange.UpdateServiceListFromDiscovery] UpdateServiceListInfo. Discrovery response is empty");
return;
}
_dicovery_aliases.BeginUpdate();
try
{
foreach (var service in records)
{
_dicovery_aliases.Set(service.ServiceInfo.ServiceKey
, service.ServiceInfo.ServiceType
, service.ServiceInfo.ServiceGroup
, NetUtils.CreateIPEndPoint(service.Endpoint));
}
5 years ago
_dicovery_aliases.Commit();
}
5 years ago
catch
{
_dicovery_aliases.Rollback();
}
});
5 years ago
if (!ir)
5 years ago
{
5 years ago
Log.SystemWarning($"[Exchange.UpdateServiceListFromDiscovery] Error request to inbox 'services'.");
}
5 years ago
}
catch (Exception ex)
{
5 years ago
Log.SystemError(ex, "[Exchange.UpdateServiceListFromDiscovery] Discovery service response is absent");
}
}
}
5 years ago
}
#endregion
5 years ago
public IClient GetConnection(string alias)
5 years ago
{
5 years ago
if (_update_discovery_table_task != -1)
5 years ago
{
5 years ago
var address = _dicovery_aliases.Get(alias);
if (address.Success)
{
return _cachee.GetClient(address.Value, true);
}
5 years ago
}
5 years ago
else
5 years ago
{
5 years ago
var address = _user_aliases.Get(alias);
if (address.Success)
{
return _cachee.GetClient(address.Value, true);
}
try
{
var endpoint = NetUtils.CreateIPEndPoint(alias);
return _cachee.GetClient(endpoint, true);
}
catch (Exception ex)
{
Log.SystemError(ex, "[Exchange.GetConnection]");
}
5 years ago
}
return null;
}
5 years ago
public IClient GetConnection(IPEndPoint endpoint)
5 years ago
{
try
{
return _cachee.GetClient(endpoint, true);
}
catch (Exception ex)
{
Log.SystemError(ex, "[Exchange.GetConnection]");
5 years ago
}
return null;
}
public IClient GetConnection(ISocketClient client)
{
try
{
return new ExClient(client);
}
catch (Exception ex)
{
Log.SystemError(ex, "[Exchange.GetConnection]");
}
return null;
}
#region Host service
public IRouter UseHost()
{
return MakeHost(new IPEndPoint(IPAddress.Any, NetUtils.GetFreeTcpPort()));
}
public IRouter UseHost(int port)
{
return MakeHost(new IPEndPoint(IPAddress.Any, port));
}
public IRouter UseHost(IPEndPoint endpoint)
{
return MakeHost(endpoint);
}
private IRouter MakeHost(IPEndPoint endpoint)
{
var server = _cachee.GetServer(endpoint, new Router());
server.RegisterInbox<ServiceDescription>("__service_description__", _ => CollectServiceDescription());
return server;
}
#endregion
#region Private
5 years ago
private IEnumerable<IPEndPoint> GetAllAddresses(string serviceKey)
{
if (_update_discovery_table_task != -1)
{
var dr = _dicovery_aliases.GetAll(serviceKey);
var ur = _user_aliases.GetAll(serviceKey);
if (dr.Success && ur.Success)
{
return Enumerable.Union<IPEndPoint>(dr.Value, ur.Value);
}
else if (dr.Success)
{
return dr.Value;
}
else if (ur.Success)
{
return ur.Value;
}
}
else
{
var result = _user_aliases.GetAll(serviceKey);
if (result.Success)
{
return result.Value;
}
}
return null;
}
private IEnumerable<IPEndPoint> GetAllAddressesByType(string serviceType)
{
if (_update_discovery_table_task != -1)
{
var dr = _dicovery_aliases.GetAllByType(serviceType);
var ur = _user_aliases.GetAllByType(serviceType);
if (dr.Success && ur.Success)
{
return Enumerable.Union<IPEndPoint>(dr.Value, ur.Value);
}
else if (dr.Success)
{
return dr.Value;
}
else if (ur.Success)
{
return ur.Value;
}
}
else
{
var result = _user_aliases.GetAllByType(serviceType);
if (result.Success)
{
return result.Value;
}
}
return null;
}
private IEnumerable<IPEndPoint> GetAllAddressesByGroup(string serviceGroup)
{
if (_update_discovery_table_task != -1)
{
var dr = _dicovery_aliases.GetAllByGroup(serviceGroup);
var ur = _user_aliases.GetAllByGroup(serviceGroup);
if (dr.Success && ur.Success)
{
return Enumerable.Union<IPEndPoint>(dr.Value, ur.Value);
}
else if (dr.Success)
{
return dr.Value;
}
else if (ur.Success)
{
return ur.Value;
}
}
else
{
var result = _user_aliases.GetAllByGroup(serviceGroup);
if (result.Success)
{
return result.Value;
}
}
return null;
}
5 years ago
private IEnumerable<IClient> GetClientEnumerator(string serviceKey)
6 years ago
{
5 years ago
IEnumerable<IPEndPoint> candidates;
6 years ago
try
{
5 years ago
candidates = GetAllAddresses(serviceKey);
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.GetClientEnumerator] Error when trying get endpoints for service key '{serviceKey}'");
candidates = null;
}
5 years ago
if (candidates != null && candidates.Any())
{
5 years ago
foreach (var endpoint in candidates)
{
5 years ago
IClient transport;
try
{
transport = _cachee.GetClient(endpoint, true);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.GetClientEnumerator] Can't get transport for endpoint '{endpoint}'");
continue;
}
5 years ago
if (transport == null) continue;
yield return transport;
}
}
else
{
Log.Debug($"[Exchange.GetClientEnumerator] Not found endpoints for service key '{serviceKey}'");
6 years ago
}
}
5 years ago
private IEnumerable<IClient> GetClientEnumeratorByType(string serviceType)
6 years ago
{
5 years ago
IEnumerable<IPEndPoint> candidates;
6 years ago
try
{
5 years ago
candidates = GetAllAddressesByType(serviceType);
6 years ago
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.GetClientEnumeratorByType] Error when trying get endpoints for service type '{serviceType}'");
candidates = null;
}
5 years ago
if (candidates != null && candidates.Any())
{
5 years ago
foreach (var endpoint in candidates)
{
5 years ago
IClient transport;
try
{
transport = _cachee.GetClient(endpoint, true);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.GetClientEnumeratorByType] Can't get transport for endpoint '{endpoint}'");
continue;
}
5 years ago
if (transport == null) continue;
yield return transport;
}
}
else
{
Log.Debug($"[Exchange.GetClientEnumeratorByType] Not found endpoints for service type '{serviceType}'");
6 years ago
}
}
5 years ago
private IEnumerable<IClient> GetClientEnumeratorByGroup(string serviceGroup)
{
5 years ago
IEnumerable<IPEndPoint> candidates;
try
{
5 years ago
candidates = GetAllAddressesByGroup(serviceGroup);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.GetClientEnumeratorByGroup] Error when trying get endpoints for service group '{serviceGroup}'");
candidates = null;
}
5 years ago
if (candidates != null && candidates.Any())
{
5 years ago
foreach (var service in candidates)
{
5 years ago
IClient transport;
try
{
transport = _cachee.GetClient(service, true);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.GetClientEnumeratorByGroup] Can't get transport for endpoint '{service}'");
continue;
}
5 years ago
if (transport == null) continue;
yield return transport;
}
}
else
{
Log.Debug($"[Exchange.GetClientEnumeratorByGroup] Not found endpoints for service group '{serviceGroup}'");
}
}
6 years ago
/// <summary>
/// Call service with round-robin balancing
6 years ago
/// </summary>
/// <param name="serviceKey">Service key</param>
/// <param name="callHandler">Service call code</param>
/// <returns>true - service called succesfully</returns>
5 years ago
private bool CallService(string serviceKey, Func<IClient, bool> callHandler)
{
5 years ago
IEnumerable<IPEndPoint> candidates;
try
{
5 years ago
candidates = GetAllAddresses(serviceKey);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.CallService] Error when trying get endpoints for service key '{serviceKey}'");
return false;
}
5 years ago
if (candidates == null || candidates.Any() == false)
{
Log.Debug($"[Exchange.CallService] Not found endpoints for service key '{serviceKey}'");
return false;
}
var success = false;
5 years ago
foreach (var endpoint in candidates)
{
5 years ago
IClient transport;
try
{
transport = _cachee.GetClient(endpoint, true);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.CallService] Can't get transport for service '{serviceKey}'");
continue;
}
5 years ago
if (transport == null) continue;
try
{
success = callHandler(transport);
}
catch (Exception ex)
{
Log.SystemError(ex, $"[Exchange.CallService] Error send/request data in service '{serviceKey}'. Endpoint '{endpoint}'");
success = false;
}
if (success)
{
break;
}
}
return success;
}
6 years ago
5 years ago
private IEnumerable<Tresp> _RequestBroadcast<Treq, Tresp>(List<IClient> clients, string inbox, Treq data)
6 years ago
{
var response = new List<Tresp>();
using (var waiter = new CountdownEvent(clients.Count))
{
foreach (var client in clients)
{
Task.Run(() =>
{
try
{
5 years ago
if (false == client.Request<Treq, Tresp>(inbox, data, resp => { response.Add(resp); waiter.Signal(); }))
6 years ago
{
waiter.Signal();
}
}
catch (Exception ex)
{
Log.SystemError(ex, $"[ExClientSet._RequestBroadcast] Error direct request to service '{client.EndPoint}' in broadcast request. Inbox '{inbox}'");
6 years ago
waiter.Signal();
}
});
}
6 years ago
waiter.Wait(BaseSocket.MAX_REQUEST_TIME_MS);
6 years ago
}
return response;
}
5 years ago
private IEnumerable<Tresp> _RequestBroadcast<Tresp>(List<IClient> clients, string inbox)
6 years ago
{
var response = new List<Tresp>();
using (var waiter = new CountdownEvent(clients.Count))
{
foreach (var client in clients)
{
Task.Run(() =>
{
try
{
5 years ago
if (false == client.Request<Tresp>(inbox, resp => { response.Add(resp); waiter.Signal(); }))
6 years ago
{
waiter.Signal();
}
}
catch (Exception ex)
{
Log.SystemError(ex, $"[ExClientSet._RequestBroadcast] Error direct request to service '{client.EndPoint}' in broadcast request. Inbox '{inbox}'");
6 years ago
waiter.Signal();
}
});
}
6 years ago
waiter.Wait(BaseSocket.MAX_REQUEST_TIME_MS);
6 years ago
}
return response;
}
#endregion
6 years ago
private ServiceDescription CollectServiceDescription()
{
return new ServiceDescription
{
ServiceInfo = this._owner?.ServiceInfo,
Inboxes = _cachee.ServerList
.SelectMany(se => se
.CollectInboxInfo()
.Select(i =>
{
i.Port = se.LocalEndpoint.Port;
return i;
})).ToList()
};
}
6 years ago
public void Dispose()
{
if (_update_discovery_table_task != -1)
{
Sheduller.Remove(_update_discovery_table_task);
}
if (_register_in_discovery_table_task != -1)
{
Sheduller.Remove(_register_in_discovery_table_task);
}
_cachee.Dispose();
6 years ago
}
}
}

Powered by TurnKey Linux.