|
| 1 | +package redis |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/cschleiden/go-workflows/web" |
| 9 | + "github.com/go-redis/redis/v8" |
| 10 | +) |
| 11 | + |
| 12 | +var _ web.WebBackend = (*redisBackend)(nil) |
| 13 | + |
| 14 | +func (rb *redisBackend) GetWorkflowInstances(ctx context.Context, afterInstanceID string, count int) ([]*web.WorkflowInstanceRef, error) { |
| 15 | + max := "+inf" |
| 16 | + |
| 17 | + if afterInstanceID != "" { |
| 18 | + scores, err := rb.rdb.ZMScore(ctx, instancesByCreation(), afterInstanceID).Result() |
| 19 | + if err != nil { |
| 20 | + return nil, fmt.Errorf("getting instance score for %v: %w", afterInstanceID, err) |
| 21 | + } |
| 22 | + |
| 23 | + if len(scores) == 0 { |
| 24 | + rb.Logger().Error("could not find instance %v", "afterInstanceID", afterInstanceID) |
| 25 | + return nil, nil |
| 26 | + } |
| 27 | + |
| 28 | + max = fmt.Sprintf("(%v", int64(scores[0])) |
| 29 | + } |
| 30 | + |
| 31 | + result, err := rb.rdb.ZRangeArgs(ctx, redis.ZRangeArgs{ |
| 32 | + Key: instancesByCreation(), |
| 33 | + Stop: max, |
| 34 | + Start: "-inf", |
| 35 | + ByScore: true, |
| 36 | + Rev: true, |
| 37 | + Count: int64(count), |
| 38 | + }).Result() |
| 39 | + if err != nil { |
| 40 | + return nil, fmt.Errorf("getting instances after %v: %w", max, err) |
| 41 | + } |
| 42 | + |
| 43 | + instanceIDs := make([]string, 0) |
| 44 | + for _, r := range result { |
| 45 | + instanceID := r |
| 46 | + instanceIDs = append(instanceIDs, instanceKey(instanceID)) |
| 47 | + } |
| 48 | + |
| 49 | + instances, err := rb.rdb.MGet(ctx, instanceIDs...).Result() |
| 50 | + if err != nil { |
| 51 | + return nil, fmt.Errorf("getting instances: %w", err) |
| 52 | + } |
| 53 | + |
| 54 | + var instanceRefs []*web.WorkflowInstanceRef |
| 55 | + for _, instance := range instances { |
| 56 | + var state instanceState |
| 57 | + if err := json.Unmarshal([]byte(instance.(string)), &state); err != nil { |
| 58 | + return nil, fmt.Errorf("unmarshaling instance state: %w", err) |
| 59 | + } |
| 60 | + |
| 61 | + instanceRefs = append(instanceRefs, &web.WorkflowInstanceRef{ |
| 62 | + Instance: state.Instance, |
| 63 | + CreatedAt: state.CreatedAt, |
| 64 | + CompletedAt: state.CompletedAt, |
| 65 | + State: state.State, |
| 66 | + }) |
| 67 | + } |
| 68 | + |
| 69 | + return instanceRefs, nil |
| 70 | +} |
| 71 | + |
| 72 | +func (rb *redisBackend) GetWorkflowInstance(ctx context.Context, instanceID string) (*web.WorkflowInstanceRef, error) { |
| 73 | + instance, err := readInstance(ctx, rb.rdb, instanceID) |
| 74 | + if err != nil { |
| 75 | + return nil, err |
| 76 | + } |
| 77 | + |
| 78 | + return &web.WorkflowInstanceRef{ |
| 79 | + Instance: instance.Instance, |
| 80 | + CreatedAt: instance.CreatedAt, |
| 81 | + CompletedAt: instance.CompletedAt, |
| 82 | + State: instance.State, |
| 83 | + }, nil |
| 84 | +} |
0 commit comments