-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathbase.js
More file actions
346 lines (307 loc) · 9.66 KB
/
Copy pathbase.js
File metadata and controls
346 lines (307 loc) · 9.66 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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
'use strict'
const request = require('../../exporters/common/request')
const { safeJSONStringify } = require('../../exporters/common/util')
const log = require('../../log')
/**
* @typedef {object} BaseFFEWriterOptions
* @property {number} [interval] - Flush interval in milliseconds
* @property {number} [timeout] - Request timeout in milliseconds
* @property {object} config - Tracer configuration object
* @property {string} endpoint - API endpoint path
* @property {URL} [agentUrl] - Initial delivery URL
* @property {number} [payloadSizeLimit] - Maximum payload size in bytes
* @property {number} [eventSizeLimit] - Maximum individual event size in bytes
* @property {object} [headers] - Additional HTTP headers
*/
/**
* @typedef {object} WriterRoute
* @property {URL} url - Route base URL
* @property {string} endpoint - Route endpoint
* @property {object} headers - Route-specific headers
* @property {import('node:https').Agent} [agent] - Optional HTTPS proxy agent
*/
/**
* @typedef {object} ActiveWriterRoute
* @property {URL} url - Route base URL
* @property {string} endpoint - Route endpoint
* @property {object} requestOptions - HTTP request options
*/
/**
* Tests whether a local route definitively rejected an event batch.
*
* @param {Error | null} error - Request error
* @param {number | undefined} statusCode - HTTP response status
* @returns {boolean} Whether direct retry is safe
*/
function isDefinitiveRejection (error, statusCode) {
return error?.code === 'ECONNREFUSED' || statusCode === 403 || statusCode === 404 || statusCode === 405
}
/**
* Base writer for Feature Flagging and Experimentation event delivery.
* @class BaseFFEWriter
*/
class BaseFFEWriter {
#destroyer
/**
* @param {BaseFFEWriterOptions} options - Writer configuration options
*/
constructor ({ interval, timeout, config, endpoint, agentUrl, payloadSizeLimit, eventSizeLimit, headers }) {
this._interval = interval ?? 1000
this._timeout = timeout ?? 5000
this._buffer = []
this._bufferLimit = 1000
this._bufferStart = 0
this._dropWarningLogged = false
this._config = config
this._endpoint = endpoint
this._baseUrl = agentUrl ?? config.url
this._payloadSizeLimit = payloadSizeLimit
this._eventSizeLimit = eventSizeLimit
this._headers = headers || {}
this._fallbackRoute = undefined
this._requestOptions = {
headers: {
...this._headers,
'Content-Type': 'application/json',
},
method: 'POST',
timeout: this._timeout,
url: this._baseUrl,
path: this._endpoint,
}
this._periodic = setInterval(() => {
this.flush()
}, this._interval)
this._periodic.unref?.()
const destroyer = this.destroy.bind(this)
globalThis[Symbol.for('dd-trace')].beforeExitHandlers.add(destroyer)
this.#destroyer = destroyer
this._droppedEvents = 0
}
/**
* Appends an event array to the buffer
* @param {Array | object} events - Event object(s) to append to buffer
*/
append (events) {
const eventArray = Array.isArray(events) ? events : [events]
for (const event of eventArray) {
if (this._buffer.length < this._bufferLimit) {
this._buffer.push(event)
} else {
this._buffer[this._bufferStart] = event
this._bufferStart = (this._bufferStart + 1) % this._bufferLimit
this._droppedEvents++
if (!this._dropWarningLogged) {
this._dropWarningLogged = true
log.warn(
'%s dropped exposure event(s) at cap %d. This may invalidate experiment results.',
this.constructor.name,
this._bufferLimit
)
}
}
}
}
/**
* Sizes, batches, and flushes all buffered events.
*/
flush () {
if (this._buffer.length === 0) {
return
}
const events = this._bufferStart === 0
? this._buffer
: [...this._buffer.slice(this._bufferStart), ...this._buffer.slice(0, this._bufferStart)]
this._buffer = []
this._bufferStart = 0
let batch = []
let batchSize = 0
for (const event of events) {
let eventSize
try {
eventSize = Buffer.byteLength(JSON.stringify(event))
} catch (error) {
log.warn('%s could not serialize an event, dropping event: %s', this.constructor.name, error.message)
this._droppedEvents++
continue
}
if (this._eventSizeLimit && eventSize > this._eventSizeLimit) {
log.warn(
'%s event size %d bytes exceeds limit %d, dropping event',
this.constructor.name,
eventSize,
this._eventSizeLimit
)
this._droppedEvents++
continue
}
if (this._payloadSizeLimit && eventSize > this._payloadSizeLimit) {
log.warn(
'%s event size %d bytes exceeds payload limit %d, dropping event',
this.constructor.name,
eventSize,
this._payloadSizeLimit
)
this._droppedEvents++
continue
}
if (batch.length > 0 && this._payloadSizeLimit && batchSize + eventSize > this._payloadSizeLimit) {
this.#send(batch)
batch = []
batchSize = 0
}
batch.push(event)
batchSize += eventSize
}
if (batch.length > 0) {
this.#send(batch)
}
}
/**
* Override in subclass to customize payload structure
* @param {Array} events - Array of events to be sent
* @returns {object} Formatted payload
*/
makePayload (events) {
// Override in subclass
return events
}
/**
* Cleans up resources and flushes remaining events
*/
destroy () {
if (this.#destroyer) {
log.debug('Stopping %s', this.constructor.name)
clearInterval(this._periodic)
this.flush()
globalThis[Symbol.for('dd-trace')].beforeExitHandlers.delete(this.#destroyer)
this.#destroyer = undefined
if (this._droppedEvents > 0) {
log.warn('%s dropped %d events due to buffer overflow', this.constructor.name, this._droppedEvents)
}
}
}
/**
* @private
* @param {Array<object>} payload - Payload to encode
* @returns {string} JSON-stringified payload
*/
_encode (payload) {
return JSON.stringify(payload)
}
/**
* Applies the active route and an optional direct fallback route.
*
* @param {WriterRoute} route - Active route
* @param {WriterRoute} [fallbackRoute] - Direct fallback route
* @returns {void}
*/
_setRoutes (route, fallbackRoute) {
this.#activateRoute(this.#createRoute(route))
this._fallbackRoute = fallbackRoute ? this.#createRoute(fallbackRoute) : undefined
}
/**
* Sends one event batch.
*
* @param {Array<object>} events - Events in the batch
* @returns {void}
*/
#send (events) {
let payload
try {
payload = this._encode(this.makePayload(events))
} catch (error) {
log.warn(
'%s could not encode %d event(s), dropping batch: %s',
this.constructor.name,
events.length,
error.message
)
this._droppedEvents += events.length
return
}
// eslint-disable-next-line eslint-rules/eslint-log-printf-style
log.debug(() => `${this.constructor.name} flushing payload: ${safeJSONStringify(payload)}`)
const route = this.#createActiveRoute()
this.#sendRequest(payload, events.length, route, this._fallbackRoute)
}
/**
* Creates request state for a configured writer route.
*
* @param {WriterRoute} route - Configured route
* @returns {ActiveWriterRoute} Active route state
*/
#createRoute (route) {
return {
url: route.url,
endpoint: route.endpoint,
requestOptions: {
...(route.agent && { agent: route.agent }),
headers: {
...route.headers,
'Content-Type': 'application/json',
},
method: 'POST',
timeout: this._timeout,
url: route.url,
path: route.endpoint,
},
}
}
/**
* Captures the current route for one event batch.
*
* @returns {ActiveWriterRoute} Active route state
*/
#createActiveRoute () {
return {
url: this._baseUrl,
endpoint: this._endpoint,
requestOptions: this._requestOptions,
}
}
/**
* Makes a route active for future event batches.
*
* @param {ActiveWriterRoute} route - Route state
* @returns {void}
*/
#activateRoute (route) {
this._baseUrl = route.url
this._endpoint = route.endpoint
this._requestOptions = route.requestOptions
}
/**
* Sends an encoded batch and retries it directly only after definitive rejection.
*
* @param {string} payload - Encoded event batch
* @param {number} eventCount - Event count
* @param {ActiveWriterRoute} route - Selected route
* @param {ActiveWriterRoute} [fallbackRoute] - Direct fallback route
* @returns {void}
*/
#sendRequest (payload, eventCount, route, fallbackRoute) {
request(payload, route.requestOptions, (error, response, statusCode) => {
if (fallbackRoute && isDefinitiveRejection(error, statusCode)) {
log.debug(
'%s switching from %s%s to direct intake after definitive rejection',
this.constructor.name,
route.url.href,
route.endpoint
)
this.#activateRoute(fallbackRoute)
this._fallbackRoute = undefined
this.#sendRequest(payload, eventCount, fallbackRoute)
return
}
if (error) {
log.error('Failed to send events to %s%s: %s', route.url.href, route.endpoint, error.message)
} else if (statusCode >= 200 && statusCode < 300) {
log.debug('Successfully sent %d events', eventCount)
} else {
log.warn('Events request returned status %d', statusCode)
}
})
}
}
module.exports = BaseFFEWriter