| | | 1 | | using Quartz; |
| | | 2 | | using System.Diagnostics; |
| | | 3 | | using Estud.Back.Features.Webhooks.CallWebhooks; |
| | | 4 | | |
| | | 5 | | namespace Estud.Back.Webhooks; |
| | | 6 | | |
| | 18 | 7 | | public class PendingWebhookCallsProcessor(IServiceScopeFactory serviceScopeFactory) : IJob |
| | | 8 | | { |
| | 2 | 9 | | private static readonly ActivitySource _activitySource = new(OpenTelemetryConfigs.WebhookCallsProcessing); |
| | | 10 | | |
| | | 11 | | public async Task Execute(IJobExecutionContext context) |
| | | 12 | | { |
| | 18 | 13 | | using var scope = serviceScopeFactory.CreateScope(); |
| | 18 | 14 | | var ctx = scope.ServiceProvider.GetRequiredService<EstudDbContext>(); |
| | | 15 | | |
| | 18 | 16 | | await Process(scope, ctx); |
| | 18 | 17 | | } |
| | | 18 | | |
| | | 19 | | private static async Task Process(IServiceScope scope, EstudDbContext ctx) |
| | | 20 | | { |
| | 12 | 21 | | while (true) |
| | | 22 | | { |
| | 30 | 23 | | using var activity = _activitySource.StartActivity("Enqueue CallWebhookCommands", ActivityKind.Producer); |
| | | 24 | | |
| | 30 | 25 | | await ctx.Database.BeginTransactionAsync(); |
| | | 26 | | |
| | 30 | 27 | | var calls = await ctx.WebhookCalls.FromSqlRaw(Sql).AsNoTracking().ToListAsync(); |
| | 30 | 28 | | if (calls.Count == 0) |
| | | 29 | | { |
| | 18 | 30 | | await ctx.Database.RollbackTransactionAsync(); |
| | 18 | 31 | | break; |
| | | 32 | | } |
| | | 33 | | |
| | 12 | 34 | | activity?.SetTag("webhook_calls.count", calls.Count); |
| | | 35 | | |
| | 60 | 36 | | foreach (var call in calls) |
| | | 37 | | { |
| | 18 | 38 | | ctx.AddCommand(call.InstitutionId, new CallWebhookCommand(call.Id)); |
| | | 39 | | } |
| | | 40 | | |
| | 12 | 41 | | await ctx.SaveChangesAsync(); |
| | 12 | 42 | | await ctx.Database.CommitTransactionAsync(); |
| | | 43 | | |
| | 12 | 44 | | var scheduler = await scope.ServiceProvider.GetRequiredService<ISchedulerFactory>().GetScheduler(); |
| | 12 | 45 | | await scheduler.TriggerCommandsProcessorJob(); |
| | 12 | 46 | | } |
| | 18 | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <summary> |
| | | 50 | | /// See <see cref="WebhookCallStatus"/> for status mapping |
| | | 51 | | /// </summary> |
| | 2 | 52 | | private static readonly string Sql = @" |
| | 2 | 53 | | UPDATE estud.webhook_calls |
| | 2 | 54 | | SET status = 1 |
| | 2 | 55 | | WHERE ctid IN ( |
| | 2 | 56 | | SELECT ctid |
| | 2 | 57 | | FROM estud.webhook_calls |
| | 2 | 58 | | WHERE status = 0 |
| | 2 | 59 | | ORDER BY created_at |
| | 2 | 60 | | FOR UPDATE SKIP LOCKED |
| | 2 | 61 | | LIMIT 100 |
| | 2 | 62 | | ) |
| | 2 | 63 | | RETURNING *; |
| | 2 | 64 | | "; |
| | | 65 | | } |