2020-07-24 13:54:03 +00:00
|
|
|
package timers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/nspcc-dev/neofs-node/pkg/morph/event"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
localTimer struct {
|
|
|
|
duration time.Duration
|
|
|
|
timer *time.Timer
|
|
|
|
handler event.Handler
|
|
|
|
}
|
|
|
|
|
|
|
|
// Timers is a component for local inner ring timers to produce local events.
|
|
|
|
Timers struct {
|
|
|
|
log *zap.Logger
|
|
|
|
|
2020-10-12 09:49:38 +00:00
|
|
|
alphabet localTimer
|
2020-07-24 13:54:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Params for timers instance constructor.
|
|
|
|
Params struct {
|
2020-10-12 09:49:38 +00:00
|
|
|
Log *zap.Logger
|
|
|
|
EpochDuration time.Duration
|
|
|
|
AlphabetDuration time.Duration
|
2020-07-24 13:54:03 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2020-10-12 09:49:38 +00:00
|
|
|
// AlphabetTimer is a type for HandlerInfo structure.
|
|
|
|
AlphabetTimer = "AlphabetTimer"
|
2020-07-24 13:54:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// New creates instance of timers component.
|
|
|
|
func New(p *Params) *Timers {
|
|
|
|
return &Timers{
|
2020-10-12 09:49:38 +00:00
|
|
|
log: p.Log,
|
|
|
|
alphabet: localTimer{duration: p.AlphabetDuration},
|
2020-07-24 13:54:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start runs all available local timers.
|
|
|
|
func (t *Timers) Start(ctx context.Context) {
|
2020-10-12 09:49:38 +00:00
|
|
|
t.alphabet.timer = time.NewTimer(t.alphabet.duration)
|
2020-07-24 13:54:03 +00:00
|
|
|
go t.serve(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Timers) serve(ctx context.Context) {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
t.log.Info("timers are getting stopped")
|
2020-10-12 09:49:38 +00:00
|
|
|
t.alphabet.timer.Stop()
|
2020-07-24 13:54:03 +00:00
|
|
|
|
|
|
|
return
|
2020-10-12 09:49:38 +00:00
|
|
|
case <-t.alphabet.timer.C:
|
|
|
|
// reset timer so it can tick once again
|
|
|
|
t.alphabet.timer.Reset(t.alphabet.duration)
|
|
|
|
// call handler, it should be always set
|
|
|
|
t.alphabet.handler(NewAlphabetEmitTick{})
|
2020-07-24 13:54:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RegisterHandler of local timers events.
|
|
|
|
func (t *Timers) RegisterHandler(h event.HandlerInfo) error {
|
|
|
|
if h.Handler() == nil {
|
|
|
|
return errors.New("ir/timers: can't register nil handler")
|
|
|
|
}
|
|
|
|
|
|
|
|
switch h.GetType() {
|
2020-10-12 09:49:38 +00:00
|
|
|
case AlphabetTimer:
|
|
|
|
t.alphabet.handler = h.Handler()
|
2020-07-24 13:54:03 +00:00
|
|
|
default:
|
|
|
|
return errors.New("ir/timers: unknown handler type")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|