-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkspaceHostedService.cs
More file actions
258 lines (240 loc) · 10.5 KB
/
Copy pathWorkspaceHostedService.cs
File metadata and controls
258 lines (240 loc) · 10.5 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
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
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RustPlusBot.Abstractions.Events;
using RustPlusBot.Features.Workspace.Reconciler;
using RustPlusBot.Features.Workspace.Registry;
using RustPlusBot.Persistence.Workspace;
namespace RustPlusBot.Features.Workspace.Hosting;
/// <summary>Runs startup reconcile, self-heals on channel deletion, and reacts to server registration.</summary>
/// <param name="client">The socket client (for Ready and ChannelDestroyed).</param>
/// <param name="eventBus">The in-process event bus.</param>
/// <param name="scopeFactory">Creates scopes for the scoped reconciler/store.</param>
/// <param name="logger">The logger.</param>
internal sealed class WorkspaceHostedService(
DiscordSocketClient client,
IEventBus eventBus,
IServiceScopeFactory scopeFactory,
ILogger<WorkspaceHostedService> logger) : IHostedService, IDisposable
{
private readonly CancellationTokenSource _cts = new();
private Task? _connectionStatusLoop;
private Task? _infoMapReadyLoop;
private Task? _serverCredentialsLoop;
private Task? _serverRegisteredLoop;
private bool _startupDone;
/// <inheritdoc />
public void Dispose() => _cts.Dispose();
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
// Force the workspace registry's construction now, synchronously, before any heal work is
// queued. Its constructor throws when a channel spec names a capability with no registered
// provider. Every other place below resolves it lazily inside a broad catch, so a misconfigured
// host would otherwise start cleanly and only fault quietly on the first reconcile. Resolving it
// here, outside any try or catch, lets that exception propagate out of this method so the host
// genuinely fails to start instead.
using (var scope = scopeFactory.CreateScope())
{
scope.ServiceProvider.GetRequiredService<IWorkspaceRegistry>();
}
client.Ready += OnReadyAsync;
client.ChannelDestroyed += OnChannelDestroyedAsync;
_serverRegisteredLoop = Task.Run(() => ConsumeServerRegisteredAsync(_cts.Token), CancellationToken.None);
_connectionStatusLoop = Task.Run(() => ConsumeConnectionStatusAsync(_cts.Token), CancellationToken.None);
_serverCredentialsLoop = Task.Run(() => ConsumeServerCredentialsAsync(_cts.Token), CancellationToken.None);
_infoMapReadyLoop = Task.Run(() => ConsumeInfoMapReadyAsync(_cts.Token), CancellationToken.None);
return Task.CompletedTask;
}
/// <inheritdoc />
public async Task StopAsync(CancellationToken cancellationToken)
{
client.Ready -= OnReadyAsync;
client.ChannelDestroyed -= OnChannelDestroyedAsync;
await _cts.CancelAsync().ConfigureAwait(false);
foreach (var loop in new[]
{
_serverRegisteredLoop, _connectionStatusLoop, _serverCredentialsLoop, _infoMapReadyLoop
})
{
if (loop is null)
{
continue;
}
try
{
#pragma warning disable VSTHRD003 // Avoid awaiting foreign Tasks — these are our own loop tasks, joined on stop.
await loop.ConfigureAwait(false);
#pragma warning restore VSTHRD003
}
catch (OperationCanceledException)
{
// Expected on shutdown.
}
}
}
private Task OnReadyAsync()
{
// Ready fires on every gateway (re)connect; only heal once per process. Ready is dispatched
// serially on the gateway thread, so no synchronization is needed — set the flag before
// offloading so a re-fired Ready can't double-run.
if (_startupDone)
{
return Task.CompletedTask;
}
_startupDone = true;
// Healing sweeps every provisioned guild's channels over REST; doing it inline blocks the
// gateway task and stalls event dispatch, so offload it. Failures must be caught here —
// nothing awaits this.
_ = Task.Run(HealProvisionedGuildsAsync, _cts.Token);
return Task.CompletedTask;
}
private async Task HealProvisionedGuildsAsync()
{
try
{
var scope = scopeFactory.CreateAsyncScope();
await using (scope.ConfigureAwait(false))
{
var store = scope.ServiceProvider.GetRequiredService<IWorkspaceStore>();
var reconciler = scope.ServiceProvider.GetRequiredService<IWorkspaceReconciler>();
foreach (var guildId in await store.GetProvisionedGuildIdsAsync(_cts.Token).ConfigureAwait(false))
{
await reconciler.HealGuildAsync(guildId, _cts.Token).ConfigureAwait(false);
}
}
}
catch (OperationCanceledException)
{
// Shutting down.
}
catch (Exception ex) // Broad catch is intentional: a faulting startup heal must not crash the host.
{
logger.LogError(ex, "Startup self-heal failed.");
}
}
private async Task OnChannelDestroyedAsync(SocketChannel channel)
{
if (channel is not SocketGuildChannel guildChannel)
{
return;
}
try
{
var scope = scopeFactory.CreateAsyncScope();
await using (scope.ConfigureAwait(false))
{
var reconciler = scope.ServiceProvider.GetRequiredService<IWorkspaceReconciler>();
await reconciler.HealGuildAsync(guildChannel.Guild.Id, _cts.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
// Shutting down.
}
catch (Exception ex) // Broad catch is intentional: a faulting self-heal must not crash the host.
{
logger.LogError(ex, "Self-heal failed for guild {GuildId}.", guildChannel.Guild.Id);
}
}
/// <summary>
/// Reconciles one server in its own scope. Every consumer below runs this through
/// <see cref="EventBusConsumption.ConsumeAsync{TEvent}"/>, which absorbs its failures: the reconcile
/// talks to Discord over REST, where a timeout or a 5xx is routine, and one of those must never end
/// the subscription that drives the channels.
/// </summary>
/// <param name="guildId">The owning guild snowflake.</param>
/// <param name="serverId">The server to reconcile.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A task that completes when the reconcile has run.</returns>
private async Task ReconcileServerAsync(ulong guildId, Guid serverId, CancellationToken cancellationToken)
{
var scope = scopeFactory.CreateAsyncScope();
await using (scope.ConfigureAwait(false))
{
var reconciler = scope.ServiceProvider.GetRequiredService<IWorkspaceReconciler>();
await reconciler.ReconcileServerAsync(guildId, serverId, cancellationToken).ConfigureAwait(false);
}
}
private async Task ConsumeConnectionStatusAsync(CancellationToken cancellationToken)
{
try
{
await eventBus.ConsumeAsync<ConnectionStatusChangedEvent>(
(evt, ct) => ReconcileServerAsync(evt.GuildId, evt.ServerId, ct),
ex => logger.LogError(ex, "Handling {EventType} failed; skipping that reconcile.",
nameof(ConnectionStatusChangedEvent)),
cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Shutting down.
}
catch (Exception ex) // Broad catch is intentional: a faulting consumer must not crash the host.
{
logger.LogError(ex, "ConnectionStatusChanged consumer faulted.");
}
}
private async Task ConsumeServerCredentialsAsync(CancellationToken cancellationToken)
{
try
{
await eventBus.ConsumeAsync<ServerCredentialsChangedEvent>(
(evt, ct) => ReconcileServerAsync(evt.GuildId, evt.ServerId, ct),
ex => logger.LogError(ex, "Handling {EventType} failed; skipping that reconcile.",
nameof(ServerCredentialsChangedEvent)),
cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Shutting down.
}
catch (Exception ex) // Broad catch is intentional: a faulting consumer must not crash the host.
{
logger.LogError(ex, "ServerCredentialsChanged consumer faulted.");
}
}
private async Task ConsumeInfoMapReadyAsync(CancellationToken cancellationToken)
{
try
{
await eventBus.ConsumeAsync<InfoMapReadyEvent>(
(evt, ct) => ReconcileServerAsync(evt.GuildId, evt.ServerId, ct),
ex => logger.LogError(ex, "Handling {EventType} failed; skipping that reconcile.",
nameof(InfoMapReadyEvent)),
cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Shutting down.
}
catch (Exception ex) // Broad catch is intentional: a faulting consumer must not crash the host.
{
logger.LogError(ex, "InfoMapReady consumer faulted.");
}
}
private async Task ConsumeServerRegisteredAsync(CancellationToken cancellationToken)
{
// Subscription is registered when this loop first calls SubscribeAsync; the in-process bus does
// not replay, so events published before this point are not delivered. Fine here (the only 1a
// producer is the runtime-only simulate-server command); a real producer (1b FCM pairing) runs
// long after startup.
try
{
await eventBus.ConsumeAsync<ServerRegisteredEvent>(
(evt, ct) => ReconcileServerAsync(evt.GuildId, evt.ServerId, ct),
ex => logger.LogError(ex, "Handling {EventType} failed; skipping that reconcile.",
nameof(ServerRegisteredEvent)),
cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Shutting down.
}
catch (Exception ex) // Broad catch is intentional: a faulting consumer must not crash the host.
{
logger.LogError(ex, "ServerRegistered consumer faulted.");
}
}
}