|
| 1 | +using System.Text.Json; |
| 2 | +using Hugo; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | +using Odin.Contracts; |
| 5 | +using Odin.Core; |
| 6 | +using Odin.Persistence.Interfaces; |
| 7 | +using Odin.Sdk; |
| 8 | +using static Hugo.Go; |
| 9 | + |
| 10 | +namespace Odin.ExecutionEngine.Matching; |
| 11 | + |
| 12 | +internal sealed record TaskDispatchItem( |
| 13 | + TaskLease Lease, |
| 14 | + WorkflowTask WorkflowTask, |
| 15 | + Func<CancellationToken, Task<Result<Unit>>> CompleteAsync, |
| 16 | + Func<string, bool, CancellationToken, Task<Result<Unit>>> FailAsync, |
| 17 | + Func<CancellationToken, Task<Result<TaskLease>>> HeartbeatAsync) |
| 18 | +{ |
| 19 | + public static Result<TaskDispatchItem> Create( |
| 20 | + TaskLease lease, |
| 21 | + ITaskQueueRepository repository, |
| 22 | + JsonSerializerOptions serializerOptions, |
| 23 | + ILogger logger) |
| 24 | + { |
| 25 | + WorkflowTask workflowTask; |
| 26 | + try |
| 27 | + { |
| 28 | + workflowTask = DeserializeWorkflowTask(lease.Task, serializerOptions); |
| 29 | + } |
| 30 | + catch (Exception ex) |
| 31 | + { |
| 32 | + logger.LogError(ex, "Failed to deserialize workflow task payload for lease {LeaseId}", lease.LeaseId); |
| 33 | + return Result.Fail<TaskDispatchItem>(Error.FromException(ex)); |
| 34 | + } |
| 35 | + |
| 36 | + async Task<Result<Unit>> CompleteAsync(CancellationToken cancellationToken) |
| 37 | + => await repository.CompleteAsync(lease.LeaseId, cancellationToken).ConfigureAwait(false); |
| 38 | + |
| 39 | + async Task<Result<Unit>> FailAsync(string reason, bool requeue, CancellationToken cancellationToken) |
| 40 | + => await repository.FailAsync(lease.LeaseId, reason, requeue, cancellationToken).ConfigureAwait(false); |
| 41 | + |
| 42 | + async Task<Result<TaskLease>> HeartbeatAsync(CancellationToken cancellationToken) |
| 43 | + => await repository.HeartbeatAsync(lease.LeaseId, cancellationToken).ConfigureAwait(false); |
| 44 | + |
| 45 | + return Result.Ok(new TaskDispatchItem(lease, workflowTask, CompleteAsync, FailAsync, HeartbeatAsync)); |
| 46 | + } |
| 47 | + |
| 48 | + private static WorkflowTask DeserializeWorkflowTask(TaskQueueItem item, JsonSerializerOptions serializerOptions) |
| 49 | + { |
| 50 | + var json = item.TaskData.RootElement.GetRawText(); |
| 51 | + var workflowTask = JsonSerializer.Deserialize<WorkflowTask>(json, serializerOptions); |
| 52 | + if (workflowTask is null) |
| 53 | + { |
| 54 | + throw new InvalidOperationException("Workflow task payload could not be deserialized."); |
| 55 | + } |
| 56 | + |
| 57 | + return workflowTask; |
| 58 | + } |
| 59 | +} |
0 commit comments