-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathAppleSentrySubsystem.cpp
474 lines (389 loc) · 18.2 KB
/
AppleSentrySubsystem.cpp
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
// Copyright (c) 2022 Sentry. All Rights Reserved.
#include "AppleSentrySubsystem.h"
#include "SentryBreadcrumbApple.h"
#include "SentryEventApple.h"
#include "SentryScopeApple.h"
#include "SentryUserApple.h"
#include "SentryUserFeedbackApple.h"
#include "SentryTransactionApple.h"
#include "SentryTransactionContextApple.h"
#include "SentrySamplingContextApple.h"
#include "SentryIdApple.h"
#include "SentryBreadcrumb.h"
#include "SentryEvent.h"
#include "SentrySettings.h"
#include "SentryBeforeSendHandler.h"
#include "SentryBeforeBreadcrumbHandler.h"
#include "SentryDefines.h"
#include "SentrySamplingContext.h"
#include "SentryTraceSampler.h"
#include "Infrastructure/SentryConvertersApple.h"
#include "Convenience/SentryInclude.h"
#include "Convenience/SentryMacro.h"
#include "Utils/SentryFileUtils.h"
#include "Utils/SentryLogUtils.h"
#include "GenericPlatform/GenericPlatformOutputDevices.h"
#include "HAL/FileManager.h"
#include "HAL/PlatformSentryAttachment.h"
#include "Misc/CoreDelegates.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "UObject/GarbageCollection.h"
#include "UObject/UObjectThreadContext.h"
void FAppleSentrySubsystem::InitWithSettings(const USentrySettings* settings, USentryBeforeSendHandler* beforeSendHandler, USentryBeforeBreadcrumbHandler* beforeBreadcrumbHandler, USentryTraceSampler* traceSampler)
{
isScreenshotAttachmentEnabled = settings->AttachScreenshot;
isGameLogAttachmentEnabled = settings->EnableAutoLogAttachment;
[SENTRY_APPLE_CLASS(PrivateSentrySDKOnly) setSdkName:@"sentry.cocoa.unreal"];
dispatch_group_t sentryDispatchGroup = dispatch_group_create();
dispatch_group_enter(sentryDispatchGroup);
dispatch_async(dispatch_get_main_queue(), ^{
[SENTRY_APPLE_CLASS(SentrySDK) startWithConfigureOptions:^(SentryOptions *options) {
options.dsn = settings->Dsn.GetNSString();
#if WITH_EDITOR
if(!settings->EditorDsn.IsEmpty()) {
options.dsn = settings->EditorDsn.GetNSString();
}
#endif
options.environment = settings->Environment.GetNSString();
options.enableAutoSessionTracking = settings->EnableAutoSessionTracking;
options.sessionTrackingIntervalMillis = settings->SessionTimeout;
options.releaseName = settings->OverrideReleaseName
? settings->Release.GetNSString()
: settings->GetFormattedReleaseName().GetNSString();
options.attachStacktrace = settings->AttachStacktrace;
options.debug = settings->Debug;
options.sampleRate = [NSNumber numberWithFloat:settings->SampleRate];
options.maxBreadcrumbs = settings->MaxBreadcrumbs;
options.sendDefaultPii = settings->SendDefaultPii;
options.maxAttachmentSize = settings->MaxAttachmentSize;
#if SENTRY_UIKIT_AVAILABLE
options.attachScreenshot = settings->AttachScreenshot;
#endif
options.onCrashedLastRun = ^(SentryEvent* event) {
if (settings->AttachScreenshot)
{
// If a screenshot was captured during assertion/crash in the previous app run
// find the most recent one and upload it to Sentry.
const FString& screenshotPath = GetLatestScreenshot();
if (!screenshotPath.IsEmpty())
{
UploadAttachmentForEvent(MakeShareable(new SentryIdApple(event.eventId)), screenshotPath, TEXT("screenshot.png"), true);
}
}
if(settings->EnableAutoLogAttachment) {
// Unreal creates game log backups automatically on every app run. If logging is enabled for current configuration SDK can
// find the most recent one and upload it to Sentry.
const FString logFilePath = GetLatestGameLog();
if (!logFilePath.IsEmpty())
{
UploadAttachmentForEvent(MakeShareable(new SentryIdApple(event.eventId)), logFilePath, SentryFileUtils::GetGameLogName());
}
}
};
options.beforeSend = ^SentryEvent* (SentryEvent* event) {
if (FUObjectThreadContext::Get().IsRoutingPostLoad)
{
UE_LOG(LogSentrySdk, Log, TEXT("Executing `beforeSend` handler is not allowed when post-loading."));
return event;
}
if (IsGarbageCollecting())
{
// If event is captured during garbage collection we can't instantiate UObjects safely or obtain a GC lock
// since it will cause a deadlock (see https://github.com/getsentry/sentry-unreal/issues/850).
// In this case event will be reported without calling a `beforeSend` handler.
UE_LOG(LogSentrySdk, Log, TEXT("Executing `beforeSend` handler is not allowed during garbage collection."));
return event;
}
USentryEvent* EventToProcess = USentryEvent::Create(MakeShareable(new SentryEventApple(event)));
USentryEvent* ProcessedEvent = beforeSendHandler->HandleBeforeSend(EventToProcess, nullptr);
return ProcessedEvent ? event : nullptr;
};
for (auto it = settings->InAppInclude.CreateConstIterator(); it; ++it)
{
[options addInAppInclude:it->GetNSString()];
}
for (auto it = settings->InAppExclude.CreateConstIterator(); it; ++it)
{
[options addInAppExclude:it->GetNSString()];
}
options.enableAppHangTracking = settings->EnableAppNotRespondingTracking;
if(settings->EnableTracing && settings->SamplingType == ESentryTracesSamplingType::UniformSampleRate)
{
options.tracesSampleRate = [NSNumber numberWithFloat:settings->TracesSampleRate];
}
if(settings->EnableTracing && settings->SamplingType == ESentryTracesSamplingType::TracesSampler)
{
options.tracesSampler = ^NSNumber* (SentrySamplingContext* samplingContext) {
FGCScopeGuard GCScopeGuard;
USentrySamplingContext* Context = USentrySamplingContext::Create(MakeShareable(new SentrySamplingContextApple(samplingContext)));
float samplingValue;
return traceSampler->Sample(Context, samplingValue) ? [NSNumber numberWithFloat:samplingValue] : nil;
};
}
if (beforeBreadcrumbHandler != nullptr)
{
options.beforeBreadcrumb = ^SentryBreadcrumb* (SentryBreadcrumb* breadcrumb) {
if (FUObjectThreadContext::Get().IsRoutingPostLoad)
{
// Don't print to logs within `onBeforeBreadcrumb` handler as this can lead to creating new breadcrumb
return breadcrumb;
}
if (IsGarbageCollecting())
{
// If breadcrumb is added during garbage collection we can't instantiate UObjects safely or obtain a GC lock
// since there is no guarantee it will be ever freed.
// In this case breadcrumb will be added without calling a `beforeBreadcrumb` handler.
return breadcrumb;
}
USentryBreadcrumb* BreadcrumbToProcess = USentryBreadcrumb::Create(MakeShareable(new SentryBreadcrumbApple(breadcrumb)));
USentryBreadcrumb* ProcessedBreadcrumb = beforeBreadcrumbHandler->HandleBeforeBreadcrumb(BreadcrumbToProcess, nullptr);
return ProcessedBreadcrumb ? breadcrumb : nullptr;
};
}
}];
dispatch_group_leave(sentryDispatchGroup);
});
// Wait synchronously until sentry-cocoa initialization finished in main thread
dispatch_group_wait(sentryDispatchGroup, DISPATCH_TIME_FOREVER);
dispatch_release(sentryDispatchGroup);
}
void FAppleSentrySubsystem::Close()
{
[SENTRY_APPLE_CLASS(SentrySDK) close];
}
bool FAppleSentrySubsystem::IsEnabled()
{
return [SENTRY_APPLE_CLASS(SentrySDK) isEnabled];
}
ESentryCrashedLastRun FAppleSentrySubsystem::IsCrashedLastRun()
{
return [SENTRY_APPLE_CLASS(SentrySDK) crashedLastRun] ? ESentryCrashedLastRun::Crashed : ESentryCrashedLastRun::NotCrashed;
}
void FAppleSentrySubsystem::AddBreadcrumb(TSharedPtr<ISentryBreadcrumb> breadcrumb)
{
TSharedPtr<SentryBreadcrumbApple> breadcrumbIOS = StaticCastSharedPtr<SentryBreadcrumbApple>(breadcrumb);
[SENTRY_APPLE_CLASS(SentrySDK) addBreadcrumb:breadcrumbIOS->GetNativeObject()];
}
void FAppleSentrySubsystem::AddBreadcrumbWithParams(const FString& Message, const FString& Category, const FString& Type, const TMap<FString, FString>& Data, ESentryLevel Level)
{
TSharedPtr<SentryBreadcrumbApple> breadcrumbIOS = MakeShareable(new SentryBreadcrumbApple());
breadcrumbIOS->SetMessage(Message);
breadcrumbIOS->SetCategory(Category);
breadcrumbIOS->SetType(Type);
breadcrumbIOS->SetData(Data);
breadcrumbIOS->SetLevel(Level);
[SENTRY_APPLE_CLASS(SentrySDK) addBreadcrumb:breadcrumbIOS->GetNativeObject()];
}
void FAppleSentrySubsystem::ClearBreadcrumbs()
{
[SENTRY_APPLE_CLASS(SentrySDK) configureScope:^(SentryScope* scope) {
[scope clearBreadcrumbs];
}];
}
TSharedPtr<ISentryId> FAppleSentrySubsystem::CaptureMessage(const FString& message, ESentryLevel level)
{
FSentryScopeDelegate onConfigureScope;
return CaptureMessageWithScope(message, onConfigureScope, level);
}
TSharedPtr<ISentryId> FAppleSentrySubsystem::CaptureMessageWithScope(const FString& message, const FSentryScopeDelegate& onConfigureScope, ESentryLevel level)
{
SentryId* id = [SENTRY_APPLE_CLASS(SentrySDK) captureMessage:message.GetNSString() withScopeBlock:^(SentryScope* scope){
[scope setLevel:SentryConvertersApple::SentryLevelToNative(level)];
if(isGameLogAttachmentEnabled) {
const FString logFilePath = GetGameLogPath();
SentryAttachment* logAttachment = [[SENTRY_APPLE_CLASS(SentryAttachment) alloc] initWithPath:logFilePath.GetNSString()];
[scope addAttachment:logAttachment];
}
onConfigureScope.ExecuteIfBound(MakeShareable(new SentryScopeApple(scope)));
}];
return MakeShareable(new SentryIdApple(id));
}
TSharedPtr<ISentryId> FAppleSentrySubsystem::CaptureEvent(TSharedPtr<ISentryEvent> event)
{
FSentryScopeDelegate onConfigureScope;
return CaptureEventWithScope(event, onConfigureScope);
}
TSharedPtr<ISentryId> FAppleSentrySubsystem::CaptureEventWithScope(TSharedPtr<ISentryEvent> event, const FSentryScopeDelegate& onConfigureScope)
{
TSharedPtr<SentryEventApple> eventIOS = StaticCastSharedPtr<SentryEventApple>(event);
SentryId* id = [SENTRY_APPLE_CLASS(SentrySDK) captureEvent:eventIOS->GetNativeObject() withScopeBlock:^(SentryScope* scope) {
if(isGameLogAttachmentEnabled) {
const FString logFilePath = GetGameLogPath();
SentryAttachment* logAttachment = [[SENTRY_APPLE_CLASS(SentryAttachment) alloc] initWithPath:logFilePath.GetNSString()];
[scope addAttachment:logAttachment];
}
onConfigureScope.ExecuteIfBound(MakeShareable(new SentryScopeApple(scope)));
}];
return MakeShareable(new SentryIdApple(id));
}
TSharedPtr<ISentryId> FAppleSentrySubsystem::CaptureEnsure(const FString& type, const FString& message)
{
SentryException *nativeException = [[SENTRY_APPLE_CLASS(SentryException) alloc] initWithValue:message.GetNSString() type:type.GetNSString()];
NSMutableArray *nativeExceptionArray = [NSMutableArray arrayWithCapacity:1];
[nativeExceptionArray addObject:nativeException];
SentryEvent *exceptionEvent = [[SENTRY_APPLE_CLASS(SentryEvent) alloc] init];
exceptionEvent.exceptions = nativeExceptionArray;
SentryId* id = [SENTRY_APPLE_CLASS(SentrySDK) captureEvent:exceptionEvent withScopeBlock:^(SentryScope* scope) {
if(isGameLogAttachmentEnabled) {
const FString logFilePath = GetGameLogPath();
SentryAttachment* logAttachment = [[SENTRY_APPLE_CLASS(SentryAttachment) alloc] initWithPath:logFilePath.GetNSString()];
[scope addAttachment:logAttachment];
}
}];
return MakeShareable(new SentryIdApple(id));
}
void FAppleSentrySubsystem::CaptureUserFeedback(TSharedPtr<ISentryUserFeedback> userFeedback)
{
TSharedPtr<SentryUserFeedbackApple> userFeedbackIOS = StaticCastSharedPtr<SentryUserFeedbackApple>(userFeedback);
[SENTRY_APPLE_CLASS(SentrySDK) captureFeedback:userFeedbackIOS->GetNativeObject()];
}
void FAppleSentrySubsystem::SetUser(TSharedPtr<ISentryUser> user)
{
TSharedPtr<SentryUserApple> userIOS = StaticCastSharedPtr<SentryUserApple>(user);
[SENTRY_APPLE_CLASS(SentrySDK) setUser:userIOS->GetNativeObject()];
}
void FAppleSentrySubsystem::RemoveUser()
{
[SENTRY_APPLE_CLASS(SentrySDK) setUser:nil];
}
void FAppleSentrySubsystem::ConfigureScope(const FSentryScopeDelegate& onConfigureScope)
{
[SENTRY_APPLE_CLASS(SentrySDK) configureScope:^(SentryScope* scope) {
onConfigureScope.ExecuteIfBound(MakeShareable(new SentryScopeApple(scope)));
}];
}
void FAppleSentrySubsystem::SetContext(const FString& key, const TMap<FString, FString>& values)
{
[SENTRY_APPLE_CLASS(SentrySDK) configureScope:^(SentryScope* scope) {
[scope setContextValue:SentryConvertersApple::StringMapToNative(values) forKey:key.GetNSString()];
}];
}
void FAppleSentrySubsystem::SetTag(const FString& key, const FString& value)
{
[SENTRY_APPLE_CLASS(SentrySDK) configureScope:^(SentryScope* scope) {
[scope setTagValue:value.GetNSString() forKey:key.GetNSString()];
}];
}
void FAppleSentrySubsystem::RemoveTag(const FString& key)
{
[SENTRY_APPLE_CLASS(SentrySDK) configureScope:^(SentryScope* scope) {
[scope removeTagForKey:key.GetNSString()];
}];
}
void FAppleSentrySubsystem::SetLevel(ESentryLevel level)
{
[SENTRY_APPLE_CLASS(SentrySDK) configureScope:^(SentryScope* scope) {
[scope setLevel:SentryConvertersApple::SentryLevelToNative(level)];
}];
}
void FAppleSentrySubsystem::StartSession()
{
[SENTRY_APPLE_CLASS(SentrySDK) startSession];
}
void FAppleSentrySubsystem::EndSession()
{
[SENTRY_APPLE_CLASS(SentrySDK) endSession];
}
TSharedPtr<ISentryTransaction> FAppleSentrySubsystem::StartTransaction(const FString& name, const FString& operation)
{
id<SentrySpan> transaction = [SENTRY_APPLE_CLASS(SentrySDK) startTransactionWithName:name.GetNSString() operation:operation.GetNSString()];
return MakeShareable(new SentryTransactionApple(transaction));
}
TSharedPtr<ISentryTransaction> FAppleSentrySubsystem::StartTransactionWithContext(TSharedPtr<ISentryTransactionContext> context)
{
TSharedPtr<SentryTransactionContextApple> transactionContextIOS = StaticCastSharedPtr<SentryTransactionContextApple>(context);
id<SentrySpan> transaction = [SENTRY_APPLE_CLASS(SentrySDK) startTransactionWithContext:transactionContextIOS->GetNativeObject()];
return MakeShareable(new SentryTransactionApple(transaction));
}
TSharedPtr<ISentryTransaction> FAppleSentrySubsystem::StartTransactionWithContextAndTimestamp(TSharedPtr<ISentryTransactionContext> context, int64 timestamp)
{
UE_LOG(LogSentrySdk, Log, TEXT("Setting transaction timestamp explicitly not supported on Mac/iOS."));
return StartTransactionWithContext(context);
}
TSharedPtr<ISentryTransaction> FAppleSentrySubsystem::StartTransactionWithContextAndOptions(TSharedPtr<ISentryTransactionContext> context, const TMap<FString, FString>& options)
{
TSharedPtr<SentryTransactionContextApple> transactionContextIOS = StaticCastSharedPtr<SentryTransactionContextApple>(context);
id<SentrySpan> transaction = [SENTRY_APPLE_CLASS(SentrySDK) startTransactionWithContext:transactionContextIOS->GetNativeObject()
customSamplingContext:SentryConvertersApple::StringMapToNative(options)];
return MakeShareable(new SentryTransactionApple(transaction));
}
TSharedPtr<ISentryTransactionContext> FAppleSentrySubsystem::ContinueTrace(const FString& sentryTrace, const TArray<FString>& baggageHeaders)
{
TArray<FString> traceParts;
sentryTrace.ParseIntoArray(traceParts, TEXT("-"));
if (traceParts.Num() < 2)
{
return nullptr;
}
SentrySampleDecision sampleDecision = kSentrySampleDecisionUndecided;
if (traceParts.Num() == 3)
{
sampleDecision = traceParts[2].Equals(TEXT("1")) ? kSentrySampleDecisionYes : kSentrySampleDecisionNo;
}
// `SentryId` definition was moved to Swift so its name that can be recognized by UE should be taken from "Sentry-Swift.h" to successfully load class on Mac
#if PLATFORM_MAC
SentryId* traceId = [[SENTRY_APPLE_CLASS(_TtC6Sentry8SentryId) alloc] initWithUUIDString:traceParts[0].GetNSString()];
#elif PLATFORM_IOS
SentryId* traceId = [[SENTRY_APPLE_CLASS(SentryId) alloc] initWithUUIDString:traceParts[0].GetNSString()];
#endif
SentryTransactionContext* transactionContext = [[SENTRY_APPLE_CLASS(SentryTransactionContext) alloc] initWithName:@"<unlabeled transaction>" operation:@"default"
traceId:traceId
spanId:[[SENTRY_APPLE_CLASS(SentrySpanId) alloc] init]
parentSpanId:[[SENTRY_APPLE_CLASS(SentrySpanId) alloc] initWithValue:traceParts[1].GetNSString()]
parentSampled:sampleDecision
parentSampleRate:nil
parentSampleRand:nil];
// currently `sentry-cocoa` doesn't have API for `SentryTransactionContext` to set `baggageHeaders`
return MakeShareable(new SentryTransactionContextApple(transactionContext));
}
void FAppleSentrySubsystem::UploadAttachmentForEvent(TSharedPtr<ISentryId> eventId, const FString& filePath, const FString& name, bool deleteAfterUpload) const
{
IFileManager& fileManager = IFileManager::Get();
if (!fileManager.FileExists(*filePath))
{
UE_LOG(LogSentrySdk, Error, TEXT("Failed to upload attachment - file path provided did not exist: %s"), *filePath);
return;
}
const FString& filePathExt = fileManager.ConvertToAbsolutePathForExternalAppForRead(*filePath);
SentryAttachment* screenshotAttachment = [[SENTRY_APPLE_CLASS(SentryAttachment) alloc] initWithPath:filePathExt.GetNSString() filename:name.GetNSString()];
SentryOptions* options = [SENTRY_APPLE_CLASS(PrivateSentrySDKOnly) options];
int32 size = options.maxAttachmentSize;
SentryEnvelopeItem* envelopeItem = [[SENTRY_APPLE_CLASS(SentryEnvelopeItem) alloc] initWithAttachment:screenshotAttachment maxAttachmentSize:size];
SentryId* id = StaticCastSharedPtr<SentryIdApple>(eventId)->GetNativeObject();
SentryEnvelope* envelope = [[SENTRY_APPLE_CLASS(SentryEnvelope) alloc] initWithId:id singleItem:envelopeItem];
[SENTRY_APPLE_CLASS(PrivateSentrySDKOnly) captureEnvelope:envelope];
if (deleteAfterUpload)
{
if (!fileManager.Delete(*filePath))
{
UE_LOG(LogSentrySdk, Error, TEXT("Failed to delete file attachment after upload: %s"), *filePath);
}
}
}
FString FAppleSentrySubsystem::GetScreenshotPath() const
{
return FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("SentryScreenshots"), FString::Printf(TEXT("screenshot-%s.png"), *FDateTime::Now().ToString()));
}
FString FAppleSentrySubsystem::GetLatestScreenshot() const
{
const FString& ScreenshotsDir = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("SentryScreenshots"));
TArray<FString> Screenshots;
IFileManager::Get().FindFiles(Screenshots, *ScreenshotsDir, TEXT("*.png"));
if(Screenshots.Num() == 0)
{
UE_LOG(LogSentrySdk, Log, TEXT("There are no screenshots found."));
return FString("");
}
for (int i = 0; i < Screenshots.Num(); ++i)
{
Screenshots[i] = ScreenshotsDir / Screenshots[i];
}
Screenshots.Sort([](const FString& A, const FString& B)
{
const FDateTime TimestampA = IFileManager::Get().GetTimeStamp(*A);
const FDateTime TimestampB = IFileManager::Get().GetTimeStamp(*B);
return TimestampB < TimestampA;
});
return Screenshots[0];
}