private async Task OnError(ErrorArgs args, Delivery delivery) { _logger.LogWarning(args.Exception, args.Message); if (args.Job is not null) { var job = args.Job; JobError jobError; if (args.Exception is null) { jobError = JobError.FromMessage(args.Message); } else { jobError = JobError.FromException(args.Exception); } job.Error(jobError); await _jobRepository.UpdateAsync(job, CancellationToken.None); } }
private async Task OnNewJob(Job job, Delivery delivery) { bool updateStatus = true; var cancel = new CancellationTokenSource( _workerConfiguration.MaximumAllowedExecutionTime) .Token; try { if (job.Input is null) { throw new ArgumentNullException(nameof(job.Input)); } using var scope = _scopeFactory.CreateScope(job); var worker = scope.GetWorker <TWorker>(); var input = _inputSerializer.Deserialize(job.Input); job.Start(worker.EstimateExecutionTime(input)); await _jobRepository.UpdateAsync(job, cancel); var result = await worker.ExecuteAsync(input, cancel); if (result.IsCancelled) { job.Cancel(); delivery.Acknowledge = true; return; } if (result.IsFinished) { if (result.Output is null) { throw new InvalidOperationException("Job finished without output"); } string output = _outputSerializer.Serialize(result.Output); job.Finish(output); delivery.Acknowledge = true; return; } if (result.IsError) { if (delivery.SupportsRepeat) { updateStatus = false; } else { delivery.Acknowledge = true; if (result.Error is not null) { job.Error(result.Error); } else { var genericError = JobError.FromMessage("Job execution failed"); job.Error(genericError); } } } } catch (OperationCanceledException e) { if (delivery.SupportsRepeat) { updateStatus = false; } else { delivery.Acknowledge = true; job.Error(e); } } catch (Exception e) { delivery.Acknowledge = true; job.Error(e); } finally { if (updateStatus) { await _jobRepository.UpdateAsync(job, CancellationToken.None); } } }