-
Notifications
You must be signed in to change notification settings - Fork 303
/
asyncdestinationmanager.go
295 lines (270 loc) · 9.13 KB
/
asyncdestinationmanager.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package asyncdestinationmanager
import (
"bufio"
stdjson "encoding/json"
"os"
"strings"
"sync"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/rudderlabs/rudder-server/config"
"github.com/rudderlabs/rudder-server/jobsdb"
"github.com/rudderlabs/rudder-server/services/rsources"
"github.com/rudderlabs/rudder-server/services/stats"
"github.com/rudderlabs/rudder-server/utils/logger"
"github.com/rudderlabs/rudder-server/utils/misc"
"github.com/tidwall/gjson"
)
type AsyncUploadOutput struct {
Key string
ImportingJobIDs []int64
ImportingParameters stdjson.RawMessage
SuccessJobIDs []int64
FailedJobIDs []int64
SucceededJobIDs []int64
SuccessResponse string
FailedReason string
AbortJobIDs []int64
AbortReason string
importingCount int
FailedCount int
AbortCount int
DestinationID string
}
type AsyncDestinationStruct struct {
ImportingJobIDs []int64
FailedJobIDs []int64
Exists bool
Size int
CreatedAt time.Time
FileName string
Count int
CanUpload bool
UploadMutex sync.RWMutex
URL string
RsourcesStats rsources.StatsCollector
}
type AsyncUploadT struct {
Config map[string]interface{} `json:"config"`
Input []AsyncJob `json:"input"`
DestType string `json:"destType"`
}
type AsyncJob struct {
Message map[string]interface{} `json:"message"`
Metadata map[string]interface{} `json:"metadata"`
}
type AsyncFailedPayload struct {
Config map[string]interface{} `json:"config"`
Input []map[string]interface{} `json:"input"`
DestType string `json:"destType"`
ImportId string `json:"importId"`
MetaData MetaDataT `json:"metadata"`
}
type MetaDataT struct {
CSVHeaders string `json:"csvHeader"`
}
type UploadStruct struct {
ImportId string `json:"importId"`
PollUrl string `json:"pollURL"`
Metadata map[string]interface{} `json:"metadata"`
}
type Parameters struct {
ImportId string `json:"importId"`
PollUrl string `json:"pollURL"`
MetaData MetaDataT `json:"metadata"`
}
var json = jsoniter.ConfigCompatibleWithStandardLibrary
var (
HTTPTimeout time.Duration
pkgLogger logger.Logger
)
func loadConfig() {
config.RegisterDurationConfigVariable(600, &HTTPTimeout, true, time.Second, "AsyncDestination.HTTPTimeout")
}
func Init() {
loadConfig()
pkgLogger = logger.NewLogger().Child("asyncDestinationManager")
}
func CleanUpData(keyMap map[string]interface{}, importingJobIDs []int64) ([]int64, []int64) {
if keyMap == nil {
return []int64{}, importingJobIDs
}
_, ok := keyMap["successfulJobs"].([]interface{})
var succesfulJobIDs, failedJobIDsTrans []int64
var err error
if ok {
succesfulJobIDs, err = misc.ConvertStringInterfaceToIntArray(keyMap["successfulJobs"])
if err != nil {
failedJobIDsTrans = importingJobIDs
}
}
_, ok = keyMap["unsuccessfulJobs"].([]interface{})
if ok {
failedJobIDsTrans, err = misc.ConvertStringInterfaceToIntArray(keyMap["unsuccessfulJobs"])
if err != nil {
failedJobIDsTrans = importingJobIDs
}
}
return succesfulJobIDs, failedJobIDsTrans
}
func Upload(url, filePath string, config map[string]interface{}, destType string, failedJobIDs, importingJobIDs []int64, destinationID string) AsyncUploadOutput {
file, err := os.Open(filePath)
if err != nil {
panic("BRT: Read File Failed" + err.Error())
}
defer file.Close()
var input []AsyncJob
scanner := bufio.NewScanner(file)
for scanner.Scan() {
var tempJob AsyncJob
jobBytes := scanner.Bytes()
err := json.Unmarshal(jobBytes, &tempJob)
if err != nil {
panic("Unmarshalling a Single Line Failed")
}
input = append(input, tempJob)
}
var uploadT AsyncUploadT
uploadT.Input = input
uploadT.Config = config
uploadT.DestType = strings.ToLower(destType)
payload, err := json.Marshal(uploadT)
if err != nil {
panic("BRT: JSON Marshal Failed " + err.Error())
}
uploadTimeStat := stats.Default.NewTaggedStat("async_upload_time", stats.TimerType, map[string]string{
"module": "batch_router",
"destType": destType,
})
payloadSizeStat := stats.Default.NewTaggedStat("payload_size", stats.TimerType, map[string]string{
"module": "batch_router",
"destType": destType,
})
startTime := time.Now()
payloadSizeStat.SendTiming(time.Millisecond * time.Duration(len(payload)))
pkgLogger.Debugf("[Async Destination Maanger] File Upload Started for Dest Type %v", destType)
responseBody, statusCodeHTTP := misc.HTTPCallWithRetryWithTimeout(url, payload, HTTPTimeout)
pkgLogger.Debugf("[Async Destination Maanger] File Upload Finished for Dest Type %v", destType)
uploadTimeStat.Since(startTime)
var bodyBytes []byte
var httpFailed bool
var statusCode string
if statusCodeHTTP != 200 {
bodyBytes = []byte(`"error" : "HTTP Call to Transformer Returned Non 200"`)
httpFailed = true
} else {
bodyBytes = responseBody
statusCode = gjson.GetBytes(bodyBytes, "statusCode").String()
}
var uploadResponse AsyncUploadOutput
if httpFailed {
uploadResponse = AsyncUploadOutput{
FailedJobIDs: append(failedJobIDs, importingJobIDs...),
FailedReason: string(bodyBytes),
FailedCount: len(failedJobIDs) + len(importingJobIDs),
DestinationID: destinationID,
}
} else if statusCode == "200" {
var responseStruct UploadStruct
err := json.Unmarshal(bodyBytes, &responseStruct)
if err != nil {
panic("Incorrect Response from Transformer: " + err.Error())
}
var parameters Parameters
parameters.ImportId = responseStruct.ImportId
parameters.PollUrl = responseStruct.PollUrl
metaDataString, ok := responseStruct.Metadata["csvHeader"].(string)
if !ok {
parameters.MetaData = MetaDataT{CSVHeaders: ""}
} else {
parameters.MetaData = MetaDataT{CSVHeaders: metaDataString}
}
importParameters, err := json.Marshal(parameters)
if err != nil {
panic("Errored in Marshalling" + err.Error())
}
successfulJobIDs, failedJobIDsTrans := CleanUpData(responseStruct.Metadata, importingJobIDs)
uploadResponse = AsyncUploadOutput{
ImportingJobIDs: successfulJobIDs,
FailedJobIDs: append(failedJobIDs, failedJobIDsTrans...),
FailedReason: `{"error":"Jobs flowed over the prescribed limit"}`,
ImportingParameters: stdjson.RawMessage(importParameters),
importingCount: len(importingJobIDs),
FailedCount: len(failedJobIDs) + len(failedJobIDsTrans),
DestinationID: destinationID,
}
} else if statusCode == "400" {
var responseStruct UploadStruct
err := json.Unmarshal(bodyBytes, &responseStruct)
if err != nil {
panic("Incorrect Response from Transformer: " + err.Error())
}
eventsAbortedStat := stats.Default.NewTaggedStat("events_delivery_aborted", stats.CountType, map[string]string{
"module": "batch_router",
"destType": destType,
})
abortedJobIDs, failedJobIDsTrans := CleanUpData(responseStruct.Metadata, importingJobIDs)
eventsAbortedStat.Count(len(abortedJobIDs))
uploadResponse = AsyncUploadOutput{
AbortJobIDs: abortedJobIDs,
FailedJobIDs: append(failedJobIDs, failedJobIDsTrans...),
FailedReason: `{"error":"Jobs flowed over the prescribed limit"}`,
AbortReason: string(bodyBytes),
AbortCount: len(importingJobIDs),
FailedCount: len(failedJobIDs) + len(failedJobIDsTrans),
DestinationID: destinationID,
}
} else {
uploadResponse = AsyncUploadOutput{
FailedJobIDs: append(failedJobIDs, importingJobIDs...),
FailedReason: string(bodyBytes),
FailedCount: len(failedJobIDs) + len(importingJobIDs),
DestinationID: destinationID,
}
}
return uploadResponse
}
func GetTransformedData(payload stdjson.RawMessage) string {
return gjson.Get(string(payload), "body.JSON").String()
}
func GetMarshalledData(payload string, jobID int64) string {
var job AsyncJob
err := json.Unmarshal([]byte(payload), &job.Message)
if err != nil {
panic("Unmarshalling Transformer Response Failed")
}
job.Metadata = make(map[string]interface{})
job.Metadata["job_id"] = jobID
responsePayload, err := json.Marshal(job)
if err != nil {
panic("Marshalling Response Payload Failed")
}
return string(responsePayload)
}
func GenerateFailedPayload(config map[string]interface{}, jobs []*jobsdb.JobT, importID, destType, csvHeaders string) []byte {
var failedPayloadT AsyncFailedPayload
failedPayloadT.Input = make([]map[string]interface{}, len(jobs))
index := 0
failedPayloadT.Config = config
for _, job := range jobs {
failedPayloadT.Input[index] = make(map[string]interface{})
var message map[string]interface{}
metadata := make(map[string]interface{})
err := json.Unmarshal([]byte(GetTransformedData(job.EventPayload)), &message)
if err != nil {
panic("Unmarshalling Transformer Data to JSON Failed")
}
metadata["job_id"] = job.JobID
failedPayloadT.Input[index]["message"] = message
failedPayloadT.Input[index]["metadata"] = metadata
index++
}
failedPayloadT.DestType = strings.ToLower(destType)
failedPayloadT.ImportId = importID
failedPayloadT.MetaData = MetaDataT{CSVHeaders: csvHeaders}
payload, err := json.Marshal(failedPayloadT)
if err != nil {
panic("JSON Marshal Failed" + err.Error())
}
return payload
}