Files
StockSharp/Algo/LookupTrackingMessageAdapter.cs
mika@stocksharp.com 6e7a7dae22 Move instrument lookups and persistence to async
Instrument lookups, configuration, credentials, CSV entities, snapshots and
the alert processing service are read and written asynchronously; the
blocking synchronous forms are obsolete wrappers.

IAsyncPersistable replaces IPersistable: every type that saves and loads its
settings has LoadAsync and SaveAsync only, and nested objects are read with
GetValueAsync, LoadEntireAsync and LoadAllAsync. The synchronous Load and Save
are the obsolete Ecng extensions. The MultiConnect sample keeps IPersistable
for two settings classes, because the settings window of the published
StockSharp.Xaml package takes it.

Copies that were made by saving and loading are made asynchronously.
IMessageAdapter, IIndicator, the risk, commission, PnL, latency, slippage and
position managers, IStorageBuffer, Strategy, DiagramElement, ICompositionModel
and its nodes get CloneAsync and no longer implement ICloneable; Clone is an
obsolete blocking wrapper. A strategy copy keeps every security and portfolio
parameter the original holds. Messages, FieldMapping, BankDetails and
WithdrawInfo are copied in memory. A CommissionRuleMessage shares its rule and
the emulator takes a copy of it. Envelope gets a constructor that takes all
three lines and CreateAsync.

ToBruteForce and ToBruteForceRandom become ToBruteForceAsync and
ToBruteForceRandomAsync and return IAsyncEnumerable; BruteForceOptimizer runs
over it and takes the next strategy through an asynchronous delegate.

Diagram elements keep their own state in SaveState, OnLoading and LoadState.
Undo restores an in-memory snapshot; a chart element holds its series and
axes in it by reference. An alert rule keeps its value in the form a message
carries it. A diagram strategy applies composition settings that were loaded
before the composition was set in SetCompositionAsync or at the start, and
saves them while they wait.

Strategies get an OnStartedAsync hook; diagram strategies resolve securities,
underlyings and strikes before the start so value processing never looks up
instruments. Paths.Serialize, SerializeInvariant, AppStartSettings.TrySave,
ICredentialsProvider.Save, ISnapshotSerializer.Serialize and the composition
registry gain async forms.

ICredentialsProvider.Delete becomes DeleteAsync, so loading, saving and
deleting the credentials wait for one another. Paths.InstalledVersion and
AppNameWithVersion are obsolete in favour of GetInstalledVersionAsync and
GetAppNameWithVersionAsync.

A file is opened for writing only after the last cancellation check, because
opening it empties it; a cancelled read reports the cancellation instead of
an empty result. A snapshot flush that failed leaves what it took due for the
next one.

The indicator templates for C#, F# and Python override LoadAsync and
SaveAsync.
2026-10-04 11:28:17 +03:00

380 lines
9.1 KiB
C#

namespace StockSharp.Algo;
/// <summary>
/// Message adapter that tracks multiple lookups requests and put them into single queue.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="LookupTrackingMessageAdapter"/> with explicit state.
/// </remarks>
/// <param name="innerAdapter">Inner message adapter.</param>
/// <param name="state">State storage.</param>
public class LookupTrackingMessageAdapter(IMessageAdapter innerAdapter, ILookupTrackingManagerState state) : MessageAdapterWrapper(innerAdapter)
{
private readonly ILookupTrackingManagerState _state = state ?? throw new ArgumentNullException(nameof(state));
private readonly Lock _timeoutSync = new();
private readonly Dictionary<long, (CancellationTokenSource source, TimeSpan timeout)> _timeoutSources = [];
private readonly Dictionary<long, (int count, TimeSpan timeout)> _processingTimeouts = [];
private static readonly TimeSpan _defaultTimeOut = TimeSpan.FromSeconds(10);
private TimeSpan? _timeOut;
private bool _isDisposed;
/// <summary>
/// Securities and portfolios lookup timeout.
/// </summary>
/// <remarks>
/// By default is 10 seconds.
/// </remarks>
private TimeSpan TimeOut
{
get => _timeOut ?? InnerAdapter.LookupTimeout ?? _defaultTimeOut;
set => _timeOut = value <= TimeSpan.Zero ? null : value;
}
/// <inheritdoc />
protected override ValueTask OnSendInMessageAsync(Message message, CancellationToken cancellationToken)
{
switch (message.Type)
{
case MessageTypes.Reset:
{
using (_timeoutSync.EnterScope())
{
_state.Clear();
CancelAllTimeouts();
}
break;
}
default:
if (message is ISubscriptionMessage subscrMsg && !ProcessLookupMessage(subscrMsg))
return default;
break;
}
return base.OnSendInMessageAsync(message, cancellationToken);
}
private bool ProcessLookupMessage(ISubscriptionMessage message)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
var transId = message.TransactionId;
var isEnqueue = false;
var isStarted = false;
try
{
if (message.IsSubscribe)
{
if (InnerAdapter.EnqueueSubscriptions)
{
if (_state.TryEnqueue(message.Type, transId, message.TypedClone()))
{
isEnqueue = true;
return false;
}
}
if (this.IsResultMessageNotSupported(message.Type) && TimeOut > TimeSpan.Zero)
{
var timeout = TimeOut;
using (_timeoutSync.EnterScope())
{
_state.AddLookup(transId, message.TypedClone(), timeout);
RestartTimeout(transId, timeout);
}
isStarted = true;
}
}
return true;
}
finally
{
if (isEnqueue)
LogInfo("Lookup queued {0}.", message);
if (isStarted)
LogInfo("Lookup timeout {0} started for {1}.", TimeOut, transId);
}
}
/// <inheritdoc />
protected override async ValueTask OnInnerAdapterNewOutMessageAsync(Message message, CancellationToken cancellationToken)
{
long[] ignoreIds = null;
List<long> pausedTimeoutIds = null;
Message nextLookup = null;
if (message is IOriginalTransactionIdMessage originIdMsg &&
(originIdMsg is SubscriptionFinishedMessage ||
originIdMsg is SubscriptionOnlineMessage ||
originIdMsg is SubscriptionResponseMessage resp && !resp.IsOk()))
{
var id = originIdMsg.OriginalTransactionId;
using (_timeoutSync.EnterScope())
{
CancelTimeout(id);
if (_state.TryGetAndRemoveLookup(id, out var info))
{
LogInfo("Lookup response {0}.", id);
nextLookup = _state.TryDequeueNext(info.Type, info.TransactionId);
}
else
{
nextLookup = _state.TryDequeueFromAnyType(id);
}
}
}
else if (message is ISubscriptionIdMessage subscrMsg)
{
ignoreIds = subscrMsg.GetSubscriptionIds();
using (_timeoutSync.EnterScope())
{
_state.IncreaseTimeOut(ignoreIds);
foreach (var id in ignoreIds.Distinct())
{
if (PauseTimeout(id))
{
pausedTimeoutIds ??= [];
pausedTimeoutIds.Add(id);
}
}
}
}
List<(ISubscriptionMessage subscription, Message nextInQueue)> timedOut = null;
if (message.LocalTime != default)
{
using (_timeoutSync.EnterScope())
{
if (_state.PreviousTime == default)
{
_state.PreviousTime = message.LocalTime;
}
else if (message.LocalTime > _state.PreviousTime)
{
var diff = message.LocalTime - _state.PreviousTime;
_state.PreviousTime = message.LocalTime;
var timeoutIgnoreIds = ignoreIds;
if (_processingTimeouts.Count > 0)
timeoutIgnoreIds = [.. (timeoutIgnoreIds ?? []).Concat(_processingTimeouts.Keys).Distinct()];
timedOut = [.. _state.ProcessTimeouts(diff, timeoutIgnoreIds)];
foreach (var (subscription, _) in timedOut)
CancelTimeout(subscription.TransactionId);
}
}
}
try
{
await base.OnInnerAdapterNewOutMessageAsync(message, cancellationToken);
}
finally
{
if (pausedTimeoutIds != null)
{
using (_timeoutSync.EnterScope())
{
foreach (var id in pausedTimeoutIds)
ResumeTimeout(id);
}
}
}
if (nextLookup != null)
{
nextLookup.LoopBack(this);
await base.OnInnerAdapterNewOutMessageAsync(nextLookup, cancellationToken);
}
List<Message> nextLookups = null;
if (timedOut != null)
{
foreach (var (subscription, nextInQueue) in timedOut)
{
var transId = subscription.TransactionId;
LogInfo("Lookup timeout {0}.", transId);
await base.OnInnerAdapterNewOutMessageAsync(subscription.CreateResult(), cancellationToken);
if (nextInQueue != null)
{
nextLookups ??= [];
nextLookups.Add(nextInQueue);
}
}
}
if (nextLookups != null)
{
foreach (var lookup in nextLookups)
{
lookup.LoopBack(this);
await base.OnInnerAdapterNewOutMessageAsync(lookup, cancellationToken);
}
}
}
private void RestartTimeout(long transactionId, TimeSpan timeout)
{
CancelTimeout(transactionId);
if (_isDisposed)
return;
var source = new CancellationTokenSource();
_timeoutSources.Add(transactionId, (source, timeout));
_ = WaitForTimeoutAsync(transactionId, timeout, source);
}
private bool PauseTimeout(long transactionId)
{
if (_processingTimeouts.TryGetValue(transactionId, out var processing))
{
_processingTimeouts[transactionId] = (processing.count + 1, processing.timeout);
return true;
}
if (!_timeoutSources.TryGetValue(transactionId, out var registration))
return false;
CancelArmedTimeout(transactionId);
_processingTimeouts.Add(transactionId, (1, registration.timeout));
return true;
}
private void ResumeTimeout(long transactionId)
{
if (!_processingTimeouts.TryGetValue(transactionId, out var processing))
return;
if (processing.count > 1)
{
_processingTimeouts[transactionId] = (processing.count - 1, processing.timeout);
return;
}
_processingTimeouts.Remove(transactionId);
RestartTimeout(transactionId, processing.timeout);
}
private async Task WaitForTimeoutAsync(long transactionId, TimeSpan timeout, CancellationTokenSource source)
{
try
{
await Task.Delay(timeout, source.Token);
}
catch (OperationCanceledException)
{
return;
}
ISubscriptionMessage subscription;
Message nextLookup;
using (_timeoutSync.EnterScope())
{
if (!_timeoutSources.TryGetValue(transactionId, out var current) || !ReferenceEquals(current.source, source))
return;
_timeoutSources.Remove(transactionId);
source.Dispose();
if (!_state.TryGetAndRemoveLookup(transactionId, out subscription))
return;
nextLookup = _state.TryDequeueNext(subscription.Type, subscription.TransactionId);
}
try
{
LogInfo("Lookup timeout {0}.", transactionId);
await base.OnInnerAdapterNewOutMessageAsync(subscription.CreateResult(), default);
if (nextLookup != null)
{
nextLookup.LoopBack(this);
await base.OnInnerAdapterNewOutMessageAsync(nextLookup, default);
}
}
catch (Exception ex)
{
this.AddErrorLog(ex);
}
}
private void CancelTimeout(long transactionId)
{
_processingTimeouts.Remove(transactionId);
CancelArmedTimeout(transactionId);
}
private void CancelArmedTimeout(long transactionId)
{
if (!_timeoutSources.Remove(transactionId, out var registration))
return;
try { registration.source.Cancel(); }
catch (ObjectDisposedException) { }
registration.source.Dispose();
}
private void CancelAllTimeouts()
{
foreach (var (source, _) in _timeoutSources.Values)
{
try { source.Cancel(); }
catch (ObjectDisposedException) { }
source.Dispose();
}
_timeoutSources.Clear();
_processingTimeouts.Clear();
}
/// <inheritdoc />
public override void Dispose()
{
using (_timeoutSync.EnterScope())
{
if (_isDisposed)
return;
_isDisposed = true;
_state.Clear();
CancelAllTimeouts();
}
base.Dispose();
}
/// <summary>
/// Create a copy of <see cref="LookupTrackingMessageAdapter"/>.
/// </summary>
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
/// <returns>Copy.</returns>
public override async ValueTask<IMessageAdapter> CloneAsync(CancellationToken cancellationToken)
=> new LookupTrackingMessageAdapter(await InnerAdapter.CloneAsync(cancellationToken), _state.GetType().CreateInstance<ILookupTrackingManagerState>()) { _timeOut = _timeOut };
}