|
| 1 | +package retransmission |
| 2 | + |
| 3 | +import "github.com/keep-network/keep-core/pkg/net" |
| 4 | + |
| 5 | +// Strategy represents a specific retransmission strategy. |
| 6 | +type Strategy interface { |
| 7 | + // Tick asks the strategy to run the provided retransmission routine. |
| 8 | + // The strategy uses their internal state and logic to decide whether to |
| 9 | + // call the retransmission function or not. |
| 10 | + Tick(retransmitFn RetransmitFn) error |
| 11 | +} |
| 12 | + |
| 13 | +// WithStrategy is a strategy factory function that returns the requested |
| 14 | +// strategy instance. |
| 15 | +func WithStrategy(strategy net.RetransmissionStrategy) Strategy { |
| 16 | + switch strategy { |
| 17 | + case net.StandardRetransmissionStrategy: |
| 18 | + return WithStandardStrategy() |
| 19 | + case net.BackoffRetransmissionStrategy: |
| 20 | + return WithBackoffStrategy() |
| 21 | + default: |
| 22 | + panic("retransmission strategy not implemented") |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +// StandardStrategy is the basic retransmission strategy that triggers the |
| 27 | +// retransmission routine on every tick. |
| 28 | +type StandardStrategy struct{} |
| 29 | + |
| 30 | +// WithStandardStrategy uses the StandardStrategy as the retransmission |
| 31 | +// strategy. |
| 32 | +func WithStandardStrategy() *StandardStrategy { |
| 33 | + return &StandardStrategy{} |
| 34 | +} |
| 35 | + |
| 36 | +// Tick implements the Strategy.Tick function. |
| 37 | +func (ss *StandardStrategy) Tick(retransmitFn RetransmitFn) error { |
| 38 | + return retransmitFn() |
| 39 | +} |
| 40 | + |
| 41 | +// BackoffStrategy is a retransmission strategy that triggers the retransmission |
| 42 | +// routine with an exponentially increasing delay. That is, the delay between |
| 43 | +// first and second retransmission is 1 tick, between second and third is 2 |
| 44 | +// ticks, between third and fourth is 4 ticks and so on. Graphically, the |
| 45 | +// schedule looks as follows: R _ R _ _ R _ _ _ _ R _ _ _ _ _ _ _ _ R |
| 46 | +type BackoffStrategy struct { |
| 47 | + tickCounter uint64 |
| 48 | + delay uint64 |
| 49 | + retransmitTick uint64 |
| 50 | +} |
| 51 | + |
| 52 | +// WithBackoffStrategy uses the BackoffStrategy as the retransmission |
| 53 | +// strategy. |
| 54 | +func WithBackoffStrategy() *BackoffStrategy { |
| 55 | + return &BackoffStrategy{ |
| 56 | + tickCounter: 0, |
| 57 | + delay: 1, |
| 58 | + retransmitTick: 1, |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +// Tick implements the Strategy.Tick function. |
| 63 | +func (bos *BackoffStrategy) Tick(retransmitFn RetransmitFn) error { |
| 64 | + bos.tickCounter++ |
| 65 | + |
| 66 | + if bos.tickCounter == bos.retransmitTick { |
| 67 | + bos.retransmitTick += bos.delay + 1 |
| 68 | + bos.delay *= 2 |
| 69 | + |
| 70 | + return retransmitFn() |
| 71 | + } |
| 72 | + |
| 73 | + return nil |
| 74 | +} |
0 commit comments