| | | 1 | | using Quartz; |
| | | 2 | | using System.Diagnostics; |
| | | 3 | | using Syki.Back.Domain.Enums; |
| | | 4 | | using System.Collections.Concurrent; |
| | | 5 | | using Syki.Back.Commands.Domain.Commands; |
| | | 6 | | |
| | | 7 | | namespace Syki.Back.Commands; |
| | | 8 | | |
| | 328 | 9 | | public class CommandsProcessor(IServiceScopeFactory serviceScopeFactory) : IJob |
| | | 10 | | { |
| | 2 | 11 | | private static readonly ActivitySource _activitySource = new (OpenTelemetryConfigs.CommandsProcessing); |
| | | 12 | | |
| | | 13 | | public async Task Execute(IJobExecutionContext context) |
| | | 14 | | { |
| | 328 | 15 | | using var scope = serviceScopeFactory.CreateScope(); |
| | 328 | 16 | | var ctx = scope.ServiceProvider.GetRequiredService<SykiDbContext>(); |
| | | 17 | | |
| | 328 | 18 | | await Process(scope, ctx); |
| | 328 | 19 | | } |
| | | 20 | | |
| | | 21 | | private static async Task Process(IServiceScope scope, SykiDbContext ctx) |
| | | 22 | | { |
| | 328 | 23 | | var processorId = Guid.NewGuid(); |
| | 328 | 24 | | var sw = Stopwatch.StartNew(); |
| | | 25 | | |
| | 0 | 26 | | while (true) |
| | | 27 | | { |
| | 632 | 28 | | var commands = await ctx.Commands.FromSqlRaw(Sql, processorId).AsNoTracking().ToListAsync(); |
| | 632 | 29 | | if (commands.Count == 0) break; |
| | | 30 | | |
| | 1216 | 31 | | foreach (var command in commands) |
| | | 32 | | { |
| | 304 | 33 | | using (var activity = _activitySource.StartActivity($"Process {command.Type}", ActivityKind.Consumer, co |
| | | 34 | | { |
| | 304 | 35 | | activity?.SetTag("command.id", command.Id); |
| | 304 | 36 | | activity?.SetTag("command.type", command.Type); |
| | 304 | 37 | | ctx.ActivityId = command.ActivityId!; |
| | 304 | 38 | | ctx.Operation = command.Type; |
| | 304 | 39 | | ctx.CommandLogs = []; |
| | | 40 | | |
| | | 41 | | try |
| | | 42 | | { |
| | 304 | 43 | | sw.Restart(); |
| | | 44 | | |
| | 304 | 45 | | ctx.ChangeTracker.Clear(); |
| | 304 | 46 | | ctx.Attach(command); |
| | | 47 | | |
| | 304 | 48 | | await ctx.Database.BeginTransactionAsync(); |
| | 304 | 49 | | ctx.Database.AutoSavepointsEnabled = false; |
| | | 50 | | |
| | 304 | 51 | | var invoker = GetInvoker(command); |
| | 304 | 52 | | await invoker.Invoke(scope.ServiceProvider, command.Id, command.Data); |
| | 304 | 53 | | } |
| | 0 | 54 | | catch (Exception ex) |
| | | 55 | | { |
| | 0 | 56 | | if (ctx.Database.CurrentTransaction is not null) |
| | 0 | 57 | | await ctx.Database.RollbackTransactionAsync(); |
| | | 58 | | |
| | 0 | 59 | | ctx.ChangeTracker.Clear(); |
| | 0 | 60 | | ctx.Attach(command); |
| | 0 | 61 | | command.Error = ex.Message + ex.InnerException?.Message; |
| | 0 | 62 | | activity?.SetStatus(ActivityStatusCode.Error, ex.Message); |
| | 0 | 63 | | activity?.AddException(ex); |
| | 0 | 64 | | await ctx.Database.BeginTransactionAsync(); |
| | 0 | 65 | | } |
| | | 66 | | |
| | 304 | 67 | | sw.Stop(); |
| | 304 | 68 | | command.Logs = ctx.CommandLogs; |
| | 304 | 69 | | command.Processed(sw.Elapsed.TotalMilliseconds); |
| | 304 | 70 | | activity?.SetTag("command.duration", command.Duration); |
| | | 71 | | |
| | 304 | 72 | | if (command.Error.HasValue() && command.MaxRetries > 0) |
| | | 73 | | { |
| | 0 | 74 | | var retryCommand = CreateRetryCommand(command, ctx.ActivityId); |
| | 0 | 75 | | ctx.Commands.Add(retryCommand); |
| | | 76 | | } |
| | | 77 | | |
| | 304 | 78 | | await ctx.SaveChangesAsync(); |
| | 304 | 79 | | await ctx.Database.CommitTransactionAsync(); |
| | 304 | 80 | | } |
| | 304 | 81 | | } |
| | | 82 | | |
| | 304 | 83 | | if (ctx.HasPendingCommands) |
| | | 84 | | { |
| | 0 | 85 | | var scheduler = await scope.ServiceProvider.GetRequiredService<ISchedulerFactory>().GetScheduler(); |
| | 0 | 86 | | await scheduler.TriggerCommandsProcessorJob(); |
| | | 87 | | } |
| | | 88 | | } |
| | 328 | 89 | | } |
| | | 90 | | |
| | | 91 | | private static Command CreateRetryCommand(Command failedCommand, string activityId) |
| | | 92 | | { |
| | 0 | 93 | | var invoker = GetInvoker(failedCommand); |
| | 0 | 94 | | var data = invoker.Deserialize(failedCommand.Data); |
| | | 95 | | |
| | 0 | 96 | | var originalId = failedCommand.OriginalId ?? failedCommand.Id; |
| | | 97 | | |
| | 0 | 98 | | var retryAttempt = failedCommand.RetryAttempt + 1; |
| | 0 | 99 | | var delaySeconds = CommandBackoffStrategies.GetDelaySeconds( |
| | 0 | 100 | | failedCommand.BackoffStrategy, failedCommand.BaseDelaySeconds, retryAttempt); |
| | | 101 | | |
| | 0 | 102 | | var retryCommand = new Command( |
| | 0 | 103 | | failedCommand.InstitutionId, |
| | 0 | 104 | | data, |
| | 0 | 105 | | originalId: originalId, |
| | 0 | 106 | | activityId: activityId, |
| | 0 | 107 | | maxRetries: failedCommand.MaxRetries - 1, |
| | 0 | 108 | | delaySeconds: delaySeconds, |
| | 0 | 109 | | backoffStrategy: failedCommand.BackoffStrategy, |
| | 0 | 110 | | baseDelaySeconds: failedCommand.BaseDelaySeconds) |
| | 0 | 111 | | { |
| | 0 | 112 | | Type = failedCommand.Type, |
| | 0 | 113 | | RetryAttempt = retryAttempt, |
| | 0 | 114 | | }; |
| | | 115 | | |
| | 0 | 116 | | return retryCommand; |
| | | 117 | | } |
| | | 118 | | |
| | 2 | 119 | | private static readonly ConcurrentDictionary<string, ICommandInvoker> _invokers = new(); |
| | | 120 | | private static ICommandInvoker GetInvoker(Command command) |
| | | 121 | | { |
| | 304 | 122 | | return _invokers.GetOrAdd(command.Type, typeName => |
| | 304 | 123 | | { |
| | 4 | 124 | | var commandType = CommandConfigs.GetCommandType(typeName); |
| | 4 | 125 | | var invokerType = typeof(CommandInvoker<>).MakeGenericType(commandType); |
| | 4 | 126 | | return (ICommandInvoker)Activator.CreateInstance(invokerType)!; |
| | 304 | 127 | | }); |
| | | 128 | | } |
| | | 129 | | |
| | | 130 | | /// <summary> |
| | | 131 | | /// See <see cref="CommandStatus"/> for status mapping |
| | | 132 | | /// </summary> |
| | 2 | 133 | | private static readonly string Sql = @" |
| | 2 | 134 | | UPDATE syki.commands |
| | 2 | 135 | | SET processor_id = {0}, status = 2 |
| | 2 | 136 | | WHERE ctid IN ( |
| | 2 | 137 | | SELECT ctid |
| | 2 | 138 | | FROM syki.commands |
| | 2 | 139 | | WHERE processor_id IS NULL AND status = 0 AND (not_before IS NULL OR not_before < NOW()) |
| | 2 | 140 | | ORDER BY created_at |
| | 2 | 141 | | FOR UPDATE SKIP LOCKED |
| | 2 | 142 | | LIMIT 10 |
| | 2 | 143 | | ) |
| | 2 | 144 | | RETURNING *; |
| | 2 | 145 | | "; |
| | | 146 | | } |