-
-
Notifications
You must be signed in to change notification settings - Fork 203
/
EnvelopeItem.cs
450 lines (377 loc) · 16 KB
/
EnvelopeItem.cs
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
using Sentry.Extensibility;
using Sentry.Internal;
using Sentry.Internal.Extensions;
using Sentry.Protocol.Metrics;
namespace Sentry.Protocol.Envelopes;
/// <summary>
/// Envelope item.
/// </summary>
public sealed class EnvelopeItem : ISerializable, IDisposable
{
private const string TypeKey = "type";
internal const string TypeValueEvent = "event";
internal const string TypeValueUserReport = "user_report";
internal const string TypeValueTransaction = "transaction";
internal const string TypeValueSession = "session";
internal const string TypeValueCheckIn = "check_in";
internal const string TypeValueAttachment = "attachment";
internal const string TypeValueClientReport = "client_report";
internal const string TypeValueProfile = "profile";
internal const string TypeValueMetric = "statsd";
internal const string TypeValueCodeLocations = "metric_meta";
private const string LengthKey = "length";
private const string FileNameKey = "filename";
/// <summary>
/// Header associated with this envelope item.
/// </summary>
public IReadOnlyDictionary<string, object?> Header { get; }
/// <summary>
/// Item payload.
/// </summary>
public ISerializable Payload { get; }
internal DataCategory DataCategory => TryGetType() switch
{
// Yes, the "event" item type corresponds to the "error" data category
TypeValueEvent => DataCategory.Error,
// These ones are equivalent
TypeValueTransaction => DataCategory.Transaction,
TypeValueSession => DataCategory.Session,
TypeValueAttachment => DataCategory.Attachment,
TypeValueProfile => DataCategory.Profile,
// Not all envelope item types equate to data categories
// Specifically, user_report and client_report just use "default"
_ => DataCategory.Default
};
/// <summary>
/// Initializes an instance of <see cref="EnvelopeItem"/>.
/// </summary>
public EnvelopeItem(IReadOnlyDictionary<string, object?> header, ISerializable payload)
{
Header = header;
Payload = payload;
}
/// <summary>
/// Tries to get item type.
/// </summary>
public string? TryGetType() => Header.GetValueOrDefault(TypeKey) as string;
/// <summary>
/// Tries to get payload length.
/// </summary>
public long? TryGetLength() =>
Header.GetValueOrDefault(LengthKey) switch
{
null => null,
var value => Convert.ToInt64(value) // can be int, long, or another numeric type
};
/// <summary>
/// Returns the file name or null if no name exists.
/// </summary>
/// <returns>The file name or null.</returns>
public string? TryGetFileName() => Header.GetValueOrDefault(FileNameKey) as string;
private async Task<MemoryStream> BufferPayloadAsync(IDiagnosticLogger? logger, CancellationToken cancellationToken)
{
var buffer = new MemoryStream();
if (Payload is JsonSerializable jsonSerializable)
{
// There's no advantage to buffer fully-materialized in-memory objects asynchronously,
// and there's some minor overhead in doing so. Thus we will serialize synchronously.
// ReSharper disable once MethodHasAsyncOverloadWithCancellation
jsonSerializable.Serialize(buffer, logger);
}
else
{
await Payload.SerializeAsync(buffer, logger, cancellationToken).ConfigureAwait(false);
}
buffer.Seek(0, SeekOrigin.Begin);
return buffer;
}
private MemoryStream BufferPayload(IDiagnosticLogger? logger)
{
var buffer = new MemoryStream();
Payload.Serialize(buffer, logger);
buffer.Seek(0, SeekOrigin.Begin);
return buffer;
}
private static async Task SerializeHeaderAsync(
Stream stream,
IReadOnlyDictionary<string, object?> header,
IDiagnosticLogger? logger,
CancellationToken cancellationToken)
{
var writer = new Utf8JsonWriter(stream);
await using (writer.ConfigureAwait(false))
{
writer.WriteDictionaryValue(header, logger);
await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}
private static void SerializeHeader(
Stream stream,
IReadOnlyDictionary<string, object?> header,
IDiagnosticLogger? logger)
{
using var writer = new Utf8JsonWriter(stream);
writer.WriteDictionaryValue(header, logger);
writer.Flush();
}
/// <inheritdoc />
public async Task SerializeAsync(Stream stream, IDiagnosticLogger? logger,
CancellationToken cancellationToken = default)
{
// Always calculate the length of the payload, as Sentry will reject envelopes that have incorrect lengths
// in item headers. Don't trust any previously calculated value to be correct.
// See https://github.com/getsentry/sentry-dotnet/issues/1956
var payloadBuffer = await BufferPayloadAsync(logger, cancellationToken).ConfigureAwait(false);
#if NETFRAMEWORK || NETSTANDARD2_0
using (payloadBuffer)
#else
await using (payloadBuffer.ConfigureAwait(false))
#endif
{
// Write to the outbound stream asynchronously. It's likely either an HttpRequestStream or a FileStream.
// Header
var headerWithLength = Header.ToDict();
headerWithLength[LengthKey] = payloadBuffer.Length;
await SerializeHeaderAsync(stream, headerWithLength, logger, cancellationToken).ConfigureAwait(false);
await stream.WriteNewlineAsync(cancellationToken).ConfigureAwait(false);
// Payload
await payloadBuffer.CopyToAsync(stream, cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
public void Serialize(Stream stream, IDiagnosticLogger? logger)
{
// Always calculate the length of the payload, as Sentry will reject envelopes that have incorrect lengths
// in item headers. Don't trust any previously calculated value to be correct.
// See https://github.com/getsentry/sentry-dotnet/issues/1956
using var payloadBuffer = BufferPayload(logger);
// Header
var headerWithLength = Header.ToDict();
headerWithLength[LengthKey] = payloadBuffer.Length;
SerializeHeader(stream, headerWithLength, logger);
stream.WriteNewline();
// Payload
payloadBuffer.CopyTo(stream);
}
/// <inheritdoc />
public void Dispose() => (Payload as IDisposable)?.Dispose();
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="event"/>.
/// </summary>
public static EnvelopeItem FromEvent(SentryEvent @event)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueEvent
};
return new EnvelopeItem(header, new JsonSerializable(@event));
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="sentryUserFeedback"/>.
/// </summary>
public static EnvelopeItem FromUserFeedback(UserFeedback sentryUserFeedback)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueUserReport
};
return new EnvelopeItem(header, new JsonSerializable(sentryUserFeedback));
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="transaction"/>.
/// </summary>
public static EnvelopeItem FromTransaction(SentryTransaction transaction)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueTransaction
};
return new EnvelopeItem(header, new JsonSerializable(transaction));
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from one or more <paramref name="codeLocations"/>.
/// </summary>
internal static EnvelopeItem FromCodeLocations(CodeLocations codeLocations)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueCodeLocations
};
// Note that metrics are serialized using statsd encoding (not JSON)
return new EnvelopeItem(header, new JsonSerializable(codeLocations));
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="metric"/>.
/// </summary>
internal static EnvelopeItem FromMetric(Metric metric)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueMetric
};
// Note that metrics are serialized using statsd encoding (not JSON)
return new EnvelopeItem(header, metric);
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="source"/>.
/// </summary>
internal static EnvelopeItem FromProfileInfo(ISerializable source)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueProfile
};
return new EnvelopeItem(header, source);
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="sessionUpdate"/>.
/// </summary>
public static EnvelopeItem FromSession(SessionUpdate sessionUpdate)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueSession
};
return new EnvelopeItem(header, new JsonSerializable(sessionUpdate));
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="checkIn"/>.
/// </summary>
public static EnvelopeItem FromCheckIn(SentryCheckIn checkIn)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueCheckIn
};
return new EnvelopeItem(header, new JsonSerializable(checkIn));
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="attachment"/>.
/// </summary>
public static EnvelopeItem FromAttachment(SentryAttachment attachment)
{
var stream = attachment.Content.GetStream();
return FromAttachment(attachment, stream);
}
internal static EnvelopeItem FromAttachment(SentryAttachment attachment, Stream stream)
{
var attachmentType = attachment.Type switch
{
AttachmentType.Minidump => "event.minidump",
AttachmentType.AppleCrashReport => "event.applecrashreport",
AttachmentType.UnrealContext => "unreal.context",
AttachmentType.UnrealLogs => "unreal.logs",
AttachmentType.ViewHierarchy => "event.view_hierarchy",
_ => "event.attachment"
};
var header = new Dictionary<string, object?>(5, StringComparer.Ordinal)
{
[TypeKey] = TypeValueAttachment,
[LengthKey] = stream.TryGetLength(),
[FileNameKey] = attachment.FileName,
["attachment_type"] = attachmentType,
["content_type"] = attachment.ContentType
};
return new EnvelopeItem(header, new StreamSerializable(stream));
}
/// <summary>
/// Creates an <see cref="EnvelopeItem"/> from <paramref name="report"/>.
/// </summary>
internal static EnvelopeItem FromClientReport(ClientReport report)
{
var header = new Dictionary<string, object?>(1, StringComparer.Ordinal)
{
[TypeKey] = TypeValueClientReport
};
return new EnvelopeItem(header, new JsonSerializable(report));
}
private static async Task<Dictionary<string, object?>> DeserializeHeaderAsync(
Stream stream,
CancellationToken cancellationToken = default)
{
var buffer = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false);
return
Json.Parse(buffer, JsonExtensions.GetDictionaryOrNull)
?? throw new InvalidOperationException("Envelope item header is malformed.");
}
private static async Task<ISerializable> DeserializePayloadAsync(
Stream stream,
IReadOnlyDictionary<string, object?> header,
CancellationToken cancellationToken = default)
{
var payloadLength = header.GetValueOrDefault(LengthKey) switch
{
null => (long?)null,
var value => Convert.ToInt64(value)
};
var payloadType = header.GetValueOrDefault(TypeKey) as string;
// Event
if (string.Equals(payloadType, TypeValueEvent, StringComparison.OrdinalIgnoreCase))
{
var bufferLength = (int)(payloadLength ?? stream.Length);
var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false);
var sentryEvent = Json.Parse(buffer, SentryEvent.FromJson);
return new JsonSerializable(sentryEvent);
}
// User report
if (string.Equals(payloadType, TypeValueUserReport, StringComparison.OrdinalIgnoreCase))
{
var bufferLength = (int)(payloadLength ?? stream.Length);
var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false);
var userFeedback = Json.Parse(buffer, UserFeedback.FromJson);
return new JsonSerializable(userFeedback);
}
// Transaction
if (string.Equals(payloadType, TypeValueTransaction, StringComparison.OrdinalIgnoreCase))
{
var bufferLength = (int)(payloadLength ?? stream.Length);
var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false);
var transaction = Json.Parse(buffer, SentryTransaction.FromJson);
return new JsonSerializable(transaction);
}
// Session
if (string.Equals(payloadType, TypeValueSession, StringComparison.OrdinalIgnoreCase))
{
var bufferLength = (int)(payloadLength ?? stream.Length);
var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false);
var sessionUpdate = Json.Parse(buffer, SessionUpdate.FromJson);
return new JsonSerializable(sessionUpdate);
}
// Client Report
if (string.Equals(payloadType, TypeValueClientReport, StringComparison.OrdinalIgnoreCase))
{
var bufferLength = (int)(payloadLength ?? stream.Length);
var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false);
var clientReport = Json.Parse(buffer, ClientReport.FromJson);
return new JsonSerializable(clientReport);
}
// Arbitrary payload
var payloadStream = new PartialStream(stream, stream.Position, payloadLength);
if (payloadLength is not null)
{
stream.Seek(payloadLength.Value, SeekOrigin.Current);
}
else
{
stream.Seek(0, SeekOrigin.End);
}
return new StreamSerializable(payloadStream);
}
/// <summary>
/// Deserializes envelope item from stream.
/// </summary>
public static async Task<EnvelopeItem> DeserializeAsync(
Stream stream,
CancellationToken cancellationToken = default)
{
var header = await DeserializeHeaderAsync(stream, cancellationToken).ConfigureAwait(false);
var payload = await DeserializePayloadAsync(stream, header, cancellationToken).ConfigureAwait(false);
// Swallow trailing newlines (some envelopes may have them after payloads)
await stream.SkipNewlinesAsync(cancellationToken).ConfigureAwait(false);
// Always remove the length header on deserialization so it will get re-calculated if later serialized.
// We cannot trust the length to be identical when round-tripped.
// See https://github.com/getsentry/sentry-dotnet/issues/1956
header.Remove(LengthKey);
return new EnvelopeItem(header, payload);
}
}