-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathAbstractConsumer.cs
More file actions
202 lines (172 loc) · 5.64 KB
/
AbstractConsumer.cs
File metadata and controls
202 lines (172 loc) · 5.64 KB
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
namespace SlimMessageBus.Host;
public abstract partial class AbstractConsumer : HasProviderExtensions, IAsyncDisposable, IConsumerControl
{
protected readonly ILogger Logger;
private readonly SemaphoreSlim _semaphore;
private readonly IReadOnlyList<IAbstractConsumerInterceptor> _interceptors;
private CancellationTokenSource _cancellationTokenSource;
private bool _starting;
private bool _stopping;
public bool IsStarted { get; private set; }
public string Path { get; }
public IReadOnlyList<AbstractConsumerSettings> Settings { get; }
protected CancellationToken CancellationToken => _cancellationTokenSource.Token;
protected AbstractConsumer(ILogger logger,
IEnumerable<AbstractConsumerSettings> consumerSettings,
string path,
IEnumerable<IAbstractConsumerInterceptor> interceptors)
{
_semaphore = new(1, 1);
_interceptors = [.. interceptors.OrderBy(x => x.Order)];
Logger = logger;
Settings = [.. consumerSettings];
Path = path;
}
private async Task<bool> CallInterceptor(Func<IAbstractConsumerInterceptor, Task<bool>> func)
{
foreach (var interceptor in _interceptors)
{
try
{
if (!await func(interceptor).ConfigureAwait(false))
{
return false;
}
}
catch (Exception e)
{
LogInterceptorFailed(interceptor.GetType(), e.Message, e);
}
}
return true;
}
/// <summary>
/// Starts the underlying transport consumer (synchronized).
/// </summary>
/// <returns></returns>
public async Task DoStart()
{
await _semaphore.WaitAsync().ConfigureAwait(false);
try
{
await InternalOnStart().ConfigureAwait(false);
}
finally
{
_semaphore.Release();
}
}
private async Task InternalOnStart()
{
await OnStart().ConfigureAwait(false);
await CallInterceptor(async x => { await x.Started(this); return true; }).ConfigureAwait(false);
}
private async Task InternalOnStop()
{
await OnStop().ConfigureAwait(false);
await CallInterceptor(async x => { await x.Stopped(this); return true; }).ConfigureAwait(false);
}
/// <summary>
/// Stops the underlying transport consumer (synchronized).
/// </summary>
/// <returns></returns>
public async Task DoStop()
{
await _semaphore.WaitAsync().ConfigureAwait(false);
try
{
await InternalOnStop().ConfigureAwait(false);
}
finally
{
_semaphore.Release();
}
}
public async Task Start()
{
if (IsStarted || _starting)
{
return;
}
await _semaphore.WaitAsync();
_starting = true;
try
{
if (_cancellationTokenSource?.IsCancellationRequested != false)
{
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = new CancellationTokenSource();
}
if (await CallInterceptor(x => x.CanStart(this)).ConfigureAwait(false))
{
await InternalOnStart().ConfigureAwait(false);
}
IsStarted = true;
}
finally
{
_starting = false;
_semaphore.Release();
}
}
public async Task Stop()
{
if (!IsStarted || _stopping)
{
return;
}
await _semaphore.WaitAsync();
_stopping = true;
try
{
await _cancellationTokenSource.CancelAsync().ConfigureAwait(false);
if (await CallInterceptor(x => x.CanStop(this)).ConfigureAwait(false))
{
await InternalOnStop().ConfigureAwait(false);
}
IsStarted = false;
}
finally
{
_stopping = false;
_semaphore.Release();
}
}
/// <summary>
/// Initializes the transport specific consumer loop after the consumer has been started.
/// </summary>
/// <returns></returns>
internal protected abstract Task OnStart();
/// <summary>
/// Destroys the transport specific consumer loop before the consumer is stopped.
/// </summary>
/// <returns></returns>
internal protected abstract Task OnStop();
#region IAsyncDisposable
public async ValueTask DisposeAsync()
{
await DisposeAsyncCore().ConfigureAwait(false);
GC.SuppressFinalize(this);
}
protected async virtual ValueTask DisposeAsyncCore()
{
await Stop().ConfigureAwait(false);
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = null;
}
#endregion
#region Logging
[LoggerMessage(
EventId = 0,
Level = LogLevel.Error,
Message = "Interceptor {InterceptorType} failed with error: {Error}")]
private partial void LogInterceptorFailed(Type interceptorType, string error, Exception ex);
#endregion
}
#if NETSTANDARD2_0
public partial class AbstractConsumer
{
private partial void LogInterceptorFailed(Type interceptorType, string error, Exception ex)
=> Logger.LogError(ex, "Interceptor {InterceptorType} failed with error: {Error}", interceptorType, error);
}
#endif