-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathrealtime.go
More file actions
137 lines (120 loc) · 3.06 KB
/
realtime.go
File metadata and controls
137 lines (120 loc) · 3.06 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package flagsmith
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"time"
"github.com/Flagsmith/flagsmith-go-client/v5/flagengine/environments"
)
// realtime handles the SSE connection and reconnection logic.
type realtime struct {
client *Client
ctx context.Context
log *slog.Logger
streamURL string
envUpdatedAt time.Time
backoff *backoff
}
// newRealtime creates a new realtime instance.
func newRealtime(client *Client, ctx context.Context, streamURL string, envUpdatedAt time.Time) *realtime {
return &realtime{
client: client,
ctx: ctx,
log: client.log.With(
slog.String("worker", "realtime"),
slog.String("stream", streamURL),
),
streamURL: streamURL,
envUpdatedAt: envUpdatedAt,
backoff: newBackoff(),
}
}
// start begins the realtime connection process.
func (r *realtime) start() {
r.log.Debug("connecting to realtime")
defer func() {
r.log.Info("stopped")
}()
for {
select {
case <-r.ctx.Done():
return
default:
if err := r.connect(); err != nil {
r.log.Error("failed to connect", "error", err)
r.backoff.wait(r.ctx)
}
}
}
}
// connect establishes and maintains the SSE connection.
func (r *realtime) connect() error {
resp, err := http.Get(r.streamURL)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("error response connecting to stream: %d", resp.StatusCode)
}
r.log.Info("connected")
r.backoff.reset()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
select {
case <-r.ctx.Done():
return r.ctx.Err()
default:
line := scanner.Text()
if strings.HasPrefix(line, "data: ") {
if err := r.handleEvent(line); err != nil {
r.log.Error("failed to handle event", "error", err, "message", line)
}
}
}
}
if err := scanner.Err(); err != nil {
r.log.Error("failed to read from stream", "error", err)
return err
}
return nil
}
// handleEvent processes a single SSE event.
func (r *realtime) handleEvent(line string) error {
parsedTime, err := parseUpdatedAtFromSSE(line)
if err != nil {
return err
}
if parsedTime.After(r.envUpdatedAt) {
if err := r.client.UpdateEnvironment(r.ctx); err != nil {
return err
}
if env, ok := r.client.environment.Load().(*environments.EnvironmentModel); ok {
r.envUpdatedAt = env.UpdatedAt
}
}
return nil
}
func parseUpdatedAtFromSSE(line string) (time.Time, error) {
var eventData struct {
UpdatedAt float64 `json:"updated_at"`
}
data := strings.TrimPrefix(line, "data: ")
err := json.Unmarshal([]byte(data), &eventData)
if err != nil {
return time.Time{}, errors.New("failed to parse event data: " + err.Error())
}
if eventData.UpdatedAt <= 0 {
return time.Time{}, errors.New("invalid 'updated_at' value in event data")
}
// Convert the float timestamp into seconds and nanoseconds
seconds := int64(eventData.UpdatedAt)
nanoseconds := int64((eventData.UpdatedAt - float64(seconds)) * 1e9)
// Return the parsed time
return time.Unix(seconds, nanoseconds), nil
}