Files
StockSharp/Tests/SubscriptionMessageAdapterTests.cs
mika@stocksharp.com d92806bf99 Tell a second subscriber its hist+live subscription started
A subscription with a history that joins a series somebody already holds is
read that history by a bounded request of its own. The confirmation of that
request was swallowed: it is no state change of the shared stream, and the
branch that says so returned nothing at all. Above the online manager a
subscription counts as started from its confirmation, so every row of that
history was dropped there, and the subscriber saw only "online" and the live
data after it.

It showed at the broker's gate, where every client asks through one
connection: of two who asked for one candle series, the one heard second got
no history, whether they asked at once or minutes apart. Two subscriptions
of one connector fare the same.

The confirmation now goes on to its subscriber and leaves the shared stream
as it was.
2026-10-12 02:51:34 +03:00

426 lines
15 KiB
C#

namespace StockSharp.Tests;
[TestClass]
public class SubscriptionMessageAdapterTests : BaseTestClass
{
[TestMethod]
public async Task SendInMessage_DelegatesToManager_AndRoutesMessages()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<ISubscriptionManager>();
var toInner = new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.Ticks,
};
var toOut = new SubscriptionResponseMessage { OriginalTransactionId = 1 };
manager
.Setup(m => m.ProcessInMessage(It.IsAny<Message>()))
.Returns((toInner: (Message[])[toInner], toOut: (Message[])[toOut]));
using var adapter = new SubscriptionMessageAdapter(inner, manager.Object);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ResetMessage(), CancellationToken);
inner.InMessages.Count.AssertEqual(1);
inner.InMessages[0].AssertSame(toInner);
output.Count.AssertEqual(1);
output[0].AssertSame(toOut);
manager.Verify(m => m.ProcessInMessage(It.IsAny<Message>()), Times.Once);
}
[TestMethod]
public async Task InnerMessage_DelegatesToManager_AndRoutesMessages()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<ISubscriptionManager>();
var forward = new ConnectMessage();
var extra = new SubscriptionResponseMessage { OriginalTransactionId = 2 };
manager
.Setup(m => m.ProcessOutMessage(It.IsAny<Message>()))
.Returns((forward: (Message)forward, extraOut: (Message[])[extra]));
using var adapter = new SubscriptionMessageAdapter(inner, manager.Object);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await inner.SendOutMessageAsync(new DisconnectMessage(), CancellationToken);
output.Count.AssertEqual(2);
output[0].AssertSame(forward);
output[1].AssertSame(extra);
manager.Verify(m => m.ProcessOutMessage(It.IsAny<Message>()), Times.Once);
}
[TestMethod]
public async Task ConnectionRestored_WhenRestoreDisabled_ShouldNotRemap()
{
var inner = new RecordingMessageAdapter();
using var adapter = new SubscriptionMessageAdapter(inner)
{
IsRestoreSubscriptionOnErrorReconnect = false,
};
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 100,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.Ticks,
}, CancellationToken);
await inner.SendOutMessageAsync(new SubscriptionResponseMessage { OriginalTransactionId = 100 }, CancellationToken);
await inner.SendOutMessageAsync(new ConnectionRestoredMessage { IsResetState = true }, CancellationToken);
output.OfType<ProcessSuspendedMessage>().Count().AssertEqual(0);
}
#region End-to-end with real manager
[TestMethod]
public async Task RealManager_TickDataFlowsThrough_AfterOnline()
{
var inner = new RecordingMessageAdapter();
using var adapter = new SubscriptionMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
var secId = Helper.CreateSecurityId();
// Subscribe
await adapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 100,
SecurityId = secId,
DataType2 = DataType.Ticks,
}, CancellationToken);
inner.InMessages.OfType<MarketDataMessage>().Count(m => m.TransactionId == 100 && m.IsSubscribe).AssertEqual(1, "Subscribe should reach inner");
// Inner sends back SubscriptionResponse OK
await inner.SendOutMessageAsync(new SubscriptionResponseMessage { OriginalTransactionId = 100 }, CancellationToken);
output.OfType<SubscriptionResponseMessage>().Count(m => m.OriginalTransactionId == 100 && m.IsOk()).AssertEqual(1, "Response should flow out");
// Inner sends back SubscriptionOnline
await inner.SendOutMessageAsync(new SubscriptionOnlineMessage { OriginalTransactionId = 100 }, CancellationToken);
output.OfType<SubscriptionOnlineMessage>().Count(m => m.OriginalTransactionId == 100).AssertEqual(1, "Online should flow out");
output.Clear();
// Inner emits tick data with subscription ID set
var tick = new ExecutionMessage
{
DataTypeEx = DataType.Ticks,
SecurityId = secId,
TradePrice = 50000m,
TradeVolume = 1m,
ServerTime = DateTime.UtcNow,
};
tick.SetSubscriptionIds(subscriptionId: 100);
await inner.SendOutMessageAsync(tick, CancellationToken);
output.OfType<ExecutionMessage>().Count(m => m.TradePrice == 50000m).AssertEqual(1,
$"Tick should flow through SubscriptionMessageAdapter, got {output.Count} messages: {output.Select(m => $"{m.Type}").JoinCommaSpace()}");
}
[TestMethod]
public async Task RealManager_TickDataDropped_WhenNoSubscription()
{
var inner = new RecordingMessageAdapter();
using var adapter = new SubscriptionMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
// Emit tick data WITHOUT any subscription registered
var tick = new ExecutionMessage
{
DataTypeEx = DataType.Ticks,
SecurityId = Helper.CreateSecurityId(),
TradePrice = 50000m,
TradeVolume = 1m,
ServerTime = DateTime.UtcNow,
};
tick.SetSubscriptionIds(subscriptionId: 999);
await inner.SendOutMessageAsync(tick, CancellationToken);
output.OfType<ExecutionMessage>().Count().AssertEqual(0, "Tick with unknown subscription should be dropped");
}
#endregion
#region Combined adapter chain
[TestMethod]
public async Task CombinedChain_TickDataFlowsThrough_SubscriptionOnline_ThenSubscription()
{
// Tests the chain: inner → SubscriptionOnlineMessageAdapter → SubscriptionMessageAdapter
var inner = new RecordingMessageAdapter();
var onlineAdapter = new SubscriptionOnlineMessageAdapter(inner);
using var subscrAdapter = new SubscriptionMessageAdapter(onlineAdapter);
var output = new List<Message>();
subscrAdapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
var secId = Helper.CreateSecurityId();
// Subscribe through chain
await subscrAdapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 100,
SecurityId = secId,
DataType2 = DataType.Ticks,
}, CancellationToken);
inner.InMessages.OfType<MarketDataMessage>().Count(m => m.TransactionId == 100 && m.IsSubscribe).AssertEqual(1, "Subscribe should reach inner adapter");
// Inner sends Response + Online
await inner.SendOutMessageAsync(new SubscriptionResponseMessage { OriginalTransactionId = 100 }, CancellationToken);
await inner.SendOutMessageAsync(new SubscriptionOnlineMessage { OriginalTransactionId = 100 }, CancellationToken);
output.OfType<SubscriptionResponseMessage>().Count(m => m.OriginalTransactionId == 100 && m.IsOk()).AssertEqual(1, "Response should flow out");
output.OfType<SubscriptionOnlineMessage>().Count(m => m.OriginalTransactionId == 100).AssertEqual(1, "Online should flow out");
output.Clear();
// Emit tick (with subscription ID)
var tick = new ExecutionMessage
{
DataTypeEx = DataType.Ticks,
SecurityId = secId,
TradePrice = 50000m,
TradeVolume = 1m,
ServerTime = DateTime.UtcNow,
};
tick.SetSubscriptionIds(subscriptionId: 100);
await inner.SendOutMessageAsync(tick, CancellationToken);
output.OfType<ExecutionMessage>().Count(m => m.TradePrice == 50000m).AssertEqual(1,
$"Tick should flow through combined chain, got {output.Count} messages: {output.Select(m => $"{m.Type}").JoinCommaSpace()}");
}
[TestMethod]
public async Task CombinedChain_TickDataWithoutId_FoundByKey()
{
// Same chain but tick has no subscription ID — SubscriptionOnlineManager must find by (DataType, SecurityId)
var inner = new RecordingMessageAdapter();
var onlineAdapter = new SubscriptionOnlineMessageAdapter(inner);
using var subscrAdapter = new SubscriptionMessageAdapter(onlineAdapter);
var output = new List<Message>();
subscrAdapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
var secId = Helper.CreateSecurityId();
// Subscribe through chain
await subscrAdapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 100,
SecurityId = secId,
DataType2 = DataType.Ticks,
}, CancellationToken);
await inner.SendOutMessageAsync(new SubscriptionResponseMessage { OriginalTransactionId = 100 }, CancellationToken);
await inner.SendOutMessageAsync(new SubscriptionOnlineMessage { OriginalTransactionId = 100 }, CancellationToken);
output.Clear();
// Emit tick WITHOUT subscription IDs
var tick = new ExecutionMessage
{
DataTypeEx = DataType.Ticks,
SecurityId = secId,
TradePrice = 42000m,
TradeVolume = 2m,
ServerTime = DateTime.UtcNow,
};
await inner.SendOutMessageAsync(tick, CancellationToken);
output.OfType<ExecutionMessage>().Count(m => m.TradePrice == 42000m).AssertEqual(1,
$"Tick without ID should be resolved by key, got {output.Count} messages: {output.Select(m => $"{m.Type}").JoinCommaSpace()}");
}
/// <summary>
/// Two subscribers ask for one series with its history. The stream the first opened stays the live source
/// of both, and the second is read a history of its own by a bounded request. Whoever asks second is told
/// its subscription started and is served that history, as the first was.
/// </summary>
[TestMethod]
public async Task CombinedChain_SecondSubscriberWithHistory_IsConfirmedAndServedItsHistory()
{
var inner = new RecordingMessageAdapter();
var onlineAdapter = new SubscriptionOnlineMessageAdapter(inner);
using var subscrAdapter = new SubscriptionMessageAdapter(onlineAdapter);
var output = new List<Message>();
subscrAdapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
var secId = Helper.CreateSecurityId();
var from = DateTime.UtcNow.AddHours(-1);
MarketDataMessage Ask(long transactionId) => new()
{
IsSubscribe = true,
TransactionId = transactionId,
SecurityId = secId,
DataType2 = DataType.Ticks,
From = from,
};
await subscrAdapter.SendInMessageAsync(Ask(100), CancellationToken);
await inner.SendOutMessageAsync(new SubscriptionResponseMessage { OriginalTransactionId = 100 }, CancellationToken);
await inner.SendOutMessageAsync(new SubscriptionOnlineMessage { OriginalTransactionId = 100 }, CancellationToken);
await subscrAdapter.SendInMessageAsync(Ask(200), CancellationToken);
inner.InMessages.OfType<MarketDataMessage>().Count(m => m.TransactionId == 200 && m.IsSubscribe && m.To is not null)
.AssertEqual(1, "The second subscriber's history should be asked for by a bounded request of its own");
output.Clear();
await inner.SendOutMessageAsync(new SubscriptionResponseMessage { OriginalTransactionId = 200 }, CancellationToken);
await inner.SendOutMessageAsync(new ExecutionMessage
{
DataTypeEx = DataType.Ticks,
SecurityId = secId,
TradePrice = 42m,
TradeVolume = 1m,
ServerTime = from.AddMinutes(1),
OriginalTransactionId = 200,
}, CancellationToken);
await inner.SendOutMessageAsync(new SubscriptionFinishedMessage { OriginalTransactionId = 200 }, CancellationToken);
var came = output.Select(m => $"{m.Type}").JoinCommaSpace();
output.OfType<SubscriptionResponseMessage>().Count(m => m.OriginalTransactionId == 200 && m.IsOk())
.AssertEqual(1, $"The second subscriber should be told its subscription started, got: {came}");
output.OfType<ExecutionMessage>().Count(m => m.TradePrice == 42m && m.GetSubscriptionIds().Contains(200L))
.AssertEqual(1, $"The second subscriber should be served its history, got: {came}");
output.OfType<SubscriptionOnlineMessage>().Count(m => m.OriginalTransactionId == 200)
.AssertEqual(1, $"The second subscriber should go online once its history is over, got: {came}");
}
#endregion
#region The adapter's own clock
// Runs on a clock the test sets and writes down whether it was actually asked to subscribe.
// Nothing above MarketDataAsync is overridden, because the base adapter's own decision about a
// range that has not happened yet is what is under test.
private sealed class ClockedAdapter : MessageAdapter
{
public ClockedAdapter()
: base(new IncrementalIdGenerator())
{
}
/// <summary>The time this adapter believes it is.</summary>
public DateTime Now { get; set; }
public List<MarketDataMessage> Subscribed { get; } = [];
public override DateTime CurrentTime => Now;
protected override ValueTask OnTicksSubscriptionAsync(MarketDataMessage mdMsg, CancellationToken cancellationToken)
{
Subscribed.Add(mdMsg);
return SendSubscriptionReplyAsync(mdMsg.TransactionId, cancellationToken);
}
public override ValueTask<IMessageAdapter> CloneAsync(CancellationToken cancellationToken)
=> new(new ClockedAdapter { Now = Now });
}
/// <summary>
/// Whether a requested range lies in the future is decided against the adapter's own clock. In an
/// emulation that clock is the simulated one, and a strategy asking for data ahead of where the
/// simulation has got to is entitled to be told there is nothing there yet - rather than having
/// the request accepted against wall-clock time and answered with whatever the feed has.
/// </summary>
[TestMethod]
public async Task MarketData_FromInTheFuture_IsJudgedByTheAdapterClock()
{
var adapter = new ClockedAdapter
{
Now = new DateTime(2020, 03, 04, 09, 30, 00, DateTimeKind.Utc),
};
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, _) => { output.Add(m); return default; };
var from = adapter.Now.AddDays(30);
await adapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.Ticks,
From = from,
To = from.AddDays(1),
}, CancellationToken);
IsEmpty(adapter.Subscribed, "the range has not happened yet on this adapter's clock, so there is nothing to go and ask for");
output.OfType<SubscriptionFinishedMessage>().Count(m => m.OriginalTransactionId == 1)
.AssertEqual(1, "and the caller is told the request is done instead of being left waiting for data that cannot come");
}
[TestMethod]
public async Task MarketData_FromInThePast_ReachesTheAdapter()
{
var adapter = new ClockedAdapter
{
Now = new DateTime(2020, 03, 04, 09, 30, 00, DateTimeKind.Utc),
};
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, _) => { output.Add(m); return default; };
var subscribe = new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 2,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.Ticks,
From = adapter.Now.AddDays(-30),
To = adapter.Now.AddDays(-29),
};
await adapter.SendInMessageAsync(subscribe, CancellationToken);
adapter.Subscribed.Single().AssertSame(subscribe,
"a range that already happened on the adapter's clock must reach the data source");
output.OfType<SubscriptionFinishedMessage>().Count().AssertEqual(0,
"the base adapter must not finish a past range before the data source handles it");
}
#endregion
}