// Copyright 2021 Cloud Native Foundation. // Licensed under the Apache 2.0 license. // See LICENSE file in the project root for full license information. using CloudNative.CloudEvents.Core; using System; using System.Collections.Generic; using System.Linq; namespace CloudNative.CloudEvents.Extensions { /// /// Support for the sampling /// CloudEvent extension. /// public static class Sampling { /// /// representing the 'sampledrate' extension attribute. /// public static CloudEventAttribute SampledRateAttribute { get; } = CloudEventAttribute.CreateExtension("sampledrate", CloudEventAttributeType.Integer, PositiveInteger); /// /// A read-only sequence of all attributes related to the sampling extension. /// public static IEnumerable AllAttributes { get; } = new[] { SampledRateAttribute }.ToList().AsReadOnly(); /// /// Sets the on the given . /// /// The CloudEvent on which to set the attribute. Must not be null. /// The sampled rate to set. May be null, in which case the attribute is /// removed from . If this value is non-null, it must be positive. /// , for convenient method chaining. public static CloudEvent SetSampledRate(this CloudEvent cloudEvent, int? sampledRate) { Validation.CheckNotNull(cloudEvent, nameof(cloudEvent)); cloudEvent[SampledRateAttribute] = sampledRate; return cloudEvent; } /// /// Retrieves the from the given . /// /// The CloudEvent from which to retrieve the attribute. Must not be null. /// The sampled rate, or null if does not have a sampled rate set. public static int? GetSampledRate(this CloudEvent cloudEvent) => (int?) Validation.CheckNotNull(cloudEvent, nameof(cloudEvent))[SampledRateAttribute]; private static void PositiveInteger(object value) { if ((int)value <= 0) { throw new ArgumentOutOfRangeException("Sampled rate must be positive."); } } } }