forked from benbjohnson/litestream
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheartbeat.go
More file actions
84 lines (68 loc) · 1.54 KB
/
Copy pathheartbeat.go
File metadata and controls
84 lines (68 loc) · 1.54 KB
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
78
79
80
81
82
83
84
package litestream
import (
"context"
"fmt"
"net/http"
"sync"
"time"
)
const (
DefaultHeartbeatInterval = 5 * time.Minute
DefaultHeartbeatTimeout = 30 * time.Second
MinHeartbeatInterval = 1 * time.Minute
)
type HeartbeatClient struct {
mu sync.Mutex
httpClient *http.Client
URL string
Interval time.Duration
Timeout time.Duration
lastPingAt time.Time
}
func NewHeartbeatClient(url string, interval time.Duration) *HeartbeatClient {
if interval < MinHeartbeatInterval {
interval = MinHeartbeatInterval
}
timeout := DefaultHeartbeatTimeout
return &HeartbeatClient{
URL: url,
Interval: interval,
Timeout: timeout,
httpClient: &http.Client{
Timeout: timeout,
},
}
}
func (c *HeartbeatClient) Ping(ctx context.Context) error {
if c.URL == "" {
return nil
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.URL, nil)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return nil
}
func (c *HeartbeatClient) ShouldPing() bool {
c.mu.Lock()
defer c.mu.Unlock()
return time.Since(c.lastPingAt) >= c.Interval
}
func (c *HeartbeatClient) LastPingAt() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.lastPingAt
}
func (c *HeartbeatClient) RecordPing() {
c.mu.Lock()
defer c.mu.Unlock()
c.lastPingAt = time.Now()
}