Skip to content

fix: Moved late option mutation into Init #2239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: fix/initialization
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
**Migration**: Update your `using` directives from `using Sentry;` to `using Sentry.Unity;`. IDEs like Rider can automatically
import the missing references. In some cases, you may need both `using Sentry.Unity;` (for the static API) and `using Sentry;`
(for types like `SentryId`). No changes are required to your actual SDK method calls (e.g., `SentrySdk.CaptureException()`
remains the same). ([#2227](https://github.com/getsentry/sentry-unity/pull/2227))
remains the same). ([#2227](https://github.com/getsentry/sentry-unity/pull/2227), [#2239](https://github.com/getsentry/sentry-unity/pull/2239))

### Features

Expand Down
11 changes: 7 additions & 4 deletions src/Sentry.Unity/Il2CppEventProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@ internal class UnityIl2CppEventExceptionProcessor : ISentryEventExceptionProcess
private static ISentryUnityInfo UnityInfo = null!; // private static will be initialized in the constructor
private readonly Il2CppMethods _il2CppMethods;

public UnityIl2CppEventExceptionProcessor(SentryUnityOptions options, ISentryUnityInfo unityInfo)
public UnityIl2CppEventExceptionProcessor(SentryUnityOptions options)
{
Options = options;
UnityInfo = unityInfo;
_il2CppMethods = unityInfo.Il2CppMethods ?? throw new ArgumentNullException(nameof(unityInfo.Il2CppMethods),
"Unity IL2CPP methods are not available.");

// We're throwing here but this should never happen. We're validating UnityInfo before adding the processor.
UnityInfo = SentryPlatformServices.UnityInfo
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great! this was my only feedback in the other PR, validation that we're at the right state before going ahead

Also note that you copy a reference to use the same/consistent reference. This also means there's no path for a user to change these values after-the-fact.

But I understand that's the goal, and we then should follow this pattern when it makes sense. Instead of accessing the static mutable property in many places try to keep it to a minimum.

?? throw new ArgumentNullException(nameof(SentryPlatformServices.UnityInfo), "UnityInfo is null");
_il2CppMethods = UnityInfo.Il2CppMethods
?? throw new ArgumentNullException(nameof(UnityInfo.Il2CppMethods), "Unity IL2CPP methods are not available.");

Options.SdkIntegrationNames.Add("IL2CPPLineNumbers");
}
Expand Down
61 changes: 10 additions & 51 deletions src/Sentry.Unity/ScriptableSentryUnityOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ internal SentryUnityOptions ToSentryUnityOptions(bool isBuilding, ISentryUnityIn
{
application ??= ApplicationAdapter.Instance;

var options = new SentryUnityOptions(isBuilding, application, unityInfo)
var options = new SentryUnityOptions(isBuilding, application, unityInfo, SentryMonoBehaviour.Instance)
{
Enabled = Enabled,
Dsn = Dsn,
Expand Down Expand Up @@ -186,6 +186,12 @@ internal SentryUnityOptions ToSentryUnityOptions(bool isBuilding, ISentryUnityIn
PerformanceAutoInstrumentationEnabled = AutoAwakeTraces,
};

// By default, the cacheDirectoryPath gets set on known platforms. The option is enabled by default
if (!EnableOfflineCaching)
{
options.CacheDirectoryPath = null;
}

if (!string.IsNullOrWhiteSpace(ReleaseOverride))
{
options.Release = ReleaseOverride;
Expand Down Expand Up @@ -227,23 +233,11 @@ internal SentryUnityOptions ToSentryUnityOptions(bool isBuilding, ISentryUnityIn
// Without setting up here we might miss out on logs between option-loading (now) and Init - i.e. native configuration
options.SetupUnityLogging();

if (options.AttachViewHierarchy)
{
options.AddEventProcessor(new ViewHierarchyEventProcessor(options));
}
if (options.AttachScreenshot)
{
options.AddEventProcessor(new ScreenshotEventProcessor(options));
}

if (!application.IsEditor && options.Il2CppLineNumberSupportEnabled && unityInfo is not null)
{
options.AddIl2CppExceptionProcessor(unityInfo);
}

HandlePlatformRestrictedOptions(options, unityInfo, application);
Comment on lines -230 to -244
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This got moved into SentryUnitySdk.Init to keep the SDKs behaviour consistent.

// ExceptionFilters are added by default to the options.
HandleExceptionFilter(options);

// The AnrDetectionIntegration is added by default. Since it is a ScriptableUnityOptions-only property we have to
// remove the integration when creating the options through here
if (!AnrDetectionEnabled)
{
options.DisableAnrIntegration();
Expand All @@ -252,41 +246,6 @@ internal SentryUnityOptions ToSentryUnityOptions(bool isBuilding, ISentryUnityIn
return options;
}

internal void HandlePlatformRestrictedOptions(SentryUnityOptions options, ISentryUnityInfo? unityInfo, IApplication application)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above. Even if users call Init the SDK should make an effort not to crash the game.

{
if (unityInfo?.IsKnownPlatform() == false)
{
options.DisableFileWrite = true;

// This is only provided on a best-effort basis for other than the explicitly supported platforms.
if (options.BackgroundWorker is null)
{
options.DiagnosticLogger?.LogDebug("Platform support for background thread execution is unknown: using WebBackgroundWorker.");
options.BackgroundWorker = new WebBackgroundWorker(options, SentryMonoBehaviour.Instance);
}

// Disable offline caching regardless whether it was enabled or not.
options.CacheDirectoryPath = null;
if (EnableOfflineCaching)
{
options.DiagnosticLogger?.LogDebug("Platform support for offline caching is unknown: disabling.");
}

// Requires file access, see https://github.com/getsentry/sentry-unity/issues/290#issuecomment-1163608988
if (options.AutoSessionTracking)
{
options.DiagnosticLogger?.LogDebug("Platform support for automatic session tracking is unknown: disabling.");
options.AutoSessionTracking = false;
}

return;
}

// Only assign the cache directory path if we're on a "known" platform. Accessing `Application.persistentDataPath`
// implicitly creates a directory and leads to crashes i.e. on the Switch.
options.CacheDirectoryPath = EnableOfflineCaching ? application.PersistentDataPath : null;
}

private void HandleExceptionFilter(SentryUnityOptions options)
{
if (!options.FilterBadGatewayExceptions)
Expand Down
57 changes: 32 additions & 25 deletions src/Sentry.Unity/SentryUnityOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Text.RegularExpressions;
using Sentry.Unity.Integrations;
using Sentry.Extensibility;
using Sentry.Unity.NativeUtils;
using UnityEngine;
using CompressionLevel = System.IO.Compression.CompressionLevel;

Expand Down Expand Up @@ -294,39 +295,38 @@ internal string? DefaultUserId

internal List<string> SdkIntegrationNames { get; set; } = new();

public SentryUnityOptions() : this(false, ApplicationAdapter.Instance) { }

internal SentryUnityOptions(bool isBuilding, IApplication application, ISentryUnityInfo? unityInfo = null) :
this(SentryMonoBehaviour.Instance, application, isBuilding, unityInfo)
Comment on lines -299 to -300
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got rid of a redundant internal constructor.

public SentryUnityOptions() :
this(false, ApplicationAdapter.Instance, SentryPlatformServices.UnityInfo, SentryMonoBehaviour.Instance)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we access SentryPlatformServices.UnityInfo here but also in other places where they take SentryOptions but also ISentryUnityInfo. This makes it a lot more confusing.

Can we then only get it from here?

Once you do new Options we read SentryPlatformServices.UnityInfo and if it's null, we throw. Or go into the mode where this doesn't exist if that's a thing. But from that point any access to UnityInfo is through options. If you find references of the getter for SentryPlatformServices.UnityInfo you'd only see tests and this contructor.

{ }

// For testing
internal SentryUnityOptions(SentryMonoBehaviour behaviour, IApplication application, bool isBuilding, ISentryUnityInfo? unityInfo = null)
internal SentryUnityOptions(bool isBuilding, IApplication application, ISentryUnityInfo? unityInfo,
SentryMonoBehaviour behaviour)
{
// IL2CPP doesn't support Process.GetCurrentProcess().StartupTime
DetectStartupTime = StartupTimeDetectionMode.Fast;

this.AddInAppExclude("UnityEngine");
this.AddInAppExclude("UnityEditor");
AddInAppExclude("UnityEngine");
AddInAppExclude("UnityEditor");
var processor = new UnityEventProcessor(this);
this.AddEventProcessor(processor);
this.AddTransactionProcessor(processor);
this.AddExceptionProcessor(new UnityExceptionProcessor());

this.AddIntegration(new UnityLogHandlerIntegration(this));
this.AddIntegration(new UnityApplicationLoggingIntegration());
this.AddIntegration(new StartupTracingIntegration());
this.AddIntegration(new AnrIntegration(behaviour));
this.AddIntegration(new UnityScopeIntegration(application, unityInfo));
this.AddIntegration(new UnityBeforeSceneLoadIntegration());
this.AddIntegration(new SceneManagerIntegration());
this.AddIntegration(new SceneManagerTracingIntegration());
this.AddIntegration(new SessionIntegration(behaviour));
this.AddIntegration(new TraceGenerationIntegration(behaviour));

this.AddExceptionFilter(new UnityBadGatewayExceptionFilter());
this.AddExceptionFilter(new UnityWebExceptionFilter());
this.AddExceptionFilter(new UnitySocketExceptionFilter());
AddEventProcessor(processor);
AddTransactionProcessor(processor);
AddExceptionProcessor(new UnityExceptionProcessor());

AddIntegration(new UnityLogHandlerIntegration(this));
AddIntegration(new UnityApplicationLoggingIntegration());
AddIntegration(new StartupTracingIntegration());
AddIntegration(new AnrIntegration(behaviour));
AddIntegration(new UnityScopeIntegration(application, unityInfo));
AddIntegration(new UnityBeforeSceneLoadIntegration());
AddIntegration(new SceneManagerIntegration());
AddIntegration(new SceneManagerTracingIntegration());
AddIntegration(new SessionIntegration(behaviour));
AddIntegration(new TraceGenerationIntegration(behaviour));

AddExceptionFilter(new UnityBadGatewayExceptionFilter());
AddExceptionFilter(new UnityWebExceptionFilter());
AddExceptionFilter(new UnitySocketExceptionFilter());

IsGlobalModeEnabled = true;

Expand Down Expand Up @@ -363,6 +363,13 @@ internal SentryUnityOptions(SentryMonoBehaviour behaviour, IApplication applicat
{ LogType.Error, true},
{ LogType.Exception, true},
};

// Only assign the cache directory path if we're on a "known" platform. Accessing `Application.persistentDataPath`
// implicitly creates a directory and leads to crashes i.e. on the Switch.
if (unityInfo?.IsKnownPlatform() ?? false)
{
CacheDirectoryPath = application.PersistentDataPath;
}
}

public override string ToString()
Expand Down
12 changes: 0 additions & 12 deletions src/Sentry.Unity/SentryUnityOptionsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,6 @@ internal static void SetupUnityLogging(this SentryUnityOptions options)
}
}

internal static void AddIl2CppExceptionProcessor(this SentryUnityOptions options, ISentryUnityInfo unityInfo)
{
if (unityInfo.Il2CppMethods is not null)
{
options.AddExceptionProcessor(new UnityIl2CppEventExceptionProcessor(options, unityInfo));
}
else
{
options.DiagnosticLogger?.LogWarning("Failed to find required IL2CPP methods - Skipping line number support");
}
}
Comment on lines -66 to -76
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved to Init.


/// <summary>
/// Disables the capture of errors through <see cref="UnityLogHandlerIntegration"/>.
/// </summary>
Expand Down
97 changes: 79 additions & 18 deletions src/Sentry.Unity/SentryUnitySdk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Threading.Tasks;
using Sentry.Extensibility;
using Sentry.Unity.Integrations;
using Sentry.Unity.NativeUtils;
using UnityEngine;

namespace Sentry.Unity;
Expand Down Expand Up @@ -30,24 +31,11 @@ private SentryUnitySdk(SentryUnityOptions options)

MainThreadData.CollectData();

// On Standalone, we disable cache dir in case multiple app instances run over the same path.
// Note: we cannot use a named Mutex, because Unit doesn't support it. Instead, we create a file with `FileShare.None`.
// https://forum.unity.com/threads/unsupported-internal-call-for-il2cpp-mutex-createmutex_internal-named-mutexes-are-not-supported.387334/
if (ApplicationAdapter.Instance.Platform is RuntimePlatform.WindowsPlayer && options.CacheDirectoryPath is not null)
{
try
{
unitySdk._lockFile = new FileStream(Path.Combine(options.CacheDirectoryPath, "sentry-unity.lock"), FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
}
catch (Exception ex)
{
options.DiagnosticLogger?.LogWarning("An exception was thrown while trying to " +
"acquire a lockfile on the config directory: .NET event cache will be disabled.", ex);
options.CacheDirectoryPath = null;
options.AutoSessionTracking = false;
}
}
// Some integrations are controlled through a flag and opt-in. Adding these integrations late so we have the
// same behaviour whether we're self or manually initializing
HandleLateIntegrations(options);
HandlePlatformRestrictedOptions(options, SentryPlatformServices.UnityInfo);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

example where we take options and also access the static mutable public property

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw, I'm saying "static public mutable property" a lot because it's a thing you should be aware, I didn't read it btw just got the first link:

https://www.reddit.com/r/learnprogramming/comments/7nzlec/why_are_mutable_static_variables_bad/

HandleWindowsPlayer(unitySdk, options);

unitySdk._dotnetSdk = Sentry.SentrySdk.Init(options);

Expand Down Expand Up @@ -137,4 +125,77 @@ public void CaptureFeedback(string message, string? email, string? name, bool ad

Sentry.SentrySdk.CurrentHub.CaptureFeedback(message, email, name, hint: hint);
}

internal static void HandleWindowsPlayer(SentryUnitySdk unitySdk, SentryUnityOptions options)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure this method is called. "Handle"? It seems it's "Setting Up"? or Initializing?

It's being called by Init so perhaps InitWindowsPlayer?

{
// On Windows-Standalone, we disable cache dir in case multiple app instances run over the same path.
// Note: we cannot use a named Mutex, because Unity doesn't support it. Instead, we create a file with `FileShare.None`.
// https://forum.unity.com/threads/unsupported-internal-call-for-il2cpp-mutex-createmutex_internal-named-mutexes-are-not-supported.387334/
if (ApplicationAdapter.Instance.Platform is not RuntimePlatform.WindowsPlayer ||
options.CacheDirectoryPath is null)
{
return;
}

try
{
unitySdk._lockFile = new FileStream(Path.Combine(options.CacheDirectoryPath, "sentry-unity.lock"), FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
}
catch (Exception ex)
{
options.DiagnosticLogger?.LogWarning("An exception was thrown while trying to " +
"acquire a lockfile on the config directory: .NET event cache will be disabled.", ex);
options.CacheDirectoryPath = null;
options.AutoSessionTracking = false;
}
}
Comment on lines +129 to +152
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To keep the Init more readable.


internal static void HandleLateIntegrations(SentryUnityOptions options)
{
if (options.AttachViewHierarchy)
{
options.AddEventProcessor(new ViewHierarchyEventProcessor(options));
}
if (options.AttachScreenshot)
{
options.AddEventProcessor(new ScreenshotEventProcessor(options));
}

if (!ApplicationAdapter.Instance.IsEditor &&
(SentryPlatformServices.UnityInfo?.IL2CPP ?? false) &&
options.Il2CppLineNumberSupportEnabled)
{
if (SentryPlatformServices.UnityInfo.Il2CppMethods is not null)
{
options.AddExceptionProcessor(new UnityIl2CppEventExceptionProcessor(options));
}
else
{
options.DiagnosticLogger?.LogWarning("Failed to find required IL2CPP methods - Skipping line number support");
}
Comment on lines +165 to +176
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The IL2CPP Exception Processor is critical and "dangerous" as it calls into the IL2CPP backend and requires certain functions to be there. These functions change depending of Unity versions and are provided via IUnityInfo. As such, this does not get added by default but late during Init with extensive checks.

}
}

internal static void HandlePlatformRestrictedOptions(SentryUnityOptions options, ISentryUnityInfo? unityInfo)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again method name is off, seems the guard is: IsKnownPlatform so how about:

InitUnknownPlatform

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a bit odd to see on the callsite:

InitWindows
InitOtherPlatform

Since you'd expect the guards to be outside the functions as the function names already 'declare' what they are supposed to be for.

But this is all internal code so not worth splitting hairs 🙈 And I don't have a great suggestion on how to improve this other than maybe trying yet other method names "TryInit" or whatever

{
if (unityInfo?.IsKnownPlatform() == false)
{
options.DisableFileWrite = true;

// Requires file access, see https://github.com/getsentry/sentry-unity/issues/290#issuecomment-1163608988
if (options.AutoSessionTracking)
{
options.DiagnosticLogger?.LogDebug("Platform support for automatic session tracking is unknown: disabling.");
options.AutoSessionTracking = false;
}

// This is only provided on a best-effort basis for other than the explicitly supported platforms.
if (options.BackgroundWorker is null)
{
options.DiagnosticLogger?.LogDebug("Platform support for background thread execution is unknown: using WebBackgroundWorker.");
options.BackgroundWorker = new WebBackgroundWorker(options, SentryMonoBehaviour.Instance);
}
}
}
}
3 changes: 2 additions & 1 deletion test/Sentry.Unity.Tests/ContextWriterTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Threading;
using NUnit.Framework;
using Sentry.Unity.NativeUtils;
using Sentry.Unity.Tests.SharedClasses;
using Sentry.Unity.Tests.Stubs;
using UnityEngine;
Expand Down Expand Up @@ -66,7 +67,7 @@ public void Arguments()

};
var context = new MockContextWriter();
var options = new SentryUnityOptions(_sentryMonoBehaviour, _testApplication, false)
var options = new SentryUnityOptions(false, _testApplication, SentryPlatformServices.UnityInfo, _sentryMonoBehaviour)
{
Dsn = "http://publickey@localhost/12345",
Enabled = true,
Expand Down
Loading
Loading