about summary refs log tree commit diff
path: root/pkg/discord/gateway/heartbeat.go
blob: 1df753a50ae853389a5129d9a04e78385d52c87e (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
72
73
74
75
76
77
package gateway

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

	"github.com/rs/zerolog"
)

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

	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 time.Duration) {
	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 time.Duration) {
	h.logger.Debug().Msgf("beating heart every %dms", interval.Milliseconds())

	// REF: heartbeat_interval * jitter
	jitter := rand.Intn(int(interval))

	select {
	case <-time.After(time.Duration(jitter)):
	case <-h.ctx.Done():
		h.logger.Debug().Msg("heartbeat routine stopped before jitter heartbeat")
		return
	}

	ticker := time.NewTicker(interval)
	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
		}
	}
}