-
Notifications
You must be signed in to change notification settings - Fork 253
/
client.js
375 lines (303 loc) · 11.1 KB
/
client.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
const config = require('./config')
const Event = require('./event')
const Breadcrumb = require('./breadcrumb')
const Session = require('./session')
const map = require('./lib/es-utils/map')
const includes = require('./lib/es-utils/includes')
const filter = require('./lib/es-utils/filter')
const reduce = require('./lib/es-utils/reduce')
const keys = require('./lib/es-utils/keys')
const assign = require('./lib/es-utils/assign')
const runCallbacks = require('./lib/callback-runner')
const metadataDelegate = require('./lib/metadata-delegate')
const runSyncCallbacks = require('./lib/sync-callback-runner')
const BREADCRUMB_TYPES = require('./lib/breadcrumb-types')
const { add, clear, merge } = require('./lib/feature-flag-delegate')
const noop = () => {}
class Client {
constructor (configuration, schema = config.schema, internalPlugins = [], notifier) {
// notifier id
this._notifier = notifier
// intialise opts and config
this._config = {}
this._schema = schema
// i/o
this._delivery = { sendSession: noop, sendEvent: noop }
this._logger = { debug: noop, info: noop, warn: noop, error: noop }
// plugins
this._plugins = {}
// state
this._breadcrumbs = []
this._session = null
this._metadata = {}
this._featuresIndex = {}
this._features = []
this._context = undefined
this._user = {}
// callbacks:
// e: onError
// s: onSession
// sp: onSessionPayload
// b: onBreadcrumb
// (note these names are minified by hand because object
// properties are not safe to minify automatically)
this._cbs = {
e: [],
s: [],
sp: [],
b: []
}
// expose internal constructors
this.Client = Client
this.Event = Event
this.Breadcrumb = Breadcrumb
this.Session = Session
this._config = this._configure(configuration, internalPlugins)
map(internalPlugins.concat(this._config.plugins), pl => {
if (pl) this._loadPlugin(pl)
})
// when notify() is called we need to know how many frames are from our own source
// this inital value is 1 not 0 because we wrap notify() to ensure it is always
// bound to have the client as its `this` value – see below.
this._depth = 1
const self = this
const notify = this.notify
this.notify = function () {
return notify.apply(self, arguments)
}
}
addMetadata (section, keyOrObj, maybeVal) {
return metadataDelegate.add(this._metadata, section, keyOrObj, maybeVal)
}
getMetadata (section, key) {
return metadataDelegate.get(this._metadata, section, key)
}
clearMetadata (section, key) {
return metadataDelegate.clear(this._metadata, section, key)
}
addFeatureFlag (name, variant = null) {
add(this._features, this._featuresIndex, name, variant)
}
addFeatureFlags (featureFlags) {
merge(this._features, featureFlags, this._featuresIndex)
}
clearFeatureFlag (name) {
clear(this._features, this._featuresIndex, name)
}
clearFeatureFlags () {
this._features = []
this._featuresIndex = {}
}
getContext () {
return this._context
}
setContext (c) {
this._context = c
}
_configure (opts, internalPlugins) {
const schema = reduce(internalPlugins, (schema, plugin) => {
if (plugin && plugin.configSchema) return assign({}, schema, plugin.configSchema)
return schema
}, this._schema)
// accumulate configuration and error messages
const { errors, config } = reduce(keys(schema), (accum, key) => {
const defaultValue = schema[key].defaultValue(opts[key])
if (opts[key] !== undefined) {
const valid = schema[key].validate(opts[key])
if (!valid) {
accum.errors[key] = schema[key].message
accum.config[key] = defaultValue
} else {
if (schema[key].allowPartialObject) {
accum.config[key] = assign(defaultValue, opts[key])
} else {
accum.config[key] = opts[key]
}
}
} else {
accum.config[key] = defaultValue
}
return accum
}, { errors: {}, config: {} })
if (schema.apiKey) {
// missing api key is the only fatal error
if (!config.apiKey) throw new Error('No Bugsnag API Key set')
// warn about an apikey that is not of the expected format
if (!/^[0-9a-f]{32}$/i.test(config.apiKey)) errors.apiKey = 'should be a string of 32 hexadecimal characters'
}
// update and elevate some options
this._metadata = assign({}, config.metadata)
merge(this._features, config.featureFlags, this._featuresIndex)
this._user = assign({}, config.user)
this._context = config.context
if (config.logger) this._logger = config.logger
// add callbacks
if (config.onError) this._cbs.e = this._cbs.e.concat(config.onError)
if (config.onBreadcrumb) this._cbs.b = this._cbs.b.concat(config.onBreadcrumb)
if (config.onSession) this._cbs.s = this._cbs.s.concat(config.onSession)
// finally warn about any invalid config where we fell back to the default
if (keys(errors).length) {
this._logger.warn(generateConfigErrorMessage(errors, opts))
}
return config
}
getUser () {
return this._user
}
setUser (id, email, name) {
this._user = { id, email, name }
}
_loadPlugin (plugin) {
const result = plugin.load(this)
// JS objects are not the safest way to store arbitrarily keyed values,
// so bookend the key with some characters that prevent tampering with
// stuff like __proto__ etc. (only store the result if the plugin had a
// name)
if (plugin.name) this._plugins[`~${plugin.name}~`] = result
}
getPlugin (name) {
return this._plugins[`~${name}~`]
}
_setDelivery (d) {
this._delivery = d(this)
}
startSession () {
const session = new Session()
session.app.releaseStage = this._config.releaseStage
session.app.version = this._config.appVersion
session.app.type = this._config.appType
session._user = assign({}, this._user)
// run onSession callbacks
const ignore = runSyncCallbacks(this._cbs.s, session, 'onSession', this._logger)
if (ignore) {
this._logger.debug('Session not started due to onSession callback')
return this
}
return this._sessionDelegate.startSession(this, session)
}
addOnError (fn, front = false) {
this._cbs.e[front ? 'unshift' : 'push'](fn)
}
removeOnError (fn) {
this._cbs.e = filter(this._cbs.e, f => f !== fn)
}
_addOnSessionPayload (fn) {
this._cbs.sp.push(fn)
}
addOnSession (fn) {
this._cbs.s.push(fn)
}
removeOnSession (fn) {
this._cbs.s = filter(this._cbs.s, f => f !== fn)
}
addOnBreadcrumb (fn, front = false) {
this._cbs.b[front ? 'unshift' : 'push'](fn)
}
removeOnBreadcrumb (fn) {
this._cbs.b = filter(this._cbs.b, f => f !== fn)
}
pauseSession () {
return this._sessionDelegate.pauseSession(this)
}
resumeSession () {
return this._sessionDelegate.resumeSession(this)
}
leaveBreadcrumb (message, metadata, type) {
// coerce bad values so that the defaults get set
message = typeof message === 'string' ? message : ''
type = (typeof type === 'string' && includes(BREADCRUMB_TYPES, type)) ? type : 'manual'
metadata = typeof metadata === 'object' && metadata !== null ? metadata : {}
// if no message, discard
if (!message) return
const crumb = new Breadcrumb(message, metadata, type)
// run onBreadcrumb callbacks
const ignore = runSyncCallbacks(this._cbs.b, crumb, 'onBreadcrumb', this._logger)
if (ignore) {
this._logger.debug('Breadcrumb not attached due to onBreadcrumb callback')
return
}
// push the valid crumb onto the queue and maintain the length
this._breadcrumbs.push(crumb)
if (this._breadcrumbs.length > this._config.maxBreadcrumbs) {
this._breadcrumbs = this._breadcrumbs.slice(this._breadcrumbs.length - this._config.maxBreadcrumbs)
}
}
_isBreadcrumbTypeEnabled (type) {
const types = this._config.enabledBreadcrumbTypes
return types === null || includes(types, type)
}
notify (maybeError, onError, postReportCallback = noop) {
const event = Event.create(maybeError, true, undefined, 'notify()', this._depth + 1, this._logger)
this._notify(event, onError, postReportCallback)
}
_notify (event, onError, postReportCallback = noop) {
event.app = assign({}, event.app, {
releaseStage: this._config.releaseStage,
version: this._config.appVersion,
type: this._config.appType
})
event.context = event.context || this._context
event._metadata = assign({}, event._metadata, this._metadata)
event._user = assign({}, event._user, this._user)
event.breadcrumbs = this._breadcrumbs.slice()
merge(event._features, this._features, event._featuresIndex)
// exit early if events should not be sent on the current releaseStage
if (this._config.enabledReleaseStages !== null && !includes(this._config.enabledReleaseStages, this._config.releaseStage)) {
this._logger.warn('Event not sent due to releaseStage/enabledReleaseStages configuration')
return postReportCallback(null, event)
}
const originalSeverity = event.severity
const onCallbackError = err => {
// errors in callbacks are tolerated but we want to log them out
this._logger.error('Error occurred in onError callback, continuing anyway…')
this._logger.error(err)
}
const callbacks = [].concat(this._cbs.e).concat(onError)
runCallbacks(callbacks, event, onCallbackError, (err, shouldSend) => {
if (err) onCallbackError(err)
if (!shouldSend) {
this._logger.debug('Event not sent due to onError callback')
return postReportCallback(null, event)
}
if (this._isBreadcrumbTypeEnabled('error')) {
// only leave a crumb for the error if actually got sent
Client.prototype.leaveBreadcrumb.call(this, event.errors[0].errorClass, {
errorClass: event.errors[0].errorClass,
errorMessage: event.errors[0].errorMessage,
severity: event.severity
}, 'error')
}
if (originalSeverity !== event.severity) {
event._handledState.severityReason = { type: 'userCallbackSetSeverity' }
}
if (event.unhandled !== event._handledState.unhandled) {
event._handledState.severityReason.unhandledOverridden = true
event._handledState.unhandled = event.unhandled
}
if (this._session) {
this._session._track(event)
event._session = this._session
}
this._delivery.sendEvent({
apiKey: event.apiKey || this._config.apiKey,
notifier: this._notifier,
events: [event]
}, (err) => postReportCallback(err, event))
})
}
}
const generateConfigErrorMessage = (errors, rawInput) => {
const er = new Error(
`Invalid configuration\n${map(keys(errors), key => ` - ${key} ${errors[key]}, got ${stringify(rawInput[key])}`).join('\n\n')}`)
return er
}
const stringify = val => {
switch (typeof val) {
case 'string':
case 'number':
case 'object':
return JSON.stringify(val)
default: return String(val)
}
}
module.exports = Client