-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathCrashReportReceiver.swift
More file actions
427 lines (393 loc) · 20.2 KB
/
Copy pathCrashReportReceiver.swift
File metadata and controls
427 lines (393 loc) · 20.2 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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-Present Datadog, Inc.
*/
import Foundation
import DatadogInternal
/// Receiver to consume crash reports as RUM events.
internal struct CrashReportReceiver: FeatureMessageReceiver {
private struct AdjustedCrashTimings {
/// Crash date read from `CrashReport`. It uses device time.
let crashDate: Date
/// Crash date adjusted with current time correction. It uses NTP time.
let realCrashDate: Date
/// Current time, adjusted with NTP correction.
let realDateNow: Date
/// Time between crash and application launch
let timeSinceAppStart: TimeInterval?
}
/// RUM feature scope.
let featureScope: FeatureScope
let applicationID: String
let dateProvider: DateProvider
let sessionSampler: Sampler
let trackBackgroundEvents: Bool
let uuidGenerator: RUMUUIDGenerator
/// Integration with CIApp tests. It contains the CIApp test context when active.
let ciTest: RUMCITest?
/// Integration with Synthetics tests. It contains the Synthetics test context when active.
let syntheticsTest: RUMSyntheticsTest?
let eventsMapper: RUMEventsMapper
private let sanitizer = RUMEventSanitizer()
// MARK: - Initialization
init(
featureScope: FeatureScope,
applicationID: String,
dateProvider: DateProvider,
sessionSampler: Sampler,
trackBackgroundEvents: Bool,
uuidGenerator: RUMUUIDGenerator,
ciTest: RUMCITest?,
syntheticsTest: RUMSyntheticsTest?,
eventsMapper: RUMEventsMapper
) {
self.featureScope = featureScope
self.applicationID = applicationID
self.dateProvider = dateProvider
self.sessionSampler = sessionSampler
self.trackBackgroundEvents = trackBackgroundEvents
self.uuidGenerator = uuidGenerator
self.ciTest = ciTest
self.syntheticsTest = syntheticsTest
self.eventsMapper = eventsMapper
}
func receive(message: FeatureMessage, from core: DatadogCoreProtocol) -> Bool {
guard case let .payload(crash as Crash) = message else {
return false
}
return send(report: crash.report, with: crash.context)
}
private func send(report: DDCrashReport, with context: CrashContext) -> Bool {
// The `crashReport.crashDate` uses system `Date` collected at the moment of crash, so we need to adjust it
// to the server time before processing. Following use of the current correction is not ideal (it's not the correction
// from the moment of crash), but this is the best approximation we can get.
let currentTimeCorrection = context.serverTimeOffset
let crashDate = report.date ?? dateProvider.now
var timeSinceAppStart: TimeInterval? = nil
if let startDate = context.appLaunchDate {
timeSinceAppStart = crashDate.timeIntervalSince(startDate)
}
let adjustedCrashTimings = AdjustedCrashTimings(
crashDate: crashDate,
realCrashDate: crashDate.addingTimeInterval(currentTimeCorrection),
realDateNow: dateProvider.now.addingTimeInterval(currentTimeCorrection),
timeSinceAppStart: timeSinceAppStart
)
// RUMM-2516 if a cross-platform crash was reported, do not send its native version
if var lastRUMViewEvent = context.lastRUMViewEvent {
if let lastRUMAttributes = context.lastRUMAttributes {
// RUM-3588: If last RUM attributes are available, use them to replace view attributes as we know that
// global RUM attributes can be updated more often than attributes in `lastRUMView`.
// See https://github.com/DataDog/dd-sdk-ios/pull/1834 for more context.
lastRUMViewEvent.context = lastRUMAttributes
}
if lastRUMViewEvent.view.crash?.count ?? 0 < 1 {
sendCrashReportLinkedToLastViewInPreviousSession(
report,
lastRUMViewEventInPreviousSession: lastRUMViewEvent,
using: adjustedCrashTimings
)
} else {
DD.logger.debug("There was a crash in previous session, but it is ignored due to another crash already present in the last view.")
return false
}
return true
}
if let lastRUMSessionState = context.lastRUMSessionState {
sendCrashReportToPreviousSession(report, crashContext: context, lastRUMSessionStateInPreviousSession: lastRUMSessionState, using: adjustedCrashTimings)
return true
}
return sendCrashReportToNewSession(report, crashContext: context, using: adjustedCrashTimings)
}
/// If the crash occurred in an existing RUM session and we know its `lastRUMViewEvent` we send the error using that session UUID and link
/// the crash to that view. The error event can be preceded with a view update based on `Constants.viewEventAvailabilityThreshold` condition.
private func sendCrashReportLinkedToLastViewInPreviousSession(
_ crashReport: DDCrashReport,
lastRUMViewEventInPreviousSession lastRUMViewEvent: RUMViewEvent,
using crashTimings: AdjustedCrashTimings
) {
if crashTimings.realDateNow.timeIntervalSince(crashTimings.realCrashDate) < FatalErrorBuilder.Constants.viewEventAvailabilityThreshold {
send(crashReport: crashReport, to: lastRUMViewEvent, using: crashTimings)
} else {
// We know it is too late for sending RUM view to previous RUM session as it is now stale on backend.
// To avoid inconsistency, we only send the RUM error.
DD.logger.debug("Sending crash as RUM error.")
featureScope.eventWriteContext(bypassConsent: true) { context, writer in
let builder = createFatalErrorBuilder(context: context, crash: crashReport, crashDate: crashTimings.realCrashDate, timeSinceAppStart: crashTimings.timeSinceAppStart)
let rumError = builder.createRUMError(with: lastRUMViewEvent)
if let mappedError = self.eventsMapper.map(event: rumError) {
writer.write(value: self.sanitizer.sanitize(event: mappedError))
} else {
DD.logger.warn("errorEventMapper returned 'nil' for a crash. Discarding crashes is not supported. The unmodified event will be sent.")
writer.write(value: self.sanitizer.sanitize(event: rumError))
}
}
}
}
/// If the crash occurred in an existing RUM session and we know its `lastRUMSessionState` but there was no `lastRUMViewEvent` we can
/// still send the error using that session UUID. Lack of `lastRUMViewEvent` means that there was no **active** view, but the presence of
/// `lastRUMSessionState` indicates that some views were tracked before.
private func sendCrashReportToPreviousSession(
_ crashReport: DDCrashReport,
crashContext: CrashContext,
lastRUMSessionStateInPreviousSession lastRUMSessionState: RUMSessionState,
using crashTimings: AdjustedCrashTimings
) {
let handlingRule = RUMOffViewEventsHandlingRule(
applicationState: nil,
sessionState: lastRUMSessionState,
isAppInForeground: crashContext.lastIsAppInForeground,
isBETEnabled: trackBackgroundEvents,
command: nil
)
let newRUMView: RUMViewEvent?
switch handlingRule {
case .handleInApplicationLaunchView:
// This indicates an edge case, where RUM session was created (we know the `lastRUMSessionState`), but no RUM view event
// was yet passed to `CrashContext` (othwesiwe we would be calling `sendCrashReportLinkedToLastViewInPreviousSession()`).
// It can happen if crash occurs shortly after starting first RUM session, but before we complete serializing first RUM view event in `CrashContext`.
newRUMView = createNewRUMViewEvent(
named: RUMOffViewEventsHandlingRule.Constants.applicationLaunchViewName,
url: RUMOffViewEventsHandlingRule.Constants.applicationLaunchViewURL,
startDate: crashTimings.realCrashDate,
sessionUUID: RUMUUID(rawValue: lastRUMSessionState.sessionUUID), // link it to previous RUM Session
context: crashContext,
hasReplay: lastRUMSessionState.didStartWithReplay
)
case .handleInBackgroundView:
// It means that the crash occurred as the very first event after sending app to background in previous session.
// This is why we don't have the `lastRUMViewEvent` (no view was active), but we know the `lastRUMSessionState`.
newRUMView = createNewRUMViewEvent(
named: RUMOffViewEventsHandlingRule.Constants.backgroundViewName,
url: RUMOffViewEventsHandlingRule.Constants.backgroundViewURL,
startDate: crashTimings.realCrashDate,
sessionUUID: RUMUUID(rawValue: lastRUMSessionState.sessionUUID), // link it to previous RUM Session
context: crashContext,
hasReplay: lastRUMSessionState.didStartWithReplay
)
case .doNotHandle:
DD.logger.debug("There was a crash in background, but it is ignored due to Background Event Tracking disabled or sampling.")
newRUMView = nil
}
if let newRUMView = newRUMView {
send(crashReport: crashReport, to: newRUMView, using: crashTimings)
}
}
/// If the crash occurred before starting RUM session (after initializing SDK, but before starting the first view) we don't have any session UUID to associate the error with.
/// In that case, we consider sending this crash within a new, single-view session: either "ApplicationLaunch" view or "Background" view.
private func sendCrashReportToNewSession(
_ crashReport: DDCrashReport,
crashContext: CrashContext,
using crashTimings: AdjustedCrashTimings
) -> Bool {
let sessionID = uuidGenerator.generateUnique()
let sampled = DeterministicSampler(
uuid: sessionID.rawValue,
samplingRate: sessionSampler.samplingRate
).sample()
guard sampled else {
DD.logger.debug("There was a crash in previous session, but it is ignored due to sampling.")
return false
}
// We can ignore `sessionState` for building the rule as we can assume there was no session sent - otherwise,
// the `lastRUMSessionState` would have been set in `CrashContext` and we could be sending the crash to previous session
// through `sendCrashReportToPreviousSession()`.
let handlingRule = RUMOffViewEventsHandlingRule(
applicationState: nil,
sessionState: nil,
isAppInForeground: crashContext.lastIsAppInForeground,
isBETEnabled: trackBackgroundEvents,
command: nil
)
let newRUMView: RUMViewEvent?
switch handlingRule {
case .handleInApplicationLaunchView:
newRUMView = createNewRUMViewEvent(
named: RUMOffViewEventsHandlingRule.Constants.applicationLaunchViewName,
url: RUMOffViewEventsHandlingRule.Constants.applicationLaunchViewURL,
startDate: crashTimings.realCrashDate,
sessionUUID: sessionID,
context: crashContext,
// As the crash occurred after initializing SDK but before starting the first view,
// we can't know if Session Replay was configured. However, lack of view implies
// that there must be no replay collected:
hasReplay: false
)
case .handleInBackgroundView:
newRUMView = createNewRUMViewEvent(
named: RUMOffViewEventsHandlingRule.Constants.backgroundViewName,
url: RUMOffViewEventsHandlingRule.Constants.backgroundViewURL,
startDate: crashTimings.realCrashDate,
sessionUUID: sessionID,
context: crashContext,
// As the crash occurred after initializing SDK but before starting the first view,
// we can't know if Session Replay was configured. However, lack of view implies
// that there must be no replay collected:
hasReplay: false
)
case .doNotHandle:
DD.logger.debug("There was a crash in background, but it is ignored due to Background Event Tracking disabled.")
newRUMView = nil
}
if let newRUMView = newRUMView {
send(crashReport: crashReport, to: newRUMView, using: crashTimings)
}
return true
}
/// Sends given `CrashReport` by linking it to given `rumView` and updating view counts accordingly.
private func send(crashReport: DDCrashReport, to rumView: RUMViewEvent, using crashTimings: AdjustedCrashTimings) {
DD.logger.debug("Updating RUM view with crash report.")
// crash reporting is considering the user consent from previous session, if an event reached
// the message bus it means that consent was granted and we can safely bypass current consent.
featureScope.eventWriteContext(bypassConsent: true) { context, writer in
let builder = createFatalErrorBuilder(context: context, crash: crashReport, crashDate: crashTimings.realCrashDate, timeSinceAppStart: crashTimings.timeSinceAppStart)
let updatedRUMView = builder.updateRUMViewWithError(rumView)
let rumError = builder.createRUMError(with: updatedRUMView)
if let mappedError = self.eventsMapper.map(event: rumError) {
writer.write(value: self.sanitizer.sanitize(event: mappedError))
} else {
DD.logger.warn("errorEventMapper returned 'nil' for a crash. Discarding crashes is not supported. The unmodified event will be sent.")
writer.write(value: self.sanitizer.sanitize(event: rumError))
}
if let mappedView = self.eventsMapper.map(event: updatedRUMView) {
writer.write(value: self.sanitizer.sanitize(event: mappedView))
}
}
}
// MARK: - Building RUM events
private func createFatalErrorBuilder(context: DatadogContext, crash: DDCrashReport, crashDate: Date, timeSinceAppStart: TimeInterval?) -> FatalErrorBuilder {
return FatalErrorBuilder(
context: context,
error: .crash,
errorUUID: uuidGenerator.generateUnique(),
errorDate: crashDate,
errorType: crash.type,
errorMessage: crash.message,
errorStack: crash.stack,
errorThreads: crash.threads.toRUMDataFormat,
errorBinaryImages: crash.binaryImages.toRUMDataFormat,
errorWasTruncated: crash.wasTruncated,
errorMeta: crash.meta.toRUMDataFormat,
additionalAttributes: crash.additionalAttributes.dd.decode(),
timeSinceAppStart: timeSinceAppStart
)
}
/// Creates new RUM view event.
private func createNewRUMViewEvent(
named viewName: String,
url viewURL: String,
startDate: Date,
sessionUUID: RUMUUID,
context: CrashContext,
hasReplay: Bool?
) -> RUMViewEvent {
let viewUUID = uuidGenerator.generateUnique()
return RUMViewEvent(
dd: .init(
browserSdkVersion: nil,
cls: nil,
configuration: .init(
sessionReplaySampleRate: nil,
sessionSampleRate: Double(self.sessionSampler.samplingRate),
startSessionReplayRecordingManually: nil
),
documentVersion: 1,
pageStates: nil,
replayStats: nil,
session: .init(
plan: .plan1,
sessionPrecondition: nil
)
),
account: context.accountInfo.map { RUMAccount(accountInfo: $0) },
application: .init(
currentLocale: context.device.locale, id: applicationID
),
buildVersion: context.buildNumber,
ciTest: ciTest,
connectivity: RUMConnectivity(
networkInfo: context.networkConnectionInfo,
carrierInfo: context.carrierInfo
),
container: nil,
// RUM-3588: We know that last RUM view is not available, so we're creating a new one. No matter that, try using last
// RUM attributes if available. There is a chance of having them as global RUM attributes can be updated more often than RUM view.
// See https://github.com/DataDog/dd-sdk-ios/pull/1834 for more context.
context: context.lastRUMAttributes,
date: startDate.timeIntervalSince1970.dd.toInt64Milliseconds,
ddtags: context.ddTags,
device: context.device,
display: nil,
// RUMM-2197: In very rare cases, the OS info computed below might not be exactly the one
// that the app crashed on. This would correspond to a scenario when the device OS was upgraded
// before restarting the app after crash. To solve this, the OS information would have to be
// persisted in `crashContext` the same way as we do for other dynamic information.
os: context.os,
privacy: nil,
service: context.service,
session: .init(
hasReplay: hasReplay,
id: sessionUUID.toRUMDataFormat,
isActive: true,
sampledForReplay: nil,
type: ciTest != nil ? .ciTest : (syntheticsTest != nil ? .synthetics : .user)
),
source: .init(rawValue: context.source) ?? .ios,
synthetics: syntheticsTest,
usr: context.userInfo.map { RUMUser(userInfo: $0) },
version: context.version,
view: .init(
action: .init(count: 0),
cpuTicksCount: nil,
cpuTicksPerSecond: nil,
crash: .init(count: 0),
cumulativeLayoutShift: nil,
cumulativeLayoutShiftTargetSelector: nil,
cumulativeLayoutShiftTime: nil,
customTimings: nil,
domComplete: nil,
domContentLoaded: nil,
domInteractive: nil,
error: .init(count: 0),
firstByte: nil,
firstContentfulPaint: nil,
firstInputDelay: nil,
firstInputTargetSelector: nil,
firstInputTime: nil,
flutterBuildTime: nil,
flutterRasterTime: nil,
freezeRate: nil,
frozenFrame: .init(count: 0),
frustration: .init(count: 0),
id: viewUUID.toRUMDataFormat,
inForegroundPeriods: nil,
interactionToNextPaint: nil,
interactionToNextPaintTargetSelector: nil,
interactionToNextPaintTime: nil,
interactionToNextViewTime: nil,
isActive: false, // we know it won't receive updates
isSlowRendered: false,
jsRefreshRate: nil,
largestContentfulPaint: nil,
largestContentfulPaintTargetSelector: nil,
loadEvent: nil,
loadingTime: nil,
loadingType: nil,
longTask: .init(count: 0),
memoryAverage: nil,
memoryMax: nil,
name: viewName,
networkSettledTime: nil,
referrer: nil,
refreshRateAverage: nil,
refreshRateMin: nil,
resource: .init(count: 0),
slowFrames: nil,
slowFramesRate: nil,
timeSpent: 1, // arbitrary, 1ns duration
url: viewURL
)
)
}
}