-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
ServiceBusSessionReceiver.cs
258 lines (240 loc) · 12.7 KB
/
ServiceBusSessionReceiver.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
254
255
256
257
258
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Core.Shared;
using Azure.Messaging.ServiceBus.Core;
using Azure.Messaging.ServiceBus.Diagnostics;
namespace Azure.Messaging.ServiceBus
{
/// <summary>
/// The <see cref="ServiceBusSessionReceiver" /> is responsible for receiving <see cref="ServiceBusReceivedMessage" />
/// and settling messages from session-enabled Queues and Subscriptions. It is constructed by calling
/// <see cref="ServiceBusClient.AcceptNextSessionAsync(string, string, ServiceBusSessionReceiverOptions, CancellationToken)"/>.
/// </summary>
public class ServiceBusSessionReceiver : ServiceBusReceiver
{
/// <summary>
/// The active connection to the Azure Service Bus service, enabling client communications for metadata
/// about the associated Service Bus entity and access to transport-aware receivers.
/// </summary>
///
private readonly ServiceBusConnection _connection;
/// <summary>
/// The Session Id associated with the receiver.
/// </summary>
public virtual string SessionId => InnerReceiver.SessionId;
/// <summary>
/// Indicates whether or not this <see cref="ServiceBusSessionReceiver"/> has been closed by the user, or whether the underlying
/// session link was closed due to either losing the session lock or having the link disconnected. If this is <c>true</c>, the
/// receiver cannot be used for any more operations. If this is <c>false</c>, it is still possible that the session lock has been lost
/// so it is important to still handle <see cref="ServiceBusException" /> with <see cref="ServiceBusException.Reason" /> equal to
/// <see cref="ServiceBusFailureReason.SessionLockLost"/>.
/// </summary>
///
/// <value>
/// <c>true</c> if the session receiver was closed by the user or if the underlying link was closed; otherwise, <c>false</c>.
/// </value>
public override bool IsClosed => IsDisposed || InnerReceiver.IsSessionLinkClosed;
/// <summary>
/// Gets the <see cref="DateTimeOffset"/> that the receiver's session is locked until.
/// </summary>
public virtual DateTimeOffset SessionLockedUntil => InnerReceiver.SessionLockedUntil;
/// <summary>
/// Creates a session receiver which can be used to interact with all messages with the same sessionId.
/// </summary>
/// <param name="entityPath">The name of the specific queue to associate the receiver with.</param>
/// <param name="connection">The <see cref="ServiceBusConnection" /> connection to use for communication with the Service Bus service.</param>
/// <param name="options">A set of options to apply when configuring the receiver.</param>
/// <param name="sessionId">The Session Id to receive from or null to receive from the next available session.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
/// <param name="isProcessor">True if called from the session processor.</param>
/// <returns>Returns a new instance of the <see cref="ServiceBusSessionReceiver"/> class.</returns>
internal static async Task<ServiceBusSessionReceiver> CreateSessionReceiverAsync(
string entityPath,
ServiceBusConnection connection,
ServiceBusSessionReceiverOptions options,
string sessionId,
CancellationToken cancellationToken,
bool isProcessor = false)
{
var receiver = new ServiceBusSessionReceiver(
connection: connection,
entityPath: entityPath,
options: options,
cancellationToken: cancellationToken,
sessionId: sessionId,
isProcessor: isProcessor);
try
{
await receiver.OpenLinkAsync(cancellationToken).ConfigureAwait(false);
receiver.Logger.ClientCreateComplete(typeof(ServiceBusSessionReceiver), receiver.Identifier);
return receiver;
}
catch (ServiceBusException e)
when (e.Reason == ServiceBusFailureReason.ServiceTimeout && isProcessor)
{
await receiver.CloseAsync(CancellationToken.None).ConfigureAwait(false);
receiver.Logger.ProcessorAcceptSessionTimeout(receiver.FullyQualifiedNamespace, entityPath, e.ToString());
throw;
}
catch (TaskCanceledException exception)
when (isProcessor)
{
await receiver.CloseAsync(CancellationToken.None).ConfigureAwait(false);
receiver.Logger.ProcessorStoppingAcceptSessionCanceled(receiver.FullyQualifiedNamespace, entityPath, exception.ToString());
throw;
}
catch (Exception ex)
{
await receiver.CloseAsync(CancellationToken.None).ConfigureAwait(false);
receiver.Logger.ClientCreateException(typeof(ServiceBusSessionReceiver), receiver.FullyQualifiedNamespace, entityPath, ex);
throw;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceBusReceiver"/> class.
/// </summary>
///
/// <param name="connection">The <see cref="ServiceBusConnection" /> connection to use for communication with the Service Bus service.</param>
/// <param name="entityPath"></param>
/// <param name="options">A set of options to apply when configuring the consumer.</param>
/// <param name="cancellationToken">The cancellation token to use when opening the receiver link.</param>
/// <param name="sessionId">An optional session Id to receive from.</param>
/// <param name="isProcessor"></param>
internal ServiceBusSessionReceiver(
ServiceBusConnection connection,
string entityPath,
ServiceBusSessionReceiverOptions options,
CancellationToken cancellationToken,
string sessionId = default,
bool isProcessor = false) :
base(connection, entityPath, true, options?.ToReceiverOptions(), sessionId, isProcessor, cancellationToken)
{
_connection = connection;
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceBusSessionReceiver"/> class for mocking.
/// </summary>
///
protected ServiceBusSessionReceiver() { }
/// <summary>
/// Gets the session state.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>The session state as <see cref="BinaryData"/>.</returns>
/// <exception cref="ServiceBusException">
/// The lock for the session has expired.
/// The <see cref="ServiceBusException.Reason" /> will be set to <see cref="ServiceBusFailureReason.SessionLockLost"/> in this case.
/// </exception>
public virtual async Task<BinaryData> GetSessionStateAsync(CancellationToken cancellationToken = default)
{
Argument.AssertNotDisposed(IsDisposed, nameof(ServiceBusSessionReceiver));
_connection.ThrowIfClosed();
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
Logger.GetSessionStateStart(Identifier, SessionId);
using DiagnosticScope scope = ClientDiagnostics.CreateScope(
DiagnosticProperty.GetSessionStateActivityName,
ActivityKind.Client);
scope.Start();
BinaryData sessionState;
try
{
sessionState = await InnerReceiver.GetStateAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
Logger.GetSessionStateException(Identifier, exception.ToString(), SessionId);
scope.Failed(exception);
throw;
}
Logger.GetSessionStateComplete(Identifier, SessionId);
return sessionState;
}
/// <summary>
/// Set a custom state on the session which can be later retrieved using <see cref="GetSessionStateAsync"/>
/// </summary>
///
/// <param name="sessionState">A <see cref="BinaryData"/> of session state</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <remarks>This state is stored on Service Bus forever unless you set an empty state on it.</remarks>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
/// <exception cref="ServiceBusException">
/// The lock for the session has expired.
/// The <see cref="ServiceBusException.Reason" /> will be set to <see cref="ServiceBusFailureReason.SessionLockLost"/> in this case.
/// </exception>
public virtual async Task SetSessionStateAsync(
BinaryData sessionState,
CancellationToken cancellationToken = default)
{
Argument.AssertNotDisposed(IsDisposed, nameof(ServiceBusSessionReceiver));
_connection.ThrowIfClosed();
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
Logger.SetSessionStateStart(Identifier, SessionId);
using DiagnosticScope scope = ClientDiagnostics.CreateScope(
DiagnosticProperty.SetSessionStateActivityName,
ActivityKind.Client);
scope.Start();
try
{
await InnerReceiver.SetStateAsync(sessionState, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
Logger.SetSessionStateException(Identifier, exception.ToString(), SessionId);
scope.Failed(exception);
throw;
}
Logger.SetSessionStateComplete(Identifier, SessionId);
}
/// <summary>
/// Renews the lock on the session specified by the <see cref="SessionId"/>. The lock will be renewed based on the setting specified on the entity.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <remarks>
/// <para>
/// When you accept a session, the session is locked for this receiver by the service for a duration as specified during the Queue/Subscription creation.
/// If processing of the session requires longer than this duration, the session-lock needs to be renewed.
/// For each renewal, it resets the time the session is locked by the LockDuration set on the Entity.
/// </para>
/// <para>
/// Renewal of session renews all the messages in the session as well. Each individual message need not be renewed.
/// </para>
/// </remarks>
/// <exception cref="ServiceBusException">
/// The lock for the session has expired.
/// The <see cref="ServiceBusException.Reason" /> will be set to <see cref="ServiceBusFailureReason.SessionLockLost"/> in this case.
/// </exception>
public virtual async Task RenewSessionLockAsync(CancellationToken cancellationToken = default)
{
Argument.AssertNotDisposed(IsDisposed, nameof(ServiceBusSessionReceiver));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
Logger.RenewSessionLockStart(Identifier, SessionId);
using DiagnosticScope scope = ClientDiagnostics.CreateScope(
DiagnosticProperty.RenewSessionLockActivityName,
ActivityKind.Client);
scope.Start();
try
{
await InnerReceiver.RenewSessionLockAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
Logger.RenewSessionLockException(Identifier, exception.ToString(), SessionId);
scope.Failed(exception);
throw;
}
Logger.RenewSessionLockComplete(Identifier, SessionId);
}
}
}