-
-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathGlobalSessionManager.cs
More file actions
392 lines (320 loc) · 14.2 KB
/
GlobalSessionManager.cs
File metadata and controls
392 lines (320 loc) · 14.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
using Sentry.Extensibility;
using Sentry.Infrastructure;
using Sentry.Internal;
using Sentry.Internal.Extensions;
namespace Sentry;
// AKA client mode
internal class GlobalSessionManager : ISessionManager
{
private const string PersistedSessionFileName = ".session";
private readonly ISystemClock _clock;
private readonly Func<string, PersistedSessionUpdate> _persistedSessionProvider;
private readonly SentryOptions _options;
private readonly string? _persistenceDirectoryPath;
private SentrySession? _currentSession;
private DateTimeOffset? _lastPauseTimestamp;
// Internal for testing
internal SentrySession? CurrentSession => _currentSession;
public bool IsSessionActive => _currentSession is not null;
public GlobalSessionManager(
SentryOptions options,
ISystemClock? clock = null,
Func<string, PersistedSessionUpdate>? persistedSessionProvider = null)
{
_options = options;
_clock = clock ?? SystemClock.Clock;
_persistedSessionProvider = persistedSessionProvider
?? (filePath => Json.Load(_options.FileSystem, filePath, PersistedSessionUpdate.FromJson));
// TODO: session file should really be process-isolated, but we
// don't have a proper mechanism for that right now.
_persistenceDirectoryPath = options.TryGetDsnSpecificCacheDirectoryPath();
}
// Take pause timestamp directly instead of referencing _lastPauseTimestamp to avoid
// potential race conditions.
private void PersistSession(SessionUpdate update, DateTimeOffset? pauseTimestamp = null, bool pendingUnhandled = false)
{
_options.LogDebug("Persisting session (SID: '{0}') to a file.", update.Id);
if (string.IsNullOrWhiteSpace(_persistenceDirectoryPath))
{
_options.LogDebug("Persistence directory is not set, returning.");
return;
}
if (_options.DisableFileWrite)
{
_options.LogInfo("File write has been disabled via the options. Skipping persisting session.");
return;
}
try
{
_options.LogDebug("Creating persistence directory for session file at '{0}'.", _persistenceDirectoryPath);
if (!_options.FileSystem.CreateDirectory(_persistenceDirectoryPath))
{
_options.LogError("Failed to create persistent directory for session file.");
return;
}
var filePath = Path.Combine(_persistenceDirectoryPath, PersistedSessionFileName);
var persistedSessionUpdate = new PersistedSessionUpdate(update, pauseTimestamp, pendingUnhandled);
if (!_options.FileSystem.CreateFileForWriting(filePath, out var file))
{
_options.LogError("Failed to persist session file.");
return;
}
try
{
using var writer = new Utf8JsonWriter(file);
persistedSessionUpdate.WriteTo(writer, _options.DiagnosticLogger);
writer.Flush();
}
finally
{
file.Dispose();
}
_options.LogDebug("Persisted session to a file '{0}'.", filePath);
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to persist session on the file system.");
}
}
private void DeletePersistedSession()
{
if (string.IsNullOrWhiteSpace(_persistenceDirectoryPath))
{
_options.LogDebug("Persistence directory is not set, not deleting any persisted session file.");
return;
}
if (_options.DisableFileWrite)
{
_options.LogInfo("File write has been disabled via the options. Skipping deletion of persisted session files.");
return;
}
var filePath = Path.Combine(_persistenceDirectoryPath, PersistedSessionFileName);
try
{
// Try to log the contents of the session file before we delete it
if (_options.DiagnosticLogger?.IsEnabled(SentryLevel.Debug) ?? false)
{
try
{
var contents = _options.FileSystem.ReadAllTextFromFile(filePath);
_options.LogDebug("Deleting persisted session file with contents: '{0}'", contents);
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to read the contents of persisted session file '{0}'.", filePath);
}
}
if (!_options.FileSystem.DeleteFile(filePath))
{
_options.LogError("Failed to delete persisted session file.");
return;
}
_options.LogInfo("Deleted persisted session file '{0}'.", filePath);
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to delete persisted session from the file system: '{0}'", filePath);
}
}
public SessionUpdate? TryRecoverPersistedSession()
{
_options.LogDebug("Attempting to recover persisted session from file.");
if (string.IsNullOrWhiteSpace(_persistenceDirectoryPath))
{
_options.LogDebug("Persistence directory is not set, returning.");
return null;
}
var filePath = Path.Combine(_persistenceDirectoryPath, PersistedSessionFileName);
if (!_options.FileSystem.FileExists(filePath))
{
_options.LogDebug("A persisted session file was not found at '{0}'.", filePath);
return null;
}
try
{
var recoveredUpdate = _persistedSessionProvider(filePath);
SessionEndStatus? status = null;
try
{
status = _options.CrashedLastRun?.Invoke() switch
{
// Native crash (if native SDK enabled):
// This takes priority - escalate to Crashed even if session had pending unhandled
true => SessionEndStatus.Crashed,
// Had unhandled exception but didn't crash:
_ when recoveredUpdate.PendingUnhandled => SessionEndStatus.Unhandled,
// Ended while on the background, healthy session:
_ when recoveredUpdate.PauseTimestamp is not null => SessionEndStatus.Exited,
// Possibly out of battery, killed by OS or user, solar flare:
_ => SessionEndStatus.Abnormal
};
}
catch (Exception e)
{
_options.LogError(e, "Invoking CrashedLastRun failed.");
}
// Create a session update to end the recovered session
var sessionUpdate = new SessionUpdate(
recoveredUpdate.Update,
// We're recovering an ongoing session, so this can never be initial
false,
// If the session was paused, then use that as timestamp, otherwise use current timestamp
recoveredUpdate.PauseTimestamp ?? _clock.GetUtcNow(),
// Increment sequence number
recoveredUpdate.Update.SequenceNumber + 1,
// If there's a callback for native crashes, check that first.
status);
_options.LogInfo("Recovered session: EndStatus: {0}. PauseTimestamp: {1}. PendingUnhandled: {2}",
sessionUpdate.EndStatus,
recoveredUpdate.PauseTimestamp,
recoveredUpdate.PendingUnhandled);
return sessionUpdate;
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to recover persisted session from the file system '{0}'.", filePath);
return null;
}
}
public SessionUpdate? StartSession()
{
// Extract release
var release = _options.SettingLocator.GetRelease();
if (string.IsNullOrWhiteSpace(release))
{
// Release health without release is just health (useless)
_options.LogError("Failed to start a session because there is no release information.");
return null;
}
// Extract other parameters
var environment = _options.SettingLocator.GetEnvironment();
var distinctId = _options.InstallationId;
// Create new session
var session = new SentrySession(distinctId, release, environment);
// Set new session and check whether we ended up overwriting an active one in the process
var previousSession = Interlocked.Exchange(ref _currentSession, session);
if (previousSession is not null)
{
_options.LogWarning("Starting a new session while an existing one is still active.");
// End previous session
EndSession(previousSession, _clock.GetUtcNow(), SessionEndStatus.Exited);
}
_options.LogInfo("Started new session (SID: {0}; DID: {1}).", session.Id, session.DistinctId);
var update = session.CreateUpdate(true, _clock.GetUtcNow());
PersistSession(update);
return update;
}
private SessionUpdate EndSession(SentrySession session, DateTimeOffset timestamp, SessionEndStatus status)
{
// If we're ending as 'Exited' but he session has a pending 'Unhandled', end as 'Unhandled'
if (status == SessionEndStatus.Exited && session.IsMarkedAsPendingUnhandled)
{
status = SessionEndStatus.Unhandled;
_options.LogDebug("Session ended with pending 'Unhandled' (but not `Terminal`) exception.");
}
if (status == SessionEndStatus.Crashed)
{
// increments the errors count, as crashed sessions should report a count of 1 per:
// https://develop.sentry.dev/sdk/sessions/#session-update-payload
session.ReportError();
}
_options.LogInfo("Ended session (SID: {0}; DID: {1}) with status '{2}'.",
session.Id, session.DistinctId, status);
var update = session.CreateUpdate(false, timestamp, status);
DeletePersistedSession();
return update;
}
public SessionUpdate? EndSession(DateTimeOffset timestamp, SessionEndStatus status)
{
var session = Interlocked.Exchange(ref _currentSession, null);
if (session is null)
{
_options.LogWarning("Failed to end session because there is none active.");
return null;
}
return EndSession(session, timestamp, status);
}
public SessionUpdate? EndSession(SessionEndStatus status) => EndSession(_clock.GetUtcNow(), status);
public void PauseSession()
{
if (_currentSession is not { } session)
{
_options.LogWarning("Attempted to pause a session, but a session has not been started.");
return;
}
_options.LogInfo("Pausing session (SID: {0}; DID: {1}).", session.Id, session.DistinctId);
var now = _clock.GetUtcNow();
_lastPauseTimestamp = now;
PersistSession(session.CreateUpdate(false, now), now, session.IsMarkedAsPendingUnhandled);
}
public IReadOnlyList<SessionUpdate> ResumeSession()
{
if (_currentSession is not { } session)
{
_options.LogWarning("Attempted to resume a session, but a session has not been started.");
return Array.Empty<SessionUpdate>();
}
// Ensure a session has been paused before
if (_lastPauseTimestamp is not { } sessionPauseTimestamp)
{
_options.LogWarning("Attempted to resume a session, but the current session hasn't been paused.");
return Array.Empty<SessionUpdate>();
}
_options.LogInfo("Resuming session (SID: {0}; DID: {1}).", session.Id, session.DistinctId);
// Reset the pause timestamp since the session is about to be resumed
_lastPauseTimestamp = null;
// If the pause duration exceeded tracking interval, start a new session
// (otherwise do nothing)
var pauseDuration = (_clock.GetUtcNow() - sessionPauseTimestamp).Duration();
if (pauseDuration >= _options.AutoSessionTrackingInterval)
{
_options.LogDebug(
"Paused session has been paused for {0}, which is longer than the configured timeout. " +
"Starting a new session instead of resuming this one.",
pauseDuration);
var updates = new List<SessionUpdate>(2);
// End current session
if (EndSession(sessionPauseTimestamp, SessionEndStatus.Exited) is { } endUpdate)
{
updates.Add(endUpdate);
}
// Start a new session
if (StartSession() is { } startUpdate)
{
updates.Add(startUpdate);
}
return updates;
}
_options.LogInfo("Resumed session (SID: {0}; DID: {1}) after being paused for {2}.",
session.Id, session.DistinctId, pauseDuration);
return Array.Empty<SessionUpdate>();
}
public SessionUpdate? ReportError()
{
if (_currentSession is not { } session)
{
_options.LogDebug("There is no session active. Skipping updating the session as errored. " +
"Consider setting 'AutoSessionTracking = true' to enable Release Health and crash free rate.");
return null;
}
session.ReportError();
// If we already have at least one error reported, the session update is pointless, so don't return anything.
if (session.ErrorCount > 1)
{
_options.LogDebug("Reported an error on a session that already contains errors. Not creating an update.");
return null;
}
return session.CreateUpdate(false, _clock.GetUtcNow());
}
public void MarkSessionAsUnhandled()
{
if (_currentSession is not { } session)
{
_options.LogDebug("There is no session active. Skipping marking session as unhandled.");
return;
}
session.MarkUnhandledException();
var sessionUpdate = session.CreateUpdate(false, _clock.GetUtcNow());
PersistSession(sessionUpdate, pendingUnhandled: true);
}
}