Skip to content

Commit

Permalink
feat: Metrics.Set now accepts string as value (#3092)
Browse files Browse the repository at this point in the history
  • Loading branch information
bitsandfoxes committed Jan 30, 2024
1 parent bc834f1 commit 8bc2e51
Show file tree
Hide file tree
Showing 13 changed files with 385 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ If you have conflicts, you can opt-out by adding the following to your `csproj`:

### Features

- `SentrySdk.Metrics.Set` now additionally accepts `string` as value ([#3092](https://github.com/getsentry/sentry-dotnet/pull/3092))
- Timing metrics can now be captured with `SentrySdk.Metrics.StartTimer` ([#3075](https://github.com/getsentry/sentry-dotnet/pull/3075))

### Fixes
Expand Down
7 changes: 7 additions & 0 deletions src/Sentry/DisabledMetricAggregator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ public void Set(string key, int value, MeasurementUnit? unit = null,
// No Op
}

public void Set(string key, string value, MeasurementUnit? unit = null,
IDictionary<string, string>? tags = null,
DateTimeOffset? timestamp = null, int stackLevel = 1)
{
// No Op
}

public void Timing(string key, double value, MeasurementUnit.Duration unit = MeasurementUnit.Duration.Second,
IDictionary<string, string>? tags = null,
DateTimeOffset? timestamp = null, int stackLevel = 1)
Expand Down
190 changes: 190 additions & 0 deletions src/Sentry/Force.Crc32/Crc32Algorithm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
// Namespace starting with Sentry makes sure the SDK cuts frames off before reporting
namespace Sentry.Force.Crc32
{
/// <summary>
/// Implementation of CRC-32.
/// This class supports several convenient static methods returning the CRC as UInt32.
/// </summary>
internal class Crc32Algorithm : HashAlgorithm
{
private uint _currentCrc;

private readonly bool _isBigEndian = true;

/// <summary>
/// Initializes a new instance of the <see cref="Crc32Algorithm"/> class.
/// </summary>
public Crc32Algorithm()
{
#if !NETCORE13
HashSizeValue = 32;
#endif
}

/// <summary>
/// Initializes a new instance of the <see cref="Crc32Algorithm"/> class.
/// </summary>
/// <param name="isBigEndian">Should return bytes result as big endian or little endian</param>
// Crc32 by dariogriffo uses big endian, so, we need to be compatible and return big endian as default
public Crc32Algorithm(bool isBigEndian = true)
: this()
{
_isBigEndian = isBigEndian;
}

/// <summary>
/// Computes CRC-32 from multiple buffers.
/// Call this method multiple times to chain multiple buffers.
/// </summary>
/// <param name="initial">
/// Initial CRC value for the algorithm. It is zero for the first buffer.
/// Subsequent buffers should have their initial value set to CRC value returned by previous call to this method.
/// </param>
/// <param name="input">Input buffer with data to be checksummed.</param>
/// <param name="offset">Offset of the input data within the buffer.</param>
/// <param name="length">Length of the input data in the buffer.</param>
/// <returns>Accumulated CRC-32 of all buffers processed so far.</returns>
public static uint Append(uint initial, byte[] input, int offset, int length)
{
if (input == null)
throw new ArgumentNullException("input");
if (offset < 0 || length < 0 || offset + length > input.Length)
throw new ArgumentOutOfRangeException("length");
return AppendInternal(initial, input, offset, length);
}

/// <summary>
/// Computes CRC-32 from multiple buffers.
/// Call this method multiple times to chain multiple buffers.
/// </summary>
/// <param name="initial">
/// Initial CRC value for the algorithm. It is zero for the first buffer.
/// Subsequent buffers should have their initial value set to CRC value returned by previous call to this method.
/// </param>
/// <param name="input">Input buffer containing data to be checksummed.</param>
/// <returns>Accumulated CRC-32 of all buffers processed so far.</returns>
public static uint Append(uint initial, byte[] input)
{
if (input == null)
throw new ArgumentNullException();
return AppendInternal(initial, input, 0, input.Length);
}

/// <summary>
/// Computes CRC-32 from input buffer.
/// </summary>
/// <param name="input">Input buffer with data to be checksummed.</param>
/// <param name="offset">Offset of the input data within the buffer.</param>
/// <param name="length">Length of the input data in the buffer.</param>
/// <returns>CRC-32 of the data in the buffer.</returns>
public static uint Compute(byte[] input, int offset, int length)
{
return Append(0, input, offset, length);
}

/// <summary>
/// Computes CRC-32 from input buffer.
/// </summary>
/// <param name="input">Input buffer containing data to be checksummed.</param>
/// <returns>CRC-32 of the buffer.</returns>
public static uint Compute(byte[] input)
{
return Append(0, input);
}

/// <summary>
/// Computes CRC-32 from input buffer and writes it after end of data (buffer should have 4 bytes reserved space for it). Can be used in conjunction with <see cref="IsValidWithCrcAtEnd(byte[],int,int)"/>
/// </summary>
/// <param name="input">Input buffer with data to be checksummed.</param>
/// <param name="offset">Offset of the input data within the buffer.</param>
/// <param name="length">Length of the input data in the buffer.</param>
/// <returns>CRC-32 of the data in the buffer.</returns>
public static uint ComputeAndWriteToEnd(byte[] input, int offset, int length)
{
if (length + 4 > input.Length)
throw new ArgumentOutOfRangeException("length", "Length of data should be less than array length - 4 bytes of CRC data");
var crc = Append(0, input, offset, length);
var r = offset + length;
input[r] = (byte)crc;
input[r + 1] = (byte)(crc >> 8);
input[r + 2] = (byte)(crc >> 16);
input[r + 3] = (byte)(crc >> 24);
return crc;
}

/// <summary>
/// Computes CRC-32 from input buffer - 4 bytes and writes it as last 4 bytes of buffer. Can be used in conjunction with <see cref="IsValidWithCrcAtEnd(byte[])"/>
/// </summary>
/// <param name="input">Input buffer with data to be checksummed.</param>
/// <returns>CRC-32 of the data in the buffer.</returns>
public static uint ComputeAndWriteToEnd(byte[] input)
{
if (input.Length < 4)
throw new ArgumentOutOfRangeException("input", "Input array should be 4 bytes at least");
return ComputeAndWriteToEnd(input, 0, input.Length - 4);
}

/// <summary>
/// Validates correctness of CRC-32 data in source buffer with assumption that CRC-32 data located at end of buffer in reverse bytes order. Can be used in conjunction with <see cref="ComputeAndWriteToEnd(byte[],int,int)"/>
/// </summary>
/// <param name="input">Input buffer with data to be checksummed.</param>
/// <param name="offset">Offset of the input data within the buffer.</param>
/// <param name="lengthWithCrc">Length of the input data in the buffer with CRC-32 bytes.</param>
/// <returns>Is checksum valid.</returns>
public static bool IsValidWithCrcAtEnd(byte[] input, int offset, int lengthWithCrc)
{
return Append(0, input, offset, lengthWithCrc) == 0x2144DF1C;
}

/// <summary>
/// Validates correctness of CRC-32 data in source buffer with assumption that CRC-32 data located at end of buffer in reverse bytes order. Can be used in conjunction with <see cref="ComputeAndWriteToEnd(byte[],int,int)"/>
/// </summary>
/// <param name="input">Input buffer with data to be checksummed.</param>
/// <returns>Is checksum valid.</returns>
public static bool IsValidWithCrcAtEnd(byte[] input)
{
if (input.Length < 4)
throw new ArgumentOutOfRangeException("input", "Input array should be 4 bytes at least");
return Append(0, input, 0, input.Length) == 0x2144DF1C;
}

/// <summary>
/// Resets internal state of the algorithm. Used internally.
/// </summary>
public override void Initialize()
{
_currentCrc = 0;
}

/// <summary>
/// Appends CRC-32 from given buffer
/// </summary>
protected override void HashCore(byte[] input, int offset, int length)
{
_currentCrc = AppendInternal(_currentCrc, input, offset, length);
}

/// <summary>
/// Computes CRC-32 from <see cref="HashCore"/>
/// </summary>
protected override byte[] HashFinal()
{
if (_isBigEndian)
return new[] { (byte)(_currentCrc >> 24), (byte)(_currentCrc >> 16), (byte)(_currentCrc >> 8), (byte)_currentCrc };
else
return new[] { (byte)_currentCrc, (byte)(_currentCrc >> 8), (byte)(_currentCrc >> 16), (byte)(_currentCrc >> 24) };
}

private static readonly SafeProxy _proxy = new SafeProxy();

private static uint AppendInternal(uint initial, byte[] input, int offset, int length)
{
if (length > 0)
{
return _proxy.Append(initial, input, offset, length);
}
else
return initial;
}
}
}
23 changes: 23 additions & 0 deletions src/Sentry/Force.Crc32/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Copied from https://github.com/force-net/Crc32.NET/blob/26c5a818a5c7a3d6a622c92d3cd08dba586c263c/LICENSE

The MIT License (MIT)

Copyright (c) 2016 force

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
13 changes: 13 additions & 0 deletions src/Sentry/Force.Crc32/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Files from force's `Crc32.NET` at `26c5a818a5c7a3d6a622c92d3cd08dba586c263c` copied:

https://github.com/force-net/Crc32.NET/commit/26c5a818a5c7a3d6a622c92d3cd08dba586c263c

Sentry's core package's goal is to be dependency-free. Because of that we use different strategies of vendoring-in code.
`Ben.Demystifier` for example comes in through a git submodule, and a commit changing all types to `internal` is added.

Here, since no changes were done to this project in years, and it's just a handful of files,
we're directly copying and changing them.

Main changes:

* Make everything internal.
77 changes: 77 additions & 0 deletions src/Sentry/Force.Crc32/SafeProxy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/* This is .NET safe implementation of Crc32 algorithm.
* This implementation was investigated as fastest from different variants. It based on Robert Vazan native implementations of Crc32C
* Also, it is good for x64 and for x86, so, it seems, there is no sense to do 2 different realizations.
*
* Addition: some speed increase was found with splitting xor to 4 independent blocks. Also, some attempts to optimize unaligned tails was unsuccessfull (JIT limitations?).
*
*
* Max Vysokikh, 2016-2017
*/

// Namespace starting with Sentry makes sure the SDK cuts frames off before reporting
namespace Sentry.Force.Crc32
{
internal class SafeProxy
{
private const uint Poly = 0xedb88320u;

private readonly uint[] _table = new uint[16 * 256];

internal SafeProxy()
{
Init(Poly);
}

protected void Init(uint poly)
{
var table = _table;
for (uint i = 0; i < 256; i++)
{
uint res = i;
for (int t = 0; t < 16; t++)
{
for (int k = 0; k < 8; k++) res = (res & 1) == 1 ? poly ^ (res >> 1) : (res >> 1);
table[(t * 256) + i] = res;
}
}
}

public uint Append(uint crc, byte[] input, int offset, int length)
{
uint crcLocal = uint.MaxValue ^ crc;

uint[] table = _table;
while (length >= 16)
{
var a = table[(3 * 256) + input[offset + 12]]
^ table[(2 * 256) + input[offset + 13]]
^ table[(1 * 256) + input[offset + 14]]
^ table[(0 * 256) + input[offset + 15]];

var b = table[(7 * 256) + input[offset + 8]]
^ table[(6 * 256) + input[offset + 9]]
^ table[(5 * 256) + input[offset + 10]]
^ table[(4 * 256) + input[offset + 11]];

var c = table[(11 * 256) + input[offset + 4]]
^ table[(10 * 256) + input[offset + 5]]
^ table[(9 * 256) + input[offset + 6]]
^ table[(8 * 256) + input[offset + 7]];

var d = table[(15 * 256) + ((byte)crcLocal ^ input[offset])]
^ table[(14 * 256) + ((byte)(crcLocal >> 8) ^ input[offset + 1])]
^ table[(13 * 256) + ((byte)(crcLocal >> 16) ^ input[offset + 2])]
^ table[(12 * 256) + ((crcLocal >> 24) ^ input[offset + 3])];

crcLocal = d ^ c ^ b ^ a;
offset += 16;
length -= 16;
}

while (--length >= 0)
crcLocal = table[(byte)(crcLocal ^ input[offset++])] ^ crcLocal >> 8;

return crcLocal ^ uint.MaxValue;
}
}
}
18 changes: 18 additions & 0 deletions src/Sentry/IMetricAggregator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,24 @@ void Set(string key,
DateTimeOffset? timestamp = null,
int stackLevel = 1);

/// <summary>
/// Emits a Set metric a
/// </summary>
/// <param name="key">A unique key identifying the metric</param>
/// <param name="value">The value to be added</param>
/// <param name="unit">An optional <see cref="MeasurementUnit"/></param>
/// <param name="tags">Optional Tags to associate with the metric</param>
/// <param name="timestamp">
/// The time when the metric was emitted. Defaults to the time at which the metric is emitted, if no value is provided.
/// </param>
/// <param name="stackLevel">Optional number of stacks levels to ignore when determining the code location</param>
void Set(string key,
string value,
MeasurementUnit? unit = null,
IDictionary<string, string>? tags = null,
DateTimeOffset? timestamp = null,
int stackLevel = 1);

/// <summary>
/// Emits a distribution with the time it takes to run a given code block.
/// </summary>
Expand Down
18 changes: 17 additions & 1 deletion src/Sentry/MetricAggregator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Sentry.Extensibility;
using Sentry.Force.Crc32;
using Sentry.Internal;
using Sentry.Internal.Extensions;
using Sentry.Protocol.Metrics;
Expand Down Expand Up @@ -132,14 +133,29 @@ public void Distribution(string key,
DateTimeOffset? timestamp = null,
int stackLevel = 1) => Emit(MetricType.Distribution, key, value, unit, tags, timestamp, stackLevel + 1);

/// <inheritdoc cref="IMetricAggregator.Set"/>
/// <inheritdoc cref="IMetricAggregator.Set(string,int,MeasurementUnit?,System.Collections.Generic.IDictionary{string,string},DateTimeOffset?,int)"/>
public void Set(string key,
int value,
MeasurementUnit? unit = null,
IDictionary<string, string>? tags = null,
DateTimeOffset? timestamp = null,
int stackLevel = 1) => Emit(MetricType.Set, key, value, unit, tags, timestamp, stackLevel + 1);

/// <inheritdoc cref="IMetricAggregator.Set(string,string,MeasurementUnit?,System.Collections.Generic.IDictionary{string,string},DateTimeOffset?,int)"/>
public void Set(string key,
string value,
MeasurementUnit? unit = null,
IDictionary<string, string>? tags = null,
DateTimeOffset? timestamp = null,
int stackLevel = 1)
{
// Compute the CRC32 hash of the value as byte array and cast it to a 32-bit signed integer
// Mask the lower 32 bits to ensure the result fits within the 32-bit integer range
var hash = (int)(Crc32Algorithm.Compute(Encoding.UTF8.GetBytes(value)) & 0xFFFFFFFF);

Emit(MetricType.Set, key, hash, unit, tags, timestamp, stackLevel + 1);
}

/// <inheritdoc cref="IMetricAggregator.Timing"/>
public void Timing(string key,
double value,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ namespace Sentry
void Gauge(string key, double value = 1, Sentry.MeasurementUnit? unit = default, System.Collections.Generic.IDictionary<string, string>? tags = null, System.DateTimeOffset? timestamp = default, int stackLevel = 1);
void Increment(string key, double value = 1, Sentry.MeasurementUnit? unit = default, System.Collections.Generic.IDictionary<string, string>? tags = null, System.DateTimeOffset? timestamp = default, int stackLevel = 1);
void Set(string key, int value, Sentry.MeasurementUnit? unit = default, System.Collections.Generic.IDictionary<string, string>? tags = null, System.DateTimeOffset? timestamp = default, int stackLevel = 1);
void Set(string key, string value, Sentry.MeasurementUnit? unit = default, System.Collections.Generic.IDictionary<string, string>? tags = null, System.DateTimeOffset? timestamp = default, int stackLevel = 1);
System.IDisposable StartTimer(string key, Sentry.MeasurementUnit.Duration unit = 3, System.Collections.Generic.IDictionary<string, string>? tags = null, int stackLevel = 1);
void Timing(string key, double value, Sentry.MeasurementUnit.Duration unit = 3, System.Collections.Generic.IDictionary<string, string>? tags = null, System.DateTimeOffset? timestamp = default, int stackLevel = 1);
}
Expand Down
Loading

0 comments on commit 8bc2e51

Please sign in to comment.