-
Notifications
You must be signed in to change notification settings - Fork 137
/
apm-server.js
344 lines (310 loc) · 9.61 KB
/
apm-server.js
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
/**
* MIT License
*
* Copyright (c) 2017-present, Elasticsearch BV
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Queue from './queue'
import throttle from './throttle'
import NDJSON from './ndjson'
import { XHR_IGNORE } from './patching/patch-utils'
import { truncateModel, METADATA_MODEL } from './truncate'
import { ERRORS, TRANSACTIONS } from './constants'
import { noop } from './utils'
import { Promise } from './polyfills'
import {
compressMetadata,
compressTransaction,
compressError,
compressPayload
} from './compress'
import { __DEV__ } from '../state'
/**
* Throttling interval defaults to 60 seconds
*/
const THROTTLE_INTERVAL = 60000
class ApmServer {
constructor(configService, loggingService) {
this._configService = configService
this._loggingService = loggingService
this.queue = undefined
this.throttleEvents = noop
}
init() {
const queueLimit = this._configService.get('queueLimit')
const flushInterval = this._configService.get('flushInterval')
const limit = this._configService.get('eventsLimit')
const onFlush = events => {
const promise = this.sendEvents(events)
if (promise) {
promise.catch(reason => {
this._loggingService.warn(
'Failed sending events!',
this._constructError(reason)
)
})
}
}
this.queue = new Queue(onFlush, { queueLimit, flushInterval })
this.throttleEvents = throttle(
this.queue.add.bind(this.queue),
() => this._loggingService.warn('Dropped events due to throttling!'),
{ limit, interval: THROTTLE_INTERVAL }
)
}
_postJson(endPoint, payload) {
const headers = {
'Content-Type': 'application/x-ndjson'
}
const apmRequest = this._configService.get('apmRequest')
const params = { payload, headers, beforeSend: apmRequest }
return compressPayload(params)
.catch(error => {
if (__DEV__) {
this._loggingService.debug(
'Compressing the payload using CompressionStream API failed',
error.message
)
}
return params
})
.then(result => this._makeHttpRequest('POST', endPoint, result))
.then(({ responseText }) => responseText)
}
_constructError(reason) {
const { url, status, responseText } = reason
/**
* The `reason` could be a different type, e.g. an Error
*/
if (typeof status == 'undefined') {
return reason
}
let message = url + ' HTTP status: ' + status
if (__DEV__ && responseText) {
try {
const serverErrors = []
const response = JSON.parse(responseText)
if (response.errors && response.errors.length > 0) {
response.errors.forEach(err => serverErrors.push(err.message))
message += ' ' + serverErrors.join(',')
}
} catch (e) {
this._loggingService.debug('Error parsing response from APM server', e)
}
}
return new Error(message)
}
_makeHttpRequest(
method,
url,
{ timeout = 10000, payload, headers, beforeSend } = {}
) {
return new Promise(function (resolve, reject) {
var xhr = new window.XMLHttpRequest()
xhr[XHR_IGNORE] = true
xhr.open(method, url, true)
xhr.timeout = timeout
if (headers) {
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, headers[header])
}
}
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
const { status, responseText } = xhr
// An http 4xx or 5xx error. Signal an error.
if (status === 0 || (status > 399 && status < 600)) {
reject({ url, status, responseText })
} else {
resolve(xhr)
}
}
}
xhr.onerror = () => {
const { status, responseText } = xhr
reject({ url, status, responseText })
}
let canSend = true
if (typeof beforeSend === 'function') {
canSend = beforeSend({ url, method, headers, payload, xhr })
}
if (canSend) {
xhr.send(payload)
} else {
reject({
url,
status: 0,
responseText: 'Request rejected by user configuration.'
})
}
})
}
fetchConfig(serviceName, environment) {
const serverUrl = this._configService.get('serverUrl')
var configEndpoint = `${serverUrl}/config/v1/rum/agents`
if (!serviceName) {
return Promise.reject(
'serviceName is required for fetching central config.'
)
}
configEndpoint += `?service.name=${serviceName}`
if (environment) {
configEndpoint += `&service.environment=${environment}`
}
let localConfig = this._configService.getLocalConfig()
if (localConfig) {
configEndpoint += `&ifnonematch=${localConfig.etag}`
}
const apmRequest = this._configService.get('apmRequest')
return this._makeHttpRequest('GET', configEndpoint, {
timeout: 5000,
beforeSend: apmRequest
})
.then(xhr => {
const { status, responseText } = xhr
if (status === 304) {
return localConfig
} else {
let remoteConfig = JSON.parse(responseText)
const etag = xhr.getResponseHeader('etag')
if (etag) {
remoteConfig.etag = etag.replace(/["]/g, '')
this._configService.setLocalConfig(remoteConfig, true)
}
return remoteConfig
}
})
.catch(reason => {
const error = this._constructError(reason)
return Promise.reject(error)
})
}
createMetaData() {
const cfg = this._configService
const metadata = {
service: {
name: cfg.get('serviceName'),
version: cfg.get('serviceVersion'),
agent: {
name: 'rum-js',
version: cfg.version
},
language: {
name: 'javascript'
},
environment: cfg.get('environment')
},
labels: cfg.get('context.tags')
}
return truncateModel(METADATA_MODEL, metadata)
}
addError(error) {
this.throttleEvents({ [ERRORS]: error })
}
addTransaction(transaction) {
this.throttleEvents({ [TRANSACTIONS]: transaction })
}
ndjsonErrors(errors, compress) {
const key = compress ? 'e' : 'error'
return errors.map(error =>
NDJSON.stringify({
[key]: compress ? compressError(error) : error
})
)
}
ndjsonMetricsets(metricsets) {
return metricsets.map(metricset => NDJSON.stringify({ metricset })).join('')
}
ndjsonTransactions(transactions, compress) {
const key = compress ? 'x' : 'transaction'
return transactions.map(tr => {
let spans = '',
breakdowns = ''
if (!compress) {
if (tr.spans) {
spans = tr.spans.map(span => NDJSON.stringify({ span })).join('')
delete tr.spans
}
if (tr.breakdown) {
breakdowns = this.ndjsonMetricsets(tr.breakdown)
delete tr.breakdown
}
}
return (
NDJSON.stringify({ [key]: compress ? compressTransaction(tr) : tr }) +
spans +
breakdowns
)
})
}
sendEvents(events) {
if (events.length === 0) {
return
}
const transactions = []
const errors = []
for (let i = 0; i < events.length; i++) {
const event = events[i]
if (event[TRANSACTIONS]) {
transactions.push(event[TRANSACTIONS])
}
if (event[ERRORS]) {
errors.push(event[ERRORS])
}
}
if (transactions.length === 0 && errors.length === 0) {
return
}
const cfg = this._configService
const payload = {
[TRANSACTIONS]: transactions,
[ERRORS]: errors
}
const filteredPayload = cfg.applyFilters(payload)
if (!filteredPayload) {
this._loggingService.warn('Dropped payload due to filtering!')
return
}
const apiVersion = cfg.get('apiVersion')
/**
* Enable payload compression only when API version is > 2
*/
const compress = apiVersion > 2
let ndjson = []
const metadata = this.createMetaData()
const metadataKey = compress ? 'm' : 'metadata'
ndjson.push(
NDJSON.stringify({
[metadataKey]: compress ? compressMetadata(metadata) : metadata
})
)
ndjson = ndjson.concat(
this.ndjsonErrors(filteredPayload[ERRORS], compress),
this.ndjsonTransactions(filteredPayload[TRANSACTIONS], compress)
)
const ndjsonPayload = ndjson.join('')
const endPoint = cfg.get('serverUrl') + `/intake/v${apiVersion}/rum/events`
return this._postJson(endPoint, ndjsonPayload)
}
}
export default ApmServer