-
-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathEnvelope.cs
More file actions
528 lines (446 loc) · 16 KB
/
Copy pathEnvelope.cs
File metadata and controls
528 lines (446 loc) · 16 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
using Sentry.Extensibility;
using Sentry.Infrastructure;
using Sentry.Internal;
using Sentry.Internal.Extensions;
using Sentry.Protocol.Metrics;
namespace Sentry.Protocol.Envelopes;
/// <summary>
/// Envelope.
/// </summary>
public sealed class Envelope : ISerializable, IDisposable
{
// caches the event id from the header
private SentryId? _eventId;
/// <summary>
/// Header associated with the envelope.
/// </summary>
public IReadOnlyDictionary<string, object?> Header { get; }
/// <summary>
/// Envelope items.
/// </summary>
public IReadOnlyList<EnvelopeItem> Items { get; }
/// <summary>
/// Initializes an instance of <see cref="Envelope"/>.
/// </summary>
public Envelope(IReadOnlyDictionary<string, object?> header, IReadOnlyList<EnvelopeItem> items)
: this(null, header, items) { }
private Envelope(SentryId? eventId, IReadOnlyDictionary<string, object?> header, IReadOnlyList<EnvelopeItem> items)
{
_eventId = eventId;
Header = header;
Items = items;
}
/// <summary>
/// Attempts to extract the value of "event_id" header if it's present.
/// </summary>
public SentryId? TryGetEventId()
{
var logger = SentrySdk.CurrentOptions?.DiagnosticLogger;
return TryGetEventId(logger);
}
/// <summary>
/// Attempts to extract the value of "event_id" header if it's present.
/// </summary>
internal SentryId? TryGetEventId(IDiagnosticLogger? logger)
{
if (_eventId != null)
{
// use the cached value
return _eventId;
}
if (!Header.TryGetValue("event_id", out var value))
{
return null;
}
if (value == null)
{
logger?.LogError("Header event_id is null");
return null;
}
if (value is not string valueString)
{
logger?.LogError($"Header event_id has incorrect type: {value.GetType()}");
return null;
}
if (!Guid.TryParse(valueString, out var guid))
{
logger?.LogError($"Header event_id is not a GUID: {value}");
return null;
}
if (guid == Guid.Empty)
{
logger?.LogError("Envelope contains an empty event_id header");
_eventId = SentryId.Empty;
return _eventId;
}
_eventId = new SentryId(guid);
return _eventId;
}
private async Task SerializeHeaderAsync(
Stream stream,
IDiagnosticLogger? logger,
ISystemClock clock,
CancellationToken cancellationToken)
{
// Append the sent_at header, except when writing to disk
var headerItems = !stream.IsFileStream()
? Header.Append("sent_at", clock.GetUtcNow())
: Header;
var writer = new Utf8JsonWriter(stream);
#if NETFRAMEWORK || NETSTANDARD2_0
await using (writer)
#else
await using (writer.ConfigureAwait(false))
#endif
{
writer.WriteDictionaryValue(headerItems, logger);
await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}
private void SerializeHeader(Stream stream, IDiagnosticLogger? logger, ISystemClock clock)
{
// Append the sent_at header, except when writing to disk
var headerItems = !stream.IsFileStream()
? Header.Append("sent_at", clock.GetUtcNow())
: Header;
using var writer = new Utf8JsonWriter(stream);
writer.WriteDictionaryValue(headerItems, logger);
writer.Flush();
}
/// <inheritdoc />
public Task SerializeAsync(
Stream stream,
IDiagnosticLogger? logger,
CancellationToken cancellationToken = default) =>
SerializeAsync(stream, logger, SystemClock.Clock, cancellationToken);
internal async Task SerializeAsync(
Stream stream,
IDiagnosticLogger? logger,
ISystemClock clock,
CancellationToken cancellationToken = default)
{
// Header
await SerializeHeaderAsync(stream, logger, clock, cancellationToken).ConfigureAwait(false);
await stream.WriteNewlineAsync(cancellationToken).ConfigureAwait(false);
// Items
foreach (var item in Items)
{
try
{
await item.SerializeAsync(stream, logger, cancellationToken).ConfigureAwait(false);
await stream.WriteNewlineAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
logger?.LogWarning(e, "Failed to serialize envelope item");
}
}
}
/// <inheritdoc />
public void Serialize(Stream stream, IDiagnosticLogger? logger) =>
Serialize(stream, logger, SystemClock.Clock);
internal void Serialize(Stream stream, IDiagnosticLogger? logger, ISystemClock clock)
{
// Header
SerializeHeader(stream, logger, clock);
stream.WriteNewline();
// Items
foreach (var item in Items)
{
try
{
item.Serialize(stream, logger);
stream.WriteNewline();
}
catch (Exception e)
{
logger?.LogWarning(e, "Failed to serialize envelope item");
}
}
}
/// <inheritdoc />
public void Dispose() => Items.DisposeAll();
// limited SDK information (no packages)
private static readonly IReadOnlyDictionary<string, string?> SdkHeader =
new Dictionary<string, string?>(2, StringComparer.Ordinal)
{
["name"] = SdkVersion.Instance.Name,
["version"] = SdkVersion.Instance.Version
}.AsReadOnly();
private static readonly IReadOnlyDictionary<string, object?> DefaultHeader =
new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
["sdk"] = SdkHeader
}.AsReadOnly();
private static Dictionary<string, object?> CreateHeader(SentryId eventId, int extraCapacity = 0) =>
new(2 + extraCapacity, StringComparer.Ordinal)
{
["sdk"] = SdkHeader,
["event_id"] = eventId.ToString()
};
private static Dictionary<string, object?> CreateHeader(SentryId eventId, DynamicSamplingContext? dsc)
{
if (dsc == null)
{
return CreateHeader(eventId);
}
var header = CreateHeader(eventId, extraCapacity: 1);
header["trace"] = dsc.Items;
return header;
}
/// <summary>
/// Creates an envelope that contains a single event.
/// </summary>
public static Envelope FromEvent(
SentryEvent @event,
IDiagnosticLogger? logger = null,
IReadOnlyCollection<SentryAttachment>? attachments = null,
SessionUpdate? sessionUpdate = null)
{
var eventId = @event.EventId;
var header = CreateHeader(eventId, @event.DynamicSamplingContext);
var items = new List<EnvelopeItem>
{
EnvelopeItem.FromEvent(@event)
};
if (attachments is not null)
{
foreach (var attachment in attachments)
{
// Safety check, in case the user forcefully added a null attachment.
if (attachment.IsNull())
{
logger?.LogWarning("Encountered a null attachment. Skipping.");
continue;
}
AddEnvelopeItemFromAttachment(items, attachment, logger);
}
}
if (sessionUpdate is not null)
{
items.Add(EnvelopeItem.FromSession(sessionUpdate));
}
return new Envelope(eventId, header, items);
}
private static void AddEnvelopeItemFromAttachment(List<EnvelopeItem> items, SentryAttachment attachment,
IDiagnosticLogger? logger)
{
try
{
// We pull the stream out here so we can length check
// to avoid adding an invalid attachment
var stream = attachment.Content.GetStream();
if (stream.TryGetLength() != 0)
{
items.Add(EnvelopeItem.FromAttachment(attachment, stream));
}
else
{
// We would normally dispose the stream when we dispose the envelope item
// But in this case, we need to explicitly dispose here or we will be leaving
// the stream open indefinitely.
stream.Dispose();
logger?.LogWarning("Did not add '{0}' to envelope because the stream was empty.",
attachment.FileName);
}
}
catch (Exception exception)
{
logger?.LogError(exception, "Failed to add attachment: {0}.", attachment.FileName);
}
}
/// <summary>
/// Creates an envelope that contains a single feedback event.
/// </summary>
public static Envelope FromFeedback(
SentryEvent @event,
IDiagnosticLogger? logger = null,
IReadOnlyCollection<SentryAttachment>? attachments = null,
SessionUpdate? sessionUpdate = null)
{
if (@event.Contexts.Feedback == null)
{
throw new ArgumentException("Unable to create envelope - the event does not contain any feedback.");
}
var eventId = @event.EventId;
var header = CreateHeader(eventId, @event.DynamicSamplingContext);
var items = new List<EnvelopeItem>
{
EnvelopeItem.FromFeedback(@event)
};
if (attachments is { Count: > 0 })
{
foreach (var attachment in attachments)
{
// Safety check, in case the user forcefully added a null attachment.
if (attachment.IsNull())
{
logger?.LogWarning("Encountered a null attachment. Skipping.");
continue;
}
AddEnvelopeItemFromAttachment(items, attachment, logger);
}
}
if (sessionUpdate is not null)
{
items.Add(EnvelopeItem.FromSession(sessionUpdate));
}
return new Envelope(eventId, header, items);
}
/// <summary>
/// Creates an envelope that contains a single transaction.
/// </summary>
public static Envelope FromTransaction(
SentryTransaction transaction,
IDiagnosticLogger? logger = null,
IReadOnlyCollection<SentryAttachment>? attachments = null)
{
var eventId = transaction.EventId;
var header = CreateHeader(eventId, transaction.DynamicSamplingContext);
var items = new List<EnvelopeItem>
{
EnvelopeItem.FromTransaction(transaction)
};
if (transaction.TransactionProfiler is { } profiler)
{
// Profiler.Collect() returns an ISerializable which may also throw asynchronously, which is handled down
// the road in AsyncJsonSerializable and the EnvelopeItem won't serialize and is omitted.
// However, it mustn't throw synchronously because that would prevent the whole transaction being sent.
if (profiler.Collect(transaction) is { } profileInfo)
{
items.Add(EnvelopeItem.FromProfileInfo(profileInfo));
}
}
if (attachments is not null)
{
foreach (var attachment in attachments)
{
if (attachment.IsNull())
{
logger?.LogWarning("Encountered a null attachment. Skipping.");
continue;
}
AddEnvelopeItemFromAttachment(items, attachment, logger);
}
}
return new Envelope(eventId, header, items);
}
/// <summary>
/// Creates an envelope that contains one or more <see cref="CodeLocations"/>
/// </summary>
internal static Envelope FromCodeLocations(CodeLocations codeLocations)
{
var header = DefaultHeader;
var items = new List<EnvelopeItem>(1);
items.Add(EnvelopeItem.FromCodeLocations(codeLocations));
return new Envelope(header, items);
}
/// <summary>
/// Creates an envelope that contains one or more Metrics
/// </summary>
internal static Envelope FromMetrics(IEnumerable<Metric> metrics)
{
var header = DefaultHeader;
List<EnvelopeItem> items = new();
foreach (var metric in metrics)
{
items.Add(EnvelopeItem.FromMetric(metric));
}
return new Envelope(header, items);
}
/// <summary>
/// Creates an envelope that contains a session update.
/// </summary>
public static Envelope FromSession(SessionUpdate sessionUpdate)
{
var header = DefaultHeader;
var items = new[]
{
EnvelopeItem.FromSession(sessionUpdate)
};
return new Envelope(header, items);
}
/// <summary>
/// Creates an envelope that contains a check in.
/// </summary>
public static Envelope FromCheckIn(SentryCheckIn checkIn)
{
var header = DefaultHeader;
var items = new[] { EnvelopeItem.FromCheckIn(checkIn) };
return new Envelope(header, items);
}
/// <summary>
/// Creates an envelope that contains a client report.
/// </summary>
internal static Envelope FromClientReport(ClientReport clientReport)
{
var header = DefaultHeader;
var items = new[]
{
EnvelopeItem.FromClientReport(clientReport)
};
return new Envelope(header, items);
}
/// <summary>
/// Creates an envelope that contains only an attachment for an existing event.
/// </summary>
internal static Envelope FromAttachment(SentryId eventId, SentryAttachment attachment, IDiagnosticLogger? logger = null) =>
new(eventId, CreateHeader(eventId), [EnvelopeItem.FromAttachment(attachment)]);
internal static Envelope FromLog(StructuredLog log)
{
var header = DefaultHeader;
var items = new[]
{
EnvelopeItem.FromLog(log),
};
return new Envelope(header, items);
}
internal static Envelope FromMetric(TraceMetric metric)
{
var header = DefaultHeader;
var items = new[]
{
EnvelopeItem.FromMetric(metric),
};
return new Envelope(header, items);
}
private static async Task<IReadOnlyDictionary<string, object?>> DeserializeHeaderAsync(
Stream stream,
CancellationToken cancellationToken = default)
{
var buffer = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false);
var header =
Json.Parse(buffer, JsonExtensions.GetDictionaryOrNull)
?? throw new InvalidOperationException("Envelope header is malformed.");
// The sent_at header should not be included in the result
header.Remove("sent_at");
return header;
}
/// <summary>
/// Deserializes envelope from stream.
/// </summary>
public static async Task<Envelope> DeserializeAsync(
Stream stream,
CancellationToken cancellationToken = default)
{
var header = await DeserializeHeaderAsync(stream, cancellationToken).ConfigureAwait(false);
var items = new List<EnvelopeItem>();
while (stream.Position < stream.Length)
{
var item = await EnvelopeItem.DeserializeAsync(stream, cancellationToken).ConfigureAwait(false);
items.Add(item);
}
return new Envelope(header, items);
}
/// <summary>
/// Creates a new <see cref="Envelope"/> starting from the current one and appends the <paramref name="item"/> given.
/// </summary>
/// <param name="item">The <see cref="EnvelopeItem"/> to append.</param>
/// <returns>A new <see cref="Envelope"/> with the same headers and items, including the new <paramref name="item"/>.</returns>
internal Envelope WithItem(EnvelopeItem item)
{
var items = Items.ToList();
items.Add(item);
return new Envelope(_eventId, Header, items);
}
}