This repository has been archived by the owner on Oct 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstrategy.go
55 lines (44 loc) · 1.55 KB
/
strategy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package composite
import (
"context"
"github.com/bitcoin-sv/go-broadcast-client/broadcast"
)
type StrategyName string
const (
// OneByOneStrategy is a strategy that executes the execution funcs one by one until one of them succeeds.
// If all execution funcs fail, then the strategy returns an error.
// The error is: ErrAllBroadcastersFailed.
OneByOneStrategy StrategyName = "OneByOneStrategy"
)
type Result interface{}
type executionFunc func(context.Context) (Result, error)
type StrategyExecutionFunc func(context.Context, []executionFunc) (Result, error)
// Strategy is a component designed to offer flexibility in selecting a communication approach
// for interacting with multiple broadcasting services, such as multiple Arc services.
type Strategy struct {
name StrategyName
executionFunc StrategyExecutionFunc
}
func New(name StrategyName) (*Strategy, error) {
switch name {
case OneByOneStrategy:
return &Strategy{name: name, executionFunc: OneByOne.executionFunc}, nil
default:
return nil, broadcast.ErrStrategyUnknown
}
}
func (s *Strategy) Execute(ctx context.Context, executionFuncs []executionFunc) (Result, error) {
return s.executionFunc(ctx, executionFuncs)
}
var (
OneByOne = &Strategy{name: OneByOneStrategy, executionFunc: func(ctx context.Context, executionFuncs []executionFunc) (Result, error) {
for _, executionFunc := range executionFuncs {
result, err := executionFunc(ctx)
if err != nil {
continue
}
return result, nil
}
return nil, broadcast.Failure("", broadcast.ErrAllBroadcastersFailed)
}}
)