/
pusher.go
47 lines (38 loc) · 1.1 KB
/
pusher.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
package activity
import (
"context"
"fmt"
"time"
"golang.org/x/time/rate"
"cdr.dev/coder-cli/coder-sdk"
"cdr.dev/coder-cli/pkg/clog"
)
const pushInterval = time.Minute
// Pusher pushes activity metrics no more than once per pushInterval. Pushes
// within the same interval are a no-op.
type Pusher struct {
workspaceID string
source string
client coder.Client
rate *rate.Limiter // Use a rate limiter to control the sampling rate.
}
// NewPusher instantiates a new instance of Pusher.
func NewPusher(c coder.Client, workspaceID, source string) *Pusher {
return &Pusher{
workspaceID: workspaceID,
source: source,
client: c,
// Sample only 1 per interval to avoid spamming the api.
rate: rate.NewLimiter(rate.Every(pushInterval), 1),
}
}
// Push pushes activity, abiding by a rate limit.
func (p *Pusher) Push(ctx context.Context) {
// If we already sampled data within the allowable range, do nothing.
if !p.rate.Allow() {
return
}
if err := p.client.PushActivity(ctx, p.source, p.workspaceID); err != nil {
clog.Log(clog.Error(fmt.Sprintf("push activity: %s", err)))
}
}