about summary refs log tree commit diff
path: root/pkg/discord/heartbeat.go
blob: 5c4a95567f579dea5e16d60cedf9f7a134940087 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package discord

import (
	"context"
	"math/rand"
	"time"

	"github.com/rs/zerolog"
)

type Heartbeat interface {
	Start(ctx context.Context, interval uint64)

	ForceHeartbeat()
	Ack()
}

var _ Heartbeat = &HeartbeatImpl{}

type HeartbeatImpl struct {
	ctx     context.Context
	logger  *zerolog.Logger
	gateway Gateway
}

func NewHeartbeat(logger *zerolog.Logger, gateway Gateway) *HeartbeatImpl {
	return &HeartbeatImpl{
		ctx:     nil,
		logger:  logger,
		gateway: gateway,
	}
}

func (h *HeartbeatImpl) Start(ctx context.Context, interval uint64) {
	h.ctx = ctx
	go h.heartbeatRoutine(interval)
}

func (h *HeartbeatImpl) ForceHeartbeat() {
	h.gateway.Heartbeat()
}

func (h *HeartbeatImpl) Ack() {
	// What do we do here?
	h.logger.Debug().Msg("received heartbeat ack")
}

func (h *HeartbeatImpl) heartbeatRoutine(interval uint64) {
	h.logger.Debug().Msgf("beating heart every %dms", interval)

	// REF: heartbeat_interval * jitter
	jitter := rand.Intn(int(interval))
	time.Sleep(time.Duration(jitter) * time.Millisecond)

	ticker := time.NewTicker(time.Duration(interval) * time.Millisecond)
	defer ticker.Stop()

	for {
		h.logger.Debug().Msg("sending heartbeat")
		if err := h.gateway.Heartbeat(); err != nil {
			h.logger.Error().Err(err).Msg("failed to send heartbeat")
		}

		select {
		case <-h.ctx.Done():
			return
		case <-ticker.C:
			continue
		}
	}
}