-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
SentryFlutterPluginApple.swift
628 lines (524 loc) · 20.7 KB
/
SentryFlutterPluginApple.swift
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
import Sentry
#if os(iOS)
import Flutter
import UIKit
#elseif os(macOS)
import FlutterMacOS
import AppKit
#endif
// swiftlint:disable file_length
// swiftlint:disable:next type_body_length
public class SentryFlutterPluginApple: NSObject, FlutterPlugin {
private var sentryOptions: Options?
// The Cocoa SDK is init. after the notification didBecomeActiveNotification is registered.
// We need to be able to receive this notification and start a session when the SDK is fully operational.
private var didReceiveDidBecomeActiveNotification = false
private var didBecomeActiveNotificationName: NSNotification.Name {
#if os(iOS)
return UIApplication.didBecomeActiveNotification
#elseif os(macOS)
return NSApplication.didBecomeActiveNotification
#endif
}
public static func register(with registrar: FlutterPluginRegistrar) {
#if os(iOS)
let channel = FlutterMethodChannel(name: "sentry_flutter", binaryMessenger: registrar.messenger())
#elseif os(macOS)
let channel = FlutterMethodChannel(name: "sentry_flutter", binaryMessenger: registrar.messenger)
#endif
let instance = SentryFlutterPluginApple()
instance.registerObserver()
registrar.addMethodCallDelegate(instance, channel: channel)
}
private func registerObserver() {
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidBecomeActive),
name: didBecomeActiveNotificationName,
object: nil)
}
@objc private func applicationDidBecomeActive() {
didReceiveDidBecomeActiveNotification = true
// we only need to do that in the 1st time, so removing it
NotificationCenter.default.removeObserver(self,
name: didBecomeActiveNotificationName,
object: nil)
}
// swiftlint:disable:next cyclomatic_complexity function_body_length
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method as String {
case "loadContexts":
loadContexts(result: result)
case "loadImageList":
loadImageList(result: result)
case "initNativeSdk":
initNativeSdk(call, result: result)
case "closeNativeSdk":
closeNativeSdk(call, result: result)
case "captureEnvelope":
captureEnvelope(call, result: result)
case "fetchNativeAppStart":
fetchNativeAppStart(result: result)
case "beginNativeFrames":
beginNativeFrames(result: result)
case "endNativeFrames":
endNativeFrames(result: result)
case "setContexts":
let arguments = call.arguments as? [String: Any?]
let key = arguments?["key"] as? String
let value = arguments?["value"] as? Any
setContexts(key: key, value: value, result: result)
case "setUser":
let arguments = call.arguments as? [String: Any?]
let user = arguments?["user"] as? [String: Any?]
setUser(user: user, result: result)
case "addBreadcrumb":
let arguments = call.arguments as? [String: Any?]
let breadcrumb = arguments?["breadcrumb"] as? [String: Any?]
addBreadcrumb(breadcrumb: breadcrumb, result: result)
case "clearBreadcrumbs":
clearBreadcrumbs(result: result)
case "setExtra":
let arguments = call.arguments as? [String: Any?]
let key = arguments?["key"] as? String
let value = arguments?["value"] as? Any
setExtra(key: key, value: value, result: result)
case "removeExtra":
let arguments = call.arguments as? [String: Any?]
let key = arguments?["key"] as? String
removeExtra(key: key, result: result)
case "setTag":
let arguments = call.arguments as? [String: Any?]
let key = arguments?["key"] as? String
let value = arguments?["value"] as? String
setTag(key: key, value: value, result: result)
case "removeTag":
let arguments = call.arguments as? [String: Any?]
let key = arguments?["key"] as? String
removeTag(key: key, result: result)
default:
result(FlutterMethodNotImplemented)
}
}
// swiftlint:disable:next cyclomatic_complexity
private func loadContexts(result: @escaping FlutterResult) {
SentrySDK.configureScope { scope in
let serializedScope = scope.serialize()
let context = serializedScope["context"]
var infos = ["contexts": context]
if let tags = serializedScope["tags"] as? [String: String] {
infos["tags"] = tags
}
if let extra = serializedScope["extra"] as? [String: Any] {
infos["extra"] = extra
}
if let user = serializedScope["user"] as? [String: Any] {
infos["user"] = user
}
if let dist = serializedScope["dist"] as? String {
infos["dist"] = dist
}
if let environment = serializedScope["environment"] as? String {
infos["environment"] = environment
}
if let fingerprint = serializedScope["fingerprint"] as? [String] {
infos["fingerprint"] = fingerprint
}
if let level = serializedScope["level"] as? String {
infos["level"] = level
}
if let breadcrumbs = serializedScope["breadcrumbs"] as? [[String: Any]] {
infos["breadcrumbs"] = breadcrumbs
}
if let user = serializedScope["user"] as? [String: Any] {
infos["user"] = user
} else {
infos["user"] = ["id": PrivateSentrySDKOnly.installationID]
}
if let integrations = self.sentryOptions?.integrations {
infos["integrations"] = integrations
}
if let sdkInfo = self.sentryOptions?.sdkInfo {
infos["package"] = ["version": sdkInfo.version, "sdk_name": "cocoapods:sentry-cocoa"]
}
result(infos)
}
}
private func loadImageList(result: @escaping FlutterResult) {
let debugImages = PrivateSentrySDKOnly.getDebugImages() as [DebugMeta]
result(debugImages.map { $0.serialize() })
}
private func initNativeSdk(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let arguments = call.arguments as? [String: Any], !arguments.isEmpty else {
print("Arguments is null or empty")
result(FlutterError(code: "4", message: "Arguments is null or empty", details: nil))
return
}
SentrySDK.start { options in
self.updateOptions(arguments: arguments, options: options)
if arguments["enableAutoPerformanceTracking"] as? Bool ?? false {
PrivateSentrySDKOnly.appStartMeasurementHybridSDKMode = true
#if os(iOS) || targetEnvironment(macCatalyst)
PrivateSentrySDKOnly.framesTrackingMeasurementHybridSDKMode = true
#endif
}
self.sentryOptions = options
// note : for now, in sentry-cocoa, beforeSend is not called before captureEnvelope
options.beforeSend = { event in
self.setEventOriginTag(event: event)
if var sdk = event.sdk, self.isValidSdk(sdk: sdk) {
if let packages = arguments["packages"] as? [String] {
if var sdkPackages = sdk["packages"] as? [String] {
sdk["packages"] = sdkPackages.append(contentsOf: packages)
} else {
sdk["packages"] = packages
}
}
if let integrations = arguments["integrations"] as? [String] {
if var sdkIntegrations = sdk["integrations"] as? [String] {
sdk["integrations"] = sdkIntegrations.append(contentsOf: integrations)
} else {
sdk["integrations"] = integrations
}
}
event.sdk = sdk
}
return event
}
}
if didReceiveDidBecomeActiveNotification &&
(sentryOptions?.enableAutoSessionTracking == true || sentryOptions?.enableOutOfMemoryTracking == true) {
// We send a SentryHybridSdkDidBecomeActive to the Sentry Cocoa SDK, so the SDK will mimics
// the didBecomeActiveNotification notification. This is needed for session and OOM tracking.
NotificationCenter.default.post(name: Notification.Name("SentryHybridSdkDidBecomeActive"), object: nil)
// we reset the flag for the sake of correctness
didReceiveDidBecomeActiveNotification = false
}
result("")
}
private func closeNativeSdk(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
SentrySDK.close()
result("")
}
// swiftlint:disable:next cyclomatic_complexity
private func updateOptions(arguments: [String: Any], options: Options) {
if let dsn = arguments["dsn"] as? String {
options.dsn = dsn
}
if let isDebug = arguments["debug"] as? Bool {
options.debug = isDebug
}
if let environment = arguments["environment"] as? String {
options.environment = environment
}
if let releaseName = arguments["release"] as? String {
options.releaseName = releaseName
}
if let enableAutoSessionTracking = arguments["enableAutoSessionTracking"] as? Bool {
options.enableAutoSessionTracking = enableAutoSessionTracking
}
if let attachStacktrace = arguments["attachStacktrace"] as? Bool {
options.attachStacktrace = attachStacktrace
}
if let diagnosticLevel = arguments["diagnosticLevel"] as? String, options.debug == true {
options.diagnosticLevel = logLevelFrom(diagnosticLevel: diagnosticLevel)
}
if let sessionTrackingIntervalMillis = arguments["autoSessionTrackingIntervalMillis"] as? UInt {
options.sessionTrackingIntervalMillis = sessionTrackingIntervalMillis
}
if let dist = arguments["dist"] as? String {
options.dist = dist
}
if let enableAutoNativeBreadcrumbs = arguments["enableAutoNativeBreadcrumbs"] as? Bool,
enableAutoNativeBreadcrumbs == false {
options.integrations = options.integrations?.filter { (name) -> Bool in
name != "SentryAutoBreadcrumbTrackingIntegration"
}
}
if let enableNativeCrashHandling = arguments["enableNativeCrashHandling"] as? Bool,
enableNativeCrashHandling == false {
options.integrations = options.integrations?.filter { (name) -> Bool in
name != "SentryCrashIntegration"
}
}
if let maxBreadcrumbs = arguments["maxBreadcrumbs"] as? UInt {
options.maxBreadcrumbs = maxBreadcrumbs
}
if let sendDefaultPii = arguments["sendDefaultPii"] as? Bool {
options.sendDefaultPii = sendDefaultPii
}
if let maxCacheItems = arguments["maxCacheItems"] as? UInt {
options.maxCacheItems = maxCacheItems
}
if let enableOutOfMemoryTracking = arguments["enableOutOfMemoryTracking"] as? Bool {
options.enableOutOfMemoryTracking = enableOutOfMemoryTracking
}
if let sendClientReports = arguments["sendClientReports"] as? Bool {
options.sendClientReports = sendClientReports
}
}
private func logLevelFrom(diagnosticLevel: String) -> SentryLevel {
switch diagnosticLevel {
case "fatal":
return .fatal
case "error":
return .error
case "debug":
return .debug
case "warning":
return .warning
case "info":
return .info
default:
return .none
}
}
private func setEventOriginTag(event: Event) {
guard let sdk = event.sdk else {
return
}
if isValidSdk(sdk: sdk) {
switch sdk["name"] as? String {
case "sentry.cocoa":
#if os(OSX)
let origin = "mac"
#elseif os(watchOS)
let origin = "watch"
#elseif os(tvOS)
let origin = "tv"
#elseif os(iOS)
#if targetEnvironment(macCatalyst)
let origin = "macCatalyst"
#else
let origin = "ios"
#endif
#endif
setEventEnvironmentTag(event: event, origin: origin, environment: "native")
default:
return
}
}
}
private func setEventEnvironmentTag(event: Event, origin: String, environment: String) {
event.tags?["event.origin"] = origin
event.tags?["event.environment"] = environment
}
private func isValidSdk(sdk: [String: Any]) -> Bool {
guard let name = sdk["name"] as? String else {
return false
}
return !name.isEmpty
}
private func captureEnvelope(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let arguments = call.arguments as? [Any],
!arguments.isEmpty,
let data = (arguments.first as? FlutterStandardTypedData)?.data else {
print("Envelope is null or empty !")
result(FlutterError(code: "2", message: "Envelope is null or empty", details: nil))
return
}
guard let envelope = PrivateSentrySDKOnly.envelope(with: data) else {
print("Cannot parse the envelope data")
result(FlutterError(code: "3", message: "Cannot parse the envelope data", details: nil))
return
}
PrivateSentrySDKOnly.capture(envelope)
result("")
return
}
private func fetchNativeAppStart(result: @escaping FlutterResult) {
guard let appStartMeasurement = PrivateSentrySDKOnly.appStartMeasurement else {
print("warning: appStartMeasurement is null")
result(nil)
return
}
let appStartTime = appStartMeasurement.appStartTimestamp.timeIntervalSince1970 * 1000
let isColdStart = appStartMeasurement.type == .cold
let item: [String: Any] = [
"appStartTime": appStartTime,
"isColdStart": isColdStart
]
result(item)
}
private var totalFrames: UInt = 0
private var frozenFrames: UInt = 0
private var slowFrames: UInt = 0
private func beginNativeFrames(result: @escaping FlutterResult) {
#if os(iOS) || targetEnvironment(macCatalyst)
guard PrivateSentrySDKOnly.isFramesTrackingRunning else {
print("Native frames tracking not running.")
result(nil)
return
}
let currentFrames = PrivateSentrySDKOnly.currentScreenFrames
totalFrames = currentFrames.total
frozenFrames = currentFrames.frozen
slowFrames = currentFrames.slow
result(nil)
#else
result(nil)
#endif
}
private func endNativeFrames(result: @escaping FlutterResult) {
#if os(iOS) || targetEnvironment(macCatalyst)
guard PrivateSentrySDKOnly.isFramesTrackingRunning else {
print("Native frames tracking not running.")
result(nil)
return
}
let currentFrames = PrivateSentrySDKOnly.currentScreenFrames
let total = currentFrames.total - totalFrames
let frozen = currentFrames.frozen - frozenFrames
let slow = currentFrames.slow - slowFrames
if total <= 0 && frozen <= 0 && slow <= 0 {
result(nil)
return
}
let item: [String: Any] = [
"totalFrames": total,
"frozenFrames": frozen,
"slowFrames": slow
]
result(item)
#else
result(nil)
#endif
}
private func setContexts(key: String?, value: Any?, result: @escaping FlutterResult) {
guard let key = key else {
result("")
return
}
SentrySDK.configureScope { scope in
if let dictionary = value as? [String: Any] {
scope.setContext(value: dictionary, key: key)
} else if let string = value as? String {
scope.setContext(value: ["value": string], key: key)
} else if let int = value as? Int {
scope.setContext(value: ["value": int], key: key)
} else if let double = value as? Double {
scope.setContext(value: ["value": double], key: key)
} else if let bool = value as? Bool {
scope.setContext(value: ["value": bool], key: key)
}
result("")
}
}
private func removeContexts(key: String?, result: @escaping FlutterResult) {
guard let key = key else {
result("")
return
}
SentrySDK.configureScope { scope in
scope.removeContext(key: key)
result("")
}
}
private func setUser(user: [String: Any?]?, result: @escaping FlutterResult) {
if let user = user {
let userInstance = User()
if let email = user["email"] as? String {
userInstance.email = email
}
if let id = user["id"] as? String {
userInstance.userId = id
}
if let username = user["username"] as? String {
userInstance.username = username
}
if let ipAddress = user["ip_address"] as? String {
userInstance.ipAddress = ipAddress
}
if let extras = user["extras"] as? [String: Any] {
userInstance.data = extras
}
SentrySDK.setUser(userInstance)
} else {
SentrySDK.setUser(nil)
}
result("")
}
// swiftlint:disable:next cyclomatic_complexity
private func addBreadcrumb(breadcrumb: [String: Any?]?, result: @escaping FlutterResult) {
guard let breadcrumb = breadcrumb else {
result("")
return
}
let breadcrumbInstance = Breadcrumb()
if let message = breadcrumb["message"] as? String {
breadcrumbInstance.message = message
}
if let type = breadcrumb["type"] as? String {
breadcrumbInstance.type = type
}
if let category = breadcrumb["category"] as? String {
breadcrumbInstance.category = category
}
if let level = breadcrumb["level"] as? String {
switch level {
case "fatal":
breadcrumbInstance.level = SentryLevel.fatal
case "warning":
breadcrumbInstance.level = SentryLevel.warning
case "info":
breadcrumbInstance.level = SentryLevel.info
case "debug":
breadcrumbInstance.level = SentryLevel.debug
case "error":
breadcrumbInstance.level = SentryLevel.error
default:
breadcrumbInstance.level = SentryLevel.error
}
}
if let data = breadcrumb["data"] as? [String: Any] {
breadcrumbInstance.data = data
}
SentrySDK.addBreadcrumb(crumb: breadcrumbInstance)
result("")
}
private func clearBreadcrumbs(result: @escaping FlutterResult) {
SentrySDK.configureScope { scope in
scope.clearBreadcrumbs()
result("")
}
}
private func setExtra(key: String?, value: Any?, result: @escaping FlutterResult) {
guard let key = key else {
result("")
return
}
SentrySDK.configureScope { scope in
scope.setExtra(value: value, key: key)
result("")
}
}
private func removeExtra(key: String?, result: @escaping FlutterResult) {
guard let key = key else {
result("")
return
}
SentrySDK.configureScope { scope in
scope.removeExtra(key: key)
result("")
}
}
private func setTag(key: String?, value: String?, result: @escaping FlutterResult) {
guard let key = key, let value = value else {
result("")
return
}
SentrySDK.configureScope { scope in
scope.setTag(value: value, key: key)
result("")
}
}
private func removeTag(key: String?, result: @escaping FlutterResult) {
guard let key = key else {
result("")
return
}
SentrySDK.configureScope { scope in
scope.removeTag(key: key)
result("")
}
}
}