-
Notifications
You must be signed in to change notification settings - Fork 307
/
eventUploader.go
252 lines (218 loc) · 6.71 KB
/
eventUploader.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
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package sourcedebugger
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"golang.org/x/exp/slices"
"github.com/rudderlabs/rudder-go-kit/config"
"github.com/rudderlabs/rudder-go-kit/logger"
backendconfig "github.com/rudderlabs/rudder-server/backend-config"
"github.com/rudderlabs/rudder-server/rruntime"
"github.com/rudderlabs/rudder-server/services/debugger"
"github.com/rudderlabs/rudder-server/services/debugger/cache"
"github.com/rudderlabs/rudder-server/utils/misc"
)
// GatewayEventBatchT is a structure to hold batch of events
type GatewayEventBatchT struct {
WriteKey string
EventBatch []byte
}
// EventUploadT is a structure to hold actual event data
type EventUploadT map[string]interface{}
// EventUploadBatchT is a structure to hold batch of events
type EventUploadBatchT struct {
WriteKey string
ReceivedAt string
Batch []EventUploadT
}
type SourceDebugger interface {
RecordEvent(writeKey string, eventBatch []byte) bool
Stop()
}
type Opt func(*Handle)
var WithDisableEventUploads = func(disableEventUploads bool) func(h *Handle) {
return func(h *Handle) {
h.disableEventUploads = disableEventUploads
}
}
type Handle struct {
started bool
uploader debugger.Uploader[*GatewayEventBatchT]
configBackendURL string
disableEventUploads bool
log logger.Logger
eventsCache cache.Cache[[]byte]
uploadEnabledWriteKeysMu sync.RWMutex
uploadEnabledWriteKeys []string
ctx context.Context
cancel func()
initialized chan struct{}
done chan struct{}
}
func NewHandle(backendConfig backendconfig.BackendConfig, opts ...Opt) (SourceDebugger, error) {
h := &Handle{
configBackendURL: config.GetString("CONFIG_BACKEND_URL", "https://api.rudderstack.com"),
log: logger.NewLogger().Child("debugger").Child("source"),
}
var err error
config.RegisterBoolConfigVariable(false, &h.disableEventUploads, true, "SourceDebugger.disableEventUploads")
url := fmt.Sprintf("%s/dataplane/v2/eventUploads", h.configBackendURL)
eventUploader := NewEventUploader(h.log)
h.uploader = debugger.New[*GatewayEventBatchT](url, eventUploader)
h.uploader.Start()
cacheType := cache.CacheType(config.GetInt("SourceDebugger.cacheType", int(cache.MemoryCacheType)))
h.eventsCache, err = cache.New[[]byte](cacheType, "source", h.log)
if err != nil {
return nil, err
}
for _, opt := range opts {
opt(h)
}
h.start(backendConfig)
return h, nil
}
// Start initializes this module
func (h *Handle) start(backendConfig backendconfig.BackendConfig) {
ctx, cancel := context.WithCancel(context.Background())
h.ctx = ctx
h.cancel = cancel
h.done = make(chan struct{})
h.initialized = make(chan struct{})
h.started = true
rruntime.Go(func() {
h.backendConfigSubscriber(backendConfig)
})
}
func (h *Handle) Stop() {
if !h.started {
return
}
h.cancel()
<-h.done
if h.eventsCache != nil {
_ = h.eventsCache.Stop()
}
h.uploader.Stop()
h.started = false
}
// RecordEvent is used to put the event batch in the eventBatchChannel,
// which will be processed by handleEvents.
func (h *Handle) RecordEvent(writeKey string, eventBatch []byte) bool {
if !h.started || h.disableEventUploads {
return false
}
<-h.initialized
// Check if writeKey part of enabled sources
h.uploadEnabledWriteKeysMu.RLock()
defer h.uploadEnabledWriteKeysMu.RUnlock()
if !slices.Contains(h.uploadEnabledWriteKeys, writeKey) {
err := h.eventsCache.Update(writeKey, eventBatch)
if err != nil {
h.log.Errorf("Error while updating cache: %v", err)
}
return false
}
h.uploader.RecordEvent(&GatewayEventBatchT{writeKey, eventBatch})
return true
}
func (h *Handle) updateConfig(config map[string]backendconfig.ConfigT) {
var uploadEnabledWriteKeys []string
for _, wConfig := range config {
for _, source := range wConfig.Sources {
if source.Config != nil {
if source.Enabled && source.Config["eventUpload"] == true {
uploadEnabledWriteKeys = append(uploadEnabledWriteKeys, source.WriteKey)
}
}
}
}
h.uploadEnabledWriteKeysMu.Lock()
h.uploadEnabledWriteKeys = uploadEnabledWriteKeys
h.uploadEnabledWriteKeysMu.Unlock()
h.recordHistoricEvents(uploadEnabledWriteKeys)
}
func (h *Handle) backendConfigSubscriber(backendConfig backendconfig.BackendConfig) {
ch := backendConfig.Subscribe(h.ctx, backendconfig.TopicProcessConfig)
for c := range ch {
h.updateConfig(c.Data.(map[string]backendconfig.ConfigT))
select {
case <-h.initialized:
default:
close(h.initialized)
}
}
close(h.done)
}
// recordHistoricEvents sends the events collected in cache as live events.
// This is called on config update.
// IMP: The function must be called before releasing configSubscriberLock lock to ensure the order of RecordEvent call
func (h *Handle) recordHistoricEvents(uploadEnabledWriteKeys []string) {
for _, writeKey := range uploadEnabledWriteKeys {
historicEvents, err := h.eventsCache.Read(writeKey)
if err != nil {
continue
}
for _, eventBatchData := range historicEvents {
h.uploader.RecordEvent(&GatewayEventBatchT{writeKey, eventBatchData})
}
}
}
type EventUploader struct {
log logger.Logger
}
func NewEventUploader(log logger.Logger) *EventUploader {
return &EventUploader{log: log}
}
func (e *EventUploader) Transform(eventBuffer []*GatewayEventBatchT) ([]byte, error) {
res := make(map[string]interface{})
res["version"] = "v2"
for _, event := range eventBuffer {
var batchedEvent EventUploadBatchT
err := json.Unmarshal(event.EventBatch, &batchedEvent)
if err != nil {
e.log.Errorf("[Source live events] Failed to unmarshal. Err: %v", err)
continue
}
receivedAtTS, err := time.Parse(time.RFC3339, batchedEvent.ReceivedAt)
if err != nil {
receivedAtTS = time.Now()
}
receivedAtStr := receivedAtTS.Format(misc.RFC3339Milli)
var arr []EventUploadT
if value, ok := res[batchedEvent.WriteKey]; ok {
arr, _ = value.([]EventUploadT)
}
for _, ev := range batchedEvent.Batch {
// add the receivedAt time to each event
event := map[string]interface{}{
"payload": ev,
"receivedAt": receivedAtStr,
"eventName": misc.GetStringifiedData(ev["event"]),
"eventType": misc.GetStringifiedData(ev["type"]),
"errorResponse": make(map[string]interface{}),
"errorCode": 200,
}
arr = append(arr, event)
}
res[batchedEvent.WriteKey] = arr
}
rawJSON, err := json.Marshal(res)
if err != nil {
e.log.Errorf("[Source live events] Failed to marshal payload. Err: %v", err)
return nil, err
}
return rawJSON, nil
}
func NewNoOpService() SourceDebugger {
return &noopService{}
}
type noopService struct{}
func (*noopService) Start(_ backendconfig.BackendConfig) {
}
func (*noopService) RecordEvent(_ string, _ []byte) bool {
return false
}
func (*noopService) Stop() {
}