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/Utils/RequestBuffer.cs

106 lines
3.2 KiB

6 years ago
using System;
5 years ago
using System.Collections.Concurrent;
6 years ago
using System.Collections.Generic;
namespace ZeroLevel.Network
{
internal sealed class RequestBuffer
{
5 years ago
private ConcurrentDictionary<long, Action<byte[]>> _callbacks = new ConcurrentDictionary<long, Action<byte[]>>();
private ConcurrentDictionary<long, Action<string>> _fallbacks = new ConcurrentDictionary<long, Action<string>>();
private ConcurrentDictionary<long, long> _timeouts = new ConcurrentDictionary<long, long>();
6 years ago
5 years ago
public void RegisterForFrame(int identity, Action<byte[]> callback, Action<string> fallback = null)
6 years ago
{
5 years ago
if (callback != null)
{
_callbacks.TryAdd(identity, callback);
}
if (fallback != null)
{
_fallbacks.TryAdd(identity, fallback);
}
6 years ago
}
5 years ago
public void Fail(long identity, string message)
6 years ago
{
5 years ago
Action<string> rec;
if (_fallbacks.TryRemove(identity, out rec))
6 years ago
{
5 years ago
try
{
rec(message);
}
catch (Exception ex)
{
Log.Error(ex, $"Fail invoke fallback for request '{identity}' with message '{message ?? string.Empty}'");
}
rec = null;
6 years ago
}
}
5 years ago
public void Success(long identity, byte[] data)
6 years ago
{
5 years ago
Action<byte[]> rec;
if (_callbacks.TryRemove(identity, out rec))
6 years ago
{
5 years ago
try
{
rec(data);
}
catch (Exception ex)
{
Log.Error(ex, $"Fail invoke callback for request '{identity}'. Response size '{data?.Length ?? 0}'");
}
rec = null;
6 years ago
}
}
5 years ago
public void StartSend(long identity)
6 years ago
{
5 years ago
if (_callbacks.ContainsKey(identity)
|| _fallbacks.ContainsKey(identity))
6 years ago
{
5 years ago
_timeouts.TryAdd(identity, DateTime.UtcNow.Ticks);
6 years ago
}
}
5 years ago
public void Timeout(List<long> identities)
6 years ago
{
5 years ago
long t;
Action<string> rec;
foreach (var id in identities)
6 years ago
{
5 years ago
if (_fallbacks.TryRemove(id, out rec))
6 years ago
{
5 years ago
try
{
rec("Timeout");
}
catch (Exception ex)
{
Log.Error(ex, $"Fail invoke fallback for request '{id}' by timeout");
}
rec = null;
6 years ago
}
5 years ago
_timeouts.TryRemove(id, out t);
6 years ago
}
5 years ago
}
public void TestForTimeouts()
{
var now_ticks = DateTime.UtcNow.Ticks;
var to_remove = new List<long>();
5 years ago
foreach (var pair in _timeouts)
6 years ago
{
5 years ago
var diff = now_ticks - pair.Value;
5 years ago
if (diff > BaseSocket.MAX_REQUEST_TIME_TICKS)
{
5 years ago
to_remove.Add(pair.Key);
5 years ago
}
6 years ago
}
5 years ago
Timeout(to_remove);
6 years ago
}
}
}

Powered by TurnKey Linux.