Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[repo/OneCollector] Prepare to .NET9 #2341

Merged
merged 18 commits into from
Nov 22, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ internal sealed class CallbackManager<T> : IDisposable
where T : Delegate
{
private readonly object lockObject = new();
private T? root;
private bool disposed;

public T? Root { get => this.root; }
public T? Root { get; private set; }

public IDisposable Add(T callback)
{
Expand All @@ -29,14 +28,14 @@ public IDisposable Add(T callback)
}
#endif

this.root = (T)Delegate.Combine(this.root, callback);
this.Root = (T)Delegate.Combine(this.Root, callback);
}

return new CallbackManagerRegistration(() =>
{
lock (this.lockObject)
{
this.root = (T?)Delegate.Remove(this.root, callback);
this.Root = (T?)Delegate.Remove(this.Root, callback);
}
});
}
Expand All @@ -45,7 +44,7 @@ public void Dispose()
{
lock (this.lockObject)
{
this.root = null;
this.Root = null;
this.disposed = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public string? InstrumentationKey
{
get
{
this.ParsedKeyValues.TryGetValue(nameof(this.InstrumentationKey), out string? instrumentationKey);
this.ParsedKeyValues.TryGetValue(nameof(this.InstrumentationKey), out var instrumentationKey);

return instrumentationKey;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,11 @@ public static bool TryParseFromMapping(
}

var parts = eventFullNameMapping!.Split('.');
if (parts.Length > 1)
{
eventFullName = new(
eventFullName = parts.Length > 1
? new(
string.Join(".", parts, 0, parts.Length - 1),
parts[parts.Length - 1]);
}
else
{
eventFullName = new(string.Empty, parts[0]);
}
parts[parts.Length - 1])
: new(string.Empty, parts[0]);

return true;
}
Expand Down Expand Up @@ -80,8 +75,8 @@ internal void Validate(string key)

length += this.EventName.Length;

if (length < EventNameManager.MinimumEventFullNameLength
|| length > EventNameManager.MaximumEventFullNameLength)
if (length is < EventNameManager.MinimumEventFullNameLength
or > EventNameManager.MaximumEventFullNameLength)
{
throw new OneCollectorExporterValidationException($"The event full name mapping value provided for key '{key}' is shorter or longer than what is allowed.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ internal sealed class EventNameManager
private readonly string defaultEventName;
private readonly IReadOnlyDictionary<string, EventFullName>? eventFullNameMappings;
private readonly ResolvedEventFullName defaultEventFullName;
private readonly Hashtable eventNamespaceCache = new(StringComparer.OrdinalIgnoreCase);

public EventNameManager(
string defaultEventNamespace,
Expand All @@ -44,7 +43,7 @@ public EventNameManager(
}

// Note: This is exposed for unit tests.
internal Hashtable EventNamespaceCache => this.eventNamespaceCache;
internal Hashtable EventNamespaceCache { get; } = new(StringComparer.OrdinalIgnoreCase);

public static bool IsEventNamespaceValid(string eventNamespace)
=> EventNamespaceValidationRegex.IsMatch(eventNamespace);
Expand Down Expand Up @@ -86,13 +85,13 @@ public ResolvedEventFullName ResolveEventFullName(
ref eventNamespace!,
ref eventName!);

byte[]? originalEventNamespaceBlob = !string.IsNullOrEmpty(originalEventNamespace)
&& originalEventNamespace != eventNamespace
var originalEventNamespaceBlob = !string.IsNullOrEmpty(originalEventNamespace)
&& originalEventNamespace != eventNamespace
? BuildEventFullName(string.Empty, originalEventNamespace!)
: null;

byte[]? originalEventNameBlob = !string.IsNullOrEmpty(originalEventName)
&& originalEventName != eventName
var originalEventNameBlob = !string.IsNullOrEmpty(originalEventName)
&& originalEventName != eventName
? BuildEventFullName(string.Empty, originalEventName!)
: null;

Expand Down Expand Up @@ -136,23 +135,23 @@ private static byte[] BuildEventFullName(string eventNamespace, string eventName

private static void WriteEventFullNameComponent(string component, Span<byte> destination, ref int cursor)
{
char firstChar = component[0];
if (firstChar >= 'a' && firstChar <= 'z')
var firstChar = component[0];
if (firstChar is >= 'a' and <= 'z')
{
firstChar -= (char)32;
}

destination[cursor++] = (byte)firstChar;

for (int i = 1; i < component.Length; i++)
for (var i = 1; i < component.Length; i++)
{
destination[cursor++] = (byte)component[i];
}
}

private Hashtable GetEventNameCacheForEventNamespace(string eventNamespace)
{
var eventNamespaceCache = this.eventNamespaceCache;
var eventNamespaceCache = this.EventNamespaceCache;

if (eventNamespaceCache[eventNamespace] is not Hashtable eventNameCacheForNamespace)
{
Expand Down Expand Up @@ -252,7 +251,7 @@ private byte[] ResolveEventNameRare(
byte[] eventFullName;

var finalEventFullNameLength = namespaceLength + eventName.Length;
if (finalEventFullNameLength < MinimumEventFullNameLength || finalEventFullNameLength > MaximumEventFullNameLength)
if (finalEventFullNameLength is < MinimumEventFullNameLength or > MaximumEventFullNameLength)
{
OneCollectorExporterEventSource.Log.EventFullNameDiscarded(eventNamespace, eventName);
eventFullName = this.defaultEventFullName.EventFullName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private static void SerializeMapValueToJson(IReadOnlyList<KeyValuePair<string, o
{
writer.WriteStartObject();

for (int i = 0; i < value.Count; i++)
for (var i = 0; i < value.Count; i++)
{
var element = value[i];

Expand Down Expand Up @@ -213,7 +213,7 @@ private static void SerializeObjectValueToJson(object value, Utf8JsonWriter writ
if (value is ISpanFormattable spanFormattable)
{
Span<char> destination = stackalloc char[MaximumStackAllocSizeInBytes / 2];
if (spanFormattable.TryFormat(destination, out int charsWritten, string.Empty, CultureInfo.InvariantCulture))
if (spanFormattable.TryFormat(destination, out var charsWritten, string.Empty, CultureInfo.InvariantCulture))
{
writer.WriteStringValue(destination.Slice(0, charsWritten));
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ internal sealed class CommonSchemaJsonSerializationState
private readonly Dictionary<string, int> keys = new(4, StringComparer.OrdinalIgnoreCase);
private readonly List<KeyValuePair<ExtensionFieldInformation, object?>> allValues = new(16);
private string itemType;
private int nextKeysToAllValuesLookupIndex;
private KeyValueLookup[] keysToAllValuesLookup = new KeyValueLookup[4];

public CommonSchemaJsonSerializationState(string itemType, Utf8JsonWriter writer)
Expand All @@ -27,7 +26,7 @@ public CommonSchemaJsonSerializationState(string itemType, Utf8JsonWriter writer

public Utf8JsonWriter Writer { get; private set; }

public int ExtensionPropertyCount => this.nextKeysToAllValuesLookupIndex;
public int ExtensionPropertyCount { get; private set; }

public int ExtensionAttributeCount => this.allValues.Count;

Expand All @@ -53,7 +52,7 @@ public void AddExtensionAttribute(KeyValuePair<string, object?> attribute)
this.AssignNewExtensionToLookupIndex(ref lookupIndex);
}
#else
if (!this.keys.TryGetValue(fieldInformation!.ExtensionName!, out int lookupIndex))
if (!this.keys.TryGetValue(fieldInformation!.ExtensionName!, out var lookupIndex))
{
this.AssignNewExtensionToLookupIndex(ref lookupIndex);
this.keys[fieldInformation.ExtensionName!] = lookupIndex;
Expand All @@ -66,15 +65,15 @@ public void AddExtensionAttribute(KeyValuePair<string, object?> attribute)
return;
}

ref KeyValueLookup keyLookup = ref this.keysToAllValuesLookup[lookupIndex];
ref var keyLookup = ref this.keysToAllValuesLookup[lookupIndex];

if (keyLookup.Count >= MaxNumberOfExtensionValuesPerKey)
{
OneCollectorExporterEventSource.Log.AttributeDropped(this.itemType, attribute.Key, "Extension value limit reached");
return;
}

int index = this.allValues.Count;
var index = this.allValues.Count;
this.allValues.Add(new KeyValuePair<ExtensionFieldInformation, object?>(fieldInformation, attribute.Value));

unsafe
Expand Down Expand Up @@ -102,9 +101,9 @@ public void SerializeExtensionPropertiesToJson(bool writeExtensionObjectEnvelope
{
var wroteStartObject = false;

ref KeyValueLookup keyLookup = ref this.keysToAllValuesLookup[extensionPropertyKey.Value];
ref var keyLookup = ref this.keysToAllValuesLookup[extensionPropertyKey.Value];

for (int i = 0; i < keyLookup.Count; i++)
for (var i = 0; i < keyLookup.Count; i++)
{
unsafe
{
Expand Down Expand Up @@ -151,13 +150,13 @@ public void BeginItem()
return;
}

for (int i = 0; i < this.nextKeysToAllValuesLookupIndex; i++)
for (var i = 0; i < this.ExtensionPropertyCount; i++)
{
ref var lookup = ref this.keysToAllValuesLookup[i];
lookup.Count = 0;
}

this.nextKeysToAllValuesLookupIndex = 0;
this.ExtensionPropertyCount = 0;

this.keys.Clear();

Expand All @@ -166,7 +165,7 @@ public void BeginItem()

private void AssignNewExtensionToLookupIndex(ref int lookupIndex)
{
lookupIndex = this.nextKeysToAllValuesLookupIndex;
lookupIndex = this.ExtensionPropertyCount;

if (lookupIndex >= this.keysToAllValuesLookup.Length)
{
Expand All @@ -181,7 +180,7 @@ private void AssignNewExtensionToLookupIndex(ref int lookupIndex)
this.keysToAllValuesLookup = newKeysToAllValuesLookup;
}

this.nextKeysToAllValuesLookupIndex++;
this.ExtensionPropertyCount++;
}

private unsafe struct KeyValueLookup
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ protected static void SerializeResourceToJsonInsideCurrentObject(Resource resour

if (resource!.Attributes is IReadOnlyList<KeyValuePair<string, object?>> resourceAttributeList)
{
for (int i = 0; i < resourceAttributeList.Count; i++)
for (var i = 0; i < resourceAttributeList.Count; i++)
{
var resourceAttribute = resourceAttributeList[i];

Expand All @@ -135,7 +135,7 @@ protected static void SerializeResourceToJsonInsideCurrentObject(Resource resour
}
else
{
foreach (KeyValuePair<string, object> resourceAttribute in resource.Attributes)
foreach (var resourceAttribute in resource.Attributes)
{
if (AttributeKeyStartWithExtensionPrefix(resourceAttribute.Key))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,27 @@ internal sealed class LogRecordCommonSchemaJsonSerializer : CommonSchemaJsonSeri
private static readonly JsonEncodedText ExceptionExtensionMessageProperty = JsonEncodedText.Encode("msg");
private static readonly JsonEncodedText ExceptionExtensionStackTraceProperty = JsonEncodedText.Encode("stack");

private static readonly JsonEncodedText[] LogLevelToSeverityTextMappings = new JsonEncodedText[]
{
private static readonly JsonEncodedText[] LogLevelToSeverityTextMappings =
[
JsonEncodedText.Encode("Trace"),
JsonEncodedText.Encode("Debug"),
JsonEncodedText.Encode("Information"),
JsonEncodedText.Encode("Warning"),
JsonEncodedText.Encode("Error"),
JsonEncodedText.Encode("Critical"),
JsonEncodedText.Encode("Trace"), // Note: This is the "None" bucket.
};
JsonEncodedText.Encode("Trace") // Note: This is the "None" bucket.
];

private static readonly int[] LogLevelToSeverityNumberMappings = new int[]
{
1, 5, 9, 13, 17, 21, 1,
};
private static readonly int[] LogLevelToSeverityNumberMappings =
[
1, 5, 9, 13, 17, 21, 1
];

private static readonly Action<LogRecordScope, CommonSchemaJsonSerializationState> SerializeScopeItemToJson = (scope, serializationState) =>
{
var writer = serializationState.Writer;

foreach (KeyValuePair<string, object?> scopeAttribute in scope)
foreach (var scopeAttribute in scope)
{
if (scopeAttribute.Key == "{OriginalFormat}")
{
Expand Down Expand Up @@ -150,7 +150,7 @@ protected override void SerializeItemToJson(Resource resource, LogRecord item, C

if (item.Attributes != null)
{
for (int i = 0; i < item.Attributes.Count; i++)
for (var i = 0; i < item.Attributes.Count; i++)
{
var attribute = item.Attributes[i];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ internal sealed class WriteDirectlyToTransportSink<T> : ISink<T>, IDisposable
{
private readonly string typeName;
private readonly ISerializer<T> serializer;
private readonly MemoryStream buffer;

public WriteDirectlyToTransportSink(
ISerializer<T> serializer,
Expand All @@ -26,14 +25,14 @@ public WriteDirectlyToTransportSink(
this.typeName = typeof(T).Name;
this.serializer = serializer;
this.Transport = transport;
this.buffer = new(initialBufferCapacity);
this.Buffer = new(initialBufferCapacity);
}

public string Description => "WriteDirectlyToTransportSink";

public ITransport Transport { get; }

internal MemoryStream Buffer => this.buffer;
internal MemoryStream Buffer { get; }

public void Dispose()
{
Expand All @@ -46,7 +45,7 @@ public int Write(Resource resource, in Batch<T> batch)
var totalNumberOfItemsSerialized = 0;
var totalNumberOfItemsDroppedDuringSerialization = 0;
var totalNumberOfItemsDroppedDueToTransmissionFailure = 0;
var buffer = this.buffer;
var buffer = this.Buffer;
ArraySegment<byte> remainingDataFromPreviousTransmission = default;
var state = new BatchSerializationState<T>(in batch);

Expand Down Expand Up @@ -80,7 +79,7 @@ public int Write(Resource resource, in Batch<T> batch)

totalNumberOfItemsDroppedDuringSerialization += result.NumberOfItemsDropped;

int numberOfItemsSerialized = result.NumberOfItemsSerialized;
var numberOfItemsSerialized = result.NumberOfItemsSerialized;

if (numberOfItemsSerialized > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public bool Send(in TransportSendRequest sendRequest)
request.Headers.TryAddWithoutValidation("sdk-version", SdkVersion);
request.Headers.TryAddWithoutValidation("x-apikey", this.instrumentationKey);

bool infoLoggingEnabled = OneCollectorExporterEventSource.Log.IsInformationalLoggingEnabled();
var infoLoggingEnabled = OneCollectorExporterEventSource.Log.IsInformationalLoggingEnabled();

if (!infoLoggingEnabled)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,8 @@ internal override void Validate()
+ this.DefaultEventNamespace.Length
+ (this.DefaultEventNamespace.Length > 0 ? 1 : 0);

if (defaultEventFullNameLength < EventNameManager.MinimumEventFullNameLength
|| defaultEventFullNameLength > EventNameManager.MaximumEventFullNameLength)
if (defaultEventFullNameLength is < EventNameManager.MinimumEventFullNameLength
or > EventNameManager.MaximumEventFullNameLength)
{
throw new OneCollectorExporterValidationException($"{nameof(this.DefaultEventNamespace)} & {nameof(this.DefaultEventName)} specified on {nameof(OneCollectorLogExporterOptions)} options cannot be less than 4 characters or greater than 100 characters in length when combined.");
}
Expand Down
Loading
Loading