-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathSenderTask.cs
186 lines (171 loc) · 7.33 KB
/
SenderTask.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//---------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//---------------------------------------------------------------------------------
namespace ThroughputTest
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Sockets;
using Azure.Messaging.ServiceBus;
sealed class SenderTask : PerformanceTask
{
readonly List<Task> senders;
public SenderTask(Settings settings, Metrics metrics, CancellationToken cancellationToken)
: base(settings, metrics, cancellationToken)
{
this.senders = new List<Task>();
}
protected override Task OnOpenAsync()
{
return Task.CompletedTask;
}
protected override Task OnStartAsync()
{
for (int i = 0; i < this.Settings.SenderCount; i++)
{
this.senders.Add(Task.Run(SendTask));
}
return Task.WhenAll(senders);
}
async Task SendTask()
{
var client = new ServiceBusClient(this.Settings.ConnectionString);
ServiceBusSender sender = client.CreateSender(this.Settings.SendPath);
var payload = new byte[this.Settings.MessageSizeInBytes];
var semaphore = new DynamicSemaphoreSlim(this.Settings.MaxInflightSends.Value);
var done = new SemaphoreSlim(1);
done.Wait();
long totalSends = 0;
this.Settings.MaxInflightSends.Changing += (a, e) => AdjustSemaphore(e, semaphore);
var sw = Stopwatch.StartNew();
// first send will fail out if the cxn string is bad
await sender.SendMessageAsync(new ServiceBusMessage(payload) { TimeToLive = TimeSpan.FromMinutes(5) });
for (int j = 0; j < Settings.MessageCount && !this.CancellationToken.IsCancellationRequested; j++)
{
var sendMetrics = new SendMetrics() { Tick = sw.ElapsedTicks };
var nsec = sw.ElapsedTicks;
semaphore.Wait();
//await semaphore.WaitAsync().ConfigureAwait(false);
sendMetrics.InflightSends = this.Settings.MaxInflightSends.Value - semaphore.CurrentCount;
sendMetrics.GateLockDuration100ns = sw.ElapsedTicks - nsec;
if (Settings.SendDelay > 0)
{
await Task.Delay(Settings.SendDelay);
}
if (Settings.SendBatchCount <= 1)
{
sender.SendMessageAsync(new ServiceBusMessage(payload) { TimeToLive = TimeSpan.FromMinutes(5) })
.ContinueWith(async (t) =>
{
if (t.IsFaulted || t.IsCanceled)
{
await HandleExceptions(semaphore, sendMetrics, t.Exception);
}
else
{
sendMetrics.SendDuration100ns = sw.ElapsedTicks - nsec;
sendMetrics.Sends = 1;
sendMetrics.Messages = 1;
semaphore.Release();
Metrics.PushSendMetrics(sendMetrics);
}
if (Interlocked.Increment(ref totalSends) >= Settings.MessageCount)
{
done.Release();
}
}).Fork();
}
else
{
var batch = new List<ServiceBusMessage>();
for (int i = 0; i < Settings.SendBatchCount && j < Settings.MessageCount && !this.CancellationToken.IsCancellationRequested; i++, j++)
{
batch.Add(new ServiceBusMessage(payload) { TimeToLive = TimeSpan.FromMinutes(5) });
}
sender.SendMessagesAsync(batch)
.ContinueWith(async (t) =>
{
if (t.IsFaulted || t.IsCanceled)
{
await HandleExceptions(semaphore, sendMetrics, t.Exception);
}
else
{
sendMetrics.SendDuration100ns = sw.ElapsedTicks - nsec;
sendMetrics.Sends = 1;
sendMetrics.Messages = Settings.SendBatchCount;
semaphore.Release();
Metrics.PushSendMetrics(sendMetrics);
}
if (Interlocked.Increment(ref totalSends) >= Settings.MessageCount)
{
done.Release();
}
}).Fork();
}
}
await done.WaitAsync();
}
static void AdjustSemaphore(Observable<int>.ChangingEventArgs e, DynamicSemaphoreSlim semaphore)
{
if (e.NewValue > e.OldValue)
{
for (int i = e.OldValue; i < e.NewValue; i++)
{
semaphore.Grant();
}
}
else
{
for (int i = e.NewValue; i < e.OldValue; i++)
{
semaphore.Revoke();
}
}
}
private async Task HandleExceptions(DynamicSemaphoreSlim semaphore, SendMetrics sendMetrics, AggregateException ex)
{
bool wait = false;
ex.Handle((x) =>
{
if (x is ServiceBusException sbException)
{
if (sbException.Reason == ServiceBusFailureReason.ServiceCommunicationProblem)
{
if (sbException.InnerException is SocketException socketException &&
socketException.SocketErrorCode == SocketError.HostNotFound)
{
return false;
}
}
if (sbException.Reason == ServiceBusFailureReason.ServiceBusy)
{
sendMetrics.BusyErrors = 1;
if (!this.CancellationToken.IsCancellationRequested)
{
wait = true;
}
}
else
{
sendMetrics.Errors = 1;
}
}
return true;
});
if (wait)
{
await Task.Delay(3000, this.CancellationToken).ConfigureAwait(false);
}
semaphore.Release();
Metrics.PushSendMetrics(sendMetrics);
}
}
}