Skip to content

Commit ada094b

Browse files
Review feedback
1 parent 29fa252 commit ada094b

File tree

8 files changed

+40
-45
lines changed

8 files changed

+40
-45
lines changed

src/Sentry/GlobalSessionManager.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,7 @@ public GlobalSessionManager(
3333
_clock = clock ?? SystemClock.Clock;
3434
_persistedSessionProvider = persistedSessionProvider
3535
?? (filePath => Json.Load(_options.FileSystem, filePath, PersistedSessionUpdate.FromJson));
36-
37-
// TODO: session file should really be process-isolated, but we
38-
// don't have a proper mechanism for that right now.
39-
_persistenceDirectoryPath = options.TryGetIsolatedCacheDirectoryPath();
36+
_persistenceDirectoryPath = options.GetIsolatedCacheDirectoryPath();
4037
}
4138

4239
// Take pause timestamp directly instead of referencing _lastPauseTimestamp to avoid

src/Sentry/Internal/CacheDirectoryCoordinator.cs

Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,33 +7,20 @@ internal class CacheDirectoryCoordinator : IDisposable
77
{
88
private readonly IDiagnosticLogger? _logger;
99
private readonly IFileSystem _fileSystem;
10-
private readonly object _gate = new();
10+
private readonly Lock _lock = new();
1111

1212
private Stream? _lockStream;
1313
private readonly string _lockFilePath;
1414

15-
private bool _acquired;
16-
private bool _disposed;
15+
private volatile bool _acquired;
16+
private volatile bool _disposed;
1717

1818
public CacheDirectoryCoordinator(string cacheDir, IDiagnosticLogger? logger, IFileSystem fileSystem)
1919
{
2020
_logger = logger;
2121
_fileSystem = fileSystem;
22+
// Note this creates a lock file in the cache directory's parent directory... not in the cache directory itself
2223
_lockFilePath = $"{cacheDir}.lock";
23-
24-
try
25-
{
26-
var baseDir = Path.GetDirectoryName(_lockFilePath);
27-
if (!string.IsNullOrWhiteSpace(baseDir))
28-
{
29-
// Not normally necessary, but just in case
30-
fileSystem.CreateDirectory(baseDir);
31-
}
32-
}
33-
catch (Exception ex)
34-
{
35-
_logger?.LogError("Failed to ensure lock directory exists for cache coordinator.", ex);
36-
}
3724
}
3825

3926
public bool TryAcquire()
@@ -43,7 +30,7 @@ public bool TryAcquire()
4330
return true;
4431
}
4532

46-
lock (_gate)
33+
lock (_lock)
4734
{
4835
if (_acquired)
4936
{
@@ -57,6 +44,11 @@ public bool TryAcquire()
5744

5845
try
5946
{
47+
var baseDir = Path.GetDirectoryName(_lockFilePath);
48+
if (!string.IsNullOrWhiteSpace(baseDir))
49+
{
50+
_fileSystem.CreateDirectory(baseDir);
51+
}
6052
_acquired = _fileSystem.TryCreateLockFile(_lockFilePath, out _lockStream);
6153
return _acquired;
6254
}
@@ -84,13 +76,13 @@ public bool TryAcquire()
8476

8577
public void Dispose()
8678
{
87-
lock (_gate)
79+
if (_disposed)
8880
{
89-
if (_disposed)
90-
{
91-
return;
92-
}
81+
return;
82+
}
9383

84+
lock (_lock)
85+
{
9486
_disposed = true;
9587

9688
if (_acquired)
@@ -140,12 +132,13 @@ internal static class CacheDirectoryHelper
140132
return null;
141133
}
142134
var processId = options.ProcessIdResolver.Invoke() ?? 0;
143-
stringBuilder.AppendJoin('_', options.Dsn.GetHashString(), processId, options.InitCounter.Count);
135+
stringBuilder.AppendJoin('_', options.Dsn.GetHashString(), processId.ToString(),
136+
options.InitCounter.Count.ToString());
144137
#endif
145138
return stringBuilder.ToString();
146139
}
147140

148-
internal static string? TryGetIsolatedCacheDirectoryPath(this SentryOptions options) =>
141+
internal static string? GetIsolatedCacheDirectoryPath(this SentryOptions options) =>
149142
GetBaseCacheDirectoryPath(options) is not { } baseCacheDir
150143
|| GetIsolatedFolderName(options) is not { } isolatedFolderName
151144
? null

src/Sentry/Internal/Http/CachingTransport.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ private CachingTransport(ITransport innerTransport, SentryOptions options, bool
7979
: 0; // just in case MaxCacheItems is set to an invalid value somehow (shouldn't happen)
8080

8181
_isolatedCacheDirectoryPath =
82-
options.TryGetIsolatedCacheDirectoryPath() ??
82+
options.GetIsolatedCacheDirectoryPath() ??
8383
throw new InvalidOperationException("Cache directory or DSN is not set.");
8484
_cacheCoordinator = new CacheDirectoryCoordinator(_isolatedCacheDirectoryPath, options.DiagnosticLogger, options.FileSystem);
8585
if (!_cacheCoordinator.TryAcquire())
@@ -207,7 +207,7 @@ internal void SalvageAbandonedCacheSessions(CancellationToken cancellationToken)
207207
continue; // Ignore the current cache directory
208208
}
209209

210-
_options.LogDebug("found abandoned cache: {0}", dir);
210+
_options.LogDebug("Found abandoned cache: {0}", dir);
211211
using var coordinator = new CacheDirectoryCoordinator(dir, _options.DiagnosticLogger, _options.FileSystem);
212212
if (!coordinator.TryAcquire())
213213
{

src/Sentry/SentrySdk.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,10 @@ static partial class SentrySdk
3030

3131
internal static IHub InitHub(SentryOptions options)
3232
{
33+
options.InitCounter.Increment();
34+
3335
options.SetupLogging();
3436

35-
options.InitCounter.Increment();
3637
ProcessInfo.Instance ??= new ProcessInfo(options);
3738

3839
// Locate the DSN

test/Sentry.Tests/HubTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2203,7 +2203,7 @@ await transport.Received(1)
22032203
Arg.Any<CancellationToken>());
22042204
if (options.Transport is CachingTransport cachingTransport)
22052205
{
2206-
cachingTransport.Dispose(); // Release cache lock so that the cacheDirectory can be removed
2206+
await cachingTransport.DisposeAsync(); // Release cache lock so that the cacheDirectory can be removed
22072207
}
22082208
}
22092209

test/Sentry.Tests/Internals/CacheDirectoryCoordinatorTests.cs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,22 @@ public class CacheDirectoryCoordinatorTests : IDisposable
66

77
public void Dispose()
88
{
9-
if (_fixture.FileSystem.FileExists(_fixture.CacheDirectoryPath))
10-
{
11-
_fixture.FileSystem.DeleteDirectory(_fixture.CacheDirectoryPath);
12-
}
9+
_fixture.CacheRoot.Dispose();
1310
}
1411

1512
private class Fixture
1613
{
14+
public readonly TempDirectory CacheRoot = new();
1715
public ReadWriteFileSystem FileSystem { get; } = new();
18-
public string CacheDirectoryPath { get; } = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
1916

20-
public CacheDirectoryCoordinator GetSut() => new(CacheDirectoryPath, null, FileSystem);
17+
public string CacheDirectoryPath { get; private set; }
18+
private readonly string _isolatedDirectory = Guid.NewGuid().ToString("N");
19+
20+
public CacheDirectoryCoordinator GetSut()
21+
{
22+
CacheDirectoryPath = Path.Combine(CacheRoot.Path, _isolatedDirectory);
23+
return new(CacheDirectoryPath, null, FileSystem);
24+
}
2125
}
2226

2327
[Fact]

test/Sentry.Tests/Internals/Http/CachingTransportTests.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ public async Task Handle_Malformed_Envelopes_Gracefully()
243243
{
244244
// Arrange
245245
var cacheDirectoryPath =
246-
_options.TryGetIsolatedCacheDirectoryPath() ??
246+
_options.GetIsolatedCacheDirectoryPath() ??
247247
throw new InvalidOperationException("Cache directory or DSN is not set.");
248248
var processingDirectoryPath = Path.Combine(cacheDirectoryPath, "__processing");
249249
var fileName = $"{Guid.NewGuid()}.envelope";
@@ -624,7 +624,7 @@ public async Task DoesntWriteSentAtHeaderToCacheFile()
624624
await transport.SendEnvelopeAsync(envelope);
625625

626626
// Assert
627-
var isolatedCacheDir = _options.TryGetIsolatedCacheDirectoryPath();
627+
var isolatedCacheDir = _options.GetIsolatedCacheDirectoryPath();
628628
var filePath = _options.FileSystem
629629
.EnumerateFiles(isolatedCacheDir!, "*", SearchOption.AllDirectories)
630630
.Single();
@@ -640,7 +640,7 @@ public async Task SalvageAbandonedCacheSessions_MovesEnvelopesFromOtherIsolatedD
640640
using var innerTransport = new FakeTransport();
641641
await using var transport = CachingTransport.Create(innerTransport, _options, startWorker: false);
642642

643-
var currentIsolated = _options.TryGetIsolatedCacheDirectoryPath()!; // already validated during creation
643+
var currentIsolated = _options.GetIsolatedCacheDirectoryPath()!; // already validated during creation
644644
var baseCacheDir = Directory.GetParent(currentIsolated)!.FullName;
645645

646646
// Create two abandoned isolated cache directories with envelope files (including in nested folder)
@@ -694,7 +694,7 @@ public async Task SalvageAbandonedCacheSessions_IgnoresCurrentDirectory()
694694
// Arrange
695695
using var innerTransport = new FakeTransport();
696696
await using var transport = CachingTransport.Create(innerTransport, _options, startWorker: false);
697-
var currentIsolated = _options.TryGetIsolatedCacheDirectoryPath()!;
697+
var currentIsolated = _options.GetIsolatedCacheDirectoryPath()!;
698698

699699
var currentFile = Path.Combine(currentIsolated, "current.envelope");
700700
if (_options.FileSystem.CreateFileForWriting(currentFile, out var stream))
@@ -717,7 +717,7 @@ public async Task SalvageAbandonedCacheSessions_SkipsDirectoriesWithActiveLock()
717717
using var innerTransport = new FakeTransport();
718718
await using var transport = CachingTransport.Create(innerTransport, _options, startWorker: false);
719719

720-
var currentIsolated = _options.TryGetIsolatedCacheDirectoryPath()!;
720+
var currentIsolated = _options.GetIsolatedCacheDirectoryPath()!;
721721
var baseCacheDir = Directory.GetParent(currentIsolated)!.FullName;
722722

723723
// Create an abandoned directory that matches the search pattern and acquire its lock

test/Sentry.Tests/SentryOptionsTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -680,7 +680,7 @@ public void CachesInstallationId()
680680
public void TryGetIsolatedCacheDirectoryPath_NullCacheDirectory_ReturnsNull()
681681
{
682682
var o = new SentryOptions { CacheDirectoryPath = null, Dsn = ValidDsn };
683-
Assert.Null(o.TryGetIsolatedCacheDirectoryPath());
683+
Assert.Null(o.GetIsolatedCacheDirectoryPath());
684684
}
685685

686686
#if IOS || ANDROID

0 commit comments

Comments
 (0)