-
Notifications
You must be signed in to change notification settings - Fork 58
/
ConfirmsAwareChannel.cs
228 lines (187 loc) · 8.4 KB
/
ConfirmsAwareChannel.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
namespace NServiceBus.Transport.RabbitMQ
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using global::RabbitMQ.Client;
using global::RabbitMQ.Client.Events;
using NServiceBus.Logging;
sealed class ConfirmsAwareChannel(IConnection connection, IRoutingTopology routingTopology) : IDisposable
{
public bool IsOpen => channel.IsOpen;
public bool IsClosed => channel.IsClosed;
public async Task Initialize(CancellationToken cancellationToken = default)
{
channel = await connection.CreateChannelAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
channel.BasicAcks += Channel_BasicAcks;
channel.BasicNacks += Channel_BasicNacks;
channel.BasicReturn += Channel_BasicReturn;
channel.ChannelShutdown += Channel_ModelShutdown;
await channel.ConfirmSelectAsync(trackConfirmations: false, cancellationToken).ConfigureAwait(false);
}
public async Task SendMessage(string address, OutgoingMessage message, BasicProperties properties, CancellationToken cancellationToken = default)
{
TaskCompletionSource taskCompletionSource;
try
{
await sequenceNumberSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
(taskCompletionSource, var registration) = GetCancellableTaskCompletionSource(cancellationToken);
await using var _ = registration.ConfigureAwait(false);
properties.SetConfirmationId(channel.NextPublishSeqNo);
if (properties.Headers != null &&
properties.Headers.TryGetValue(DelayInfrastructure.DelayHeader, out var delayValue))
{
var routingKey =
DelayInfrastructure.CalculateRoutingKey((int)delayValue, address, out var startingDelayLevel);
await routingTopology.BindToDelayInfrastructure(channel, address,
DelayInfrastructure.DeliveryExchange, DelayInfrastructure.BindingKey(address),
cancellationToken).ConfigureAwait(false);
// The channel is used here directly because it is not the routing topologies concern to know about the sends to the delay infrastructure
await channel.BasicPublishAsync(DelayInfrastructure.LevelName(startingDelayLevel), routingKey, true,
properties, message.Body, cancellationToken).ConfigureAwait(false);
}
else
{
await routingTopology.Send(channel, address, message, properties, cancellationToken)
.ConfigureAwait(false);
}
}
finally
{
sequenceNumberSemaphore.Release();
}
await taskCompletionSource.Task.ConfigureAwait(false);
}
public async Task PublishMessage(Type type, OutgoingMessage message, BasicProperties properties, CancellationToken cancellationToken = default)
{
TaskCompletionSource taskCompletionSource;
try
{
await sequenceNumberSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
(taskCompletionSource, var registration) = GetCancellableTaskCompletionSource(cancellationToken);
await using var _ = registration.ConfigureAwait(false);
properties.SetConfirmationId(channel.NextPublishSeqNo);
await routingTopology.Publish(channel, type, message, properties, cancellationToken)
.ConfigureAwait(false);
}
finally
{
sequenceNumberSemaphore.Release();
}
await taskCompletionSource.Task.ConfigureAwait(false);
}
public async Task RawSendInCaseOfFailure(string address, ReadOnlyMemory<byte> body, BasicProperties properties, CancellationToken cancellationToken = default)
{
properties.Headers ??= new Dictionary<string, object>();
TaskCompletionSource taskCompletionSource;
try
{
await sequenceNumberSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
(taskCompletionSource, var registration) = GetCancellableTaskCompletionSource(cancellationToken);
await using var _ = registration.ConfigureAwait(false);
properties.SetConfirmationId(channel.NextPublishSeqNo);
await routingTopology.RawSendInCaseOfFailure(channel, address, body, properties, cancellationToken)
.ConfigureAwait(false);
}
finally
{
sequenceNumberSemaphore.Release();
}
await taskCompletionSource.Task.ConfigureAwait(false);
}
(TaskCompletionSource, IAsyncDisposable) GetCancellableTaskCompletionSource(CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
// There is no need to capture the execution context therefore using UnsafeRegister
var registration = cancellationToken.UnsafeRegister(static state =>
{
var (tcs, cancellationToken) = ((TaskCompletionSource, CancellationToken))state!;
tcs.TrySetCanceled(cancellationToken);
}, (tcs, cancellationToken));
var added = messages.TryAdd(channel.NextPublishSeqNo, tcs);
if (!added)
{
throw new Exception($"Cannot publish a message with sequence number '{channel.NextPublishSeqNo}' on this channel. A message was already published on this channel with the same confirmation number.");
}
return (tcs, registration);
}
void Channel_BasicAcks(object sender, BasicAckEventArgs e)
{
if (!e.Multiple)
{
SetResult(e.DeliveryTag);
}
else
{
foreach (var message in messages)
{
if (message.Key <= e.DeliveryTag)
{
SetResult(message.Key);
}
}
}
}
void Channel_BasicNacks(object sender, BasicNackEventArgs e)
{
if (!e.Multiple)
{
SetException(e.DeliveryTag, "Message rejected by broker.");
}
else
{
foreach (var message in messages)
{
if (message.Key <= e.DeliveryTag)
{
SetException(message.Key, "Message rejected by broker.");
}
}
}
}
void Channel_BasicReturn(object sender, BasicReturnEventArgs e)
{
var message = $"Message could not be routed to {e.Exchange + e.RoutingKey}: {e.ReplyCode} {e.ReplyText}";
if (e.BasicProperties.TryGetConfirmationId(out var deliveryTag))
{
SetException(deliveryTag, message);
}
else
{
Logger.Warn(message);
}
}
void Channel_ModelShutdown(object sender, ShutdownEventArgs e)
{
do
{
foreach (var message in messages)
{
SetException(message.Key, $"Channel has been closed: {e}");
}
}
while (!messages.IsEmpty);
}
void SetResult(ulong key)
{
if (messages.TryRemove(key, out var tcs))
{
tcs.SetResult();
}
}
void SetException(ulong key, string exceptionMessage)
{
if (messages.TryRemove(key, out var tcs))
{
tcs.SetException(new Exception(exceptionMessage));
}
}
public void Dispose() => channel?.Dispose();
IChannel channel;
readonly ConcurrentDictionary<ulong, TaskCompletionSource> messages = new();
readonly SemaphoreSlim sequenceNumberSemaphore = new(1, 1);
static readonly ILog Logger = LogManager.GetLogger(typeof(ConfirmsAwareChannel));
}
}