-
Notifications
You must be signed in to change notification settings - Fork 496
/
AmqpIotSendingLink.cs
253 lines (194 loc) · 9.74 KB
/
AmqpIotSendingLink.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Amqp;
using Microsoft.Azure.Amqp.Framing;
namespace Microsoft.Azure.Devices.Client.Transport.AmqpIot
{
internal sealed class AmqpIotSendingLink
{
public event EventHandler Closed;
private readonly SendingAmqpLink _sendingAmqpLink;
public AmqpIotSendingLink(SendingAmqpLink sendingAmqpLink)
{
_sendingAmqpLink = sendingAmqpLink;
_sendingAmqpLink.Closed += SendingAmqpLinkClosed;
}
// This event handler is not invoked by the AMQP library in an async fashion.
// This also co-relates with the fact that SendingAmqpLink.SafeClose() is a sync method.
private void SendingAmqpLinkClosed(object sender, EventArgs e)
{
if (Logging.IsEnabled)
Logging.Enter(this, nameof(SendingAmqpLinkClosed));
Closed?.Invoke(this, e);
// After the Closed event handler has been invoked, the SendingAmqpLink has now been effectively cleaned up.
// This is a good point for us to detach the Closed event handler from the SendingAmqpLink instance.
_sendingAmqpLink.Closed -= SendingAmqpLinkClosed;
if (Logging.IsEnabled)
Logging.Exit(this, nameof(SendingAmqpLinkClosed));
}
internal Task CloseAsync(CancellationToken cancellationToken)
{
if (Logging.IsEnabled)
Logging.Enter(this, nameof(CloseAsync));
return _sendingAmqpLink.CloseAsync(cancellationToken);
}
internal void SafeClose()
{
if (Logging.IsEnabled)
Logging.Enter(this, nameof(SafeClose));
_sendingAmqpLink.SafeClose();
if (Logging.IsEnabled)
Logging.Exit(this, nameof(SafeClose));
}
internal bool IsClosing()
{
return _sendingAmqpLink.IsClosing();
}
#region Telemetry handling
internal async Task<AmqpIotOutcome> SendMessageAsync(TelemetryMessage message, CancellationToken cancellationToken)
{
if (Logging.IsEnabled)
Logging.Enter(this, message, nameof(SendMessageAsync));
// After this message is sent, we will return the outcome that has no references to the message
// So it can safely be disposed.
using AmqpMessage amqpMessage = AmqpIotMessageConverter.OutgoingMessageToAmqpMessage(message);
Outcome outcome = await SendAmqpMessageAsync(amqpMessage, cancellationToken).ConfigureAwait(false);
if (Logging.IsEnabled)
Logging.Exit(this, message, nameof(SendMessageAsync));
return new AmqpIotOutcome(outcome);
}
internal async Task<AmqpIotOutcome> SendMessagesAsync(IEnumerable<TelemetryMessage> messages, CancellationToken cancellationToken)
{
if (Logging.IsEnabled)
Logging.Enter(this, nameof(SendMessagesAsync));
cancellationToken.ThrowIfCancellationRequested();
// List to hold messages in AMQP friendly format
var messageList = new List<Data>(messages.Count());
foreach (TelemetryMessage message in messages)
{
using AmqpMessage amqpMessage = AmqpIotMessageConverter.OutgoingMessageToAmqpMessage(message);
var data = new Data
{
Value = AmqpIotMessageConverter.ReadStream(amqpMessage.ToStream()),
};
messageList.Add(data);
}
using var batchMessage = AmqpMessage.Create(messageList);
batchMessage.MessageFormat = AmqpConstants.AmqpBatchedMessageFormat;
Outcome outcome = await SendAmqpMessageAsync(batchMessage, cancellationToken).ConfigureAwait(false);
var amqpIotOutcome = new AmqpIotOutcome(outcome);
amqpIotOutcome.ThrowIfNotAccepted();
if (Logging.IsEnabled)
Logging.Exit(this, nameof(SendMessagesAsync));
return amqpIotOutcome;
}
private async Task<Outcome> SendAmqpMessageAsync(AmqpMessage amqpMessage, CancellationToken cancellationToken)
{
if (Logging.IsEnabled)
Logging.Enter(this, nameof(SendAmqpMessageAsync));
try
{
return await _sendingAmqpLink
.SendMessageAsync(
amqpMessage,
new ArraySegment<byte>(Guid.NewGuid().ToByteArray()),
AmqpConstants.NullBinary,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex) when (!Fx.IsFatal(ex))
{
Exception iotEx = AmqpIotExceptionAdapter.ConvertToIotHubException(ex, _sendingAmqpLink);
if (iotEx is OperationCanceledException && !cancellationToken.IsCancellationRequested)
{
// OperationCanceledException may be thrown here when there is networking disconnect
// even if cancellation has not been requested yet. This case is treated as a transient
// network error rather than an OperationCanceledException.
throw new IotHubClientException(iotEx.Message, IotHubClientErrorCode.NetworkErrors, iotEx);
}
if (ReferenceEquals(ex, iotEx))
{
throw;
}
if (iotEx is IotHubClientException hubEx && hubEx.InnerException is AmqpException)
{
_sendingAmqpLink.SafeClose();
throw iotEx;
}
throw iotEx;
}
finally
{
if (Logging.IsEnabled)
Logging.Exit(this, nameof(SendAmqpMessageAsync));
}
}
#endregion Telemetry handling
#region Method handling
internal async Task<AmqpIotOutcome> SendMethodResponseAsync(DirectMethodResponse methodResponse, CancellationToken cancellationToken)
{
if (Logging.IsEnabled)
Logging.Enter(this, methodResponse, nameof(SendMethodResponseAsync));
cancellationToken.ThrowIfCancellationRequested();
using AmqpMessage amqpMessage = AmqpIotMessageConverter.ConvertDirectMethodResponseToAmqpMessage(methodResponse);
AmqpIotMessageConverter.PopulateAmqpMessageFromMethodResponse(amqpMessage, methodResponse);
Outcome outcome = await SendAmqpMessageAsync(amqpMessage, cancellationToken).ConfigureAwait(false);
if (Logging.IsEnabled)
Logging.Exit(this, nameof(SendMethodResponseAsync));
return new AmqpIotOutcome(outcome);
}
#endregion Method handling
#region Twin handling
internal async Task<AmqpIotOutcome> SendTwinGetMessageAsync(string correlationId, CancellationToken cancellationToken)
{
if (Logging.IsEnabled)
Logging.Enter(this, nameof(SendTwinGetMessageAsync));
using var amqpMessage = AmqpMessage.Create();
amqpMessage.Properties.CorrelationId = correlationId;
amqpMessage.MessageAnnotations.Map["operation"] = "GET";
Outcome outcome = await SendAmqpMessageAsync(amqpMessage, cancellationToken).ConfigureAwait(false);
if (Logging.IsEnabled)
Logging.Exit(this, nameof(SendTwinGetMessageAsync));
return new AmqpIotOutcome(outcome);
}
internal async Task<AmqpIotOutcome> SendTwinPatchMessageAsync(
string correlationId,
ReportedProperties reportedProperties,
CancellationToken cancellationToken)
{
if (Logging.IsEnabled)
Logging.Enter(this, nameof(SendTwinPatchMessageAsync));
var bodyStream = new MemoryStream(reportedProperties.GetObjectBytes());
using var amqpMessage = AmqpMessage.Create(bodyStream, true);
amqpMessage.Properties.CorrelationId = correlationId;
amqpMessage.MessageAnnotations.Map["operation"] = "PATCH";
amqpMessage.MessageAnnotations.Map["resource"] = "/properties/reported";
amqpMessage.MessageAnnotations.Map["version"] = null;
Outcome outcome = await SendAmqpMessageAsync(amqpMessage, cancellationToken).ConfigureAwait(false);
if (Logging.IsEnabled)
Logging.Exit(this, nameof(SendTwinPatchMessageAsync));
return new AmqpIotOutcome(outcome);
}
internal async Task<AmqpIotOutcome> SubscribeToDesiredPropertiesAsync(string correlationId, CancellationToken cancellationToken)
{
if (Logging.IsEnabled)
Logging.Enter(this, nameof(SubscribeToDesiredPropertiesAsync));
using var amqpMessage = AmqpMessage.Create();
amqpMessage.Properties.CorrelationId = correlationId;
amqpMessage.MessageAnnotations.Map["operation"] = "PUT";
amqpMessage.MessageAnnotations.Map["resource"] = "/notifications/twin/properties/desired";
amqpMessage.MessageAnnotations.Map["version"] = null;
Outcome outcome = await SendAmqpMessageAsync(amqpMessage, cancellationToken).ConfigureAwait(false);
if (Logging.IsEnabled)
Logging.Exit(this, nameof(SubscribeToDesiredPropertiesAsync));
return new AmqpIotOutcome(outcome);
}
#endregion Twin handling
}
}