| | | 1 | | using ArturRios.Heimdall.Command.Services; |
| | | 2 | | |
| | | 3 | | namespace ArturRios.Heimdall.WebApi.Email; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Works through <see cref="PasswordRecoveryQueue" />: for each request, a fresh DI scope and one |
| | | 7 | | /// <see cref="PasswordRecoveryProcessor" /> run — UC-12's lookup, token and email, after the caller |
| | | 8 | | /// has already been answered. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks> |
| | | 11 | | /// <para> |
| | | 12 | | /// A scope per request, not one for the service's lifetime: the database context and the |
| | | 13 | | /// Mailgun client are scoped, and each request's work should neither see the last one's |
| | | 14 | | /// tracked entities nor depend on an HTTP request's scope that ended when it was answered. |
| | | 15 | | /// That is the difference from firing the send off from the handler, which would have used a |
| | | 16 | | /// client the request scope disposes underneath it. |
| | | 17 | | /// </para> |
| | | 18 | | /// <para> |
| | | 19 | | /// One request at a time. Volume is bounded by the per-address rate limit, and a failure — |
| | | 20 | | /// a database blip, Mailgun refusing — is logged and the next request is taken, as the |
| | | 21 | | /// scheduled passes do: one person's email must not stop the next person's. |
| | | 22 | | /// </para> |
| | | 23 | | /// </remarks> |
| | 901 | 24 | | public sealed class PasswordRecoveryDispatcher( |
| | 901 | 25 | | PasswordRecoveryQueue queue, |
| | 901 | 26 | | IServiceScopeFactory scopeFactory, |
| | 901 | 27 | | ILogger<PasswordRecoveryDispatcher> logger) : BackgroundService |
| | | 28 | | { |
| | | 29 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | 30 | | { |
| | | 31 | | try |
| | | 32 | | { |
| | 1864 | 33 | | await foreach (var request in queue.Reader.ReadAllAsync(stoppingToken)) |
| | | 34 | | { |
| | 31 | 35 | | await ProcessAsync(request); |
| | | 36 | | } |
| | 0 | 37 | | } |
| | 901 | 38 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 39 | | { |
| | | 40 | | // Shutdown. Whatever is still queued is dropped; see PasswordRecoveryQueue for why that |
| | | 41 | | // is acceptable. |
| | 901 | 42 | | } |
| | 901 | 43 | | } |
| | | 44 | | |
| | | 45 | | private async Task ProcessAsync(PasswordRecoveryRequest request) |
| | | 46 | | { |
| | | 47 | | try |
| | | 48 | | { |
| | 31 | 49 | | await using var scope = scopeFactory.CreateAsyncScope(); |
| | | 50 | | |
| | 31 | 51 | | await scope.ServiceProvider.GetRequiredService<PasswordRecoveryProcessor>().ProcessAsync(request); |
| | 30 | 52 | | } |
| | 1 | 53 | | catch (Exception exception) |
| | | 54 | | { |
| | 1 | 55 | | logger.LogError(exception, "A password recovery request could not be processed"); |
| | 1 | 56 | | } |
| | 31 | 57 | | } |
| | | 58 | | } |