-
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathSentryJava.cs
More file actions
534 lines (479 loc) · 18.2 KB
/
SentryJava.cs
File metadata and controls
534 lines (479 loc) · 18.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
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
using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Threading;
using Sentry.Extensibility;
using UnityEngine;
namespace Sentry.Unity.Android;
internal interface ISentryJava
{
public bool? IsEnabled();
public void Init(SentryUnityOptions options);
public string? GetInstallationId();
public bool? CrashedLastRun();
public void Close();
public void WriteScope(
string? AppStartTime,
string? AppBuildType,
int? GpuId,
string? GpuName,
string? GpuVendorName,
int? GpuMemorySize,
string? GpuNpotSupport,
string? GpuVersion,
string? GpuApiType,
int? GpuMaxTextureSize,
bool? GpuSupportsDrawCallInstancing,
bool? GpuSupportsRayTracing,
bool? GpuSupportsComputeShaders,
bool? GpuSupportsGeometryShaders,
string? GpuVendorId,
bool? GpuMultiThreadedRendering,
string? GpuGraphicsShaderLevel);
public bool IsSentryJavaPresent();
// Methods for the ScopeObserver
public void AddBreadcrumb(Breadcrumb breadcrumb);
public void SetExtra(string key, string? value);
public void SetTag(string key, string? value);
public void UnsetTag(string key);
public void SetUser(SentryUser user);
public void UnsetUser();
public void SetTrace(SentryId traceId, SpanId spanId);
void AddAttachment(string path, string fileName, string? contentType);
void AddAttachmentBytes(byte[] data, string fileName, string? contentType);
void ClearAttachments();
}
/// <summary>
/// JNI access to `sentry-java` methods.
/// </summary>
/// <remarks>
/// The `sentry-java` SDK on Android is brought in through the `sentry-android-core`
/// and `sentry-java` maven packages.
/// </remarks>
/// <see href="https://github.com/getsentry/sentry-java"/>
internal class SentryJava : ISentryJava
{
private readonly IAndroidJNI _androidJNI;
private readonly IDiagnosticLogger? _logger;
private readonly CancellationTokenSource _scopeSyncShutdownSource;
private readonly AutoResetEvent _scopeSyncEvent;
private readonly Thread _scopeSyncThread;
private readonly ConcurrentQueue<(Action action, string actionName)> _scopeSyncItems = new();
private volatile bool _closed;
private static AndroidJavaObject GetInternalSentryJava() => new AndroidJavaClass("io.sentry.android.core.InternalSentrySdk");
private static AndroidJavaObject GetSentryJava() => new AndroidJavaClass("io.sentry.Sentry");
public SentryJava(IDiagnosticLogger? logger, IAndroidJNI? androidJNI = null)
{
_logger = logger;
_androidJNI ??= androidJNI ?? AndroidJNIAdapter.Instance;
_scopeSyncEvent = new AutoResetEvent(false);
_scopeSyncShutdownSource = new CancellationTokenSource();
_scopeSyncThread = new Thread(SyncScope) { IsBackground = true, Name = "SentryScopeSyncWorkerThread" };
_scopeSyncThread.Start();
}
public bool? IsEnabled()
{
if (!MainThreadData.IsMainThread())
{
_logger?.LogError("Calling IsEnabled() on Android SDK requires running on MainThread");
return null;
}
try
{
using var sentry = GetSentryJava();
return sentry.CallStatic<bool>("isEnabled");
}
catch (Exception e)
{
_logger?.LogError(e, "Calling 'SentryJava.IsEnabled' failed.");
}
return null;
}
public void Init(SentryUnityOptions options)
{
if (!MainThreadData.IsMainThread())
{
_logger?.LogError("Calling Init() on Android SDK requires running on MainThread");
return;
}
try
{
using var sentry = new AndroidJavaClass("io.sentry.android.core.SentryAndroid");
using var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
using var context = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
sentry.CallStatic("init", context, new AndroidOptionsConfiguration(androidOptions =>
{
androidOptions.Call("setDsn", options.Dsn);
androidOptions.Call("setDebug", options.Debug);
androidOptions.Call("setRelease", options.Release);
androidOptions.Call("setDist", options.Distribution);
androidOptions.Call("setEnvironment", options.Environment);
using var sentryLevelClass = new AndroidJavaClass("io.sentry.SentryLevel");
var levelString = GetLevelString(options.DiagnosticLevel);
using var sentryLevel = sentryLevelClass.GetStatic<AndroidJavaObject>(levelString);
androidOptions.Call("setDiagnosticLevel", sentryLevel);
if (options.SampleRate.HasValue)
{
androidOptions.SetIfNotNull("setSampleRate", options.SampleRate.Value);
}
androidOptions.Call("setMaxBreadcrumbs", options.MaxBreadcrumbs);
androidOptions.Call("setMaxCacheItems", options.MaxCacheItems);
androidOptions.Call("setSendDefaultPii", options.SendDefaultPii);
androidOptions.Call("setEnableNdk", options.NdkIntegrationEnabled);
androidOptions.Call("setEnableScopeSync", options.NdkScopeSyncEnabled);
androidOptions.Call("setNativeSdkName", "sentry.native.android.unity");
// Options that are not to be set by the user
// We're disabling some integrations as to not duplicate event or because the SDK relies on the .NET SDK
// implementation of certain feature - i.e. Session Tracking
// Note: doesn't work - produces a blank (white) screenshot
androidOptions.Call("setAttachScreenshot", false);
androidOptions.Call("setEnableAutoSessionTracking", false);
androidOptions.Call("setEnableActivityLifecycleBreadcrumbs", false);
androidOptions.Call("setAnrEnabled", false);
androidOptions.Call("setEnableScopePersistence", false);
// Disable user interaction tracking to prevent conflicts with VR platforms (e.g., Oculus InputHooks)
androidOptions.Call("setEnableUserInteractionBreadcrumbs", false);
androidOptions.Call("setEnableUserInteractionTracing", false);
}, options.DiagnosticLogger));
}
catch (Exception e)
{
_logger?.LogError(e, "Calling 'SentryJava.Init' failed.");
}
}
public string? GetInstallationId()
{
if (!MainThreadData.IsMainThread())
{
_logger?.LogError("Calling GetInstallationId() on Android SDK requires running on MainThread");
return null;
}
try
{
using var sentry = GetSentryJava();
using var hub = sentry.CallStatic<AndroidJavaObject>("getCurrentHub");
using var options = hub?.Call<AndroidJavaObject>("getOptions");
return options?.Call<string>("getDistinctId");
}
catch (Exception e)
{
_logger?.LogError(e, "Calling 'SentryJava.GetInstallationId' failed.");
}
return null;
}
/// <summary>
/// Returns whether the last run resulted in a crash.
/// </summary>
/// <remarks>
/// This value is returned by the Android SDK and reports for both ART and NDK.
/// </remarks>
/// <returns>
/// True if the last run terminated in a crash, false otherwise.
/// If the SDK wasn't able to find this information, null is returned.
/// </returns>
public bool? CrashedLastRun()
{
if (!MainThreadData.IsMainThread())
{
_logger?.LogError("Calling CrashedLastRun() on Android SDK requires running on MainThread");
return null;
}
try
{
using var sentry = GetSentryJava();
using var jo = sentry.CallStatic<AndroidJavaObject>("isCrashedLastRun");
return jo?.Call<bool>("booleanValue");
}
catch (Exception e)
{
_logger?.LogError(e, "Calling 'SentryJava.CrashedLastRun' failed.");
}
return null;
}
public void WriteScope(
string? AppStartTime,
string? AppBuildType,
int? GpuId,
string? GpuName,
string? GpuVendorName,
int? GpuMemorySize,
string? GpuNpotSupport,
string? GpuVersion,
string? GpuApiType,
int? GpuMaxTextureSize,
bool? GpuSupportsDrawCallInstancing,
bool? GpuSupportsRayTracing,
bool? GpuSupportsComputeShaders,
bool? GpuSupportsGeometryShaders,
string? GpuVendorId,
bool? GpuMultiThreadedRendering,
string? GpuGraphicsShaderLevel)
{
RunJniSafe(() =>
{
using var app = new AndroidJavaObject("io.sentry.protocol.App");
if (AppStartTime is not null)
{
var epochMs = DateTimeOffset.Parse(AppStartTime).ToUnixTimeMilliseconds();
using var date = new AndroidJavaObject("java.util.Date", epochMs);
app.Set("appStartTime", date);
}
app.SetIfNotNull("buildType", AppBuildType);
using var gpu = new AndroidJavaObject("io.sentry.protocol.Gpu");
gpu.SetIfNotNull("name", GpuName);
gpu.SetIfNotNull("id", GpuId);
gpu.SetIfNotNull("vendorId", GpuVendorId);
gpu.SetIfNotNull("vendorName", GpuVendorName);
gpu.SetIfNotNull("memorySize", GpuMemorySize);
gpu.SetIfNotNull("apiType", GpuApiType);
gpu.SetIfNotNull("multiThreadedRendering", GpuMultiThreadedRendering);
gpu.SetIfNotNull("version", GpuVersion);
gpu.SetIfNotNull("npotSupport", GpuNpotSupport);
using var sentry = GetSentryJava();
sentry.CallStatic("configureScope", new ScopeCallback(scope =>
{
using var contexts = scope.Call<AndroidJavaObject>("getContexts");
contexts.Call("setApp", app);
contexts.Call("setGpu", gpu);
}));
});
}
public bool IsSentryJavaPresent()
{
try
{
using var _ = GetSentryJava();
}
catch (AndroidJavaException)
{
return false;
}
return true;
}
public void AddBreadcrumb(Breadcrumb breadcrumb)
{
RunJniSafe(() =>
{
using var sentry = GetSentryJava();
using var javaBreadcrumb = new AndroidJavaObject("io.sentry.Breadcrumb");
javaBreadcrumb.Set("message", breadcrumb.Message);
javaBreadcrumb.Set("type", breadcrumb.Type);
javaBreadcrumb.Set("category", breadcrumb.Category);
using var javaLevel = breadcrumb.Level.ToJavaSentryLevel();
javaBreadcrumb.Set("level", javaLevel);
sentry.CallStatic("addBreadcrumb", javaBreadcrumb, null);
});
}
public void SetExtra(string key, string? value)
{
RunJniSafe(() =>
{
using var sentry = GetSentryJava();
sentry.CallStatic("setExtra", key, value);
});
}
public void SetTag(string key, string? value)
{
RunJniSafe(() =>
{
using var sentry = GetSentryJava();
sentry.CallStatic("setTag", key, value);
});
}
public void UnsetTag(string key)
{
RunJniSafe(() =>
{
using var sentry = GetSentryJava();
sentry.CallStatic("removeTag", key);
});
}
public void SetUser(SentryUser user)
{
RunJniSafe(() =>
{
AndroidJavaObject? javaUser = null;
try
{
javaUser = new AndroidJavaObject("io.sentry.protocol.User");
javaUser.Set("email", user.Email);
javaUser.Set("id", user.Id);
javaUser.Set("username", user.Username);
javaUser.Set("ipAddress", user.IpAddress);
using var sentry = GetSentryJava();
sentry.CallStatic("setUser", javaUser);
}
finally
{
javaUser?.Dispose();
}
});
}
public void UnsetUser()
{
RunJniSafe(() =>
{
using var sentry = GetSentryJava();
sentry.CallStatic("setUser", null);
});
}
public void SetTrace(SentryId traceId, SpanId spanId)
{
RunJniSafe(() =>
{
using var sentry = GetInternalSentryJava();
// We have to explicitly cast to `(Double?)`
sentry.CallStatic("setTrace", traceId.ToString(), spanId.ToString(), (Double?)null, (Double?)null);
});
}
public void AddAttachment(string path, string fileName, string? contentType)
{
RunJniSafe(() =>
{
using var attachment = contentType is not null
? new AndroidJavaObject("io.sentry.Attachment", path, fileName, contentType)
: new AndroidJavaObject("io.sentry.Attachment", path, fileName);
using var sentry = GetSentryJava();
sentry.CallStatic("configureScope", new ScopeCallback(scope =>
scope.Call("addAttachment", attachment)));
});
}
public void AddAttachmentBytes(byte[] data, string fileName, string? contentType)
{
RunJniSafe(() =>
{
using var attachment = contentType is not null
? new AndroidJavaObject("io.sentry.Attachment", data, fileName, contentType)
: new AndroidJavaObject("io.sentry.Attachment", data, fileName);
using var sentry = GetSentryJava();
sentry.CallStatic("configureScope", new ScopeCallback(scope =>
scope.Call("addAttachment", attachment)));
});
}
public void ClearAttachments()
{
RunJniSafe(() =>
{
using var sentry = GetSentryJava();
sentry.CallStatic("configureScope", new ScopeCallback(scope =>
scope.Call("clearAttachments")));
});
}
// https://github.com/getsentry/sentry-java/blob/db4dfc92f202b1cefc48d019fdabe24d487db923/sentry/src/main/java/io/sentry/SentryLevel.java#L4-L9
internal static string GetLevelString(SentryLevel level) => level switch
{
SentryLevel.Debug => "DEBUG",
SentryLevel.Error => "ERROR",
SentryLevel.Fatal => "FATAL",
SentryLevel.Info => "INFO",
SentryLevel.Warning => "WARNING",
_ => "DEBUG"
};
internal void RunJniSafe(Action action, [CallerMemberName] string actionName = "", bool? isMainThread = null)
{
if (_closed)
{
_logger?.LogInfo("Scope sync is closed, skipping '{0}'", actionName);
return;
}
isMainThread ??= MainThreadData.IsMainThread();
if (isMainThread is true)
{
try
{
action.Invoke();
}
catch (Exception e)
{
_logger?.LogError(e, "Calling '{0}' failed.", actionName);
}
}
else
{
_scopeSyncItems.Enqueue((action, actionName));
_scopeSyncEvent.Set();
}
}
private void SyncScope()
{
_androidJNI.AttachCurrentThread();
try
{
var waitHandles = new[] { _scopeSyncEvent, _scopeSyncShutdownSource.Token.WaitHandle };
while (true)
{
var index = WaitHandle.WaitAny(waitHandles);
if (index > 0)
{
// Shutdown requested
break;
}
while (_scopeSyncItems.TryDequeue(out var workItem))
{
var (action, actionName) = workItem;
try
{
action.Invoke();
}
catch (Exception e)
{
_logger?.LogError(e, "Calling '{0}' failed.", actionName);
}
}
}
}
finally
{
_androidJNI.DetachCurrentThread();
}
}
public void Close()
{
_closed = true;
_scopeSyncShutdownSource.Cancel();
_scopeSyncThread.Join();
// Note: We intentionally don't dispose _scopeSyncEvent to avoid race conditions
// where other threads might call RunJniSafe() after Close() but before disposal.
// The memory overhead of a single AutoResetEvent is negligible.
_scopeSyncShutdownSource.Dispose();
if (!MainThreadData.IsMainThread())
{
_logger?.LogError("Calling Close() on Android SDK requires running on MainThread. " +
"Scope sync thread stopped but Java SDK was not closed.");
return;
}
try
{
using var sentry = GetSentryJava();
sentry.CallStatic("close");
}
catch (Exception e)
{
_logger?.LogError(e, "Calling 'SentryJava.Close' failed.");
}
}
}
internal static class AndroidJavaObjectExtension
{
public static void SetIfNotNull<T>(this AndroidJavaObject javaObject, string property, T? value, string? valueClass = null)
{
if (value is not null)
{
if (valueClass is null)
{
javaObject.Set(property, value!);
}
else
{
using var valueObject = new AndroidJavaObject(valueClass, value!);
javaObject.Set(property, valueObject);
}
}
}
public static void SetIfNotNull(this AndroidJavaObject javaObject, string property, int? value) =>
SetIfNotNull(javaObject, property, value, "java.lang.Integer");
public static void SetIfNotNull(this AndroidJavaObject javaObject, string property, bool value) =>
SetIfNotNull(javaObject, property, value, "java.lang.Boolean");
public static void SetIfNotNull(this AndroidJavaObject javaObject, string property, bool? value) =>
SetIfNotNull(javaObject, property, value, "java.lang.Boolean");
}