diff --git a/tracer/build/_build/UpdateVendors/UpdateVendors.cs b/tracer/build/_build/UpdateVendors/UpdateVendors.cs index 82f5909b1fb7..e382ab9f0ba2 100644 --- a/tracer/build/_build/UpdateVendors/UpdateVendors.cs +++ b/tracer/build/_build/UpdateVendors/UpdateVendors.cs @@ -71,10 +71,14 @@ private static async Task UpdateVendor(VendoredDependency dependency, AbsolutePa File.Delete(projFile); Console.WriteLine($"Renamed {libraryName} project file."); - // Delete the assembly properties - var assemblyPropertiesFolder = Path.Combine(sourceLocation, @"Properties"); - SafeDeleteDirectory(assemblyPropertiesFolder); - Console.WriteLine($"Deleted {libraryName} assembly properties file."); + // Delete the assembly info file + var assemblyInfo = Path.Combine(sourceLocation, @"Properties", "AssemblyInfo.cs"); + if (File.Exists(assemblyInfo)) + { + File.Delete(assemblyInfo); + } + + Console.WriteLine($"Deleted {libraryName} assembly info file."); Console.WriteLine($"Running transforms on files for {libraryName}."); @@ -111,7 +115,9 @@ private static bool ShouldDropFile(VendoredDependency dependency, string basePat foreach (var relativeFileToDrop in dependency.RelativePathsToExclude) { var absolutePath = Path.Combine(basePath, relativeFileToDrop).Replace('/', '\\'); - if (normalizedFilePath.Equals(absolutePath, StringComparison.OrdinalIgnoreCase)) + if (normalizedFilePath.Equals(absolutePath, StringComparison.OrdinalIgnoreCase) + || (absolutePath.EndsWith('\\') && + normalizedFilePath.StartsWith(absolutePath, StringComparison.OrdinalIgnoreCase))) { return true; } diff --git a/tracer/build/_build/UpdateVendors/VendoredDependency.cs b/tracer/build/_build/UpdateVendors/VendoredDependency.cs index 7f911712c89e..15a082e3c2d1 100644 --- a/tracer/build/_build/UpdateVendors/VendoredDependency.cs +++ b/tracer/build/_build/UpdateVendors/VendoredDependency.cs @@ -15,12 +15,34 @@ public class VendoredDependency { private const string AutoGeneratedMessage = @"//------------------------------------------------------------------------------ // -// This file was automatically generated by the UpdateVendors tool. +// This file was automatically generated by the UpdateVendoredCode tool. //------------------------------------------------------------------------------ "; static VendoredDependency() { + Add( + libraryName: "Microsoft.OpenApi", + "1.6.23", + "https://github.com/microsoft/OpenAPI.NET/archive/1.6.23.zip", + new[] { "OpenAPI.NET-1.6.23", "src", "Microsoft.OpenApi" }, + filePath => RewriteCsFileWithStandardTransform(filePath, "Microsoft.OpenApi"), + new[] + { + "Extensions/OpenApiElementExtensions.cs", + "Extensions/OpenApiSerializableExtensions.cs", + "Extensions/OpenApiTypeMapper.cs", + "MicrosoftExtensions/", // whole folder + "Services/CopyReferences.cs", + "Services/OpenApiFilterService.cs", + "Services/OpenApiUrlTreeNode.cs", + "Services/OperationSearch.cs", + "Services/SearchResult.cs", + "Validations/", // whole folder + "Writers/FormattingStreamWriter.cs", + "Writers/OpenApiYamlWriter.cs" + }); + Add( libraryName: "Serilog", version: "2.10.0", diff --git a/tracer/dependabot/Datadog.Dependabot.Vendors.csproj b/tracer/dependabot/Datadog.Dependabot.Vendors.csproj index cefa00f782b0..57a26e75a5b2 100644 --- a/tracer/dependabot/Datadog.Dependabot.Vendors.csproj +++ b/tracer/dependabot/Datadog.Dependabot.Vendors.csproj @@ -1,11 +1,14 @@ - netcoreapp3.1 + net8.0 Datadog.Dependabot.Honeypot + + + @@ -30,18 +33,24 @@ - + - + - + + + + + + + diff --git a/tracer/src/Datadog.Trace.Trimming/build/Datadog.Trace.Trimming.xml b/tracer/src/Datadog.Trace.Trimming/build/Datadog.Trace.Trimming.xml index 6567951c659f..52dbf326a37d 100644 --- a/tracer/src/Datadog.Trace.Trimming/build/Datadog.Trace.Trimming.xml +++ b/tracer/src/Datadog.Trace.Trimming/build/Datadog.Trace.Trimming.xml @@ -223,6 +223,7 @@ + @@ -246,6 +247,7 @@ + @@ -494,6 +496,7 @@ + @@ -538,6 +541,8 @@ + + @@ -546,6 +551,8 @@ + + @@ -554,6 +561,7 @@ + @@ -719,6 +727,7 @@ + @@ -970,7 +979,10 @@ + + + diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/AnyType.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/AnyType.cs new file mode 100644 index 000000000000..49c9b99b7bf3 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/AnyType.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Type of an + /// + internal enum AnyType + { + /// + /// Primitive. + /// + Primitive, + + /// + /// Null. + /// + Null, + + /// + /// Array. + /// + Array, + + /// + /// Object. + /// + Object + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/IOpenApiAny.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/IOpenApiAny.cs new file mode 100644 index 000000000000..8a68a3f5d875 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/IOpenApiAny.cs @@ -0,0 +1,23 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Base interface for all the types that represent Open API Any. + /// + internal interface IOpenApiAny : IOpenApiElement, IOpenApiExtension + { + /// + /// Type of an . + /// + AnyType AnyType { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/IOpenApiPrimitive.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/IOpenApiPrimitive.cs new file mode 100644 index 000000000000..cdeeab83dc04 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/IOpenApiPrimitive.cs @@ -0,0 +1,82 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Primitive type. + /// + internal enum PrimitiveType + { + /// + /// Integer + /// + Integer, + + /// + /// Long + /// + Long, + + /// + /// Float + /// + Float, + + /// + /// Double + /// + Double, + + /// + /// String + /// + String, + + /// + /// Byte + /// + Byte, + + /// + /// Binary + /// + Binary, + + /// + /// Boolean + /// + Boolean, + + /// + /// Date + /// + Date, + + /// + /// DateTime + /// + DateTime, + + /// + /// Password + /// + Password + } + + /// + /// Base interface for the Primitive type. + /// + internal interface IOpenApiPrimitive : IOpenApiAny + { + /// + /// Primitive type. + /// + PrimitiveType PrimitiveType { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs new file mode 100644 index 000000000000..dc37f55728b8 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs @@ -0,0 +1,66 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Diagnostics.CodeAnalysis; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Contains logic for cloning objects through copy constructors. + /// + internal class OpenApiAnyCloneHelper + { + /// + /// Clones an instance of object from the copy constructor + /// + /// The object instance. + /// A clone copy or the object itself. + [Obsolete("Use native AoT-friendly generic overload of CloneFromCopyConstructor instead.")] + [RequiresUnreferencedCode("CloneFromCopyConstructor is not trim-compatible. Recommended to use native AoT-friendly type-specific overloads of CloneFromCopyConstructor instead.")] + public static IOpenApiAny CloneFromCopyConstructor(IOpenApiAny obj) + { + if (obj != null) + { + var t = obj.GetType(); + foreach (var ci in t.GetConstructors()) + { + var pi = ci.GetParameters(); + if (pi.Length == 1 && pi[0].ParameterType == t) + { + return (IOpenApiAny)ci.Invoke(new object[] { obj }); + } + } + } + + return obj; + } + + /// + /// Clones an instance of object from the copy constructor + /// + /// The object instance. + /// A clone copy or the object itself. + public static T CloneFromCopyConstructor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(T obj) where T : IOpenApiAny + { + if (obj != null) + { + foreach (var ci in typeof(T).GetConstructors()) + { + var pi = ci.GetParameters(); + if (pi.Length == 1 && pi[0].ParameterType == typeof(T)) + { + return (T)ci.Invoke([obj]); + } + } + } + + return obj; + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiArray.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiArray.cs new file mode 100644 index 000000000000..8048a8de0373 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiArray.cs @@ -0,0 +1,58 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; +using System.Collections.Generic; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API array. + /// + internal class OpenApiArray : List, IOpenApiAny + { + /// + /// The type of + /// + public AnyType AnyType { get; } = AnyType.Array; + + /// + /// Parameterless constructor + /// + public OpenApiArray() { } + + /// + /// Initializes a copy of object + /// + public OpenApiArray(OpenApiArray array) + { + AnyType = array.AnyType; + foreach (var item in array) + { + Add(OpenApiAnyCloneHelper.CloneFromCopyConstructor(item)); + } + } + + /// + /// Write out contents of OpenApiArray to passed writer + /// + /// Instance of JSON or YAML writer. + /// Version of the OpenAPI specification that that will be output. + public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + writer.WriteStartArray(); + + foreach (var item in this) + { + writer.WriteAny(item); + } + + writer.WriteEndArray(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiBinary.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiBinary.cs new file mode 100644 index 000000000000..9ce03de6c8c7 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiBinary.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API binary. + /// + internal class OpenApiBinary : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + /// + public OpenApiBinary(byte[] value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Binary; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiBoolean.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiBoolean.cs new file mode 100644 index 000000000000..a4ba9f7712e5 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiBoolean.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API boolean. + /// + internal class OpenApiBoolean : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + /// + public OpenApiBoolean(bool value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Boolean; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiByte.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiByte.cs new file mode 100644 index 000000000000..293baf17cb81 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiByte.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API Byte + /// + internal class OpenApiByte : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + public OpenApiByte(byte value) + : this(new[] { value }) + { + } + + /// + /// Initializes the class. + /// + public OpenApiByte(byte[] value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Byte; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDate.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDate.cs new file mode 100644 index 000000000000..2a6f05c93d42 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDate.cs @@ -0,0 +1,31 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API Date + /// + internal class OpenApiDate : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + public OpenApiDate(DateTime value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Date; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDateTime.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDateTime.cs new file mode 100644 index 000000000000..e620601f5277 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDateTime.cs @@ -0,0 +1,31 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API Datetime + /// + internal class OpenApiDateTime : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + public OpenApiDateTime(DateTimeOffset value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.DateTime; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDouble.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDouble.cs new file mode 100644 index 000000000000..1ceddc5dc009 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiDouble.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API Double + /// + internal class OpenApiDouble : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + public OpenApiDouble(double value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Double; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiFloat.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiFloat.cs new file mode 100644 index 000000000000..6d5a380f258b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiFloat.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API Float + /// + internal class OpenApiFloat : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + public OpenApiFloat(float value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Float; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiInteger.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiInteger.cs new file mode 100644 index 000000000000..f65e20a754d6 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiInteger.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API Integer + /// + internal class OpenApiInteger : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + public OpenApiInteger(int value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Integer; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiLong.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiLong.cs new file mode 100644 index 000000000000..deee698575a4 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiLong.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API long. + /// + internal class OpenApiLong : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + public OpenApiLong(long value) + : base(value) + { + } + + /// + /// Primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Long; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiNull.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiNull.cs new file mode 100644 index 000000000000..03c2c58cbf70 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiNull.cs @@ -0,0 +1,46 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API null. + /// + internal class OpenApiNull : IOpenApiAny + { + /// + /// The type of + /// + public AnyType AnyType { get; } = AnyType.Null; + + /// + /// Parameterless constructor + /// + public OpenApiNull() { } + + /// + /// Initializes a copy of object + /// + public OpenApiNull(OpenApiNull openApiNull) + { + AnyType = openApiNull.AnyType; + } + + /// + /// Write out null representation + /// + /// + /// Version of the OpenAPI specification that that will be output. + public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + writer.WriteAny(this); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiObject.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiObject.cs new file mode 100644 index 000000000000..a9184c19f9f2 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiObject.cs @@ -0,0 +1,59 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API object. + /// + internal class OpenApiObject : Dictionary, IOpenApiAny + { + /// + /// Type of . + /// + public AnyType AnyType { get; } = AnyType.Object; + + /// + /// Parameterless constructor + /// + public OpenApiObject() { } + + /// + /// Initializes a copy of object + /// + public OpenApiObject(OpenApiObject obj) + { + AnyType = obj.AnyType; + foreach (var key in obj.Keys) + { + this[key] = OpenApiAnyCloneHelper.CloneFromCopyConstructor(obj[key]); + } + } + + /// + /// Serialize OpenApiObject to writer + /// + /// + /// Version of the OpenAPI specification that that will be output. + public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + writer.WriteStartObject(); + + foreach (var item in this) + { + writer.WritePropertyName(item.Key); + writer.WriteAny(item.Value); + } + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiPassword.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiPassword.cs new file mode 100644 index 000000000000..aa8d9e0e912d --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiPassword.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API password. + /// + internal class OpenApiPassword : OpenApiPrimitive + { + /// + /// Initializes the class. + /// + public OpenApiPassword(string value) + : base(value) + { + } + + /// + /// The primitive type this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.Password; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiPrimitive.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiPrimitive.cs new file mode 100644 index 000000000000..16028451c061 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiPrimitive.cs @@ -0,0 +1,160 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Globalization; +using System.Text; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API primitive class. + /// + /// + internal abstract class OpenApiPrimitive : IOpenApiPrimitive + { + /// + /// Initializes the class with the given value. + /// + /// + public OpenApiPrimitive(T value) + { + Value = value; + } + + /// + /// Initializes a copy of an object + /// + /// + public OpenApiPrimitive(OpenApiPrimitive openApiPrimitive) + { + Value = openApiPrimitive.Value; + } + + /// + /// The kind of . + /// + public AnyType AnyType => AnyType.Primitive; + + /// + /// The primitive class this object represents. + /// + public abstract PrimitiveType PrimitiveType { get; } + + /// + /// Value of this + /// + public T Value { get; } + + /// + /// Write out content of primitive element + /// + /// + /// + public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + switch (this.PrimitiveType) + { + case PrimitiveType.Integer: + var intValue = (OpenApiInteger)(IOpenApiPrimitive)this; + writer.WriteValue(intValue.Value); + break; + + case PrimitiveType.Long: + var longValue = (OpenApiLong)(IOpenApiPrimitive)this; + writer.WriteValue(longValue.Value); + break; + + case PrimitiveType.Float: + var floatValue = (OpenApiFloat)(IOpenApiPrimitive)this; + writer.WriteValue(floatValue.Value); + break; + + case PrimitiveType.Double: + var doubleValue = (OpenApiDouble)(IOpenApiPrimitive)this; + var actualValue = doubleValue.Value; + if (actualValue.Equals(double.NaN) + || actualValue.Equals(double.NegativeInfinity) + || actualValue.Equals(double.PositiveInfinity)) + { + // Write out NaN, -Infinity, Infinity as strings + writer.WriteValue(actualValue.ToString(CultureInfo.InvariantCulture)); + break; + } + else + { + writer.WriteValue(actualValue); + } + break; + + case PrimitiveType.String: + var stringValue = (OpenApiString)(IOpenApiPrimitive)this; + if (stringValue.IsRawString()) + writer.WriteRaw(stringValue.Value); + else + writer.WriteValue(stringValue.Value); + break; + + case PrimitiveType.Byte: + var byteValue = (OpenApiByte)(IOpenApiPrimitive)this; + if (byteValue.Value == null) + { + writer.WriteNull(); + } + else + { + writer.WriteValue(Convert.ToBase64String(byteValue.Value)); + } + + break; + + case PrimitiveType.Binary: + var binaryValue = (OpenApiBinary)(IOpenApiPrimitive)this; + if (binaryValue.Value == null) + { + writer.WriteNull(); + } + else + { + writer.WriteValue(Encoding.UTF8.GetString(binaryValue.Value)); + } + + break; + + case PrimitiveType.Boolean: + var boolValue = (OpenApiBoolean)(IOpenApiPrimitive)this; + writer.WriteValue(boolValue.Value); + break; + + case PrimitiveType.Date: + var dateValue = (OpenApiDate)(IOpenApiPrimitive)this; + writer.WriteValue(dateValue.Value.ToString("o").Substring(0, 10)); + break; + + case PrimitiveType.DateTime: + var dateTimeValue = (OpenApiDateTime)(IOpenApiPrimitive)this; + writer.WriteValue(dateTimeValue.Value); + break; + + case PrimitiveType.Password: + var passwordValue = (OpenApiPassword)(IOpenApiPrimitive)this; + writer.WriteValue(passwordValue.Value); + break; + + default: + throw new OpenApiWriterException( + string.Format( + SRResource.PrimitiveTypeNotSupported, + this.PrimitiveType)); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiString.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiString.cs new file mode 100644 index 000000000000..20c7000f2186 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Any/OpenApiString.cs @@ -0,0 +1,73 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Any +{ + /// + /// Open API string type. + /// + internal class OpenApiString : OpenApiPrimitive + { + private bool isExplicit; + private bool isRawString; + + /// + /// Initializes the class. + /// + /// + public OpenApiString(string value) + : this(value, false) + { + } + + /// + /// Initializes the class. + /// + /// + /// Used to indicate if a string is quoted. + public OpenApiString(string value, bool isExplicit) + : base(value) + { + this.isExplicit = isExplicit; + } + + /// + /// Initializes the class. + /// + /// + /// Used to indicate if a string is quoted. + /// Used to indicate to the writer that the value should be written without encoding. + public OpenApiString(string value, bool isExplicit, bool isRawString) + : base(value) + { + this.isExplicit = isExplicit; + this.isRawString = isRawString; + } + + /// + /// The primitive class this object represents. + /// + public override PrimitiveType PrimitiveType => PrimitiveType.String; + + /// + /// True if string was specified explicitly by the means of double quotes, single quotes, or literal or folded style. + /// + public bool IsExplicit() + { + return this.isExplicit; + } + + /// + /// True if the writer should process the value as supplied without encoding. + /// + public bool IsRawString() + { + return this.isRawString; + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Attributes/DisplayAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Attributes/DisplayAttribute.cs new file mode 100644 index 000000000000..195dd7d35df2 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Attributes/DisplayAttribute.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Attributes +{ + /// + /// Represents the Open Api Data type metadata attribute. + /// + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + internal class DisplayAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The display name. + public DisplayAttribute(string name) + { + Name = Utils.CheckArgumentNullOrEmpty(name); + } + + /// + /// The display Name. + /// + public string Name { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Attributes/TrimmingAttributes.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Attributes/TrimmingAttributes.cs new file mode 100644 index 000000000000..8a17bab8c31b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Attributes/TrimmingAttributes.cs @@ -0,0 +1,430 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +#nullable enable + +// This collection of attribute definitions are helpers for accessing trim-related attributes in +// projects targeting .NET 6 or lower. Since the trimmer queries for these attributes by name, having +// these attributes source included is sufficient for the trimmer to recognize them. For more information +// on this approach, see https://devblogs.microsoft.com/dotnet/creating-aot-compatible-libraries/#approach-2-define-the-attributes-internally. +namespace System.Diagnostics.CodeAnalysis +{ +#if !NET7_0_OR_GREATER + /// + /// Indicates that the specified method requires the ability to generate new code at runtime, + /// for example through . + /// + /// + /// This allows tools to understand which methods are unsafe to call when compiling ahead of time. + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)] + internal sealed class RequiresDynamicCodeAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified message. + /// + /// + /// A message that contains information about the usage of dynamic code. + /// + public RequiresDynamicCodeAttribute(string message) + { + Message = message; + } + + /// + /// Gets a message that contains information about the usage of dynamic code. + /// + public string Message { get; } + + /// + /// Gets or sets an optional URL that contains more information about the method, + /// why it requires dynamic code, and what options a consumer has to deal with it. + /// + public string? Url { get; set; } + } +#endif + +#if !NET5_0_OR_GREATER + /// + /// Indicates that the specified method requires dynamic access to code that is not referenced + /// statically, for example through . + /// + /// + /// This allows tools to understand which methods are unsafe to call when removing unreferenced + /// code from an application. + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)] + internal sealed class RequiresUnreferencedCodeAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified message. + /// + /// + /// A message that contains information about the usage of unreferenced code. + /// + public RequiresUnreferencedCodeAttribute(string message) + { + Message = message; + } + + /// + /// Gets a message that contains information about the usage of unreferenced code. + /// + public string Message { get; } + + /// + /// Gets or sets an optional URL that contains more information about the method, + /// why it requires unreferenced code, and what options a consumer has to deal with it. + /// + public string? Url { get; set; } + } + + /// + /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a + /// single code artifact. + /// + /// + /// is different than + /// in that it doesn't have a + /// . So it is always preserved in the compiled assembly. + /// + [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] + internal sealed class UnconditionalSuppressMessageAttribute : Attribute + { + /// + /// Initializes a new instance of the + /// class, specifying the category of the tool and the identifier for an analysis rule. + /// + /// The category for the attribute. + /// The identifier of the analysis rule the attribute applies to. + public UnconditionalSuppressMessageAttribute(string category, string checkId) + { + Category = category; + CheckId = checkId; + } + + /// + /// Gets the category identifying the classification of the attribute. + /// + /// + /// The property describes the tool or tool analysis category + /// for which a message suppression attribute applies. + /// + public string Category { get; } + + /// + /// Gets the identifier of the analysis tool rule to be suppressed. + /// + /// + /// Concatenated together, the and + /// properties form a unique check identifier. + /// + public string CheckId { get; } + + /// + /// Gets or sets the scope of the code that is relevant for the attribute. + /// + /// + /// The Scope property is an optional argument that specifies the metadata scope for which + /// the attribute is relevant. + /// + public string? Scope { get; set; } + + /// + /// Gets or sets a fully qualified path that represents the target of the attribute. + /// + /// + /// The property is an optional argument identifying the analysis target + /// of the attribute. An example value is "System.IO.Stream.ctor():System.Void". + /// Because it is fully qualified, it can be long, particularly for targets such as parameters. + /// The analysis tool user interface should be capable of automatically formatting the parameter. + /// + public string? Target { get; set; } + + /// + /// Gets or sets an optional argument expanding on exclusion criteria. + /// + /// + /// The property is an optional argument that specifies additional + /// exclusion where the literal metadata target is not sufficiently precise. For example, + /// the cannot be applied within a method, + /// and it may be desirable to suppress a violation against a statement in the method that will + /// give a rule violation, but not against all statements in the method. + /// + public string? MessageId { get; set; } + + /// + /// Gets or sets the justification for suppressing the code analysis message. + /// + public string? Justification { get; set; } + } + + /// + /// States a dependency that one member has on another. + /// + /// + /// This can be used to inform tooling of a dependency that is otherwise not evident purely from + /// metadata and IL, for example a member relied on via reflection. + /// + [AttributeUsage( + AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method, + AllowMultiple = true, Inherited = false)] + internal sealed class DynamicDependencyAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified signature of a member on the same type as the consumer. + /// + /// The signature of the member depended on. + public DynamicDependencyAttribute(string memberSignature) + { + MemberSignature = memberSignature; + } + + /// + /// Initializes a new instance of the class + /// with the specified signature of a member on a . + /// + /// The signature of the member depended on. + /// The containing . + public DynamicDependencyAttribute(string memberSignature, Type type) + { + MemberSignature = memberSignature; + Type = type; + } + + /// + /// Initializes a new instance of the class + /// with the specified signature of a member on a type in an assembly. + /// + /// The signature of the member depended on. + /// The full name of the type containing the specified member. + /// The assembly name of the type containing the specified member. + public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) + { + MemberSignature = memberSignature; + TypeName = typeName; + AssemblyName = assemblyName; + } + + /// + /// Initializes a new instance of the class + /// with the specified types of members on a . + /// + /// The types of members depended on. + /// The containing the specified members. + public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) + { + MemberTypes = memberTypes; + Type = type; + } + + /// + /// Initializes a new instance of the class + /// with the specified types of members on a type in an assembly. + /// + /// The types of members depended on. + /// The full name of the type containing the specified members. + /// The assembly name of the type containing the specified members. + public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) + { + MemberTypes = memberTypes; + TypeName = typeName; + AssemblyName = assemblyName; + } + + /// + /// Gets the signature of the member depended on. + /// + /// + /// Either must be a valid string or + /// must not equal , but not both. + /// + public string? MemberSignature { get; } + + /// + /// Gets the which specifies the type + /// of members depended on. + /// + /// + /// Either must be a valid string or + /// must not equal , but not both. + /// + public DynamicallyAccessedMemberTypes MemberTypes { get; } + + /// + /// Gets the containing the specified member. + /// + /// + /// If neither nor are specified, + /// the type of the consumer is assumed. + /// + public Type? Type { get; } + + /// + /// Gets the full name of the type containing the specified member. + /// + /// + /// If neither nor are specified, + /// the type of the consumer is assumed. + /// + public string? TypeName { get; } + + /// + /// Gets the assembly name of the specified type. + /// + /// + /// is only valid when is specified. + /// + public string? AssemblyName { get; } + + /// + /// Gets or sets the condition in which the dependency is applicable, e.g. "DEBUG". + /// + public string? Condition { get; set; } + } + + /// + /// Indicates that certain members on a specified are accessed dynamically, + /// for example through . + /// + /// + /// This allows tools to understand which members are being accessed during the execution + /// of a program. + /// + /// This attribute is valid on members whose type is or . + /// + /// When this attribute is applied to a location of type , the assumption is + /// that the string represents a fully qualified type name. + /// + /// When this attribute is applied to a class, interface, or struct, the members specified + /// can be accessed dynamically on instances returned from calling + /// on instances of that class, interface, or struct. + /// + /// If the attribute is applied to a method it's treated as a special case and it implies + /// the attribute should be applied to the "this" parameter of the method. As such the attribute + /// should only be used on instance methods of types assignable to System.Type (or string, but no methods + /// will use it there). + /// + [AttributeUsage( + AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter | + AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method | + AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct, + Inherited = false)] + internal sealed class DynamicallyAccessedMembersAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified member types. + /// + /// The types of members dynamically accessed. + public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) + { + MemberTypes = memberTypes; + } + + /// + /// Gets the which specifies the type + /// of members dynamically accessed. + /// + public DynamicallyAccessedMemberTypes MemberTypes { get; } + } + + /// + /// Specifies the types of members that are dynamically accessed. + /// + /// This enumeration has a attribute that allows a + /// bitwise combination of its member values. + /// + [Flags] + internal enum DynamicallyAccessedMemberTypes + { + /// + /// Specifies no members. + /// + None = 0, + + /// + /// Specifies the default, parameterless public constructor. + /// + PublicParameterlessConstructor = 0x0001, + + /// + /// Specifies all public constructors. + /// + PublicConstructors = 0x0002 | PublicParameterlessConstructor, + + /// + /// Specifies all non-public constructors. + /// + NonPublicConstructors = 0x0004, + + /// + /// Specifies all public methods. + /// + PublicMethods = 0x0008, + + /// + /// Specifies all non-public methods. + /// + NonPublicMethods = 0x0010, + + /// + /// Specifies all public fields. + /// + PublicFields = 0x0020, + + /// + /// Specifies all non-public fields. + /// + NonPublicFields = 0x0040, + + /// + /// Specifies all public nested types. + /// + PublicNestedTypes = 0x0080, + + /// + /// Specifies all non-public nested types. + /// + NonPublicNestedTypes = 0x0100, + + /// + /// Specifies all public properties. + /// + PublicProperties = 0x0200, + + /// + /// Specifies all non-public properties. + /// + NonPublicProperties = 0x0400, + + /// + /// Specifies all public events. + /// + PublicEvents = 0x0800, + + /// + /// Specifies all non-public events. + /// + NonPublicEvents = 0x1000, + + /// + /// Specifies all interfaces implemented by the type. + /// + Interfaces = 0x2000, + + /// + /// Specifies all members. + /// + All = ~None + } +#endif +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs new file mode 100644 index 000000000000..62ac70a05434 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs @@ -0,0 +1,23 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +#if !NETCOREAPP3_1_OR_GREATER +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter)] +sealed class CallerArgumentExpressionAttribute : + Attribute +{ + public CallerArgumentExpressionAttribute(string parameterName) => + ParameterName = parameterName; + + public string ParameterName { get; } +} +#endif diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Exceptions/OpenApiException.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Exceptions/OpenApiException.cs new file mode 100644 index 000000000000..eb8d8d15cc72 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Exceptions/OpenApiException.cs @@ -0,0 +1,56 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions +{ + /// + /// Exception type representing exceptions in the Open API library. + /// + internal class OpenApiException : Exception + { + /// + /// Creates a new instance of the class with default values. + /// + public OpenApiException() + : this(SRResource.OpenApiExceptionGenericError) + { + } + + /// + /// Creates a new instance of the class with an error message. + /// + /// The plain text error message for this exception. + public OpenApiException(string message) + : this(message, null) + { + } + + /// + /// Creates a new instance of the class with an error message and an inner exception. + /// + /// The plain text error message for this exception. + /// The inner exception that is the cause of this exception to be thrown. + public OpenApiException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// The reference pointer. This is a fragment identifier used to point to where the error occurred in the document. + /// If the document has been parsed as JSON/YAML then the identifier will be a + /// JSON Pointer as per https://tools.ietf.org/html/rfc6901 + /// If the document fails to parse as JSON/YAML then the fragment will be based on + /// a text/plain pointer as defined in https://tools.ietf.org/html/rfc5147 + /// Currently only line= is provided because using char= causes tests to break due to CR/LF and LF differences + /// + public string Pointer { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Exceptions/OpenApiWriterException.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Exceptions/OpenApiWriterException.cs new file mode 100644 index 000000000000..240f5438d788 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Exceptions/OpenApiWriterException.cs @@ -0,0 +1,46 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions +{ + /// + /// Exception type representing exceptions in the OpenAPI writer. + /// + internal class OpenApiWriterException : OpenApiException + { + /// + /// Creates a new instance of the class with default values. + /// + public OpenApiWriterException() + : this(SRResource.OpenApiWriterExceptionGenericError) + { + } + + /// + /// Creates a new instance of the class with an error message. + /// + /// The plain text error message for this exception. + public OpenApiWriterException(string message) + : this(message, null) + { + } + + /// + /// Creates a new instance of the class with an error message and an inner exception. + /// + /// The plain text error message for this exception. + /// The inner exception that is the cause of this exception to be thrown. + public OpenApiWriterException(string message, Exception innerException) + : base(message, innerException) + { + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/BodyExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/BodyExpression.cs new file mode 100644 index 000000000000..c37e69880b65 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/BodyExpression.cs @@ -0,0 +1,65 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// Body expression. + /// + internal sealed class BodyExpression : SourceExpression + { + /// + /// body string + /// + public const string Body = "body"; + + /// + /// Prefix for a pointer + /// + public const string PointerPrefix = "#"; + + /// + /// Initializes a new instance of the class. + /// + public BodyExpression() + : base(null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// a JSON Pointer [RFC 6901](https://tools.ietf.org/html/rfc6901). + public BodyExpression(JsonPointer pointer) + : base(pointer?.ToString()) + { + Utils.CheckArgumentNull(pointer); + } + + /// + /// Gets the expression string. + /// + public override string Expression + { + get + { + if (string.IsNullOrWhiteSpace(Value)) + { + return Body; + } + + return Body + PointerPrefix + Value; + } + } + + /// + /// Gets the fragment string. + /// + public string Fragment { get => Value; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/CompositeExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/CompositeExpression.cs new file mode 100644 index 000000000000..9dfd60bf2e33 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/CompositeExpression.cs @@ -0,0 +1,51 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// String literal with embedded expressions + /// + internal class CompositeExpression : RuntimeExpression + { + private readonly string template; + private Regex expressionPattern = new(@"{(?\$[^}]*)"); + + /// + /// Expressions embedded into string literal + /// + public List ContainedExpressions = new(); + + /// + /// Create a composite expression from a string literal with an embedded expression + /// + /// + public CompositeExpression(string expression) + { + template = expression; + + // Extract subexpressions and convert to RuntimeExpressions + var matches = expressionPattern.Matches(expression); + + foreach (var item in matches.Cast()) + { + var value = item.Groups["exp"].Captures.Cast().First().Value; + ContainedExpressions.Add(Build(value)); + } + } + + /// + /// Return original string literal with embedded expression + /// + public override string Expression => template; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/HeaderExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/HeaderExpression.cs new file mode 100644 index 000000000000..f17380d8ebe6 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/HeaderExpression.cs @@ -0,0 +1,41 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// Header expression, The token identifier in header is case-insensitive. + /// + internal class HeaderExpression : SourceExpression + { + /// + /// header. string + /// + public const string Header = "header."; + + /// + /// Initializes a new instance of the class. + /// + /// The token string, it's case-insensitive. + public HeaderExpression(string token) + : base(token) + { + Utils.CheckArgumentNullOrEmpty(token); + } + + /// + /// Gets the expression string. + /// + public override string Expression { get => Header + Value; } + + /// + /// Gets the token string. + /// + public string Token { get => Value; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/MethodExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/MethodExpression.cs new file mode 100644 index 000000000000..265feaf26d50 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/MethodExpression.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// Method expression. + /// + internal sealed class MethodExpression : RuntimeExpression + { + /// + /// $method. string + /// + public const string Method = "$method"; + + /// + /// Gets the expression string. + /// + public override string Expression => Method; + + /// + /// Private constructor. + /// + public MethodExpression() + { + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/PathExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/PathExpression.cs new file mode 100644 index 000000000000..37210c817079 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/PathExpression.cs @@ -0,0 +1,41 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// Path expression, the name in path is case-sensitive. + /// + internal sealed class PathExpression : SourceExpression + { + /// + /// path. string + /// + public const string Path = "path."; + + /// + /// Initializes a new instance of the class. + /// + /// The name string, it's case-insensitive. + public PathExpression(string name) + : base(name) + { + Utils.CheckArgumentNullOrEmpty(name); + } + + /// + /// Gets the expression string. + /// + public override string Expression { get => Path + Value; } + + /// + /// Gets the name string. + /// + public string Name { get => Value; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/QueryExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/QueryExpression.cs new file mode 100644 index 000000000000..dc6d773b98bf --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/QueryExpression.cs @@ -0,0 +1,41 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// Query expression, the name in query is case-sensitive. + /// + internal sealed class QueryExpression : SourceExpression + { + /// + /// query. string + /// + public const string Query = "query."; + + /// + /// Initializes a new instance of the class. + /// + /// The name string, it's case-insensitive. + public QueryExpression(string name) + : base(name) + { + Utils.CheckArgumentNullOrEmpty(name); + } + + /// + /// Gets the expression string. + /// + public override string Expression { get => Query + Value; } + + /// + /// Gets the name string. + /// + public string Name { get => Value; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/RequestExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/RequestExpression.cs new file mode 100644 index 000000000000..fa5359eff9db --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/RequestExpression.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// $request. expression. + /// + internal sealed class RequestExpression : RuntimeExpression + { + /// + /// $request. string + /// + public const string Request = "$request."; + + /// + /// Initializes a new instance of the class. + /// + /// The source of the request. + public RequestExpression(SourceExpression source) + { + Source = Utils.CheckArgumentNull(source); + } + + /// + /// Gets the expression string. + /// + public override string Expression => Request + Source.Expression; + + /// + /// The expression. + /// + public SourceExpression Source { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/ResponseExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/ResponseExpression.cs new file mode 100644 index 000000000000..533b78b76094 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/ResponseExpression.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// $response. expression. + /// + internal sealed class ResponseExpression : RuntimeExpression + { + /// + /// $response. string + /// + public const string Response = "$response."; + + /// + /// Initializes a new instance of the class. + /// + /// The source of the response. + public ResponseExpression(SourceExpression source) + { + Source = Utils.CheckArgumentNull(source); + } + + /// + /// Gets the expression string. + /// + public override string Expression => Response + Source.Expression; + + /// + /// The expression. + /// + public SourceExpression Source { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/RuntimeExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/RuntimeExpression.cs new file mode 100644 index 000000000000..f0e60a3e4f34 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/RuntimeExpression.cs @@ -0,0 +1,111 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// Base class for the Open API runtime expression. + /// + internal abstract class RuntimeExpression : IEquatable + { + /// + /// The dollar sign prefix for a runtime expression. + /// + public const string Prefix = "$"; + + /// + /// The expression string. + /// + public abstract string Expression { get; } + + /// + /// Build the runtime expression from input string. + /// + /// The runtime expression. + /// The built runtime expression object. + public static RuntimeExpression Build(string expression) + { + Utils.CheckArgumentNullOrEmpty(expression); + + if (!expression.StartsWith(Prefix)) + { + return new CompositeExpression(expression); + } + + // $url + if (expression == UrlExpression.Url) + { + return new UrlExpression(); + } + + // $method + if (expression == MethodExpression.Method) + { + return new MethodExpression(); + } + + // $statusCode + if (expression == StatusCodeExpression.StatusCode) + { + return new StatusCodeExpression(); + } + + // $request. + if (expression.StartsWith(RequestExpression.Request)) + { + var subString = expression.Substring(RequestExpression.Request.Length); + var source = SourceExpression.Build(subString); + return new RequestExpression(source); + } + + // $response. + if (expression.StartsWith(ResponseExpression.Response)) + { + var subString = expression.Substring(ResponseExpression.Response.Length); + var source = SourceExpression.Build(subString); + return new ResponseExpression(source); + } + + throw new OpenApiException(string.Format(SRResource.RuntimeExpressionHasInvalidFormat, expression)); + } + + /// + /// GetHashCode implementation for IEquatable. + /// + public override int GetHashCode() + { + return Expression.GetHashCode(); + } + + /// + /// Equals implementation for IEquatable. + /// + public override bool Equals(object obj) + { + return Equals(obj as RuntimeExpression); + } + + /// + /// Equals implementation for object of the same type. + /// + public bool Equals(RuntimeExpression obj) + { + return obj != null && obj.Expression == Expression; + } + + /// + public override string ToString() + { + return Expression; + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/SourceExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/SourceExpression.cs new file mode 100644 index 000000000000..00a9caa08d4b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/SourceExpression.cs @@ -0,0 +1,80 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// Source expression. + /// + internal abstract class SourceExpression : RuntimeExpression + { + /// + /// Initializes a new instance of the class. + /// + /// The value string. + protected SourceExpression(string value) + { + Value = value; + } + + /// + /// Gets the expression string. + /// + protected string Value { get; } + + /// + /// Build the source expression from input string. + /// + /// The source expression. + /// The built source expression. + public new static SourceExpression Build(string expression) + { + if (!string.IsNullOrWhiteSpace(expression)) + { + var expressions = expression.Split('.'); + if (expressions.Length == 2) + { + if (expression.StartsWith(HeaderExpression.Header)) + { + // header. + return new HeaderExpression(expressions[1]); + } + + if (expression.StartsWith(QueryExpression.Query)) + { + // query. + return new QueryExpression(expressions[1]); + } + + if (expression.StartsWith(PathExpression.Path)) + { + // path. + return new PathExpression(expressions[1]); + } + } + + // body + if (expression.StartsWith(BodyExpression.Body)) + { + var subString = expression.Substring(BodyExpression.Body.Length); + if (string.IsNullOrEmpty(subString)) + { + return new BodyExpression(); + } + + return new BodyExpression(new(subString)); + } + } + + throw new OpenApiException(string.Format(SRResource.SourceExpressionHasInvalidFormat, expression)); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/StatusCodeExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/StatusCodeExpression.cs new file mode 100644 index 000000000000..1ad412ec36f7 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/StatusCodeExpression.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// StatusCode expression. + /// + internal sealed class StatusCodeExpression : RuntimeExpression + { + /// + /// $statusCode string. + /// + public const string StatusCode = "$statusCode"; + + /// + /// Gets the expression string. + /// + public override string Expression => StatusCode; + + /// + /// Private constructor. + /// + public StatusCodeExpression() + { + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/UrlExpression.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/UrlExpression.cs new file mode 100644 index 000000000000..dcb9c66b1a7b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Expressions/UrlExpression.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions +{ + /// + /// Url expression. + /// + internal sealed class UrlExpression : RuntimeExpression + { + /// + /// $url string. + /// + public const string Url = "$url"; + + /// + /// Gets the expression string. + /// + public override string Expression => Url; + + /// + /// Private constructor. + /// + public UrlExpression() + { + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/EnumExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/EnumExtensions.cs new file mode 100644 index 000000000000..2f786986ab6a --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/EnumExtensions.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Attributes; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions +{ + /// + /// Enumeration type extension methods. + /// + internal static class EnumExtensions + { + // Cache to store display names of enum values + private static readonly ConcurrentDictionary DisplayNameCache = new(); + + /// + /// Gets an attribute on an enum field value. + /// + /// The type of the attribute to retrieve. + /// The enum value. + /// + /// The attribute of the specified type or null. + /// + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Fields are never trimmed for enum types.")] + public static T GetAttributeOfType(this Enum enumValue) where T : Attribute + { + var type = enumValue.GetType(); + // Use GetField to get the field info for the enum value + var memInfo = type.GetField(enumValue.ToString(), BindingFlags.Public | BindingFlags.Static); + + if (memInfo == null) + return null; + + // Retrieve the custom attributes of type T + var attributes = memInfo.GetCustomAttributes(false); + return attributes.FirstOrDefault(); + } + + /// + /// Gets the enum display name. + /// + /// The enum value. + /// + /// Use if it exists. + /// Otherwise, use the standard string representation. + /// + public static string GetDisplayName(this Enum enumValue) + { + // Retrieve the display name from the cache if it exists + return DisplayNameCache.GetOrAdd(enumValue, e => + { + // Get the DisplayAttribute + var attribute = e.GetAttributeOfType(); + + // Return the DisplayAttribute name if it exists, otherwise return the enum's string representation + return attribute == null ? e.ToString() : attribute.Name; + }); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs new file mode 100644 index 000000000000..6224669355ed --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi +{ + internal static class OpenAPIWriterExtensions + { + /// + /// Temporary extension method until we add Settings property to IOpenApiWriter in next major version + /// + /// + /// + internal static OpenApiWriterSettings GetSettings(this IOpenApiWriter openApiWriter) + { + if (openApiWriter is OpenApiWriterBase @base) + { + return @base.Settings; + } + return new(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs new file mode 100644 index 000000000000..6d0500d0cb14 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions +{ + /// + /// Extension methods to verify validity and add an extension to Extensions property. + /// + internal static class OpenApiExtensibleExtensions + { + /// + /// Add extension into the Extensions + /// + /// . + /// The extensible Open API element. + /// The extension name. + /// The extension value. + public static void AddExtension(this T element, string name, IOpenApiExtension any) + where T : IOpenApiExtensible + { + Utils.CheckArgumentNull(element); + Utils.CheckArgumentNullOrEmpty(name); + + if (!name.StartsWith(OpenApiConstants.ExtensionFieldNamePrefix)) + { + throw new OpenApiException(string.Format(SRResource.ExtensionFieldNameMustBeginWithXDash, name)); + } + + element.Extensions[name] = Utils.CheckArgumentNull(any); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiReferencableExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiReferencableExtensions.cs new file mode 100644 index 000000000000..514b0b595bb5 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiReferencableExtensions.cs @@ -0,0 +1,110 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions +{ + /// + /// Extension methods for resolving references on elements. + /// + internal static class OpenApiReferencableExtensions + { + /// + /// Resolves a JSON Pointer with respect to an element, returning the referenced element. + /// + /// The referencable Open API element on which to apply the JSON pointer + /// a JSON Pointer [RFC 6901](https://tools.ietf.org/html/rfc6901). + /// The element pointed to by the JSON pointer. + public static IOpenApiReferenceable ResolveReference(this IOpenApiReferenceable element, JsonPointer pointer) + { + if (!pointer.Tokens.Any()) + { + return element; + } + var propertyName = pointer.Tokens.FirstOrDefault(); + var mapKey = pointer.Tokens.ElementAtOrDefault(1); + try + { + if (element is OpenApiHeader header) + { + return ResolveReferenceOnHeaderElement(header, propertyName, mapKey, pointer); + } + if (element is OpenApiParameter parameter) + { + return ResolveReferenceOnParameterElement(parameter, propertyName, mapKey, pointer); + } + if (element is OpenApiResponse response) + { + return ResolveReferenceOnResponseElement(response, propertyName, mapKey, pointer); + } + } + catch (KeyNotFoundException) + { + throw new OpenApiException(string.Format(SRResource.InvalidReferenceId, pointer)); + } + throw new OpenApiException(string.Format(SRResource.InvalidReferenceId, pointer)); + } + + private static IOpenApiReferenceable ResolveReferenceOnHeaderElement( + OpenApiHeader headerElement, + string propertyName, + string mapKey, + JsonPointer pointer) + { + switch (propertyName) + { + case OpenApiConstants.Schema: + return headerElement.Schema; + case OpenApiConstants.Examples when mapKey != null: + return headerElement.Examples[mapKey]; + default: + throw new OpenApiException(string.Format(SRResource.InvalidReferenceId, pointer)); + } + } + + private static IOpenApiReferenceable ResolveReferenceOnParameterElement( + OpenApiParameter parameterElement, + string propertyName, + string mapKey, + JsonPointer pointer) + { + switch (propertyName) + { + case OpenApiConstants.Schema: + return parameterElement.Schema; + case OpenApiConstants.Examples when mapKey != null: + return parameterElement.Examples[mapKey]; + default: + throw new OpenApiException(string.Format(SRResource.InvalidReferenceId, pointer)); + } + } + + private static IOpenApiReferenceable ResolveReferenceOnResponseElement( + OpenApiResponse responseElement, + string propertyName, + string mapKey, + JsonPointer pointer) + { + switch (propertyName) + { + case OpenApiConstants.Headers when mapKey != null: + return responseElement.Headers[mapKey]; + case OpenApiConstants.Links when mapKey != null: + return responseElement.Links[mapKey]; + default: + throw new OpenApiException(string.Format(SRResource.InvalidReferenceId, pointer)); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiServerExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiServerExtensions.cs new file mode 100644 index 000000000000..d62536d1c7c3 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/OpenApiServerExtensions.cs @@ -0,0 +1,62 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; + +/// +/// Extension methods for serialization. +/// +internal static class OpenApiServerExtensions +{ + /// + /// Replaces URL variables in a server's URL + /// + /// The OpenAPI server object + /// The server variable values that will be used to replace the default values. + /// A URL with the provided variables substituted. + /// + /// Thrown when: + /// 1. A substitution has no valid value in both the supplied dictionary and the default + /// 2. A substitution's value is not available in the enum provided + /// + public static string ReplaceServerUrlVariables(this OpenApiServer server, IDictionary values = null) + { + var parsedUrl = server.Url; + foreach (var variable in server.Variables) + { + // Try to get the value from the provided values + if (values is not { } v || !v.TryGetValue(variable.Key, out var value) || string.IsNullOrEmpty(value)) + { + // Fall back to the default value + value = variable.Value.Default; + } + + // Validate value + if (string.IsNullOrEmpty(value)) + { + // According to the spec, the variable's default value is required. + // This code path should be hit when a value isn't provided & a default value isn't available + throw new ArgumentException( + string.Format(SRResource.ParseServerUrlDefaultValueNotAvailable, variable.Key), nameof(server)); + } + + // If an enum is provided, the array should not be empty & the value should exist in the enum + if (variable.Value.Enum is {} e && (e.Count == 0 || !e.Contains(value))) + { + throw new ArgumentException( + string.Format(SRResource.ParseServerUrlValueNotValid, value, variable.Key), nameof(values)); + } + + parsedUrl = parsedUrl.Replace($"{{{variable.Key}}}", value); + } + + return parsedUrl; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/StringExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/StringExtensions.cs new file mode 100644 index 000000000000..31baf9bc2b67 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Extensions/StringExtensions.cs @@ -0,0 +1,47 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Attributes; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions +{ + /// + /// String extension methods. + /// + internal static class StringExtensions + { + /// + /// Gets the enum value based on the given enum type and display name. + /// + /// The display name. + public static T GetEnumFromDisplayName<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>(this string displayName) + { + var type = typeof(T); + if (!type.IsEnum) + { + return default; + } + + foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static)) + { + var displayAttribute = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute)); + if (displayAttribute != null && displayAttribute.Name == displayName) + { + return (T)field.GetValue(null); + } + } + + return default; + } + internal static string ToFirstCharacterLowerCase(this string input) + => string.IsNullOrEmpty(input) ? string.Empty : char.ToLowerInvariant(input[0]) + input.Substring(1); + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IEffective.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IEffective.cs new file mode 100644 index 000000000000..18f9db6a919b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IEffective.cs @@ -0,0 +1,28 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces +{ + /// + /// OpenApiElements that implement IEffective indicate that their description is not self-contained. + /// External elements affect the effective description. + /// + /// Currently this will only be used for accessing external references. + /// In the next major version, this will be the approach accessing all referenced elements. + /// This will enable us to support merging properties that are peers of the $ref + /// Type of OpenApi Element that is being referenced. + internal interface IEffective where T : class,IOpenApiElement + { + /// + /// Returns a calculated and cloned version of the element. + /// + T GetEffective(OpenApiDocument document); + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiAnnotatable.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiAnnotatable.cs new file mode 100644 index 000000000000..4b4bf23cd5cf --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiAnnotatable.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces +{ + /// + /// Represents an Open API element that can be annotated with + /// non-serializable properties in a property bag. + /// + internal interface IOpenApiAnnotatable + { + /// + /// A collection of properties associated with the current OpenAPI element. + /// + IDictionary Annotations { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiElement.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiElement.cs new file mode 100644 index 000000000000..c1d7c75a5a76 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiElement.cs @@ -0,0 +1,17 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces +{ + /// + /// Represents an Open API element. + /// + internal interface IOpenApiElement + { + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs new file mode 100644 index 000000000000..b518aa751223 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiExtensible.cs @@ -0,0 +1,23 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces +{ + /// + /// Represents an Extensible Open API element. + /// + internal interface IOpenApiExtensible : IOpenApiElement + { + /// + /// Specification extensions. + /// + IDictionary Extensions { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs new file mode 100644 index 000000000000..217a75d2cd08 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs @@ -0,0 +1,25 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces +{ + /// + /// Interface required for implementing any custom extension + /// + internal interface IOpenApiExtension + { + /// + /// Write out contents of custom extension + /// + /// + /// Version of the OpenAPI specification that that will be output. + void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion); + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs new file mode 100644 index 000000000000..2e14765c8769 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiReferenceable.cs @@ -0,0 +1,40 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces +{ + /// + /// Represents an Open API element is referenceable. + /// + internal interface IOpenApiReferenceable : IOpenApiSerializable + { + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + bool UnresolvedReference { get; set; } + + /// + /// Reference object. + /// + OpenApiReference Reference { get; set; } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + void SerializeAsV3WithoutReference(IOpenApiWriter writer); + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + void SerializeAsV2WithoutReference(IOpenApiWriter writer); + + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs new file mode 100644 index 000000000000..e124bcbfae43 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces +{ + /// + /// Represents an Open API element that comes with serialization functionality. + /// + internal interface IOpenApiSerializable : IOpenApiElement + { + /// + /// Serialize Open API element to v3.0. + /// + /// The writer. + void SerializeAsV3(IOpenApiWriter writer); + + /// + /// Serialize Open API element to v2.0. + /// + /// The writer. + void SerializeAsV2(IOpenApiWriter writer); + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/JsonPointer.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/JsonPointer.cs new file mode 100644 index 000000000000..83647c18ff19 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/JsonPointer.cs @@ -0,0 +1,76 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Linq; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi +{ + /// + /// JSON pointer. + /// + internal class JsonPointer + { + /// + /// Initializes the class. + /// + /// Pointer as string. + public JsonPointer(string pointer) + { + Tokens = string.IsNullOrEmpty(pointer) || pointer == "/" + ? new string[0] + : pointer.Split('/').Skip(1).Select(Decode).ToArray(); + } + + /// + /// Initializes the class. + /// + /// Pointer as tokenized string. + private JsonPointer(string[] tokens) + { + Tokens = tokens; + } + + /// + /// Tokens. + /// + public string[] Tokens { get; } + + /// + /// Gets the parent pointer. + /// + public JsonPointer ParentPointer + { + get + { + if (Tokens.Length == 0) + { + return null; + } + + return new(Tokens.Take(Tokens.Length - 1).ToArray()); + } + } + + /// + /// Decode the string. + /// + private string Decode(string token) + { + return Uri.UnescapeDataString(token).Replace("~1", "/").Replace("~0", "~"); + } + + /// + /// Gets the string representation of this JSON pointer. + /// + public override string ToString() + { + return "/" + string.Join("/", Tokens); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Microsoft.OpenApi.csproj.txt b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Microsoft.OpenApi.csproj.txt new file mode 100644 index 000000000000..9eacf3c170f6 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Microsoft.OpenApi.csproj.txt @@ -0,0 +1,45 @@ + + + netstandard2.0 + Latest + true + 1.6.23 + .NET models with JSON and YAML writers for OpenAPI specification + true + + true + NU5048 + README.md + + + + bin\$(Configuration)\$(TargetFramework)\Microsoft.OpenApi.xml + ..\Microsoft.OpenApi.snk + + + + + True + True + SRResource.resx + + + + + + ResXFileCodeGenerator + SRResource.Designer.cs + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiCallback.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiCallback.cs new file mode 100644 index 000000000000..7fe319028a6f --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -0,0 +1,154 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Callback Object: A map of possible out-of band callbacks related to the parent operation. + /// + internal class OpenApiCallback : IOpenApiReferenceable, IOpenApiExtensible, IEffective + { + /// + /// A Path Item Object used to define a callback request and expected responses. + /// + public Dictionary PathItems { get; set; } + = new(); + + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference pointer. + /// + public OpenApiReference Reference { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiCallback() { } + + /// + /// Initializes a copy of an object + /// + public OpenApiCallback(OpenApiCallback callback) + { + PathItems = callback?.PathItems != null ? new(callback?.PathItems) : null; + UnresolvedReference = callback?.UnresolvedReference ?? UnresolvedReference; + Reference = callback?.Reference != null ? new(callback?.Reference) : null; + Extensions = callback?.Extensions != null ? new Dictionary(callback.Extensions) : null; + } + + /// + /// Add a into the . + /// + /// The runtime expression. + /// The path item. + public void AddPathItem(RuntimeExpression expression, OpenApiPathItem pathItem) + { + Utils.CheckArgumentNull(expression); + Utils.CheckArgumentNull(pathItem); + + if (PathItems == null) + { + PathItems = new(); + } + + PathItems.Add(expression, pathItem); + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiCallback object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiCallback + public OpenApiCallback GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // path items + foreach (var item in PathItems) + { + writer.WriteRequiredObject(item.Key.Expression, item.Value, (w, p) => p.SerializeAsV3(w)); + } + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // Callback object does not exist in V2. + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + // Callback object does not exist in V2. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiComponents.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiComponents.cs new file mode 100644 index 000000000000..ff74fa27beee --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -0,0 +1,295 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Components Object. + /// + internal class OpenApiComponents : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// An object to hold reusable Objects. + /// + public IDictionary Schemas { get; set; } = new Dictionary(); + + /// + /// An object to hold reusable Objects. + /// + public IDictionary Responses { get; set; } = new Dictionary(); + + /// + /// An object to hold reusable Objects. + /// + public IDictionary Parameters { get; set; } = + new Dictionary(); + + /// + /// An object to hold reusable Objects. + /// + public IDictionary Examples { get; set; } = new Dictionary(); + + /// + /// An object to hold reusable Objects. + /// + public IDictionary RequestBodies { get; set; } = + new Dictionary(); + + /// + /// An object to hold reusable Objects. + /// + public IDictionary Headers { get; set; } = new Dictionary(); + + /// + /// An object to hold reusable Objects. + /// + public IDictionary SecuritySchemes { get; set; } = + new Dictionary(); + + /// + /// An object to hold reusable Objects. + /// + public IDictionary Links { get; set; } = new Dictionary(); + + /// + /// An object to hold reusable Objects. + /// + public IDictionary Callbacks { get; set; } = new Dictionary(); + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiComponents() { } + + /// + /// Initializes a copy of an object + /// + public OpenApiComponents(OpenApiComponents components) + { + Schemas = components?.Schemas != null ? new Dictionary(components.Schemas) : null; + Responses = components?.Responses != null ? new Dictionary(components.Responses) : null; + Parameters = components?.Parameters != null ? new Dictionary(components.Parameters) : null; + Examples = components?.Examples != null ? new Dictionary(components.Examples) : null; + RequestBodies = components?.RequestBodies != null ? new Dictionary(components.RequestBodies) : null; + Headers = components?.Headers != null ? new Dictionary(components.Headers) : null; + SecuritySchemes = components?.SecuritySchemes != null ? new Dictionary(components.SecuritySchemes) : null; + Links = components?.Links != null ? new Dictionary(components.Links) : null; + Callbacks = components?.Callbacks != null ? new Dictionary(components.Callbacks) : null; + Extensions = components?.Extensions != null ? new Dictionary(components.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0. + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + // If references have been inlined we don't need the to render the components section + // however if they have cycles, then we will need a component rendered + if (writer.GetSettings().InlineLocalReferences) + { + var loops = writer.GetSettings().LoopDetector.Loops; + writer.WriteStartObject(); + if (loops.TryGetValue(typeof(OpenApiSchema), out var schemas)) + { + var openApiSchemas = schemas.Cast().Distinct().ToList() + .ToDictionary(k => k.Reference.Id); + + writer.WriteOptionalMap( + OpenApiConstants.Schemas, + Schemas, + (w, _, component) => component.SerializeAsV3WithoutReference(w)); + } + writer.WriteEndObject(); + return; + } + + writer.WriteStartObject(); + + // Serialize each referenceable object as full object without reference if the reference in the object points to itself. + // If the reference exists but points to other objects, the object is serialized to just that reference. + + // schemas + writer.WriteOptionalMap( + OpenApiConstants.Schemas, + Schemas, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Schema} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // responses + writer.WriteOptionalMap( + OpenApiConstants.Responses, + Responses, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Response} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // parameters + writer.WriteOptionalMap( + OpenApiConstants.Parameters, + Parameters, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Parameter} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // examples + writer.WriteOptionalMap( + OpenApiConstants.Examples, + Examples, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Example} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // requestBodies + writer.WriteOptionalMap( + OpenApiConstants.RequestBodies, + RequestBodies, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.RequestBody} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // headers + writer.WriteOptionalMap( + OpenApiConstants.Headers, + Headers, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Header} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // securitySchemes + writer.WriteOptionalMap( + OpenApiConstants.SecuritySchemes, + SecuritySchemes, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.SecurityScheme} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // links + writer.WriteOptionalMap( + OpenApiConstants.Links, + Links, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Link} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // callbacks + writer.WriteOptionalMap( + OpenApiConstants.Callbacks, + Callbacks, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Callback} && + component.Reference.Id == key) + { + component.SerializeAsV3WithoutReference(w); + } + else + { + component.SerializeAsV3(w); + } + }); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0. + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // Components object does not exist in V2. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiConstants.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiConstants.cs new file mode 100644 index 000000000000..d12c84d3d273 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiConstants.cs @@ -0,0 +1,652 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Constants used in the Open API document. + /// + internal static class OpenApiConstants + { + /// + /// Field: OpenApi + /// + public const string OpenApi = "openapi"; + + /// + /// Field: Info + /// + public const string Info = "info"; + + /// + /// Field: Title + /// + public const string Title = "title"; + + /// + /// Field: Type + /// + public const string Type = "type"; + + /// + /// Field: Format + /// + public const string Format = "format"; + + /// + /// Field: Version + /// + public const string Version = "version"; + + /// + /// Field: Contact + /// + public const string Contact = "contact"; + + /// + /// Field: License + /// + public const string License = "license"; + + /// + /// Field: TermsOfService + /// + public const string TermsOfService = "termsOfService"; + + /// + /// Field: Servers + /// + public const string Servers = "servers"; + + /// + /// Field: Server + /// + public const string Server = "server"; + + /// + /// Field: Paths + /// + public const string Paths = "paths"; + + /// + /// Field: Components + /// + public const string Components = "components"; + + /// + /// Field: Security + /// + public const string Security = "security"; + + /// + /// Field: Tags + /// + public const string Tags = "tags"; + + /// + /// Field: ExternalDocs + /// + public const string ExternalDocs = "externalDocs"; + + /// + /// Field: OperationRef + /// + public const string OperationRef = "operationRef"; + + /// + /// Field: OperationId + /// + public const string OperationId = "operationId"; + + /// + /// Field: Parameters + /// + public const string Parameters = "parameters"; + + /// + /// Field: RequestBody + /// + public const string RequestBody = "requestBody"; + + /// + /// Field: ExtensionFieldNamePrefix + /// + public const string ExtensionFieldNamePrefix = "x-"; + + /// + /// Field: Name + /// + public const string Name = "name"; + + /// + /// Field: Namespace + /// + public const string Namespace = "namespace"; + + /// + /// Field: Prefix + /// + public const string Prefix = "prefix"; + + /// + /// Field: Attribute + /// + public const string Attribute = "attribute"; + + /// + /// Field: Wrapped + /// + public const string Wrapped = "wrapped"; + + /// + /// Field: In + /// + public const string In = "in"; + + /// + /// Field: Summary + /// + public const string Summary = "summary"; + + /// + /// Field: Variables + /// + public const string Variables = "variables"; + + /// + /// Field: Description + /// + public const string Description = "description"; + + /// + /// Field: Required + /// + public const string Required = "required"; + + /// + /// Field: Deprecated + /// + public const string Deprecated = "deprecated"; + + /// + /// Field: Style + /// + public const string Style = "style"; + + /// + /// Field: Explode + /// + public const string Explode = "explode"; + + /// + /// Field: AllowReserved + /// + public const string AllowReserved = "allowReserved"; + + /// + /// Field: Schema + /// + public const string Schema = "schema"; + + /// + /// Field: Schemas + /// + public const string Schemas = "schemas"; + + /// + /// Field: Responses + /// + public const string Responses = "responses"; + + /// + /// Field: Example + /// + public const string Example = "example"; + + /// + /// Field: Examples + /// + public const string Examples = "examples"; + + /// + /// Field: Encoding + /// + public const string Encoding = "encoding"; + + /// + /// Field: RequestBodies + /// + public const string RequestBodies = "requestBodies"; + + /// + /// Field: AllowEmptyValue + /// + public const string AllowEmptyValue = "allowEmptyValue"; + + /// + /// Field: Value + /// + public const string Value = "value"; + + /// + /// Field: ExternalValue + /// + public const string ExternalValue = "externalValue"; + + /// + /// Field: DollarRef + /// + public const string DollarRef = "$ref"; + + /// + /// Field: Headers + /// + public const string Headers = "headers"; + + /// + /// Field: SecuritySchemes + /// + public const string SecuritySchemes = "securitySchemes"; + + /// + /// Field: Content + /// + public const string Content = "content"; + + /// + /// Field: Links + /// + public const string Links = "links"; + + /// + /// Field: Callbacks + /// + public const string Callbacks = "callbacks"; + + /// + /// Field: Url + /// + public const string Url = "url"; + + /// + /// Field: Email + /// + public const string Email = "email"; + + /// + /// Field: Default + /// + public const string Default = "default"; + + /// + /// Field: Enum + /// + public const string Enum = "enum"; + + /// + /// Field: MultipleOf + /// + public const string MultipleOf = "multipleOf"; + + /// + /// Field: Maximum + /// + public const string Maximum = "maximum"; + + /// + /// Field: ExclusiveMaximum + /// + public const string ExclusiveMaximum = "exclusiveMaximum"; + + /// + /// Field: Minimum + /// + public const string Minimum = "minimum"; + + /// + /// Field: ExclusiveMinimum + /// + public const string ExclusiveMinimum = "exclusiveMinimum"; + + /// + /// Field: MaxLength + /// + public const string MaxLength = "maxLength"; + + /// + /// Field: MinLength + /// + public const string MinLength = "minLength"; + + /// + /// Field: Pattern + /// + public const string Pattern = "pattern"; + + /// + /// Field: MaxItems + /// + public const string MaxItems = "maxItems"; + + /// + /// Field: MinItems + /// + public const string MinItems = "minItems"; + + /// + /// Field: UniqueItems + /// + public const string UniqueItems = "uniqueItems"; + + /// + /// Field: MaxProperties + /// + public const string MaxProperties = "maxProperties"; + + /// + /// Field: MinProperties + /// + public const string MinProperties = "minProperties"; + + /// + /// Field: AllOf + /// + public const string AllOf = "allOf"; + + /// + /// Field: OneOf + /// + public const string OneOf = "oneOf"; + + /// + /// Field: AnyOf + /// + public const string AnyOf = "anyOf"; + + /// + /// Field: Not + /// + public const string Not = "not"; + + /// + /// Field: Items + /// + public const string Items = "items"; + + /// + /// Field: Properties + /// + public const string Properties = "properties"; + + /// + /// Field: AdditionalProperties + /// + public const string AdditionalProperties = "additionalProperties"; + + /// + /// Field: Nullable + /// + public const string Nullable = "nullable"; + + /// + /// Field: Discriminator + /// + public const string Discriminator = "discriminator"; + + /// + /// Field: ReadOnly + /// + public const string ReadOnly = "readOnly"; + + /// + /// Field: WriteOnly + /// + public const string WriteOnly = "writeOnly"; + + /// + /// Field: Xml + /// + public const string Xml = "xml"; + + /// + /// Field: Flow + /// + public const string Flow = "flow"; + + /// + /// Field: Application + /// + public const string Application = "application"; + + /// + /// Field: AccessCode + /// + public const string AccessCode = "accessCode"; + + /// + /// Field: Implicit + /// + public const string Implicit = "implicit"; + + /// + /// Field: Password + /// + public const string Password = "password"; + + /// + /// Field: ClientCredentials + /// + public const string ClientCredentials = "clientCredentials"; + + /// + /// Field: AuthorizationCode + /// + public const string AuthorizationCode = "authorizationCode"; + + /// + /// Field: AuthorizationUrl + /// + public const string AuthorizationUrl = "authorizationUrl"; + + /// + /// Field: TokenUrl + /// + public const string TokenUrl = "tokenUrl"; + + /// + /// Field: RefreshUrl + /// + public const string RefreshUrl = "refreshUrl"; + + /// + /// Field: Scopes + /// + public const string Scopes = "scopes"; + + /// + /// Field: ContentType + /// + public const string ContentType = "contentType"; + + /// + /// Field: Get + /// + public const string Get = "get"; + + /// + /// Field: Put + /// + public const string Put = "put"; + + /// + /// Field: Post + /// + public const string Post = "post"; + + /// + /// Field: Delete + /// + public const string Delete = "delete"; + + /// + /// Field: Options + /// + public const string Options = "options"; + + /// + /// Field: Head + /// + public const string Head = "head"; + + /// + /// Field: Patch + /// + public const string Patch = "patch"; + + /// + /// Field: Trace + /// + public const string Trace = "trace"; + + /// + /// Field: PropertyName + /// + public const string PropertyName = "propertyName"; + + /// + /// Field: Mapping + /// + public const string Mapping = "mapping"; + + /// + /// Field: Scheme + /// + public const string Scheme = "scheme"; + + /// + /// Field: BearerFormat + /// + public const string BearerFormat = "bearerFormat"; + + /// + /// Field: Flows + /// + public const string Flows = "flows"; + + /// + /// Field: OpenIdConnectUrl + /// + public const string OpenIdConnectUrl = "openIdConnectUrl"; + + /// + /// Field: DefaultName + /// + public const string DefaultName = "Default Name"; + + /// + /// Field: DefaultDefault + /// + public const string DefaultDefault = "Default Default"; + + /// + /// Field: DefaultTitle + /// + public const string DefaultTitle = "Default Title"; + + /// + /// Field: DefaultDescription + /// + public const string DefaultDescription = "Default Description"; + + /// + /// Field: BodyName extensions + /// + public const string BodyName = "x-bodyName"; + + /// + /// Field: Examples Extension + /// + public const string ExamplesExtension = "x-examples"; + + /// + /// Field: version3_0_0 + /// + public static readonly Version version3_0_0 = new(3, 0, 0); + + /// + /// Field: defaultUrl + /// + public static readonly Uri defaultUrl = new("http://localhost/"); + + #region V2.0 + + /// + /// Field: Host + /// + public const string Host = "host"; + + /// + /// Field: Swagger + /// + public const string Swagger = "swagger"; + + /// + /// Field: version2_0 + /// + public static readonly Version version2_0 = new(2, 0); + + /// + /// Field: BasePath + /// + public const string BasePath = "basePath"; + + /// + /// Field: Schemes + /// + public const string Schemes = "schemes"; + + /// + /// Field: SecurityDefinitions + /// + public const string SecurityDefinitions = "securityDefinitions"; + + /// + /// Field: Definitions + /// + public const string Definitions = "definitions"; + + /// + /// Field: Basic + /// + public const string Basic = "basic"; + + /// + /// Field: Bearer + /// + public const string Bearer = "bearer"; + + /// + /// Field: JWT + /// + public const string Jwt = "JWT"; + + /// + /// Field: Consumes + /// + public const string Consumes = "consumes"; + + /// + /// Field: Produces + /// + public const string Produces = "produces"; + + #endregion + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiContact.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiContact.cs new file mode 100644 index 000000000000..911e8a87c86a --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -0,0 +1,93 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Contact Object. + /// + internal class OpenApiContact : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// The identifying name of the contact person/organization. + /// + public string Name { get; set; } + + /// + /// The URL pointing to the contact information. MUST be in the format of a URL. + /// + public Uri Url { get; set; } + + /// + /// The email address of the contact person/organization. + /// MUST be in the format of an email address. + /// + public string Email { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiContact() { } + + /// + /// Initializes a copy of an instance + /// + public OpenApiContact(OpenApiContact contact) + { + Name = contact?.Name ?? Name; + Url = contact?.Url != null ? new Uri(contact.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; + Email = contact?.Email ?? Email; + Extensions = contact?.Extensions != null ? new Dictionary(contact.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + WriteInternal(writer, OpenApiSpecVersion.OpenApi3_0); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + WriteInternal(writer, OpenApiSpecVersion.OpenApi2_0); + } + + private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + writer.WriteStartObject(); + + // name + writer.WriteProperty(OpenApiConstants.Name, Name); + + // url + writer.WriteProperty(OpenApiConstants.Url, Url?.OriginalString); + + // email + writer.WriteProperty(OpenApiConstants.Email, Email); + + // extensions + writer.WriteExtensions(Extensions, specVersion); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs new file mode 100644 index 000000000000..f02d91457007 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Discriminator object. + /// + internal class OpenApiDiscriminator : IOpenApiSerializable + { + /// + /// REQUIRED. The name of the property in the payload that will hold the discriminator value. + /// + public string PropertyName { get; set; } + + /// + /// An object to hold mappings between payload values and schema names or references. + /// + public IDictionary Mapping { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiDiscriminator() { } + + /// + /// Initializes a copy of an instance + /// + public OpenApiDiscriminator(OpenApiDiscriminator discriminator) + { + PropertyName = discriminator?.PropertyName ?? PropertyName; + Mapping = discriminator?.Mapping != null ? new Dictionary(discriminator.Mapping) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // propertyName + writer.WriteProperty(OpenApiConstants.PropertyName, PropertyName); + + // mapping + writer.WriteOptionalMap(OpenApiConstants.Mapping, Mapping, (w, s) => w.WriteValue(s)); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // Discriminator object does not exist in V2. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiDocument.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiDocument.cs new file mode 100644 index 000000000000..a14d65ed3057 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -0,0 +1,564 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Services; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Describes an OpenAPI object (OpenAPI document). See: https://swagger.io/specification + /// + internal class OpenApiDocument : IOpenApiSerializable, IOpenApiExtensible, IOpenApiAnnotatable + { + /// + /// Related workspace containing OpenApiDocuments that are referenced in this document + /// + public OpenApiWorkspace Workspace { get; set; } + + /// + /// REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required. + /// + public OpenApiInfo Info { get; set; } + + /// + /// An array of Server Objects, which provide connectivity information to a target server. + /// + public IList Servers { get; set; } = new List(); + + /// + /// REQUIRED. The available paths and operations for the API. + /// + public OpenApiPaths Paths { get; set; } + + /// + /// An element to hold various schemas for the specification. + /// + public OpenApiComponents Components { get; set; } + + /// + /// A declaration of which security mechanisms can be used across the API. + /// + public IList SecurityRequirements { get; set; } = new List(); + + /// + /// A list of tags used by the specification with additional metadata. + /// + public IList Tags { get; set; } = new List(); + + /// + /// Additional external documentation. + /// + public OpenApiExternalDocs ExternalDocs { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// The unique hash code of the generated OpenAPI document + /// + public string HashCode => GenerateHashValue(this); + + /// + public IDictionary Annotations { get; set; } + + /// + /// Parameter-less constructor + /// + public OpenApiDocument() {} + + /// + /// Initializes a copy of an an object + /// + public OpenApiDocument(OpenApiDocument document) + { + Workspace = document?.Workspace != null ? new(document?.Workspace) : null; + Info = document?.Info != null ? new(document?.Info) : null; + Servers = document?.Servers != null ? new List(document.Servers) : null; + Paths = document?.Paths != null ? new(document?.Paths) : null; + Components = document?.Components != null ? new(document?.Components) : null; + SecurityRequirements = document?.SecurityRequirements != null ? new List(document.SecurityRequirements) : null; + Tags = document?.Tags != null ? new List(document.Tags) : null; + ExternalDocs = document?.ExternalDocs != null ? new(document?.ExternalDocs) : null; + Extensions = document?.Extensions != null ? new Dictionary(document.Extensions) : null; + Annotations = document?.Annotations != null ? new Dictionary(document.Annotations) : null; + } + + /// + /// Serialize to the latest patch of OpenAPI object V3.0. + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // openapi + writer.WriteProperty(OpenApiConstants.OpenApi, "3.0.4"); + + // info + writer.WriteRequiredObject(OpenApiConstants.Info, Info, (w, i) => i.SerializeAsV3(w)); + + // servers + writer.WriteOptionalCollection(OpenApiConstants.Servers, Servers, (w, s) => s.SerializeAsV3(w)); + + // paths + writer.WriteRequiredObject(OpenApiConstants.Paths, Paths, (w, p) => p.SerializeAsV3(w)); + + // components + writer.WriteOptionalObject(OpenApiConstants.Components, Components, (w, c) => c.SerializeAsV3(w)); + + // security + writer.WriteOptionalCollection( + OpenApiConstants.Security, + SecurityRequirements, + (w, s) => s.SerializeAsV3(w)); + + // tags + writer.WriteOptionalCollection(OpenApiConstants.Tags, Tags, (w, t) => t.SerializeAsV3WithoutReference(w)); + + // external docs + writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV3(w)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to OpenAPI object V2.0. + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // swagger + writer.WriteProperty(OpenApiConstants.Swagger, "2.0"); + + // info + writer.WriteRequiredObject(OpenApiConstants.Info, Info, (w, i) => i.SerializeAsV2(w)); + + // host, basePath, schemes, consumes, produces + WriteHostInfoV2(writer, Servers); + + // paths + writer.WriteRequiredObject(OpenApiConstants.Paths, Paths, (w, p) => p.SerializeAsV2(w)); + + // If references have been inlined we don't need to render the components section + // however if they have cycles, then we will need a component rendered + if (writer.GetSettings().InlineLocalReferences) + { + var loops = writer.GetSettings().LoopDetector.Loops; + + if (loops.TryGetValue(typeof(OpenApiSchema), out var schemas)) + { + var openApiSchemas = schemas.Cast().Distinct().ToList() + .ToDictionary(k => k.Reference.Id); + + foreach (var schema in openApiSchemas.Values.ToList()) + { + FindSchemaReferences.ResolveSchemas(Components, openApiSchemas); + } + + writer.WriteOptionalMap( + OpenApiConstants.Definitions, + openApiSchemas, + (w, _, component) => component.SerializeAsV2WithoutReference(w)); + } + } + else + { + // Serialize each referenceable object as full object without reference if the reference in the object points to itself. + // If the reference exists but points to other objects, the object is serialized to just that reference. + // definitions + writer.WriteOptionalMap( + OpenApiConstants.Definitions, + Components?.Schemas, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Schema} && + component.Reference.Id == key) + { + component.SerializeAsV2WithoutReference(w); + } + else + { + component.SerializeAsV2(w); + } + }); + } + // parameters + var parameters = Components?.Parameters != null + ? new(Components.Parameters) + : new Dictionary(); + + if (Components?.RequestBodies != null) + { + foreach (var requestBody in Components.RequestBodies.Where(b => !parameters.ContainsKey(b.Key))) + { + parameters.Add(requestBody.Key, requestBody.Value.ConvertToBodyParameter()); + } + } + writer.WriteOptionalMap( + OpenApiConstants.Parameters, + parameters, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Parameter} && + component.Reference.Id == key) + { + component.SerializeAsV2WithoutReference(w); + } + else + { + component.SerializeAsV2(w); + } + }); + + // responses + writer.WriteOptionalMap( + OpenApiConstants.Responses, + Components?.Responses, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.Response} && + component.Reference.Id == key) + { + component.SerializeAsV2WithoutReference(w); + } + else + { + component.SerializeAsV2(w); + } + }); + + // securityDefinitions + writer.WriteOptionalMap( + OpenApiConstants.SecurityDefinitions, + Components?.SecuritySchemes, + (w, key, component) => + { + if (component.Reference is {Type: ReferenceType.SecurityScheme} && + component.Reference.Id == key) + { + component.SerializeAsV2WithoutReference(w); + } + else + { + component.SerializeAsV2(w); + } + }); + + // security + writer.WriteOptionalCollection( + OpenApiConstants.Security, + SecurityRequirements, + (w, s) => s.SerializeAsV2(w)); + + // tags + writer.WriteOptionalCollection(OpenApiConstants.Tags, Tags, (w, t) => t.SerializeAsV2WithoutReference(w)); + + // externalDocs + writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV2(w)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + + private static string ParseServerUrl(OpenApiServer server) + { + return server.ReplaceServerUrlVariables(new Dictionary(0)); + } + + private static void WriteHostInfoV2(IOpenApiWriter writer, IList servers) + { + if (servers == null || !servers.Any()) + { + return; + } + + // Arbitrarily choose the first server given that V2 only allows + // one host, port, and base path. + var serverUrl = ParseServerUrl(servers.First()); + + // Divide the URL in the Url property into host and basePath required in OpenAPI V2 + // The Url property cannot contain path templating to be valid for V2 serialization. + var firstServerUrl = new Uri(serverUrl, UriKind.RelativeOrAbsolute); + + // host + if (firstServerUrl.IsAbsoluteUri) + { + writer.WriteProperty( + OpenApiConstants.Host, + firstServerUrl.GetComponents(UriComponents.Host | UriComponents.Port, UriFormat.SafeUnescaped)); + + // basePath + if (firstServerUrl.AbsolutePath != "/") + { + writer.WriteProperty(OpenApiConstants.BasePath, firstServerUrl.AbsolutePath); + } + } else + { + var relativeUrl = firstServerUrl.OriginalString; + if (relativeUrl.StartsWith("//")) + { + var pathPosition = relativeUrl.IndexOf('/', 3); + writer.WriteProperty(OpenApiConstants.Host, relativeUrl.Substring(0, pathPosition)); + relativeUrl = relativeUrl.Substring(pathPosition); + } + if (!String.IsNullOrEmpty(relativeUrl) && relativeUrl != "/") + { + writer.WriteProperty(OpenApiConstants.BasePath, relativeUrl); + } + } + + // Consider all schemes of the URLs in the server list that have the same + // host, port, and base path as the first server. + var schemes = servers.Select( + s => + { + Uri.TryCreate(ParseServerUrl(s), UriKind.RelativeOrAbsolute, out var url); + return url; + }) + .Where( + u => Uri.Compare( + u, + firstServerUrl, + UriComponents.Host | UriComponents.Port | UriComponents.Path, + UriFormat.SafeUnescaped, + StringComparison.OrdinalIgnoreCase) == + 0 && u.IsAbsoluteUri) + .Select(u => u.Scheme) + .Distinct() + .ToList(); + + // schemes + writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) => w.WriteValue(s)); + } + + /// + /// Walk the OpenApiDocument and resolve unresolved references + /// + /// + /// This method will be replaced by a LoadExternalReferences in the next major update to this library. + /// Resolving references at load time is going to go away. + /// + public IEnumerable ResolveReferences() + { + var resolver = new OpenApiReferenceResolver(this, false); + var walker = new OpenApiWalker(resolver); + walker.Walk(this); + return resolver.Errors; + } + + /// + /// Load the referenced object from a object + /// + internal T ResolveReferenceTo(OpenApiReference reference) where T : class, IOpenApiReferenceable + { + if (reference.IsExternal) + { + return ResolveReference(reference, true) as T; + } + else + { + return ResolveReference(reference, false) as T; + } + } + + /// + /// Load the referenced object from a object + /// + public IOpenApiReferenceable ResolveReference(OpenApiReference reference) + { + return ResolveReference(reference, false); + } + + /// + /// Takes in an OpenApi document instance and generates its hash value + /// + /// The OpenAPI description to hash. + /// The hash value. + public static string GenerateHashValue(OpenApiDocument doc) + { + using HashAlgorithm sha = SHA512.Create(); + using var cryptoStream = new CryptoStream(Stream.Null, sha, CryptoStreamMode.Write); + using var streamWriter = new StreamWriter(cryptoStream); + + var openApiJsonWriter = new OpenApiJsonWriter(streamWriter, new() { Terse = true }); + doc.SerializeAsV3(openApiJsonWriter); + openApiJsonWriter.Flush(); + + cryptoStream.FlushFinalBlock(); + var hash = sha.Hash; + + return ConvertByteArrayToString(hash); + } + + private static string ConvertByteArrayToString(byte[] hash) + { + // Build the final string by converting each byte + // into hex and appending it to a StringBuilder + var sb = new StringBuilder(); + for (var i = 0; i < hash.Length; i++) + { + sb.Append(hash[i].ToString("X2")); + } + + return sb.ToString(); + } + + /// + /// Load the referenced object from a object + /// + internal IOpenApiReferenceable ResolveReference(OpenApiReference reference, bool useExternal) + { + if (reference == null) + { + return null; + } + + // Todo: Verify if we need to check to see if this external reference is actually targeted at this document. + if (useExternal) + { + if (this.Workspace == null) + { + throw new ArgumentException(Properties.SRResource.WorkspaceRequredForExternalReferenceResolution); + } + return this.Workspace.ResolveReference(reference); + } + + if (!reference.Type.HasValue) + { + throw new ArgumentException(Properties.SRResource.LocalReferenceRequiresType); + } + + // Special case for Tag + if (reference.Type == ReferenceType.Tag) + { + foreach (var tag in this.Tags) + { + if (tag.Name == reference.Id) + { + tag.Reference = reference; + return tag; + } + } + + return null; + } + + if (this.Components == null) + { + throw new OpenApiException(string.Format(Properties.SRResource.InvalidReferenceId, reference.Id)); + } + + try + { + switch (reference.Type) + { + case ReferenceType.Schema: + return this.Components.Schemas[reference.Id]; + + case ReferenceType.Response: + return this.Components.Responses[reference.Id]; + + case ReferenceType.Parameter: + return this.Components.Parameters[reference.Id]; + + case ReferenceType.Example: + return this.Components.Examples[reference.Id]; + + case ReferenceType.RequestBody: + return this.Components.RequestBodies[reference.Id]; + + case ReferenceType.Header: + return this.Components.Headers[reference.Id]; + + case ReferenceType.SecurityScheme: + return this.Components.SecuritySchemes[reference.Id]; + + case ReferenceType.Link: + return this.Components.Links[reference.Id]; + + case ReferenceType.Callback: + return this.Components.Callbacks[reference.Id]; + + case ReferenceType.Path: + return this.Paths[reference.Id]; + + default: + throw new OpenApiException(Properties.SRResource.InvalidReferenceType); + } + } + catch (KeyNotFoundException) + { + throw new OpenApiException(string.Format(Properties.SRResource.InvalidReferenceId, reference.Id)); + } + } + } + + internal class FindSchemaReferences : OpenApiVisitorBase + { + private Dictionary Schemas; + + public static void ResolveSchemas(OpenApiComponents components, Dictionary schemas ) + { + var visitor = new FindSchemaReferences(); + visitor.Schemas = schemas; + var walker = new OpenApiWalker(visitor); + walker.Walk(components); + } + + public override void Visit(IOpenApiReferenceable referenceable) + { + switch (referenceable) + { + case OpenApiSchema schema: + if (!Schemas.ContainsKey(schema.Reference.Id)) + { + Schemas.Add(schema.Reference.Id, schema); + } + break; + + default: + break; + } + base.Visit(referenceable); + } + + public override void Visit(OpenApiSchema schema) + { + // This is needed to handle schemas used in Responses in components + if (schema.Reference != null) + { + if (!Schemas.ContainsKey(schema.Reference.Id)) + { + Schemas.Add(schema.Reference.Id, schema); + } + } + base.Visit(schema); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiEncoding.cs new file mode 100644 index 000000000000..5609e1f14a8e --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -0,0 +1,116 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// ExternalDocs object. + /// + internal class OpenApiEncoding : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// The Content-Type for encoding a specific property. + /// The value can be a specific media type (e.g. application/json), + /// a wildcard media type (e.g. image/*), or a comma-separated list of the two types. + /// + public string ContentType { get; set; } + + /// + /// A map allowing additional information to be provided as headers. + /// + public IDictionary Headers { get; set; } = new Dictionary(); + + /// + /// Describes how a specific property value will be serialized depending on its type. + /// + public ParameterStyle? Style { get; set; } + + /// + /// When this is true, property values of type array or object generate separate parameters + /// for each value of the array, or key-value-pair of the map. For other types of properties + /// this property has no effect. When style is form, the default value is true. + /// For all other styles, the default value is false. + /// This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded. + /// + public bool? Explode { get; set; } + + /// + /// Determines whether the parameter value SHOULD allow reserved characters, + /// as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding. + /// The default value is false. This property SHALL be ignored + /// if the request body media type is not application/x-www-form-urlencoded. + /// + public bool? AllowReserved { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiEncoding() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiEncoding(OpenApiEncoding encoding) + { + ContentType = encoding?.ContentType ?? ContentType; + Headers = encoding?.Headers != null ? new Dictionary(encoding.Headers) : null; + Style = encoding?.Style ?? Style; + Explode = encoding?.Explode ?? Explode; + AllowReserved = encoding?.AllowReserved ?? AllowReserved; + Extensions = encoding?.Extensions != null ? new Dictionary(encoding.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0. + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // contentType + writer.WriteProperty(OpenApiConstants.ContentType, ContentType); + + // headers + writer.WriteOptionalMap(OpenApiConstants.Headers, Headers, (w, h) => h.SerializeAsV3(w)); + + // style + writer.WriteProperty(OpenApiConstants.Style, Style?.GetDisplayName()); + + // explode + writer.WriteProperty(OpenApiConstants.Explode, Explode, false); + + // allowReserved + writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0. + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // nothing here + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiError.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiError.cs new file mode 100644 index 000000000000..781d1be21556 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiError.cs @@ -0,0 +1,61 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Error related to the Open API Document. + /// + internal class OpenApiError + { + /// + /// Initializes the class using the message and pointer from the given exception. + /// + public OpenApiError(OpenApiException exception) : this(exception.Pointer, exception.Message) + { + } + + /// + /// Initializes the class. + /// + public OpenApiError(string pointer, string message) + { + Pointer = pointer; + Message = message; + } + + /// + /// Initializes a copy of an object + /// + public OpenApiError(OpenApiError error) + { + Pointer = error.Pointer; + Message = error.Message; + } + + /// + /// Message explaining the error. + /// + public string Message { get; set; } + + /// + /// Pointer to the location of the error. + /// + public string Pointer { get; set; } + + /// + /// Gets the string representation of . + /// + public override string ToString() + { + return Message + (!string.IsNullOrEmpty(Pointer) ? " [" + Pointer + "]" : ""); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExample.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExample.cs new file mode 100644 index 000000000000..55a158619607 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -0,0 +1,177 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Example Object. + /// + internal class OpenApiExample : IOpenApiReferenceable, IOpenApiExtensible, IEffective + { + /// + /// Short description for the example. + /// + public string Summary { get; set; } + + /// + /// Long description for the example. + /// CommonMark syntax MAY be used for rich text representation. + /// + public string Description { get; set; } + + /// + /// Embedded literal example. The value field and externalValue field are mutually + /// exclusive. To represent examples of media types that cannot naturally represented + /// in JSON or YAML, use a string value to contain the example, escaping where necessary. + /// + public IOpenApiAny Value { get; set; } + + /// + /// A URL that points to the literal example. + /// This provides the capability to reference examples that cannot easily be + /// included in JSON or YAML documents. + /// The value field and externalValue field are mutually exclusive. + /// + public string ExternalValue { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Reference object. + /// + public OpenApiReference Reference { get; set; } + + /// + /// Indicates object is a placeholder reference to an actual object and does not contain valid data. + /// + public bool UnresolvedReference { get; set; } + + /// + /// Parameter-less constructor + /// + public OpenApiExample() {} + + /// + /// Initializes a copy of object + /// + public OpenApiExample(OpenApiExample example) + { + Summary = example?.Summary ?? Summary; + Description = example?.Description ?? Description; + Value = OpenApiAnyCloneHelper.CloneFromCopyConstructor(example?.Value); + ExternalValue = example?.ExternalValue ?? ExternalValue; + Extensions = example?.Extensions != null ? new Dictionary(example.Extensions) : null; + Reference = example?.Reference != null ? new(example?.Reference) : null; + UnresolvedReference = example?.UnresolvedReference ?? UnresolvedReference; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiExample object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiExample + public OpenApiExample GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + Serialize(writer, OpenApiSpecVersion.OpenApi3_0); + } + + /// + /// Writes out existing examples in a mediatype object + /// + /// + /// + public void Serialize(IOpenApiWriter writer, OpenApiSpecVersion version) + { + writer.WriteStartObject(); + + // summary + writer.WriteProperty(OpenApiConstants.Summary, Summary); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // value + writer.WriteOptionalObject(OpenApiConstants.Value, Value, (w, v) => w.WriteAny(v)); + + // externalValue + writer.WriteProperty(OpenApiConstants.ExternalValue, ExternalValue); + + // extensions + writer.WriteExtensions(Extensions, version); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // Example object of this form does not exist in V2. + // V2 Example object requires knowledge of media type and exists only + // in Response object, so it will be serialized as a part of the Response object. + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + // Example object of this form does not exist in V2. + // V2 Example object requires knowledge of media type and exists only + // in Response object, so it will be serialized as a part of the Response object. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs new file mode 100644 index 000000000000..0f6bacfc865a --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs @@ -0,0 +1,84 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Generic dictionary type for Open API dictionary element. + /// + /// The Open API element, + internal abstract class OpenApiExtensibleDictionary : Dictionary, + IOpenApiSerializable, + IOpenApiExtensible + where T : IOpenApiSerializable + { + /// + /// Parameterless constructor + /// + protected OpenApiExtensibleDictionary() { } + + /// + /// Initializes a copy of class. + /// + /// The generic dictionary. + /// The dictionary of . + protected OpenApiExtensibleDictionary( + Dictionary dictionary = null, + IDictionary extensions = null) : base (dictionary) + { + Extensions = extensions != null ? new Dictionary(extensions) : null; + } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + foreach (var item in this) + { + writer.WriteRequiredObject(item.Key, item.Value, (w, p) => p.SerializeAsV3(w)); + } + + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + foreach (var item in this) + { + writer.WriteRequiredObject(item.Key, item.Value, (w, p) => p.SerializeAsV2(w)); + } + + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs new file mode 100644 index 000000000000..bc33ec634c8b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -0,0 +1,83 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// ExternalDocs object. + /// + internal class OpenApiExternalDocs : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// A short description of the target documentation. + /// + public string Description { get; set; } + + /// + /// REQUIRED. The URL for the target documentation. Value MUST be in the format of a URL. + /// + public Uri Url { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiExternalDocs() { } + + /// + /// Initializes a copy of an object + /// + public OpenApiExternalDocs(OpenApiExternalDocs externalDocs) + { + Description = externalDocs?.Description ?? Description; + Url = externalDocs?.Url != null ? new Uri(externalDocs.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; + Extensions = externalDocs?.Extensions != null ? new Dictionary(externalDocs.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0. + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + WriteInternal(writer, OpenApiSpecVersion.OpenApi3_0); + } + + /// + /// Serialize to Open Api v2.0. + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + WriteInternal(writer, OpenApiSpecVersion.OpenApi2_0); + } + + private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + writer.WriteStartObject(); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // url + writer.WriteProperty(OpenApiConstants.Url, Url?.OriginalString); + + // extensions + writer.WriteExtensions(Extensions, specVersion); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiHeader.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiHeader.cs new file mode 100644 index 000000000000..d878a0b63a07 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -0,0 +1,271 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Header Object. + /// The Header Object follows the structure of the Parameter Object. + /// + internal class OpenApiHeader : IOpenApiReferenceable, IOpenApiExtensible, IEffective + { + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference pointer. + /// + public OpenApiReference Reference { get; set; } + + /// + /// A brief description of the header. + /// + public string Description { get; set; } + + /// + /// Determines whether this header is mandatory. + /// + public bool Required { get; set; } + + /// + /// Specifies that a header is deprecated and SHOULD be transitioned out of usage. + /// + public bool Deprecated { get; set; } + + /// + /// Sets the ability to pass empty-valued headers. + /// + public bool AllowEmptyValue { get; set; } + + /// + /// Describes how the header value will be serialized depending on the type of the header value. + /// + public ParameterStyle? Style { get; set; } + + /// + /// When this is true, header values of type array or object generate separate parameters + /// for each value of the array or key-value pair of the map. + /// + public bool Explode { get; set; } + + /// + /// Determines whether the header value SHOULD allow reserved characters, as defined by RFC3986. + /// + public bool AllowReserved { get; set; } + + /// + /// The schema defining the type used for the header. + /// + public OpenApiSchema Schema { get; set; } + + /// + /// Example of the media type. + /// + public IOpenApiAny Example { get; set; } + + /// + /// Examples of the media type. + /// + public IDictionary Examples { get; set; } = new Dictionary(); + + /// + /// A map containing the representations for the header. + /// + public IDictionary Content { get; set; } = new Dictionary(); + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiHeader() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiHeader(OpenApiHeader header) + { + UnresolvedReference = header?.UnresolvedReference ?? UnresolvedReference; + Reference = header?.Reference != null ? new(header?.Reference) : null; + Description = header?.Description ?? Description; + Required = header?.Required ?? Required; + Deprecated = header?.Deprecated ?? Deprecated; + AllowEmptyValue = header?.AllowEmptyValue ?? AllowEmptyValue; + Style = header?.Style ?? Style; + Explode = header?.Explode ?? Explode; + AllowReserved = header?.AllowReserved ?? AllowReserved; + Schema = header?.Schema != null ? new(header?.Schema) : null; + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(header?.Example); + Examples = header?.Examples != null ? new Dictionary(header.Examples) : null; + Content = header?.Content != null ? new Dictionary(header.Content) : null; + Extensions = header?.Extensions != null ? new Dictionary(header.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiHeader object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiHeader + public OpenApiHeader GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // required + writer.WriteProperty(OpenApiConstants.Required, Required, false); + + // deprecated + writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false); + + // allowEmptyValue + writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false); + + // style + writer.WriteProperty(OpenApiConstants.Style, Style?.GetDisplayName()); + + // explode + writer.WriteProperty(OpenApiConstants.Explode, Explode, false); + + // allowReserved + writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false); + + // schema + writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV3(w)); + + // example + writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, s) => w.WriteAny(s)); + + // examples + writer.WriteOptionalMap(OpenApiConstants.Examples, Examples, (w, e) => e.SerializeAsV3(w)); + + // content + writer.WriteOptionalMap(OpenApiConstants.Content, Content, (w, c) => c.SerializeAsV3(w)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV2WithoutReference(writer); + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // required + writer.WriteProperty(OpenApiConstants.Required, Required, false); + + // deprecated + writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false); + + // allowEmptyValue + writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false); + + // style + writer.WriteProperty(OpenApiConstants.Style, Style?.GetDisplayName()); + + // explode + writer.WriteProperty(OpenApiConstants.Explode, Explode, false); + + // allowReserved + writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false); + + // schema + Schema?.WriteAsItemsProperties(writer); + + // example + writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, s) => w.WriteAny(s)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiInfo.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiInfo.cs new file mode 100644 index 000000000000..d0c740794e25 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -0,0 +1,141 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Open API Info Object, it provides the metadata about the Open API. + /// + internal class OpenApiInfo : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// REQUIRED. The title of the application. + /// + public string Title { get; set; } + + /// + /// A short description of the application. + /// + public string Description { get; set; } + + /// + /// REQUIRED. The version of the OpenAPI document. + /// + public string Version { get; set; } + + /// + /// A URL to the Terms of Service for the API. MUST be in the format of a URL. + /// + public Uri TermsOfService { get; set; } + + /// + /// The contact information for the exposed API. + /// + public OpenApiContact Contact { get; set; } + + /// + /// The license information for the exposed API. + /// + public OpenApiLicense License { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiInfo() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiInfo(OpenApiInfo info) + { + Title = info?.Title ?? Title; + Description = info?.Description ?? Description; + Version = info?.Version ?? Version; + TermsOfService = info?.TermsOfService ?? TermsOfService; + Contact = info?.Contact != null ? new(info?.Contact) : null; + License = info?.License != null ? new(info?.License) : null; + Extensions = info?.Extensions != null ? new Dictionary(info.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // title + writer.WriteProperty(OpenApiConstants.Title, Title); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // termsOfService + writer.WriteProperty(OpenApiConstants.TermsOfService, TermsOfService?.OriginalString); + + // contact object + writer.WriteOptionalObject(OpenApiConstants.Contact, Contact, (w, c) => c.SerializeAsV3(w)); + + // license object + writer.WriteOptionalObject(OpenApiConstants.License, License, (w, l) => l.SerializeAsV3(w)); + + // version + writer.WriteProperty(OpenApiConstants.Version, Version); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // title + writer.WriteProperty(OpenApiConstants.Title, Title); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // termsOfService + writer.WriteProperty(OpenApiConstants.TermsOfService, TermsOfService?.OriginalString); + + // contact object + writer.WriteOptionalObject(OpenApiConstants.Contact, Contact, (w, c) => c.SerializeAsV2(w)); + + // license object + writer.WriteOptionalObject(OpenApiConstants.License, License, (w, l) => l.SerializeAsV2(w)); + + // version + writer.WriteProperty(OpenApiConstants.Version, Version); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiLicense.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiLicense.cs new file mode 100644 index 000000000000..8d71d2a617fb --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -0,0 +1,83 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// License Object. + /// + internal class OpenApiLicense : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// REQUIRED. The license name used for the API. + /// + public string Name { get; set; } + + /// + /// The URL pointing to the contact information. MUST be in the format of a URL. + /// + public Uri Url { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameterless constructor + /// + public OpenApiLicense() { } + + /// + /// Initializes a copy of an object + /// + public OpenApiLicense(OpenApiLicense license) + { + Name = license?.Name ?? Name; + Url = license?.Url != null ? new Uri(license.Url.OriginalString, UriKind.RelativeOrAbsolute) : null; + Extensions = license?.Extensions != null ? new Dictionary(license.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + WriteInternal(writer, OpenApiSpecVersion.OpenApi3_0); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + WriteInternal(writer, OpenApiSpecVersion.OpenApi2_0); + } + + private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + writer.WriteStartObject(); + + // name + writer.WriteProperty(OpenApiConstants.Name, Name); + + // url + writer.WriteProperty(OpenApiConstants.Url, Url?.OriginalString); + + // specification extensions + writer.WriteExtensions(Extensions, specVersion); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiLink.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiLink.cs new file mode 100644 index 000000000000..ac2e9f349996 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -0,0 +1,177 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Link Object. + /// + internal class OpenApiLink : IOpenApiReferenceable, IOpenApiExtensible, IEffective + { + /// + /// A relative or absolute reference to an OAS operation. + /// This field is mutually exclusive of the operationId field, and MUST point to an Operation Object. + /// + public string OperationRef { get; set; } + + /// + /// The name of an existing, resolvable OAS operation, as defined with a unique operationId. + /// This field is mutually exclusive of the operationRef field. + /// + public string OperationId { get; set; } + + /// + /// A map representing parameters to pass to an operation as specified with operationId or identified via operationRef. + /// + public Dictionary Parameters { get; set; } = + new(); + + /// + /// A literal value or {expression} to use as a request body when calling the target operation. + /// + public RuntimeExpressionAnyWrapper RequestBody { get; set; } + + /// + /// A description of the link. + /// + public string Description { get; set; } + + /// + /// A server object to be used by the target operation. + /// + public OpenApiServer Server { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference pointer. + /// + public OpenApiReference Reference { get; set; } + + /// + /// Parameterless constructor + /// + public OpenApiLink() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiLink(OpenApiLink link) + { + OperationRef = link?.OperationRef ?? OperationRef; + OperationId = link?.OperationId ?? OperationId; + Parameters = link?.Parameters != null ? new(link?.Parameters) : null; + RequestBody = link?.RequestBody != null ? new(link?.RequestBody) : null; + Description = link?.Description ?? Description; + Server = link?.Server != null ? new(link?.Server) : null; + Extensions = link?.Extensions != null ? new Dictionary(link.Extensions) : null; + UnresolvedReference = link?.UnresolvedReference ?? UnresolvedReference; + Reference = link?.Reference != null ? new(link?.Reference) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiLink object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiLink + public OpenApiLink GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // operationRef + writer.WriteProperty(OpenApiConstants.OperationRef, OperationRef); + + // operationId + writer.WriteProperty(OpenApiConstants.OperationId, OperationId); + + // parameters + writer.WriteOptionalMap(OpenApiConstants.Parameters, Parameters, (w, p) => p.WriteValue(w)); + + // requestBody + writer.WriteOptionalObject(OpenApiConstants.RequestBody, RequestBody, (w, r) => r.WriteValue(w)); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // server + writer.WriteOptionalObject(OpenApiConstants.Server, Server, (w, s) => s.SerializeAsV3(w)); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // Link object does not exist in V2. + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + // Link object does not exist in V2. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiMediaType.cs new file mode 100644 index 000000000000..f8b97ff1504b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -0,0 +1,135 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Media Type Object. + /// + internal class OpenApiMediaType : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// The schema defining the type used for the request body. + /// + public OpenApiSchema Schema { get; set; } + + /// + /// Example of the media type. + /// The example object SHOULD be in the correct format as specified by the media type. + /// + public IOpenApiAny Example { get; set; } + + /// + /// Examples of the media type. + /// Each example object SHOULD match the media type and specified schema if present. + /// + public IDictionary Examples { get; set; } = new Dictionary(); + + /// + /// A map between a property name and its encoding information. + /// The key, being the property name, MUST exist in the schema as a property. + /// The encoding object SHALL only apply to requestBody objects + /// when the media type is multipart or application/x-www-form-urlencoded. + /// + public IDictionary Encoding { get; set; } = new Dictionary(); + + /// + /// Serialize to Open Api v3.0. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameterless constructor + /// + public OpenApiMediaType() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiMediaType(OpenApiMediaType mediaType) + { + Schema = mediaType?.Schema != null ? new(mediaType?.Schema) : null; + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(mediaType?.Example); + Examples = mediaType?.Examples != null ? new Dictionary(mediaType.Examples) : null; + Encoding = mediaType?.Encoding != null ? new Dictionary(mediaType.Encoding) : null; + Extensions = mediaType?.Extensions != null ? new Dictionary(mediaType.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0. + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // schema + writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV3(w)); + + // example + writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, e) => w.WriteAny(e)); + + // examples + if (Examples != null && Examples.Any()) + { + SerializeExamples(writer, Examples); + } + + // encoding + writer.WriteOptionalMap(OpenApiConstants.Encoding, Encoding, (w, e) => e.SerializeAsV3(w)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0. + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // Media type does not exist in V2. + } + + private static void SerializeExamples(IOpenApiWriter writer, IDictionary examples) + { + /* Special case for writing out empty arrays as valid response examples + * Check if there is any example with an empty array as its value and set the flag `hasEmptyArray` to true + * */ + var hasEmptyArray = examples.Values.Any( static example => + example.Value is OpenApiArray arr && arr.Count == 0 + ); + + if (hasEmptyArray) + { + writer.WritePropertyName(OpenApiConstants.Examples); + writer.WriteStartObject(); + foreach (var kvp in examples.Where(static kvp => kvp.Value.Value is OpenApiArray arr && arr.Count == 0)) + { + writer.WritePropertyName(kvp.Key); + writer.WriteStartObject(); + writer.WriteRequiredObject(OpenApiConstants.Value, kvp.Value.Value, (w, v) => w.WriteAny(v)); + writer.WriteEndObject(); + } + writer.WriteEndObject(); + } + else + { + writer.WriteOptionalMap(OpenApiConstants.Examples, examples, (w, e) => e.SerializeAsV3(w)); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs new file mode 100644 index 000000000000..7b68d1f05e06 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -0,0 +1,100 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// OAuth Flow Object. + /// + internal class OpenApiOAuthFlow : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// REQUIRED. The authorization URL to be used for this flow. + /// Applies to implicit and authorizationCode OAuthFlow. + /// + public Uri AuthorizationUrl { get; set; } + + /// + /// REQUIRED. The token URL to be used for this flow. + /// Applies to password, clientCredentials, and authorizationCode OAuthFlow. + /// + public Uri TokenUrl { get; set; } + + /// + /// The URL to be used for obtaining refresh tokens. + /// + public Uri RefreshUrl { get; set; } + + /// + /// REQUIRED. A map between the scope name and a short description for it. + /// + public IDictionary Scopes { get; set; } = new Dictionary(); + + /// + /// Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameterless constructor + /// + public OpenApiOAuthFlow() { } + + /// + /// Initializes a copy of an object + /// + public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) + { + AuthorizationUrl = oAuthFlow?.AuthorizationUrl != null ? new Uri(oAuthFlow.AuthorizationUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; + TokenUrl = oAuthFlow?.TokenUrl != null ? new Uri(oAuthFlow.TokenUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; + RefreshUrl = oAuthFlow?.RefreshUrl != null ? new Uri(oAuthFlow.RefreshUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; + Scopes = oAuthFlow?.Scopes != null ? new Dictionary(oAuthFlow.Scopes) : null; + Extensions = oAuthFlow?.Extensions != null ? new Dictionary(oAuthFlow.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // authorizationUrl + writer.WriteProperty(OpenApiConstants.AuthorizationUrl, AuthorizationUrl?.ToString()); + + // tokenUrl + writer.WriteProperty(OpenApiConstants.TokenUrl, TokenUrl?.ToString()); + + // refreshUrl + writer.WriteProperty(OpenApiConstants.RefreshUrl, RefreshUrl?.ToString()); + + // scopes + writer.WriteRequiredMap(OpenApiConstants.Scopes, Scopes, (w, s) => w.WriteValue(s)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // OAuthFlow object does not exist in V2. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs new file mode 100644 index 000000000000..ef73ad56dd59 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -0,0 +1,104 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// OAuth Flows Object. + /// + internal class OpenApiOAuthFlows : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// Configuration for the OAuth Implicit flow + /// + public OpenApiOAuthFlow Implicit { get; set; } + + /// + /// Configuration for the OAuth Resource Owner Password flow. + /// + public OpenApiOAuthFlow Password { get; set; } + + /// + /// Configuration for the OAuth Client Credentials flow. + /// + public OpenApiOAuthFlow ClientCredentials { get; set; } + + /// + /// Configuration for the OAuth Authorization Code flow. + /// + public OpenApiOAuthFlow AuthorizationCode { get; set; } + + /// + /// Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameterless constructor + /// + public OpenApiOAuthFlows() {} + + /// + /// Initializes a copy of an object + /// + /// + public OpenApiOAuthFlows(OpenApiOAuthFlows oAuthFlows) + { + Implicit = oAuthFlows?.Implicit != null ? new(oAuthFlows?.Implicit) : null; + Password = oAuthFlows?.Password != null ? new(oAuthFlows?.Password) : null; + ClientCredentials = oAuthFlows?.ClientCredentials != null ? new(oAuthFlows?.ClientCredentials) : null; + AuthorizationCode = oAuthFlows?.AuthorizationCode != null ? new(oAuthFlows?.AuthorizationCode) : null; + Extensions = oAuthFlows?.Extensions != null ? new Dictionary(oAuthFlows.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // implicit + writer.WriteOptionalObject(OpenApiConstants.Implicit, Implicit, (w, o) => o.SerializeAsV3(w)); + + // password + writer.WriteOptionalObject(OpenApiConstants.Password, Password, (w, o) => o.SerializeAsV3(w)); + + // clientCredentials + writer.WriteOptionalObject( + OpenApiConstants.ClientCredentials, + ClientCredentials, + (w, o) => o.SerializeAsV3(w)); + + // authorizationCode + writer.WriteOptionalObject( + OpenApiConstants.AuthorizationCode, + AuthorizationCode, + (w, o) => o.SerializeAsV3(w)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // OAuthFlows object does not exist in V2. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOperation.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOperation.cs new file mode 100644 index 000000000000..c0d96c21a197 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -0,0 +1,343 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Operation Object. + /// + internal class OpenApiOperation : IOpenApiSerializable, IOpenApiExtensible, IOpenApiAnnotatable + { + /// + /// Default value for . + /// + public const bool DeprecatedDefault = false; + + /// + /// A list of tags for API documentation control. + /// Tags can be used for logical grouping of operations by resources or any other qualifier. + /// + public IList Tags { get; set; } = new List(); + + /// + /// A short summary of what the operation does. + /// + public string Summary { get; set; } + + /// + /// A verbose explanation of the operation behavior. + /// CommonMark syntax MAY be used for rich text representation. + /// + public string Description { get; set; } + + /// + /// Additional external documentation for this operation. + /// + public OpenApiExternalDocs ExternalDocs { get; set; } + + /// + /// Unique string used to identify the operation. The id MUST be unique among all operations described in the API. + /// Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, + /// it is RECOMMENDED to follow common programming naming conventions. + /// + public string OperationId { get; set; } + + /// + /// A list of parameters that are applicable for this operation. + /// If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. + /// The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. + /// The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters. + /// + public IList Parameters { get; set; } = new List(); + + /// + /// The request body applicable for this operation. + /// The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 + /// has explicitly defined semantics for request bodies. + /// In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers. + /// + public OpenApiRequestBody RequestBody { get; set; } + + /// + /// REQUIRED. The list of possible responses as they are returned from executing this operation. + /// + public OpenApiResponses Responses { get; set; } = new(); + + /// + /// A map of possible out-of band callbacks related to the parent operation. + /// The key is a unique identifier for the Callback Object. + /// Each value in the map is a Callback Object that describes a request + /// that may be initiated by the API provider and the expected responses. + /// The key value used to identify the callback object is an expression, evaluated at runtime, + /// that identifies a URL to use for the callback operation. + /// + public IDictionary Callbacks { get; set; } = new Dictionary(); + + /// + /// Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. + /// + public bool Deprecated { get; set; } = DeprecatedDefault; + + /// + /// A declaration of which security mechanisms can be used for this operation. + /// The list of values includes alternative security requirement objects that can be used. + /// Only one of the security requirement objects need to be satisfied to authorize a request. + /// This definition overrides any declared top-level security. + /// To remove a top-level security declaration, an empty array can be used. + /// + public IList Security { get; set; } = new List(); + + /// + /// An alternative server array to service this operation. + /// If an alternative server object is specified at the Path Item Object or Root level, + /// it will be overridden by this value. + /// + public IList Servers { get; set; } = new List(); + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + public IDictionary Annotations { get; set; } + + /// + /// Parameterless constructor + /// + public OpenApiOperation() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiOperation(OpenApiOperation operation) + { + Tags = operation?.Tags != null ? new List(operation?.Tags) : null; + Summary = operation?.Summary ?? Summary; + Description = operation?.Description ?? Description; + ExternalDocs = operation?.ExternalDocs != null ? new(operation?.ExternalDocs) : null; + OperationId = operation?.OperationId ?? OperationId; + Parameters = operation?.Parameters != null ? new List(operation.Parameters) : null; + RequestBody = operation?.RequestBody != null ? new(operation?.RequestBody) : null; + Responses = operation?.Responses != null ? new(operation?.Responses) : null; + Callbacks = operation?.Callbacks != null ? new Dictionary(operation.Callbacks) : null; + Deprecated = operation?.Deprecated ?? Deprecated; + Security = operation?.Security != null ? new List(operation.Security) : null; + Servers = operation?.Servers != null ? new List(operation.Servers) : null; + Extensions = operation?.Extensions != null ? new Dictionary(operation.Extensions) : null; + Annotations = operation?.Annotations != null ? new Dictionary(operation.Annotations) : null; + } + + /// + /// Serialize to Open Api v3.0. + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // tags + writer.WriteOptionalCollection( + OpenApiConstants.Tags, + Tags, + (w, t) => t.SerializeAsV3(w)); + + // summary + writer.WriteProperty(OpenApiConstants.Summary, Summary); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // externalDocs + writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV3(w)); + + // operationId + writer.WriteProperty(OpenApiConstants.OperationId, OperationId); + + // parameters + writer.WriteOptionalCollection(OpenApiConstants.Parameters, Parameters, (w, p) => p.SerializeAsV3(w)); + + // requestBody + writer.WriteOptionalObject(OpenApiConstants.RequestBody, RequestBody, (w, r) => r.SerializeAsV3(w)); + + // responses + writer.WriteRequiredObject(OpenApiConstants.Responses, Responses, (w, r) => r.SerializeAsV3(w)); + + // callbacks + writer.WriteOptionalMap(OpenApiConstants.Callbacks, Callbacks, (w, c) => c.SerializeAsV3(w)); + + // deprecated + writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false); + + // security + writer.WriteOptionalCollection(OpenApiConstants.Security, Security, (w, s) => s.SerializeAsV3(w)); + + // servers + writer.WriteOptionalCollection(OpenApiConstants.Servers, Servers, (w, s) => s.SerializeAsV3(w)); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0. + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // tags + writer.WriteOptionalCollection( + OpenApiConstants.Tags, + Tags, + (w, t) => t.SerializeAsV2(w)); + + // summary + writer.WriteProperty(OpenApiConstants.Summary, Summary); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // externalDocs + writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV2(w)); + + // operationId + writer.WriteProperty(OpenApiConstants.OperationId, OperationId); + + List parameters; + if (Parameters == null) + { + parameters = new(); + } + else + { + parameters = new(Parameters); + } + + if (RequestBody != null) + { + // consumes + var consumes = RequestBody.Content.Keys.Distinct().ToList(); + if (consumes.Any()) + { + // This is form data. We need to split the request body into multiple parameters. + if (consumes.Contains("application/x-www-form-urlencoded") || + consumes.Contains("multipart/form-data")) + { + parameters.AddRange(RequestBody.ConvertToFormDataParameters()); + } + else + { + parameters.Add(RequestBody.ConvertToBodyParameter()); + } + } + else if (RequestBody.Reference != null) + { + parameters.Add( + new() + { + UnresolvedReference = true, + Reference = RequestBody.Reference + }); + + if (RequestBody.Reference.HostDocument != null) + { + var effectiveRequestBody = RequestBody.GetEffective(RequestBody.Reference.HostDocument); + if (effectiveRequestBody != null) + consumes = effectiveRequestBody.Content.Keys.Distinct().ToList(); + } + } + + if (consumes.Any()) + { + writer.WritePropertyName(OpenApiConstants.Consumes); + writer.WriteStartArray(); + foreach (var mediaType in consumes) + { + writer.WriteValue(mediaType); + } + writer.WriteEndArray(); + } + } + + if (Responses != null) + { + var produces = Responses + .Where(static r => r.Value.Content != null) + .SelectMany(static r => r.Value.Content?.Keys) + .Concat( + Responses + .Where(static r => r.Value.Reference is {HostDocument: not null}) + .SelectMany(static r => r.Value.GetEffective(r.Value.Reference.HostDocument)?.Content?.Keys)) + .Distinct() + .ToList(); + + if (produces.Any()) + { + // produces + writer.WritePropertyName(OpenApiConstants.Produces); + writer.WriteStartArray(); + foreach (var mediaType in produces) + { + writer.WriteValue(mediaType); + } + + writer.WriteEndArray(); + } + } + + // parameters + // Use the parameters created locally to include request body if exists. + writer.WriteOptionalCollection(OpenApiConstants.Parameters, parameters, (w, p) => p.SerializeAsV2(w)); + + // responses + writer.WriteRequiredObject(OpenApiConstants.Responses, Responses, (w, r) => r.SerializeAsV2(w)); + + // schemes + // All schemes in the Servers are extracted, regardless of whether the host matches + // the host defined in the outermost Swagger object. This is due to the + // inaccessibility of information for that host in the context of an inner object like this Operation. + if (Servers != null) + { + var schemes = Servers.Select( + s => + { + Uri.TryCreate(s.Url, UriKind.RelativeOrAbsolute, out var url); + return url?.Scheme; + }) + .Where(s => s != null) + .Distinct() + .ToList(); + + writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) => w.WriteValue(s)); + } + + // deprecated + writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false); + + // security + writer.WriteOptionalCollection(OpenApiConstants.Security, Security, (w, s) => s.SerializeAsV2(w)); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiParameter.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiParameter.cs new file mode 100644 index 000000000000..d6f5033b6122 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -0,0 +1,444 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Parameter Object. + /// + internal class OpenApiParameter : IOpenApiReferenceable, IEffective, IOpenApiExtensible + { + private bool? _explode; + /// + /// The style of the parameter. + /// + public ParameterStyle? _style; + + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference object. + /// + public OpenApiReference Reference { get; set; } + + /// + /// REQUIRED. The name of the parameter. Parameter names are case sensitive. + /// If in is "path", the name field MUST correspond to the associated path segment from the path field in the Paths Object. + /// If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the parameter definition SHALL be ignored. + /// For all other cases, the name corresponds to the parameter name used by the in property. + /// + public string Name { get; set; } + + /// + /// REQUIRED. The location of the parameter. + /// Possible values are "query", "header", "path" or "cookie". + /// + public ParameterLocation? In { get; set; } + + /// + /// A brief description of the parameter. This could contain examples of use. + /// CommonMark syntax MAY be used for rich text representation. + /// + public string Description { get; set; } + + /// + /// Determines whether this parameter is mandatory. + /// If the parameter location is "path", this property is REQUIRED and its value MUST be true. + /// Otherwise, the property MAY be included and its default value is false. + /// + public bool Required { get; set; } + + /// + /// Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. + /// + public bool Deprecated { get; set; } + + /// + /// Sets the ability to pass empty-valued parameters. + /// This is valid only for query parameters and allows sending a parameter with an empty value. + /// Default value is false. + /// If style is used, and if behavior is n/a (cannot be serialized), + /// the value of allowEmptyValue SHALL be ignored. + /// + public bool AllowEmptyValue { get; set; } + + /// + /// Describes how the parameter value will be serialized depending on the type of the parameter value. + /// Default values (based on value of in): for query - form; for path - simple; for header - simple; + /// for cookie - form. + /// + public ParameterStyle? Style + { + get => _style ?? SetDefaultStyleValue(); + set => _style = value; + } + + /// + /// When this is true, parameter values of type array or object generate separate parameters + /// for each value of the array or key-value pair of the map. + /// For other types of parameters this property has no effect. + /// When style is form, the default value is true. + /// For all other styles, the default value is false. + /// + public bool Explode + { + get => _explode ?? Style == ParameterStyle.Form; + set => _explode = value; + } + + /// + /// Determines whether the parameter value SHOULD allow reserved characters, + /// as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding. + /// This property only applies to parameters with an in value of query. + /// The default value is false. + /// + public bool AllowReserved { get; set; } + + /// + /// The schema defining the type used for the parameter. + /// + public OpenApiSchema Schema { get; set; } + + /// + /// Examples of the media type. Each example SHOULD contain a value + /// in the correct format as specified in the parameter encoding. + /// The examples object is mutually exclusive of the example object. + /// Furthermore, if referencing a schema which contains an example, + /// the examples value SHALL override the example provided by the schema. + /// + public IDictionary Examples { get; set; } = new Dictionary(); + + /// + /// Example of the media type. The example SHOULD match the specified schema and encoding properties + /// if present. The example object is mutually exclusive of the examples object. + /// Furthermore, if referencing a schema which contains an example, + /// the example value SHALL override the example provided by the schema. + /// To represent examples of media types that cannot naturally be represented in JSON or YAML, + /// a string value can contain the example with escaping where necessary. + /// + public IOpenApiAny Example { get; set; } + + /// + /// A map containing the representations for the parameter. + /// The key is the media type and the value describes it. + /// The map MUST only contain one entry. + /// For more complex scenarios, the content property can define the media type and schema of the parameter. + /// A parameter MUST contain either a schema property, or a content property, but not both. + /// When example or examples are provided in conjunction with the schema object, + /// the example MUST follow the prescribed serialization strategy for the parameter. + /// + public IDictionary Content { get; set; } = new Dictionary(); + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// A parameterless constructor + /// + public OpenApiParameter() {} + + /// + /// Initializes a clone instance of object + /// + public OpenApiParameter(OpenApiParameter parameter) + { + UnresolvedReference = parameter?.UnresolvedReference ?? UnresolvedReference; + Reference = parameter?.Reference != null ? new(parameter?.Reference) : null; + Name = parameter?.Name ?? Name; + In = parameter?.In ?? In; + Description = parameter?.Description ?? Description; + Required = parameter?.Required ?? Required; + Style = parameter?.Style ?? Style; + Explode = parameter?.Explode ?? Explode; + AllowReserved = parameter?.AllowReserved ?? AllowReserved; + Schema = parameter?.Schema != null ? new(parameter?.Schema) : null; + Examples = parameter?.Examples != null ? new Dictionary(parameter.Examples) : null; + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(parameter?.Example); + Content = parameter?.Content != null ? new Dictionary(parameter.Content) : null; + Extensions = parameter?.Extensions != null ? new Dictionary(parameter.Extensions) : null; + AllowEmptyValue = parameter?.AllowEmptyValue ?? AllowEmptyValue; + Deprecated = parameter?.Deprecated ?? Deprecated; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = this.GetEffective(Reference.HostDocument); + } + } + + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiParameter object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiParameter + public OpenApiParameter GetEffective(OpenApiDocument doc) + { + return Reference != null ? doc.ResolveReferenceTo(Reference) : this; + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // name + writer.WriteProperty(OpenApiConstants.Name, Name); + + // in + writer.WriteProperty(OpenApiConstants.In, In?.GetDisplayName()); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // required + writer.WriteProperty(OpenApiConstants.Required, Required, false); + + // deprecated + writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false); + + // allowEmptyValue + writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false); + + // style + if (_style.HasValue) + { + writer.WriteProperty(OpenApiConstants.Style, _style.Value.GetDisplayName()); + } + + // explode + writer.WriteProperty(OpenApiConstants.Explode, _explode, _style is ParameterStyle.Form); + + // allowReserved + writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false); + + // schema + writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV3(w)); + + // example + writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, s) => w.WriteAny(s)); + + // examples + writer.WriteOptionalMap(OpenApiConstants.Examples, Examples, (w, e) => e.SerializeAsV3(w)); + + // content + writer.WriteOptionalMap(OpenApiConstants.Content, Content, (w, c) => c.SerializeAsV3(w)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + target = this.GetEffective(Reference.HostDocument); + } + } + + target.SerializeAsV2WithoutReference(writer); + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // in + if (this is OpenApiFormDataParameter) + { + writer.WriteProperty(OpenApiConstants.In, "formData"); + } + else if (this is OpenApiBodyParameter) + { + writer.WriteProperty(OpenApiConstants.In, "body"); + } + else + { + writer.WriteProperty(OpenApiConstants.In, In?.GetDisplayName()); + } + + // name + writer.WriteProperty(OpenApiConstants.Name, Name); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // required + writer.WriteProperty(OpenApiConstants.Required, Required, false); + + // deprecated + writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false); + + var extensionsClone = new Dictionary(Extensions); + + // schema + if (this is OpenApiBodyParameter) + { + writer.WriteOptionalObject(OpenApiConstants.Schema, Schema, (w, s) => s.SerializeAsV2(w)); + } + // In V2 parameter's type can't be a reference to a custom object schema or can't be of type object + // So in that case map the type as string. + else + if (Schema?.UnresolvedReference == true || "object".Equals(Schema?.Type, StringComparison.OrdinalIgnoreCase)) + { + writer.WriteProperty(OpenApiConstants.Type, "string"); + } + else + { + // type + // format + // items + // collectionFormat + // default + // maximum + // exclusiveMaximum + // minimum + // exclusiveMinimum + // maxLength + // minLength + // pattern + // maxItems + // minItems + // uniqueItems + // enum + // multipleOf + if (Schema != null) + { + Schema.WriteAsItemsProperties(writer); + + if (Schema.Extensions != null) + { + foreach (var key in Schema.Extensions.Keys) + { + // The extension will already have been serialized as part of the call to WriteAsItemsProperties above, + // so remove it from the cloned collection so we don't write it again. + extensionsClone.Remove(key); + } + } + } + + // allowEmptyValue + writer.WriteProperty(OpenApiConstants.AllowEmptyValue, AllowEmptyValue, false); + + if (this.In == ParameterLocation.Query && "array".Equals(Schema?.Type, StringComparison.OrdinalIgnoreCase)) + { + if (this.Style == ParameterStyle.Form && this.Explode == true) + { + writer.WriteProperty("collectionFormat", "multi"); + } + else if (this.Style == ParameterStyle.PipeDelimited) + { + writer.WriteProperty("collectionFormat", "pipes"); + } + else if (this.Style == ParameterStyle.SpaceDelimited) + { + writer.WriteProperty("collectionFormat", "ssv"); + } + } + } + + //examples + if (Examples != null && Examples.Any()) + { + writer.WritePropertyName(OpenApiConstants.ExamplesExtension); + writer.WriteStartObject(); + + foreach (var example in Examples) + { + writer.WritePropertyName(example.Key); + example.Value.Serialize(writer, OpenApiSpecVersion.OpenApi2_0); + } + writer.WriteEndObject(); + } + + // extensions + writer.WriteExtensions(extensionsClone, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + + private ParameterStyle? SetDefaultStyleValue() + { + Style = In switch + { + ParameterLocation.Query => ParameterStyle.Form, + ParameterLocation.Header => ParameterStyle.Simple, + ParameterLocation.Path => ParameterStyle.Simple, + ParameterLocation.Cookie => ParameterStyle.Form, + _ => (ParameterStyle?)ParameterStyle.Simple, + }; + + return Style; + } + } + + /// + /// Body parameter class to propagate information needed for + /// + internal class OpenApiBodyParameter : OpenApiParameter + { + } + + /// + /// Form parameter class to propagate information needed for + /// + internal class OpenApiFormDataParameter : OpenApiParameter + { + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiPathItem.cs new file mode 100644 index 000000000000..71dd4c8d0efe --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -0,0 +1,230 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Path Item Object: to describe the operations available on a single path. + /// + internal class OpenApiPathItem : IOpenApiExtensible, IOpenApiReferenceable, IEffective + { + /// + /// An optional, string summary, intended to apply to all operations in this path. + /// + public string Summary { get; set; } + + /// + /// An optional, string description, intended to apply to all operations in this path. + /// + public string Description { get; set; } + + /// + /// Gets the definition of operations on this path. + /// + public IDictionary Operations { get; set; } + = new Dictionary(); + + /// + /// An alternative server array to service all operations in this path. + /// + public IList Servers { get; set; } = new List(); + + /// + /// A list of parameters that are applicable for all the operations described under this path. + /// These parameters can be overridden at the operation level, but cannot be removed there. + /// + public IList Parameters { get; set; } = new List(); + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference object. + /// + public OpenApiReference Reference { get; set; } + + /// + /// Add one operation into this path item. + /// + /// The operation type kind. + /// The operation item. + public void AddOperation(OperationType operationType, OpenApiOperation operation) + { + Operations[operationType] = operation; + } + + /// + /// Parameterless constructor + /// + public OpenApiPathItem() {} + + /// + /// Initializes a clone of an object + /// + public OpenApiPathItem(OpenApiPathItem pathItem) + { + Summary = pathItem?.Summary ?? Summary; + Description = pathItem?.Description ?? Description; + Operations = pathItem?.Operations != null ? new Dictionary(pathItem.Operations) : null; + Servers = pathItem?.Servers != null ? new List(pathItem.Servers) : null; + Parameters = pathItem?.Parameters != null ? new List(pathItem.Parameters) : null; + Extensions = pathItem?.Extensions != null ? new Dictionary(pathItem.Extensions) : null; + UnresolvedReference = pathItem?.UnresolvedReference ?? UnresolvedReference; + Reference = pathItem?.Reference != null ? new(pathItem?.Reference) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiPathItem object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiPathItem + public OpenApiPathItem GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } + else + { + return this; + } + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + target = this.GetEffective(Reference.HostDocument); + } + } + + target.SerializeAsV2WithoutReference(writer); + } + + /// + /// Serialize inline PathItem in OpenAPI V2 + /// + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // operations except "trace" + foreach (var operation in Operations) + { + if (operation.Key != OperationType.Trace) + { + writer.WriteOptionalObject( + operation.Key.GetDisplayName(), + operation.Value, + (w, o) => o.SerializeAsV2(w)); + } + } + + // parameters + writer.WriteOptionalCollection(OpenApiConstants.Parameters, Parameters, (w, p) => p.SerializeAsV2(w)); + + // write "summary" as extensions + writer.WriteProperty(OpenApiConstants.ExtensionFieldNamePrefix + OpenApiConstants.Summary, Summary); + + // write "description" as extensions + writer.WriteProperty( + OpenApiConstants.ExtensionFieldNamePrefix + OpenApiConstants.Description, + Description); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize inline PathItem in OpenAPI V3 + /// + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // summary + writer.WriteProperty(OpenApiConstants.Summary, Summary); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // operations + foreach (var operation in Operations) + { + writer.WriteOptionalObject( + operation.Key.GetDisplayName(), + operation.Value, + (w, o) => o.SerializeAsV3(w)); + } + + // servers + writer.WriteOptionalCollection(OpenApiConstants.Servers, Servers, (w, s) => s.SerializeAsV3(w)); + + // parameters + writer.WriteOptionalCollection(OpenApiConstants.Parameters, Parameters, (w, p) => p.SerializeAsV3(w)); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiPaths.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiPaths.cs new file mode 100644 index 000000000000..20dd6adf832e --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiPaths.cs @@ -0,0 +1,27 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Paths object. + /// + internal class OpenApiPaths : OpenApiExtensibleDictionary + { + /// + /// Parameterless constructor + /// + public OpenApiPaths() {} + + /// + /// Initializes a copy of object + /// + /// The . + public OpenApiPaths(OpenApiPaths paths) : base(dictionary: paths) { } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiReference.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiReference.cs new file mode 100644 index 000000000000..d4431b3995e0 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -0,0 +1,236 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// A simple object to allow referencing other components in the specification, internally and externally. + /// + internal class OpenApiReference : IOpenApiSerializable + { + /// + /// External resource in the reference. + /// It maybe: + /// 1. a absolute/relative file path, for example: ../commons/pet.json + /// 2. a Url, for example: http://localhost/pet.json + /// + public string ExternalResource { get; set; } + + /// + /// The element type referenced. + /// + /// This must be present if is not present. + public ReferenceType? Type { get; set; } + + /// + /// The identifier of the reusable component of one particular ReferenceType. + /// If ExternalResource is present, this is the path to the component after the '#/'. + /// For example, if the reference is 'example.json#/path/to/component', the Id is 'path/to/component'. + /// If ExternalResource is not present, this is the name of the component without the reference type name. + /// For example, if the reference is '#/components/schemas/componentName', the Id is 'componentName'. + /// + public string Id { get; set; } + + /// + /// Gets a flag indicating whether this reference is an external reference. + /// + public bool IsExternal => ExternalResource != null; + + /// + /// Gets a flag indicating whether this reference is a local reference. + /// + public bool IsLocal => ExternalResource == null; + + /// + /// Gets a flag indicating whether a file is a valid OpenAPI document or a fragment + /// + public bool IsFragrament = false; + + /// + /// The OpenApiDocument that is hosting the OpenApiReference instance. This is used to enable dereferencing the reference. + /// + public OpenApiDocument HostDocument { get; set; } + + /// + /// Gets the full reference string for v3.0. + /// + public string ReferenceV3 + { + get + { + if (IsExternal) + { + return GetExternalReferenceV3(); + } + + if (!Type.HasValue) + { + throw new ArgumentNullException(nameof(Type)); + } + + if (Type == ReferenceType.Tag) + { + return Id; + } + + if (Type == ReferenceType.SecurityScheme) + { + return Id; + } + + return "#/components/" + Type.Value.GetDisplayName() + "/" + Id; + } + } + + /// + /// Gets the full reference string for V2.0 + /// + public string ReferenceV2 + { + get + { + if (IsExternal) + { + return GetExternalReferenceV2(); + } + + if (!Type.HasValue) + { + throw new ArgumentNullException(nameof(Type)); + } + + if (Type == ReferenceType.Tag) + { + return Id; + } + + if (Type == ReferenceType.SecurityScheme) + { + return Id; + } + + return "#/" + GetReferenceTypeNameAsV2(Type.Value) + "/" + Id; + } + } + + /// + /// Parameterless constructor + /// + public OpenApiReference() {} + + /// + /// Initializes a copy instance of the object + /// + public OpenApiReference(OpenApiReference reference) + { + ExternalResource = reference?.ExternalResource; + Type = reference?.Type; + Id = reference?.Id; + HostDocument = new(reference?.HostDocument); + } + + /// + /// Serialize to Open Api v3.0. + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + if (Type == ReferenceType.Tag) + { + // Write the string value only + writer.WriteValue(ReferenceV3); + return; + } + + writer.WriteStartObject(); + + // $ref + writer.WriteProperty(OpenApiConstants.DollarRef, ReferenceV3); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0. + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + if (Type == ReferenceType.Tag) + { + // Write the string value only + writer.WriteValue(ReferenceV2); + return; + } + + if (Type == ReferenceType.SecurityScheme) + { + // Write the string as property name + writer.WritePropertyName(ReferenceV2); + return; + } + + writer.WriteStartObject(); + + // $ref + writer.WriteProperty(OpenApiConstants.DollarRef, ReferenceV2); + + writer.WriteEndObject(); + } + + private string GetExternalReferenceV3() + { + if (Id != null) + { + if (IsFragrament) + { + return ExternalResource + "#" + Id; + } + + if (Type.HasValue) + { + return ExternalResource + "#/components/" + Type.Value.GetDisplayName() + "/"+ Id; + } + } + + return ExternalResource; + } + + private string GetExternalReferenceV2() + { + if (Id != null) + { + return ExternalResource + "#/" + GetReferenceTypeNameAsV2((ReferenceType)Type) + "/" + Id; + } + + return ExternalResource; + } + + private string GetReferenceTypeNameAsV2(ReferenceType type) + { + return type switch + { + ReferenceType.Schema => OpenApiConstants.Definitions, + ReferenceType.Parameter or ReferenceType.RequestBody => OpenApiConstants.Parameters, + ReferenceType.Response => OpenApiConstants.Responses, + ReferenceType.Header => OpenApiConstants.Headers, + ReferenceType.Tag => OpenApiConstants.Tags, + ReferenceType.SecurityScheme => OpenApiConstants.SecurityDefinitions, + _ => null,// If the reference type is not supported in V2, simply return null + // to indicate that the reference is not pointing to any object. + }; + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiRequestBody.cs new file mode 100644 index 000000000000..d841f83d9fef --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -0,0 +1,192 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Request Body Object + /// + internal class OpenApiRequestBody : IOpenApiReferenceable, IOpenApiExtensible, IEffective + { + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference object. + /// + public OpenApiReference Reference { get; set; } + + /// + /// A brief description of the request body. This could contain examples of use. + /// CommonMark syntax MAY be used for rich text representation. + /// + public string Description { get; set; } + + /// + /// Determines if the request body is required in the request. Defaults to false. + /// + public bool Required { get; set; } + + /// + /// REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. + /// For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* + /// + public IDictionary Content { get; set; } = new Dictionary(); + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameter-less constructor + /// + public OpenApiRequestBody() { } + + /// + /// Initializes a copy instance of an object + /// + public OpenApiRequestBody(OpenApiRequestBody requestBody) + { + UnresolvedReference = requestBody?.UnresolvedReference ?? UnresolvedReference; + Reference = requestBody?.Reference != null ? new(requestBody?.Reference) : null; + Description = requestBody?.Description ?? Description; + Required = requestBody?.Required ?? Required; + Content = requestBody?.Content != null ? new Dictionary(requestBody.Content) : null; + Extensions = requestBody?.Extensions != null ? new Dictionary(requestBody.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiRequestBody object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiRequestBody + public OpenApiRequestBody GetEffective(OpenApiDocument doc) + { + return Reference != null ? doc.ResolveReferenceTo(Reference) : this; + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // content + writer.WriteRequiredMap(OpenApiConstants.Content, Content, (w, c) => c.SerializeAsV3(w)); + + // required + writer.WriteProperty(OpenApiConstants.Required, Required, false); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // RequestBody object does not exist in V2. + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + // RequestBody object does not exist in V2. + } + + internal OpenApiBodyParameter ConvertToBodyParameter() + { + var bodyParameter = new OpenApiBodyParameter + { + Description = Description, + // V2 spec actually allows the body to have custom name. + // To allow round-tripping we use an extension to hold the name + Name = "body", + Schema = Content.Values.FirstOrDefault()?.Schema ?? new OpenApiSchema(), + Examples = Content.Values.FirstOrDefault()?.Examples, + Required = Required, + Extensions = Extensions.ToDictionary(static k => k.Key, static v => v.Value) // Clone extensions so we can remove the x-bodyName extensions from the output V2 model. + }; + if (bodyParameter.Extensions.ContainsKey(OpenApiConstants.BodyName)) + { + bodyParameter.Name = (Extensions[OpenApiConstants.BodyName] as OpenApiString)?.Value ?? "body"; + bodyParameter.Extensions.Remove(OpenApiConstants.BodyName); + } + return bodyParameter; + } + + internal IEnumerable ConvertToFormDataParameters() + { + if (Content == null || !Content.Any()) + yield break; + + foreach (var property in Content.First().Value.Schema.Properties) + { + var paramSchema = property.Value; + if ("string".Equals(paramSchema.Type, StringComparison.OrdinalIgnoreCase) + && ("binary".Equals(paramSchema.Format, StringComparison.OrdinalIgnoreCase) + || "base64".Equals(paramSchema.Format, StringComparison.OrdinalIgnoreCase))) + { + paramSchema.Type = "file"; + paramSchema.Format = null; + } + yield return new() + { + Description = property.Value.Description, + Name = property.Key, + Schema = property.Value, + Examples = Content.Values.FirstOrDefault()?.Examples, + Required = Content.First().Value.Schema.Required?.Contains(property.Key) ?? false + }; + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiResponse.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiResponse.cs new file mode 100644 index 000000000000..cbbfef21d312 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -0,0 +1,238 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Response object. + /// + internal class OpenApiResponse : IOpenApiReferenceable, IOpenApiExtensible, IEffective + { + /// + /// REQUIRED. A short description of the response. + /// + public string Description { get; set; } + + /// + /// Maps a header name to its definition. + /// + public IDictionary Headers { get; set; } = new Dictionary(); + + /// + /// A map containing descriptions of potential response payloads. + /// The key is a media type or media type range and the value describes it. + /// + public IDictionary Content { get; set; } = new Dictionary(); + + /// + /// A map of operations links that can be followed from the response. + /// The key of the map is a short name for the link, + /// following the naming constraints of the names for Component Objects. + /// + public IDictionary Links { get; set; } = new Dictionary(); + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference pointer. + /// + public OpenApiReference Reference { get; set; } + + /// + /// Parameterless constructor + /// + public OpenApiResponse() {} + + /// + /// Initializes a copy of object + /// + public OpenApiResponse(OpenApiResponse response) + { + Description = response?.Description ?? Description; + Headers = response?.Headers != null ? new Dictionary(response.Headers) : null; + Content = response?.Content != null ? new Dictionary(response.Content) : null; + Links = response?.Links != null ? new Dictionary(response.Links) : null; + Extensions = response?.Extensions != null ? new Dictionary(response.Extensions) : null; + UnresolvedReference = response?.UnresolvedReference ?? UnresolvedReference; + Reference = response?.Reference != null ? new(response?.Reference) : null; + } + + /// + /// Serialize to Open Api v3.0. + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV3WithoutReference(writer); + } + + /// + /// Returns an effective OpenApiRequestBody object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiResponse + public OpenApiResponse GetEffective(OpenApiDocument doc) + { + return Reference != null ? doc.ResolveReferenceTo(Reference) : this; + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // description + writer.WriteRequiredProperty(OpenApiConstants.Description, Description); + + // headers + writer.WriteOptionalMap(OpenApiConstants.Headers, Headers, (w, h) => h.SerializeAsV3(w)); + + // content + writer.WriteOptionalMap(OpenApiConstants.Content, Content, (w, c) => c.SerializeAsV3(w)); + + // links + writer.WriteOptionalMap(OpenApiConstants.Links, Links, (w, l) => l.SerializeAsV3(w)); + + // extension + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0. + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var target = this; + + if (Reference != null) + { + if (!writer.GetSettings().ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + target = GetEffective(Reference.HostDocument); + } + } + target.SerializeAsV2WithoutReference(writer); + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // description + writer.WriteRequiredProperty(OpenApiConstants.Description, Description); + + var extensionsClone = new Dictionary(Extensions); + + if (Content != null) + { + var mediatype = Content.FirstOrDefault(); + if (mediatype.Value != null) + { + // schema + writer.WriteOptionalObject( + OpenApiConstants.Schema, + mediatype.Value.Schema, + (w, s) => s.SerializeAsV2(w)); + + // examples + if (Content.Values.Any(m => m.Example != null)) + { + writer.WritePropertyName(OpenApiConstants.Examples); + writer.WriteStartObject(); + + foreach (var mediaTypePair in Content) + { + if (mediaTypePair.Value.Example != null) + { + writer.WritePropertyName(mediaTypePair.Key); + writer.WriteAny(mediaTypePair.Value.Example); + } + } + + writer.WriteEndObject(); + } + + if (Content.Values.Any(m => m.Examples != null && m.Examples.Any())) + { + writer.WritePropertyName(OpenApiConstants.ExamplesExtension); + writer.WriteStartObject(); + + foreach (var example in Content + .Where(mediaTypePair => mediaTypePair.Value.Examples != null && mediaTypePair.Value.Examples.Any()) + .SelectMany(mediaTypePair => mediaTypePair.Value.Examples)) + { + writer.WritePropertyName(example.Key); + example.Value.Serialize(writer, OpenApiSpecVersion.OpenApi2_0); + } + + writer.WriteEndObject(); + } + + writer.WriteExtensions(mediatype.Value.Extensions, OpenApiSpecVersion.OpenApi2_0); + + foreach (var key in mediatype.Value.Extensions.Keys) + { + // The extension will already have been serialized as part of the call above, + // so remove it from the cloned collection so we don't write it again. + extensionsClone.Remove(key); + } + } + } + + // headers + writer.WriteOptionalMap(OpenApiConstants.Headers, Headers, (w, h) => h.SerializeAsV2(w)); + + // extension + writer.WriteExtensions(extensionsClone, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiResponses.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiResponses.cs new file mode 100644 index 000000000000..950ad57fed4f --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiResponses.cs @@ -0,0 +1,27 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Responses object. + /// + internal class OpenApiResponses : OpenApiExtensibleDictionary + { + /// + /// Parameterless constructor + /// + public OpenApiResponses() { } + + /// + /// Initializes a copy of object + /// + /// The + public OpenApiResponses(OpenApiResponses openApiResponses) : base(dictionary: openApiResponses) {} + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSchema.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSchema.cs new file mode 100644 index 000000000000..cb43738d08be --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -0,0 +1,777 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Schema Object. + /// + internal class OpenApiSchema : IOpenApiReferenceable, IEffective, IOpenApiExtensible, IOpenApiAnnotatable + { + /// + /// Follow JSON Schema definition. Short text providing information about the data. + /// + public string Title { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// Value MUST be a string. Multiple types via an array are not supported. + /// + public string Type { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// While relying on JSON Schema's defined formats, + /// the OAS offers a few additional predefined formats. + /// + public string Format { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// CommonMark syntax MAY be used for rich text representation. + /// + public string Description { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public decimal? Maximum { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public bool? ExclusiveMaximum { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public decimal? Minimum { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public bool? ExclusiveMinimum { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public int? MaxLength { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public int? MinLength { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect + /// + public string Pattern { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public decimal? MultipleOf { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. + /// Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. + /// For example, if type is string, then default can be "foo" but cannot be 1. + /// + public IOpenApiAny Default { get; set; } + + /// + /// Relevant only for Schema "properties" definitions. Declares the property as "read only". + /// This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. + /// If the property is marked as readOnly being true and is in the required list, + /// the required will take effect on the response only. + /// A property MUST NOT be marked as both readOnly and writeOnly being true. + /// Default value is false. + /// + public bool ReadOnly { get; set; } + + /// + /// Relevant only for Schema "properties" definitions. Declares the property as "write only". + /// Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. + /// If the property is marked as writeOnly being true and is in the required list, + /// the required will take effect on the request only. + /// A property MUST NOT be marked as both readOnly and writeOnly being true. + /// Default value is false. + /// + public bool WriteOnly { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. + /// + public IList AllOf { get; set; } = new List(); + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. + /// + public IList OneOf { get; set; } = new List(); + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. + /// + public IList AnyOf { get; set; } = new List(); + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. + /// + public OpenApiSchema Not { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public ISet Required { get; set; } = new HashSet(); + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object + /// and not a standard JSON Schema. items MUST be present if the type is array. + /// + public OpenApiSchema Items { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public int? MaxItems { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public int? MinItems { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public bool? UniqueItems { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced). + /// + public IDictionary Properties { get; set; } = new Dictionary(); + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public int? MaxProperties { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public int? MinProperties { get; set; } + + /// + /// Indicates if the schema can contain properties other than those defined by the properties map. + /// + public bool AdditionalPropertiesAllowed { get; set; } = true; + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// Value can be boolean or object. Inline or referenced schema + /// MUST be of a Schema Object and not a standard JSON Schema. + /// + public OpenApiSchema AdditionalProperties { get; set; } + + /// + /// Adds support for polymorphism. The discriminator is an object name that is used to differentiate + /// between other schemas which may satisfy the payload description. + /// + public OpenApiDiscriminator Discriminator { get; set; } + + /// + /// A free-form property to include an example of an instance for this schema. + /// To represent examples that cannot be naturally represented in JSON or YAML, + /// a string value can be used to contain the example with escaping where necessary. + /// + public IOpenApiAny Example { get; set; } + + /// + /// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00 + /// + public IList Enum { get; set; } = new List(); + + /// + /// Allows sending a null value for the defined schema. Default value is false. + /// + public bool Nullable { get; set; } + + /// + /// Additional external documentation for this schema. + /// + public OpenApiExternalDocs ExternalDocs { get; set; } + + /// + /// Specifies that a schema is deprecated and SHOULD be transitioned out of usage. + /// Default value is false. + /// + public bool Deprecated { get; set; } + + /// + /// This MAY be used only on properties schemas. It has no effect on root schemas. + /// Adds additional metadata to describe the XML representation of this property. + /// + public OpenApiXml Xml { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Indicates object is a placeholder reference to an actual object and does not contain valid data. + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference object. + /// + public OpenApiReference Reference { get; set; } + + /// + public IDictionary Annotations { get; set; } + + /// + /// Parameterless constructor + /// + public OpenApiSchema() {} + + /// + /// Initializes a copy of object + /// + public OpenApiSchema(OpenApiSchema schema) + { + Title = schema?.Title ?? Title; + Type = schema?.Type ?? Type; + Format = schema?.Format ?? Format; + Description = schema?.Description ?? Description; + Maximum = schema?.Maximum ?? Maximum; + ExclusiveMaximum = schema?.ExclusiveMaximum ?? ExclusiveMaximum; + Minimum = schema?.Minimum ?? Minimum; + ExclusiveMinimum = schema?.ExclusiveMinimum ?? ExclusiveMinimum; + MaxLength = schema?.MaxLength ?? MaxLength; + MinLength = schema?.MinLength ?? MinLength; + Pattern = schema?.Pattern ?? Pattern; + MultipleOf = schema?.MultipleOf ?? MultipleOf; + Default = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema?.Default); + ReadOnly = schema?.ReadOnly ?? ReadOnly; + WriteOnly = schema?.WriteOnly ?? WriteOnly; + AllOf = schema?.AllOf != null ? new List(schema.AllOf) : null; + OneOf = schema?.OneOf != null ? new List(schema.OneOf) : null; + AnyOf = schema?.AnyOf != null ? new List(schema.AnyOf) : null; + Not = schema?.Not != null ? new(schema?.Not) : null; + Required = schema?.Required != null ? new HashSet(schema.Required) : null; + Items = schema?.Items != null ? new(schema?.Items) : null; + MaxItems = schema?.MaxItems ?? MaxItems; + MinItems = schema?.MinItems ?? MinItems; + UniqueItems = schema?.UniqueItems ?? UniqueItems; + Properties = schema?.Properties != null ? new Dictionary(schema.Properties) : null; + MaxProperties = schema?.MaxProperties ?? MaxProperties; + MinProperties = schema?.MinProperties ?? MinProperties; + AdditionalPropertiesAllowed = schema?.AdditionalPropertiesAllowed ?? AdditionalPropertiesAllowed; + AdditionalProperties = schema?.AdditionalProperties != null ? new(schema?.AdditionalProperties) : null; + Discriminator = schema?.Discriminator != null ? new(schema?.Discriminator) : null; + Example = OpenApiAnyCloneHelper.CloneFromCopyConstructor(schema?.Example); + Enum = schema?.Enum != null ? new List(schema.Enum) : null; + Nullable = schema?.Nullable ?? Nullable; + ExternalDocs = schema?.ExternalDocs != null ? new(schema?.ExternalDocs) : null; + Deprecated = schema?.Deprecated ?? Deprecated; + Xml = schema?.Xml != null ? new(schema?.Xml) : null; + Extensions = schema?.Extensions != null ? new Dictionary(schema.Extensions) : null; + UnresolvedReference = schema?.UnresolvedReference ?? UnresolvedReference; + Reference = schema?.Reference != null ? new(schema?.Reference) : null; + Annotations = schema?.Annotations != null ? new Dictionary(schema?.Annotations) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + var settings = writer.GetSettings(); + var target = this; + + if (Reference != null) + { + if (!settings.ShouldInlineReference(Reference)) + { + Reference.SerializeAsV3(writer); + return; + } + else + { + if (Reference.IsExternal) // Temporary until v2 + { + target = this.GetEffective(Reference.HostDocument); + } + } + + // If Loop is detected then just Serialize as a reference. + if (!settings.LoopDetector.PushLoop(this)) + { + settings.LoopDetector.SaveLoop(this); + Reference.SerializeAsV3(writer); + return; + } + } + + target.SerializeAsV3WithoutReference(writer); + + if (Reference != null) + { + settings.LoopDetector.PopLoop(); + } + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // title + writer.WriteProperty(OpenApiConstants.Title, Title); + + // multipleOf + writer.WriteProperty(OpenApiConstants.MultipleOf, MultipleOf); + + // maximum + writer.WriteProperty(OpenApiConstants.Maximum, Maximum); + + // exclusiveMaximum + writer.WriteProperty(OpenApiConstants.ExclusiveMaximum, ExclusiveMaximum); + + // minimum + writer.WriteProperty(OpenApiConstants.Minimum, Minimum); + + // exclusiveMinimum + writer.WriteProperty(OpenApiConstants.ExclusiveMinimum, ExclusiveMinimum); + + // maxLength + writer.WriteProperty(OpenApiConstants.MaxLength, MaxLength); + + // minLength + writer.WriteProperty(OpenApiConstants.MinLength, MinLength); + + // pattern + writer.WriteProperty(OpenApiConstants.Pattern, Pattern); + + // maxItems + writer.WriteProperty(OpenApiConstants.MaxItems, MaxItems); + + // minItems + writer.WriteProperty(OpenApiConstants.MinItems, MinItems); + + // uniqueItems + writer.WriteProperty(OpenApiConstants.UniqueItems, UniqueItems); + + // maxProperties + writer.WriteProperty(OpenApiConstants.MaxProperties, MaxProperties); + + // minProperties + writer.WriteProperty(OpenApiConstants.MinProperties, MinProperties); + + // required + writer.WriteOptionalCollection(OpenApiConstants.Required, Required, (w, s) => w.WriteValue(s)); + + // enum + writer.WriteOptionalCollection(OpenApiConstants.Enum, Enum, (nodeWriter, s) => nodeWriter.WriteAny(s)); + + // type + writer.WriteProperty(OpenApiConstants.Type, Type); + + // allOf + writer.WriteOptionalCollection(OpenApiConstants.AllOf, AllOf, (w, s) => s.SerializeAsV3(w)); + + // anyOf + writer.WriteOptionalCollection(OpenApiConstants.AnyOf, AnyOf, (w, s) => s.SerializeAsV3(w)); + + // oneOf + writer.WriteOptionalCollection(OpenApiConstants.OneOf, OneOf, (w, s) => s.SerializeAsV3(w)); + + // not + writer.WriteOptionalObject(OpenApiConstants.Not, Not, (w, s) => s.SerializeAsV3(w)); + + // items + writer.WriteOptionalObject(OpenApiConstants.Items, Items, (w, s) => s.SerializeAsV3(w)); + + // properties + writer.WriteOptionalMap(OpenApiConstants.Properties, Properties, (w, s) => s.SerializeAsV3(w)); + + // additionalProperties + if (AdditionalPropertiesAllowed) + { + writer.WriteOptionalObject( + OpenApiConstants.AdditionalProperties, + AdditionalProperties, + (w, s) => s.SerializeAsV3(w)); + } + else + { + writer.WriteProperty(OpenApiConstants.AdditionalProperties, AdditionalPropertiesAllowed); + } + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // format + writer.WriteProperty(OpenApiConstants.Format, Format); + + // default + writer.WriteOptionalObject(OpenApiConstants.Default, Default, (w, d) => w.WriteAny(d)); + + // nullable + writer.WriteProperty(OpenApiConstants.Nullable, Nullable, false); + + // discriminator + writer.WriteOptionalObject(OpenApiConstants.Discriminator, Discriminator, (w, s) => s.SerializeAsV3(w)); + + // readOnly + writer.WriteProperty(OpenApiConstants.ReadOnly, ReadOnly, false); + + // writeOnly + writer.WriteProperty(OpenApiConstants.WriteOnly, WriteOnly, false); + + // xml + writer.WriteOptionalObject(OpenApiConstants.Xml, Xml, (w, s) => s.SerializeAsV2(w)); + + // externalDocs + writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, s) => s.SerializeAsV3(w)); + + // example + writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, e) => w.WriteAny(e)); + + // deprecated + writer.WriteProperty(OpenApiConstants.Deprecated, Deprecated, false); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + SerializeAsV2(writer: writer, parentRequiredProperties: new HashSet(), propertyName: null); + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + SerializeAsV2WithoutReference( + writer: writer, + parentRequiredProperties: new HashSet(), + propertyName: null); + } + + /// + /// Serialize to Open Api v2.0 and handles not marking the provided property + /// as readonly if its included in the provided list of required properties of parent schema. + /// + /// The open api writer. + /// The list of required properties in parent schema. + /// The property name that will be serialized. + internal void SerializeAsV2( + IOpenApiWriter writer, + ISet parentRequiredProperties, + string propertyName) + { + var settings = writer.GetSettings(); + var target = this; + + if (Reference != null) + { + if (!settings.ShouldInlineReference(Reference)) + { + Reference.SerializeAsV2(writer); + return; + } + else + { + if (Reference.IsExternal) // Temporary until v2 + { + target = this.GetEffective(Reference.HostDocument); + } + } + + // If Loop is detected then just Serialize as a reference. + if (!settings.LoopDetector.PushLoop(this)) + { + settings.LoopDetector.SaveLoop(this); + Reference.SerializeAsV2(writer); + return; + } + } + + if (parentRequiredProperties == null) + { + parentRequiredProperties = new HashSet(); + } + + target.SerializeAsV2WithoutReference(writer, parentRequiredProperties, propertyName); + + if (Reference != null) + { + settings.LoopDetector.PopLoop(); + } + } + + /// + /// Serialize to OpenAPI V2 document without using reference and handles not marking the provided property + /// as readonly if its included in the provided list of required properties of parent schema. + /// + /// The open api writer. + /// The list of required properties in parent schema. + /// The property name that will be serialized. + internal void SerializeAsV2WithoutReference( + IOpenApiWriter writer, + ISet parentRequiredProperties, + string propertyName) + { + writer.WriteStartObject(); + WriteAsSchemaProperties(writer, parentRequiredProperties, propertyName); + writer.WriteEndObject(); + } + + internal void WriteAsItemsProperties(IOpenApiWriter writer) + { + // type + writer.WriteProperty(OpenApiConstants.Type, Type); + + // format + if (string.IsNullOrEmpty(Format)) + { + Format = AllOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? + AnyOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? + OneOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format; + } + + writer.WriteProperty(OpenApiConstants.Format, Format); + + // items + writer.WriteOptionalObject(OpenApiConstants.Items, Items, (w, s) => s.SerializeAsV2(w)); + + // collectionFormat + // We need information from style in parameter to populate this. + // The best effort we can make is to pull this information from the first parameter + // that leverages this schema. However, that in itself may not be as simple + // as the schema directly under parameter might be referencing one in the Components, + // so we will need to do a full scan of the object before we can write the value for + // this property. This is not supported yet, so we will skip this property at the moment. + + // default + writer.WriteOptionalObject(OpenApiConstants.Default, Default, (w, d) => w.WriteAny(d)); + + // maximum + writer.WriteProperty(OpenApiConstants.Maximum, Maximum); + + // exclusiveMaximum + writer.WriteProperty(OpenApiConstants.ExclusiveMaximum, ExclusiveMaximum); + + // minimum + writer.WriteProperty(OpenApiConstants.Minimum, Minimum); + + // exclusiveMinimum + writer.WriteProperty(OpenApiConstants.ExclusiveMinimum, ExclusiveMinimum); + + // maxLength + writer.WriteProperty(OpenApiConstants.MaxLength, MaxLength); + + // minLength + writer.WriteProperty(OpenApiConstants.MinLength, MinLength); + + // pattern + writer.WriteProperty(OpenApiConstants.Pattern, Pattern); + + // maxItems + writer.WriteProperty(OpenApiConstants.MaxItems, MaxItems); + + // minItems + writer.WriteProperty(OpenApiConstants.MinItems, MinItems); + + // enum + writer.WriteOptionalCollection(OpenApiConstants.Enum, Enum, (w, s) => w.WriteAny(s)); + + // multipleOf + writer.WriteProperty(OpenApiConstants.MultipleOf, MultipleOf); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + } + + internal void WriteAsSchemaProperties( + IOpenApiWriter writer, + ISet parentRequiredProperties, + string propertyName) + { + // format + if (string.IsNullOrEmpty(Format)) + { + Format = AllOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? + AnyOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format ?? + OneOf?.FirstOrDefault(static x => !string.IsNullOrEmpty(x.Format))?.Format; + } + + writer.WriteProperty(OpenApiConstants.Format, Format); + + // title + writer.WriteProperty(OpenApiConstants.Title, Title); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // default + writer.WriteOptionalObject(OpenApiConstants.Default, Default, (w, d) => w.WriteAny(d)); + + // multipleOf + writer.WriteProperty(OpenApiConstants.MultipleOf, MultipleOf); + + // maximum + writer.WriteProperty(OpenApiConstants.Maximum, Maximum); + + // exclusiveMaximum + writer.WriteProperty(OpenApiConstants.ExclusiveMaximum, ExclusiveMaximum); + + // minimum + writer.WriteProperty(OpenApiConstants.Minimum, Minimum); + + // exclusiveMinimum + writer.WriteProperty(OpenApiConstants.ExclusiveMinimum, ExclusiveMinimum); + + // maxLength + writer.WriteProperty(OpenApiConstants.MaxLength, MaxLength); + + // minLength + writer.WriteProperty(OpenApiConstants.MinLength, MinLength); + + // pattern + writer.WriteProperty(OpenApiConstants.Pattern, Pattern); + + // maxItems + writer.WriteProperty(OpenApiConstants.MaxItems, MaxItems); + + // minItems + writer.WriteProperty(OpenApiConstants.MinItems, MinItems); + + // uniqueItems + writer.WriteProperty(OpenApiConstants.UniqueItems, UniqueItems); + + // maxProperties + writer.WriteProperty(OpenApiConstants.MaxProperties, MaxProperties); + + // minProperties + writer.WriteProperty(OpenApiConstants.MinProperties, MinProperties); + + // required + writer.WriteOptionalCollection(OpenApiConstants.Required, Required, (w, s) => w.WriteValue(s)); + + // enum + writer.WriteOptionalCollection(OpenApiConstants.Enum, Enum, (w, s) => w.WriteAny(s)); + + // type + writer.WriteProperty(OpenApiConstants.Type, Type); + + // items + writer.WriteOptionalObject(OpenApiConstants.Items, Items, (w, s) => s.SerializeAsV2(w)); + + // allOf + writer.WriteOptionalCollection(OpenApiConstants.AllOf, AllOf, (w, s) => s.SerializeAsV2(w)); + + // If there isn't already an allOf, and the schema contains a oneOf or anyOf write an allOf with the first + // schema in the list as an attempt to guess at a graceful downgrade situation. + if (AllOf == null || AllOf.Count == 0) + { + // anyOf (Not Supported in V2) - Write the first schema only as an allOf. + writer.WriteOptionalCollection(OpenApiConstants.AllOf, AnyOf?.Take(1), (w, s) => s.SerializeAsV2(w)); + + if (AnyOf == null || AnyOf.Count == 0) + { + // oneOf (Not Supported in V2) - Write the first schema only as an allOf. + writer.WriteOptionalCollection(OpenApiConstants.AllOf, OneOf?.Take(1), (w, s) => s.SerializeAsV2(w)); + } + } + + // properties + writer.WriteOptionalMap(OpenApiConstants.Properties, Properties, (w, key, s) => + s.SerializeAsV2(w, Required, key)); + + // additionalProperties + if (AdditionalPropertiesAllowed) + { + writer.WriteOptionalObject( + OpenApiConstants.AdditionalProperties, + AdditionalProperties, + (w, s) => s.SerializeAsV2(w)); + } + else + { + writer.WriteProperty(OpenApiConstants.AdditionalProperties, AdditionalPropertiesAllowed); + } + + // discriminator + writer.WriteProperty(OpenApiConstants.Discriminator, Discriminator?.PropertyName); + + // readOnly + // In V2 schema if a property is part of required properties of parent schema, + // it cannot be marked as readonly. + if (!parentRequiredProperties.Contains(propertyName)) + { + writer.WriteProperty(name: OpenApiConstants.ReadOnly, value: ReadOnly, defaultValue: false); + } + + // xml + writer.WriteOptionalObject(OpenApiConstants.Xml, Xml, (w, s) => s.SerializeAsV2(w)); + + // externalDocs + writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, s) => s.SerializeAsV2(w)); + + // example + writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, e) => w.WriteAny(e)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + } + + /// + /// Returns an effective OpenApiSchema object based on the presence of a $ref + /// + /// The host OpenApiDocument that contains the reference. + /// OpenApiSchema + public OpenApiSchema GetEffective(OpenApiDocument doc) + { + if (this.Reference != null) + { + return doc.ResolveReferenceTo(this.Reference); + } else + { + return this; + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs new file mode 100644 index 000000000000..62756d7e9e24 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs @@ -0,0 +1,148 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Security Requirement Object. + /// Each name MUST correspond to a security scheme which is declared in + /// the Security Schemes under the Components Object. + /// If the security scheme is of type "oauth2" or "openIdConnect", + /// then the value is a list of scope names required for the execution. + /// For other security scheme types, the array MUST be empty. + /// + internal class OpenApiSecurityRequirement : Dictionary>, + IOpenApiSerializable + { + /// + /// Initializes the class. + /// This constructor ensures that only Reference.Id is considered when two dictionary keys + /// of type are compared. + /// + public OpenApiSecurityRequirement() + : base(new OpenApiSecuritySchemeReferenceEqualityComparer()) + { + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + foreach (var securitySchemeAndScopesValuePair in this) + { + var securityScheme = securitySchemeAndScopesValuePair.Key; + var scopes = securitySchemeAndScopesValuePair.Value; + + if (securityScheme.Reference == null) + { + // Reaching this point means the reference to a specific OpenApiSecurityScheme fails. + // We are not able to serialize this SecurityScheme/Scopes key value pair since we do not know what + // string to output. + continue; + } + + writer.WritePropertyName(securityScheme.Reference.ReferenceV3); + + writer.WriteStartArray(); + + foreach (var scope in scopes) + { + writer.WriteValue(scope); + } + + writer.WriteEndArray(); + } + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + foreach (var securitySchemeAndScopesValuePair in this) + { + var securityScheme = securitySchemeAndScopesValuePair.Key; + var scopes = securitySchemeAndScopesValuePair.Value; + + if (securityScheme.Reference == null) + { + // Reaching this point means the reference to a specific OpenApiSecurityScheme fails. + // We are not able to serialize this SecurityScheme/Scopes key value pair since we do not know what + // string to output. + continue; + } + + securityScheme.SerializeAsV2(writer); + + writer.WriteStartArray(); + + foreach (var scope in scopes) + { + writer.WriteValue(scope); + } + + writer.WriteEndArray(); + } + + writer.WriteEndObject(); + } + + /// + /// Comparer for OpenApiSecurityScheme that only considers the Id in the Reference + /// (i.e. the string that will actually be displayed in the written document) + /// + private class OpenApiSecuritySchemeReferenceEqualityComparer : IEqualityComparer + { + /// + /// Determines whether the specified objects are equal. + /// + public bool Equals(OpenApiSecurityScheme x, OpenApiSecurityScheme y) + { + if (x == null && y == null) + { + return true; + } + + if (x == null || y == null) + { + return false; + } + + if (x.Reference == null || y.Reference == null) + { + return false; + } + + return x.Reference.Id == y.Reference.Id; + } + + /// + /// Returns a hash code for the specified object. + /// + public int GetHashCode(OpenApiSecurityScheme obj) + { + return obj?.Reference?.Id == null ? 0 : obj.Reference.Id.GetHashCode(); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs new file mode 100644 index 000000000000..21a4dd7524fe --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -0,0 +1,283 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Security Scheme Object. + /// + internal class OpenApiSecurityScheme : IOpenApiReferenceable, IOpenApiExtensible + { + /// + /// REQUIRED. The type of the security scheme. Valid values are "apiKey", "http", "oauth2", "openIdConnect". + /// + public SecuritySchemeType Type { get; set; } + + /// + /// A short description for security scheme. CommonMark syntax MAY be used for rich text representation. + /// + public string Description { get; set; } + + /// + /// REQUIRED. The name of the header, query or cookie parameter to be used. + /// + public string Name { get; set; } + + /// + /// REQUIRED. The location of the API key. Valid values are "query", "header" or "cookie". + /// + public ParameterLocation In { get; set; } + + /// + /// REQUIRED. The name of the HTTP Authorization scheme to be used + /// in the Authorization header as defined in RFC7235. + /// + public string Scheme { get; set; } + + /// + /// A hint to the client to identify how the bearer token is formatted. + /// Bearer tokens are usually generated by an authorization server, + /// so this information is primarily for documentation purposes. + /// + public string BearerFormat { get; set; } + + /// + /// REQUIRED. An object containing configuration information for the flow types supported. + /// + public OpenApiOAuthFlows Flows { get; set; } + + /// + /// REQUIRED. OpenId Connect URL to discover OAuth2 configuration values. + /// + public Uri OpenIdConnectUrl { get; set; } + + /// + /// Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference object. + /// + public OpenApiReference Reference { get; set; } + + /// + /// Parameterless constructor + /// + public OpenApiSecurityScheme() { } + + /// + /// Initializes a copy of object + /// + public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) + { + Type = securityScheme?.Type ?? Type; + Description = securityScheme?.Description ?? Description; + Name = securityScheme?.Name ?? Name; + In = securityScheme?.In ?? In; + Scheme = securityScheme?.Scheme ?? Scheme; + BearerFormat = securityScheme?.BearerFormat ?? BearerFormat; + Flows = securityScheme?.Flows != null ? new(securityScheme?.Flows) : null; + OpenIdConnectUrl = securityScheme?.OpenIdConnectUrl != null ? new Uri(securityScheme.OpenIdConnectUrl.OriginalString, UriKind.RelativeOrAbsolute) : null; + Extensions = securityScheme?.Extensions != null ? new Dictionary(securityScheme.Extensions) : null; + UnresolvedReference = securityScheme?.UnresolvedReference ?? UnresolvedReference; + Reference = securityScheme?.Reference != null ? new(securityScheme?.Reference) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + if (Reference != null) + { + Reference.SerializeAsV3(writer); + return; + } + + SerializeAsV3WithoutReference(writer); + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // type + writer.WriteProperty(OpenApiConstants.Type, Type.GetDisplayName()); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + switch (Type) + { + case SecuritySchemeType.ApiKey: + // These properties apply to apiKey type only. + // name + // in + writer.WriteProperty(OpenApiConstants.Name, Name); + writer.WriteProperty(OpenApiConstants.In, In.GetDisplayName()); + break; + case SecuritySchemeType.Http: + // These properties apply to http type only. + // scheme + // bearerFormat + writer.WriteProperty(OpenApiConstants.Scheme, Scheme); + writer.WriteProperty(OpenApiConstants.BearerFormat, BearerFormat); + break; + case SecuritySchemeType.OAuth2: + // This property apply to oauth2 type only. + // flows + writer.WriteOptionalObject(OpenApiConstants.Flows, Flows, (w, o) => o.SerializeAsV3(w)); + break; + case SecuritySchemeType.OpenIdConnect: + // This property apply to openIdConnect only. + // openIdConnectUrl + writer.WriteProperty(OpenApiConstants.OpenIdConnectUrl, OpenIdConnectUrl?.ToString()); + break; + } + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + if (Reference != null) + { + Reference.SerializeAsV2(writer); + return; + } + + SerializeAsV2WithoutReference(writer); + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + if (Type == SecuritySchemeType.Http && Scheme != OpenApiConstants.Basic) + { + // Bail because V2 does not support non-basic HTTP scheme + writer.WriteStartObject(); + writer.WriteEndObject(); + return; + } + + if (Type == SecuritySchemeType.OpenIdConnect) + { + // Bail because V2 does not support OpenIdConnect + writer.WriteStartObject(); + writer.WriteEndObject(); + return; + } + + writer.WriteStartObject(); + + // type + switch (Type) + { + case SecuritySchemeType.Http: + writer.WriteProperty(OpenApiConstants.Type, OpenApiConstants.Basic); + break; + + case SecuritySchemeType.OAuth2: + // These properties apply to oauth2 type only. + // flow + // authorizationUrl + // tokenUrl + // scopes + writer.WriteProperty(OpenApiConstants.Type, Type.GetDisplayName()); + WriteOAuthFlowForV2(writer, Flows); + break; + + case SecuritySchemeType.ApiKey: + // These properties apply to apiKey type only. + // name + // in + writer.WriteProperty(OpenApiConstants.Type, Type.GetDisplayName()); + writer.WriteProperty(OpenApiConstants.Name, Name); + writer.WriteProperty(OpenApiConstants.In, In.GetDisplayName()); + break; + } + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + + /// + /// Arbitrarily chooses one object from the + /// to populate in V2 security scheme. + /// + private static void WriteOAuthFlowForV2(IOpenApiWriter writer, OpenApiOAuthFlows flows) + { + if (flows != null) + { + if (flows.Implicit != null) + { + WriteOAuthFlowForV2(writer, OpenApiConstants.Implicit, flows.Implicit); + } + else if (flows.Password != null) + { + WriteOAuthFlowForV2(writer, OpenApiConstants.Password, flows.Password); + } + else if (flows.ClientCredentials != null) + { + WriteOAuthFlowForV2(writer, OpenApiConstants.Application, flows.ClientCredentials); + } + else if (flows.AuthorizationCode != null) + { + WriteOAuthFlowForV2(writer, OpenApiConstants.AccessCode, flows.AuthorizationCode); + } + } + } + + private static void WriteOAuthFlowForV2(IOpenApiWriter writer, string flowValue, OpenApiOAuthFlow flow) + { + // flow + writer.WriteProperty(OpenApiConstants.Flow, flowValue); + + // authorizationUrl + writer.WriteProperty(OpenApiConstants.AuthorizationUrl, flow.AuthorizationUrl?.ToString()); + + // tokenUrl + writer.WriteProperty(OpenApiConstants.TokenUrl, flow.TokenUrl?.ToString()); + + // scopes + writer.WriteOptionalMap(OpenApiConstants.Scopes, flow.Scopes, (w, s) => w.WriteValue(s)); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiServer.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiServer.cs new file mode 100644 index 000000000000..72f973363f31 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -0,0 +1,91 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Server Object: an object representing a Server. + /// + internal class OpenApiServer : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation. + /// + public string Description { get; set; } + + /// + /// REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, + /// to indicate that the host location is relative to the location where the OpenAPI document is being served. + /// Variable substitutions will be made when a variable is named in {brackets}. + /// + public string Url { get; set; } + + /// + /// A map between a variable name and its value. The value is used for substitution in the server's URL template. + /// + public IDictionary Variables { get; set; } = + new Dictionary(); + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameterless constructor + /// + public OpenApiServer() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiServer(OpenApiServer server) + { + Description = server?.Description ?? Description; + Url = server?.Url ?? Url; + Variables = server?.Variables != null ? new Dictionary(server.Variables) : null; + Extensions = server?.Extensions != null ? new Dictionary(server.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // url + writer.WriteProperty(OpenApiConstants.Url, Url); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // variables + writer.WriteOptionalMap(OpenApiConstants.Variables, Variables, (w, v) => v.SerializeAsV3(w)); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // Server object does not exist in V2. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiServerVariable.cs new file mode 100644 index 000000000000..fc7d68a1d1b3 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -0,0 +1,92 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Server Variable Object. + /// + internal class OpenApiServerVariable : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// An optional description for the server variable. CommonMark syntax MAY be used for rich text representation. + /// + public string Description { get; set; } + + /// + /// REQUIRED. The default value to use for substitution, and to send, if an alternate value is not supplied. + /// Unlike the Schema Object's default, this value MUST be provided by the consumer. + /// + public string Default { get; set; } + + /// + /// An enumeration of string values to be used if the substitution options are from a limited set. + /// + /// + /// If the server variable in the OpenAPI document has no enum member, this property will be null. + /// + public List Enum { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameterless constructor + /// + public OpenApiServerVariable() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiServerVariable(OpenApiServerVariable serverVariable) + { + Description = serverVariable?.Description; + Default = serverVariable?.Default; + Enum = serverVariable?.Enum != null ? new(serverVariable?.Enum) : serverVariable?.Enum; + Extensions = serverVariable?.Extensions != null ? new Dictionary(serverVariable?.Extensions) : serverVariable?.Extensions; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + writer.WriteStartObject(); + + // default + writer.WriteProperty(OpenApiConstants.Default, Default); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // enums + writer.WriteOptionalCollection(OpenApiConstants.Enum, Enum, (w, s) => w.WriteValue(s)); + + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + // ServerVariable does not exist in V2. + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiTag.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiTag.cs new file mode 100644 index 000000000000..3b5e6f11a5e1 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -0,0 +1,144 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Tag Object. + /// + internal class OpenApiTag : IOpenApiReferenceable, IOpenApiExtensible + { + /// + /// The name of the tag. + /// + public string Name { get; set; } + + /// + /// A short description for the tag. + /// + public string Description { get; set; } + + /// + /// Additional external documentation for this tag. + /// + public OpenApiExternalDocs ExternalDocs { get; set; } + + /// + /// This object MAY be extended with Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Indicates if object is populated with data or is just a reference to the data + /// + public bool UnresolvedReference { get; set; } + + /// + /// Reference. + /// + public OpenApiReference Reference { get; set; } + + /// + /// Parameterless constructor + /// + public OpenApiTag() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiTag(OpenApiTag tag) + { + Name = tag?.Name ?? Name; + Description = tag?.Description ?? Description; + ExternalDocs = tag?.ExternalDocs != null ? new(tag?.ExternalDocs) : null; + Extensions = tag?.Extensions != null ? new Dictionary(tag.Extensions) : null; + UnresolvedReference = tag?.UnresolvedReference ?? UnresolvedReference; + Reference = tag?.Reference != null ? new(tag?.Reference) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + if (Reference != null) + { + Reference.SerializeAsV3(writer); + return; + } + + writer.WriteValue(Name); + } + + /// + /// Serialize to OpenAPI V3 document without using reference. + /// + public void SerializeAsV3WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // name + writer.WriteProperty(OpenApiConstants.Name, Name); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // external docs + writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV3(w)); + + // extensions. + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + + writer.WriteEndObject(); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + if (Reference != null) + { + Reference.SerializeAsV2(writer); + return; + } + + writer.WriteValue(Name); + } + + /// + /// Serialize to OpenAPI V2 document without using reference. + /// + public void SerializeAsV2WithoutReference(IOpenApiWriter writer) + { + writer.WriteStartObject(); + + // name + writer.WriteProperty(OpenApiConstants.Name, Name); + + // description + writer.WriteProperty(OpenApiConstants.Description, Description); + + // external docs + writer.WriteOptionalObject(OpenApiConstants.ExternalDocs, ExternalDocs, (w, e) => e.SerializeAsV2(w)); + + // extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi2_0); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiXml.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiXml.cs new file mode 100644 index 000000000000..efab3890eb56 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -0,0 +1,112 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// XML Object. + /// + internal class OpenApiXml : IOpenApiSerializable, IOpenApiExtensible + { + /// + /// Replaces the name of the element/attribute used for the described schema property. + /// + public string Name { get; set; } + + /// + /// The URI of the namespace definition. Value MUST be in the form of an absolute URI. + /// + public Uri Namespace { get; set; } + + /// + /// The prefix to be used for the name + /// + public string Prefix { get; set; } + + /// + /// Declares whether the property definition translates to an attribute instead of an element. + /// Default value is false. + /// + public bool Attribute { get; set; } + + /// + /// Signifies whether the array is wrapped. + /// Default value is false. + /// + public bool Wrapped { get; set; } + + /// + /// Specification Extensions. + /// + public IDictionary Extensions { get; set; } = new Dictionary(); + + /// + /// Parameterless constructor + /// + public OpenApiXml() {} + + /// + /// Initializes a copy of an object + /// + public OpenApiXml(OpenApiXml xml) + { + Name = xml?.Name ?? Name; + Namespace = xml?.Namespace ?? Namespace; + Prefix = xml?.Prefix ?? Prefix; + Attribute = xml?.Attribute ?? Attribute; + Wrapped = xml?.Wrapped ?? Wrapped; + Extensions = xml?.Extensions != null ? new Dictionary(xml.Extensions) : null; + } + + /// + /// Serialize to Open Api v3.0 + /// + public void SerializeAsV3(IOpenApiWriter writer) + { + Write(writer, OpenApiSpecVersion.OpenApi3_0); + } + + /// + /// Serialize to Open Api v2.0 + /// + public void SerializeAsV2(IOpenApiWriter writer) + { + Write(writer, OpenApiSpecVersion.OpenApi2_0); + } + + private void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) + { + writer.WriteStartObject(); + + // name + writer.WriteProperty(OpenApiConstants.Name, Name); + + // namespace + writer.WriteProperty(OpenApiConstants.Namespace, Namespace?.AbsoluteUri); + + // prefix + writer.WriteProperty(OpenApiConstants.Prefix, Prefix); + + // attribute + writer.WriteProperty(OpenApiConstants.Attribute, Attribute, false); + + // wrapped + writer.WriteProperty(OpenApiConstants.Wrapped, Wrapped, false); + + // extensions + writer.WriteExtensions(Extensions, specVersion); + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OperationType.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OperationType.cs new file mode 100644 index 000000000000..0672a4016bbe --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/OperationType.cs @@ -0,0 +1,58 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Attributes; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// Operation type. + /// + internal enum OperationType + { + /// + /// A definition of a GET operation on this path. + /// + [Display("get")] Get, + + /// + /// A definition of a PUT operation on this path. + /// + [Display("put")] Put, + + /// + /// A definition of a POST operation on this path. + /// + [Display("post")] Post, + + /// + /// A definition of a DELETE operation on this path. + /// + [Display("delete")] Delete, + + /// + /// A definition of a OPTIONS operation on this path. + /// + [Display("options")] Options, + + /// + /// A definition of a HEAD operation on this path. + /// + [Display("head")] Head, + + /// + /// A definition of a PATCH operation on this path. + /// + [Display("patch")] Patch, + + /// + /// A definition of a TRACE operation on this path. + /// + [Display("trace")] Trace + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ParameterLocation.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ParameterLocation.cs new file mode 100644 index 000000000000..4d517a1e35db --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ParameterLocation.cs @@ -0,0 +1,39 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Attributes; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// The location of the parameter. + /// + internal enum ParameterLocation + { + /// + /// Parameters that are appended to the URL. + /// + [Display("query")] Query, + + /// + /// Custom headers that are expected as part of the request. + /// + [Display("header")] Header, + + /// + /// Used together with Path Templating, + /// where the parameter value is actually part of the operation's URL + /// + [Display("path")] Path, + + /// + /// Used to pass a specific cookie value to the API. + /// + [Display("cookie")] Cookie + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ParameterStyle.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ParameterStyle.cs new file mode 100644 index 000000000000..e9cd35c670c7 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ParameterStyle.cs @@ -0,0 +1,53 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Attributes; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// The style of the parameter. + /// + internal enum ParameterStyle + { + /// + /// Path-style parameters. + /// + [Display("matrix")] Matrix, + + /// + /// Label style parameters. + /// + [Display("label")] Label, + + /// + /// Form style parameters. + /// + [Display("form")] Form, + + /// + /// Simple style parameters. + /// + [Display("simple")] Simple, + + /// + /// Space separated array values. + /// + [Display("spaceDelimited")] SpaceDelimited, + + /// + /// Pipe separated array values. + /// + [Display("pipeDelimited")] PipeDelimited, + + /// + /// Provides a simple way of rendering nested objects using form parameters. + /// + [Display("deepObject")] DeepObject + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ReferenceType.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ReferenceType.cs new file mode 100644 index 000000000000..e7f63fa9655b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/ReferenceType.cs @@ -0,0 +1,73 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Attributes; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// The reference type. + /// + internal enum ReferenceType + { + /// + /// Schema item. + /// + [Display("schemas")] Schema, + + /// + /// Responses item. + /// + [Display("responses")] Response, + + /// + /// Parameters item. + /// + [Display("parameters")] Parameter, + + /// + /// Examples item. + /// + [Display("examples")] Example, + + /// + /// RequestBodies item. + /// + [Display("requestBodies")] RequestBody, + + /// + /// Headers item. + /// + [Display("headers")] Header, + + /// + /// SecuritySchemes item. + /// + [Display("securitySchemes")] SecurityScheme, + + /// + /// Links item. + /// + [Display("links")] Link, + + /// + /// Callbacks item. + /// + [Display("callbacks")] Callback, + + /// + /// Tags item. + /// + [Display("tags")] Tag, + + /// + /// Paths item. + /// + [Display("paths")] Path + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs new file mode 100644 index 000000000000..c713f9f2665b --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -0,0 +1,87 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Expressions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Writers; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// The wrapper either for or + /// + internal class RuntimeExpressionAnyWrapper : IOpenApiElement + { + private IOpenApiAny _any; + private RuntimeExpression _expression; + + /// + /// Parameterless constructor + /// + public RuntimeExpressionAnyWrapper() {} + + /// + /// Initializes a copy of an object + /// + public RuntimeExpressionAnyWrapper(RuntimeExpressionAnyWrapper runtimeExpressionAnyWrapper) + { + Any = OpenApiAnyCloneHelper.CloneFromCopyConstructor(runtimeExpressionAnyWrapper?.Any); + Expression = runtimeExpressionAnyWrapper?.Expression; + } + + /// + /// Gets/Sets the + /// + public IOpenApiAny Any + { + get + { + return _any; + } + set + { + _expression = null; + _any = value; + } + } + + /// + /// Gets/Set the + /// + public RuntimeExpression Expression + { + get + { + return _expression; + } + set + { + _any = null; + _expression = value; + } + } + + /// + /// Write + /// + public void WriteValue(IOpenApiWriter writer) + { + Utils.CheckArgumentNull(writer); + + if (_any != null) + { + writer.WriteAny(_any); + } + else if (_expression != null) + { + writer.WriteValue(_expression.Expression); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/SecuritySchemeType.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/SecuritySchemeType.cs new file mode 100644 index 000000000000..2cea9aec6676 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Models/SecuritySchemeType.cs @@ -0,0 +1,38 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Attributes; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Models +{ + /// + /// The type of the security scheme + /// + internal enum SecuritySchemeType + { + /// + /// Use API key + /// + [Display("apiKey")] ApiKey, + + /// + /// Use basic or bearer token authorization header. + /// + [Display("http")] Http, + + /// + /// Use OAuth2 + /// + [Display("oauth2")] OAuth2, + + /// + /// Use OAuth2 with OpenId Connect URL to discover OAuth2 configuration value. + /// + [Display("openIdConnect")] OpenIdConnect + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/OpenApiFormat.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/OpenApiFormat.cs new file mode 100644 index 000000000000..b7e6ba05ca60 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/OpenApiFormat.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi +{ + /// + /// Represents the Open Api document format. + /// + internal enum OpenApiFormat + { + /// + /// JSON format. + /// + Json, + + /// + /// Yaml format. + /// + Yaml + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/OpenApiSpecVersion.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/OpenApiSpecVersion.cs new file mode 100644 index 000000000000..a4704f872253 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/OpenApiSpecVersion.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi +{ + /// + /// Represents versions of OpenAPI specification. + /// + internal enum OpenApiSpecVersion + { + /// + /// Represents OpenAPI V2.0 spec + /// + OpenApi2_0, + + /// + /// Represents all patches of OpenAPI V3.0 spec (e.g. 3.0.0, 3.0.1) + /// + OpenApi3_0 + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Properties/SRResource.Designer.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Properties/SRResource.Designer.cs new file mode 100644 index 000000000000..2d448485e913 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Properties/SRResource.Designer.cs @@ -0,0 +1,410 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class SRResource { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal SRResource() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.OpenApi.Properties.SRResource", typeof(SRResource).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to There must be an active scope for name '{0}' to be written.. + /// + internal static string ActiveScopeNeededForPropertyNameWriting { + get { + return ResourceManager.GetString("ActiveScopeNeededForPropertyNameWriting", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The argument '{0}' is null, empty or consists only of white-space.. + /// + internal static string ArgumentNullOrWhiteSpace { + get { + return ResourceManager.GetString("ArgumentNullOrWhiteSpace", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to http://localhost/. + /// + internal static string DefaultBaseUri { + get { + return ResourceManager.GetString("DefaultBaseUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The filed name '{0}' of extension doesn't begin with x-.. + /// + internal static string ExtensionFieldNameMustBeginWithXDash { + get { + return ResourceManager.GetString("ExtensionFieldNameMustBeginWithXDash", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Indentation level cannot be lower than 0.. + /// + internal static string IndentationLevelInvalid { + get { + return ResourceManager.GetString("IndentationLevelInvalid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The input item should be in type of '{0}'.. + /// + internal static string InputItemShouldBeType { + get { + return ResourceManager.GetString("InputItemShouldBeType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid Reference identifier '{0}'.. + /// + internal static string InvalidReferenceId { + get { + return ResourceManager.GetString("InvalidReferenceId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid Reference Type '{0}'.. + /// + internal static string InvalidReferenceType { + get { + return ResourceManager.GetString("InvalidReferenceType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Local reference must have type specified.. + /// + internal static string LocalReferenceRequiresType { + get { + return ResourceManager.GetString("LocalReferenceRequiresType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The active scope must be an object scope for property name '{0}' to be written.. + /// + internal static string ObjectScopeNeededForPropertyNameWriting { + get { + return ResourceManager.GetString("ObjectScopeNeededForPropertyNameWriting", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to An error occurred while processing the Open API document.. + /// + internal static string OpenApiExceptionGenericError { + get { + return ResourceManager.GetString("OpenApiExceptionGenericError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The given OpenAPI format '{0}' is not supported.. + /// + internal static string OpenApiFormatNotSupported { + get { + return ResourceManager.GetString("OpenApiFormatNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The object element name '{0}' is required.. + /// + internal static string OpenApiObjectElementIsRequired { + get { + return ResourceManager.GetString("OpenApiObjectElementIsRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The OpenApi element '{0}' is already marked as reference object.. + /// + internal static string OpenApiObjectMarkAsReference { + get { + return ResourceManager.GetString("OpenApiObjectMarkAsReference", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to If the parameter location is "path", this property is REQUIRED and its value MUST be true. + /// + internal static string OpenApiParameterRequiredPropertyMandatory { + get { + return ResourceManager.GetString("OpenApiParameterRequiredPropertyMandatory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The given OpenAPI specification version '{0}' is not supported.. + /// + internal static string OpenApiSpecVersionNotSupported { + get { + return ResourceManager.GetString("OpenApiSpecVersionNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The type '{0}' is not supported in Open API document.. + /// + internal static string OpenApiUnsupportedValueType { + get { + return ResourceManager.GetString("OpenApiUnsupportedValueType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to An error occurred while writing the Open API document.. + /// + internal static string OpenApiWriterExceptionGenericError { + get { + return ResourceManager.GetString("OpenApiWriterExceptionGenericError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid server variable '{0}'. A value was not provided and no default value was provided.. + /// + internal static string ParseServerUrlDefaultValueNotAvailable { + get { + return ResourceManager.GetString("ParseServerUrlDefaultValueNotAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value '{0}' is not a valid value for variable '{1}'. If an enum is provided, it should not be empty and the value provided should exist in the enum. + /// + internal static string ParseServerUrlValueNotValid { + get { + return ResourceManager.GetString("ParseServerUrlValueNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The given primitive type '{0}' is not supported.. + /// + internal static string PrimitiveTypeNotSupported { + get { + return ResourceManager.GetString("PrimitiveTypeNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The reference string '{0}' has invalid format.. + /// + internal static string ReferenceHasInvalidFormat { + get { + return ResourceManager.GetString("ReferenceHasInvalidFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remote reference not supported.. + /// + internal static string RemoteReferenceNotSupported { + get { + return ResourceManager.GetString("RemoteReferenceNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The runtime expression '{0}' has invalid format.. + /// + internal static string RuntimeExpressionHasInvalidFormat { + get { + return ResourceManager.GetString("RuntimeExpressionHasInvalidFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The runtime expression '{0}' should start with '$'. + /// + internal static string RuntimeExpressionMustBeginWithDollar { + get { + return ResourceManager.GetString("RuntimeExpressionMustBeginWithDollar", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Scope must be present to end.. + /// + internal static string ScopeMustBePresentToEnd { + get { + return ResourceManager.GetString("ScopeMustBePresentToEnd", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The scope to end is expected to be of type '{0}' but it is of type '{0}'.. + /// + internal static string ScopeToEndHasIncorrectType { + get { + return ResourceManager.GetString("ScopeToEndHasIncorrectType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The source expression '{0}' has invalid format.. + /// + internal static string SourceExpressionHasInvalidFormat { + get { + return ResourceManager.GetString("SourceExpressionHasInvalidFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can not find visitor type registered for type '{0}'.. + /// + internal static string UnknownVisitorType { + get { + return ResourceManager.GetString("UnknownVisitorType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The key '{0}' in '{1}' of components MUST match the regular expression '{2}'.. + /// + internal static string Validation_ComponentsKeyMustMatchRegularExpr { + get { + return ResourceManager.GetString("Validation_ComponentsKeyMustMatchRegularExpr", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The extension name '{0}' in '{1}' object MUST begin with 'x-'.. + /// + internal static string Validation_ExtensionNameMustBeginWithXDash { + get { + return ResourceManager.GetString("Validation_ExtensionNameMustBeginWithXDash", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The field '{0}' in '{1}' object is REQUIRED.. + /// + internal static string Validation_FieldIsRequired { + get { + return ResourceManager.GetString("Validation_FieldIsRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The path item name '{0}' MUST begin with a slash.. + /// + internal static string Validation_PathItemMustBeginWithSlash { + get { + return ResourceManager.GetString("Validation_PathItemMustBeginWithSlash", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The path signature '{0}' MUST be unique.. + /// + internal static string Validation_PathSignatureMustBeUnique { + get { + return ResourceManager.GetString("Validation_PathSignatureMustBeUnique", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The same rule cannot be in the same rule set twice.. + /// + internal static string Validation_RuleAddTwice { + get { + return ResourceManager.GetString("Validation_RuleAddTwice", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Schema {0} must contain property specified in the discriminator {1} in the required field list.. + /// + internal static string Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator { + get { + return ResourceManager.GetString("Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminat" + + "or", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The string '{0}' MUST be in the format of an email address.. + /// + internal static string Validation_StringMustBeEmailAddress { + get { + return ResourceManager.GetString("Validation_StringMustBeEmailAddress", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to OpenAPI document must be added to an OpenApiWorkspace to be able to resolve external references.. + /// + internal static string WorkspaceRequredForExternalReferenceResolution { + get { + return ResourceManager.GetString("WorkspaceRequredForExternalReferenceResolution", resourceCulture); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Properties/SRResource.resx b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Properties/SRResource.resx new file mode 100644 index 000000000000..0effa1d4440f --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Properties/SRResource.resx @@ -0,0 +1,234 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + There must be an active scope for name '{0}' to be written. + + + The argument '{0}' is null, empty or consists only of white-space. + + + http://localhost/ + + + The filed name '{0}' of extension doesn't begin with x-. + + + Indentation level cannot be lower than 0. + + + The input item should be in type of '{0}'. + + + Invalid Reference identifier '{0}'. + + + Invalid Reference Type '{0}'. + + + Local reference must have type specified. + + + The active scope must be an object scope for property name '{0}' to be written. + + + An error occurred while processing the Open API document. + + + The given OpenAPI format '{0}' is not supported. + + + The object element name '{0}' is required. + + + The OpenApi element '{0}' is already marked as reference object. + + + If the parameter location is "path", this property is REQUIRED and its value MUST be true + + + The given OpenAPI specification version '{0}' is not supported. + + + The type '{0}' is not supported in Open API document. + + + An error occurred while writing the Open API document. + + + The given primitive type '{0}' is not supported. + + + The reference string '{0}' has invalid format. + + + Remote reference not supported. + + + The runtime expression '{0}' has invalid format. + + + The runtime expression '{0}' should start with '$' + + + Scope must be present to end. + + + The scope to end is expected to be of type '{0}' but it is of type '{0}'. + + + The source expression '{0}' has invalid format. + + + Can not find visitor type registered for type '{0}'. + + + The key '{0}' in '{1}' of components MUST match the regular expression '{2}'. + + + The extension name '{0}' in '{1}' object MUST begin with 'x-'. + + + The field '{0}' in '{1}' object is REQUIRED. + + + The path item name '{0}' MUST begin with a slash. + + + The path signature '{0}' MUST be unique. + + + The same rule cannot be in the same rule set twice. + + + Schema {0} must contain property specified in the discriminator {1} in the required field list. + + + The string '{0}' MUST be in the format of an email address. + + + OpenAPI document must be added to an OpenApiWorkspace to be able to resolve external references. + + + Invalid server variable '{0}'. A value was not provided and no default value was provided. + + + Value '{0}' is not a valid value for variable '{1}'. If an enum is provided, it should not be empty and the value provided should exist in the enum + + diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/LoopDetector.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/LoopDetector.cs new file mode 100644 index 000000000000..2e680a986479 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/LoopDetector.cs @@ -0,0 +1,72 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +using System; +using System.Collections.Generic; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Services +{ + internal class LoopDetector + { + private readonly Dictionary> _loopStacks = new(); + + /// + /// Maintain history of traversals to avoid stack overflows from cycles + /// + /// Identifier used for current context. + /// If method returns false a loop was detected and the key is not added. + public bool PushLoop(T key) + { + if (!_loopStacks.TryGetValue(typeof(T), out var stack)) + { + stack = new(); + _loopStacks.Add(typeof(T), stack); + } + + if (!stack.Contains(key)) + { + stack.Push(key); + return true; + } + else + { + return false; // Loop detected + } + } + + /// + /// Exit from the context in cycle detection + /// + public void PopLoop() + { + if (_loopStacks[typeof(T)].Count > 0) + { + _loopStacks[typeof(T)].Pop(); + } + } + + public void SaveLoop(T loop) + { + if (!Loops.ContainsKey(typeof(T))) + { + Loops[typeof(T)] = new(); + } + Loops[typeof(T)].Add(loop); + } + + /// + /// List of Loops detected + /// + public Dictionary> Loops { get; } = new(); + + /// + /// Reset loop tracking stack + /// + internal void ClearLoop() + { + _loopStacks[typeof(T)].Clear(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiReferenceError.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiReferenceError.cs new file mode 100644 index 000000000000..af4d8a261bc0 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiReferenceError.cs @@ -0,0 +1,37 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Services +{ + /// + /// + /// + internal class OpenApiReferenceError : OpenApiError + { + private OpenApiReference _reference; + /// + /// Initializes the class using the message and pointer from the given exception. + /// + public OpenApiReferenceError(OpenApiException exception) : base(exception.Pointer, exception.Message) + { + } + + /// + /// + /// + /// + /// + public OpenApiReferenceError(OpenApiReference reference, string message) : base("", message) + { + _reference = reference; + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs new file mode 100644 index 000000000000..5992db7f0950 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -0,0 +1,318 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Services +{ + /// + /// This class is used to walk an OpenApiDocument and convert unresolved references to references to populated objects + /// + internal class OpenApiReferenceResolver : OpenApiVisitorBase + { + private OpenApiDocument _currentDocument; + private readonly bool _resolveRemoteReferences; + private List _errors = new(); + + /// + /// Initializes the class. + /// + public OpenApiReferenceResolver(OpenApiDocument currentDocument, bool resolveRemoteReferences = true) + { + _currentDocument = currentDocument; + _resolveRemoteReferences = resolveRemoteReferences; + } + + /// + /// List of errors related to the OpenApiDocument + /// + public IEnumerable Errors => _errors; + + /// + /// Resolves tags in OpenApiDocument + /// + /// + public override void Visit(OpenApiDocument doc) + { + if (doc.Tags != null) + { + ResolveTags(doc.Tags); + } + } + + /// + /// Visits the referenceable element in the host document + /// + /// The referenceable element in the doc. + public override void Visit(IOpenApiReferenceable referenceable) + { + if (referenceable.Reference != null) + { + referenceable.Reference.HostDocument = _currentDocument; + } + } + + /// + /// Resolves references in components + /// + /// + public override void Visit(OpenApiComponents components) + { + ResolveMap(components.Parameters); + ResolveMap(components.RequestBodies); + ResolveMap(components.Responses); + ResolveMap(components.Links); + ResolveMap(components.Callbacks); + ResolveMap(components.Examples); + ResolveMap(components.Schemas); + ResolveMap(components.SecuritySchemes); + ResolveMap(components.Headers); + } + + /// + /// Resolves all references used in callbacks + /// + /// + public override void Visit(IDictionary callbacks) + { + ResolveMap(callbacks); + } + + /// + /// Resolve all references used in an operation + /// + public override void Visit(OpenApiOperation operation) + { + ResolveObject(operation.RequestBody, r => operation.RequestBody = r); + ResolveList(operation.Parameters); + + if (operation.Tags != null) + { + ResolveTags(operation.Tags); + } + } + + /// + /// Resolve all references using in mediaType object + /// + /// + public override void Visit(OpenApiMediaType mediaType) + { + ResolveObject(mediaType.Schema, r => mediaType.Schema = r); + } + + /// + /// Resolve all references to examples + /// + /// + public override void Visit(IDictionary examples) + { + ResolveMap(examples); + } + + /// + /// Resolve all references to responses + /// + public override void Visit(OpenApiResponses responses) + { + ResolveMap(responses); + } + + /// + /// Resolve all references to headers + /// + /// + public override void Visit(IDictionary headers) + { + ResolveMap(headers); + } + + /// + /// Resolve all references to SecuritySchemes + /// + public override void Visit(OpenApiSecurityRequirement securityRequirement) + { + foreach (var scheme in securityRequirement.Keys.ToList()) + { + ResolveObject(scheme, (resolvedScheme) => + { + if (resolvedScheme != null) + { + // If scheme was unresolved + // copy Scopes and remove old unresolved scheme + var scopes = securityRequirement[scheme]; + securityRequirement.Remove(scheme); + securityRequirement.Add(resolvedScheme, scopes); + } + }); + } + } + + /// + /// Resolve all references to parameters + /// + public override void Visit(IList parameters) + { + ResolveList(parameters); + } + + /// + /// Resolve all references used in a parameter + /// + public override void Visit(OpenApiParameter parameter) + { + ResolveObject(parameter.Schema, r => parameter.Schema = r); + ResolveMap(parameter.Examples); + } + + /// + /// Resolve all references to links + /// + public override void Visit(IDictionary links) + { + ResolveMap(links); + } + + /// + /// Resolve all references used in a schema + /// + public override void Visit(OpenApiSchema schema) + { + ResolveObject(schema.Items, r => schema.Items = r); + ResolveList(schema.OneOf); + ResolveList(schema.AllOf); + ResolveList(schema.AnyOf); + ResolveMap(schema.Properties); + ResolveObject(schema.AdditionalProperties, r => schema.AdditionalProperties = r); + } + + /// + /// Replace references to tags with either tag objects declared in components, or inline tag object + /// + private void ResolveTags(IList tags) + { + for (var i = 0; i < tags.Count; i++) + { + var tag = tags[i]; + if (IsUnresolvedReference(tag)) + { + var resolvedTag = ResolveReference(tag.Reference); + + if (resolvedTag == null) + { + resolvedTag = new() + { + Name = tag.Reference.Id + }; + } + tags[i] = resolvedTag; + } + } + } + + private void ResolveObject(T entity, Action assign) where T : class, IOpenApiReferenceable, new() + { + if (entity == null) return; + + if (IsUnresolvedReference(entity)) + { + assign(ResolveReference(entity.Reference)); + } + } + + private void ResolveList(IList list) where T : class, IOpenApiReferenceable, new() + { + if (list == null) return; + + for (var i = 0; i < list.Count; i++) + { + var entity = list[i]; + if (IsUnresolvedReference(entity)) + { + list[i] = ResolveReference(entity.Reference); + } + } + } + + private void ResolveMap(IDictionary map) where T : class, IOpenApiReferenceable, new() + { + if (map == null) return; + + foreach (var key in map.Keys.ToList()) + { + var entity = map[key]; + if (IsUnresolvedReference(entity)) + { + map[key] = ResolveReference(entity.Reference); + } + } + } + + private T ResolveReference(OpenApiReference reference) where T : class, IOpenApiReferenceable, new() + { + if (string.IsNullOrEmpty(reference?.ExternalResource)) + { + try + { + var referencedObject = typeof(T).Name; + var referenceType = reference?.Type.ToString(); + if (referenceType is not null && !referencedObject.Contains(referenceType)) + { + throw new OpenApiException(string.Format(Properties.SRResource.InvalidReferenceType, referenceType)); + } + + return _currentDocument.ResolveReference(reference, false) as T; + } + catch (OpenApiException ex) + { + _errors.Add(new OpenApiReferenceError(ex)); + return null; + } + } + // The concept of merging references with their target at load time is going away in the next major version + // External references will not support this approach. + //else if (_resolveRemoteReferences == true) + //{ + // if (_currentDocument.Workspace == null) + // { + // _errors.Add(new OpenApiReferenceError(reference,"Cannot resolve external references for documents not in workspaces.")); + // // Leave as unresolved reference + // return new T() + // { + // UnresolvedReference = true, + // Reference = reference + // }; + // } + // var target = _currentDocument.Workspace.ResolveReference(reference); + + // // TODO: If it is a document fragment, then we should resolve it within the current context + + // return target as T; + //} + else + { + // Leave as unresolved reference + return new() + { + UnresolvedReference = true, + Reference = reference + }; + } + } + + private bool IsUnresolvedReference(IOpenApiReferenceable possibleReference) + { + return possibleReference is {UnresolvedReference: true}; + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs new file mode 100644 index 000000000000..5cd0d565c020 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs @@ -0,0 +1,347 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Services +{ + /// + /// Open API visitor base provides common logic for concrete visitors + /// + internal abstract class OpenApiVisitorBase + { + private readonly Stack _path = new(); + + /// + /// Properties available to identify context of where an object is within OpenAPI Document + /// + public CurrentKeys CurrentKeys { get; } = new(); + + /// + /// Allow Rule to indicate validation error occured at a deeper context level. + /// + /// Identifier for context + public virtual void Enter(string segment) + { + this._path.Push(segment); + } + + /// + /// Exit from path context level. Enter and Exit calls should be matched. + /// + public virtual void Exit() + { + this._path.Pop(); + } + + /// + /// Pointer to source of validation error in document + /// + public string PathString { get => "#/" + String.Join("/", _path.Reverse()); } + + /// + /// Visits + /// + public virtual void Visit(OpenApiDocument doc) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiInfo info) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiContact contact) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiLicense license) + { + } + + /// + /// Visits list of + /// + public virtual void Visit(IList servers) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiServer server) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiPaths paths) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiPathItem pathItem) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiServerVariable serverVariable) + { + } + + /// + /// Visits the operations. + /// + public virtual void Visit(IDictionary operations) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiOperation operation) + { + } + + /// + /// Visits list of + /// + public virtual void Visit(IList parameters) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiParameter parameter) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiRequestBody requestBody) + { + } + + /// + /// Visits headers. + /// + public virtual void Visit(IDictionary headers) + { + } + + /// + /// Visits callbacks. + /// + public virtual void Visit(IDictionary callbacks) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiResponse response) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiResponses response) + { + } + + /// + /// Visits media type content. + /// + public virtual void Visit(IDictionary content) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiMediaType mediaType) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiEncoding encoding) + { + } + + /// + /// Visits the examples. + /// + public virtual void Visit(IDictionary examples) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiComponents components) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiExternalDocs externalDocs) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiSchema schema) + { + } + + /// + /// Visits the links. + /// + public virtual void Visit(IDictionary links) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiLink link) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiCallback callback) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiTag tag) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiHeader tag) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiOAuthFlow openApiOAuthFlow) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiSecurityRequirement securityRequirement) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiSecurityScheme securityScheme) + { + } + + /// + /// Visits + /// + public virtual void Visit(OpenApiExample example) + { + } + + /// + /// Visits list of + /// + public virtual void Visit(IList openApiTags) + { + } + + /// + /// Visits list of + /// + public virtual void Visit(IList openApiSecurityRequirements) + { + } + + /// + /// Visits + /// + public virtual void Visit(IOpenApiExtensible openApiExtensible) + { + } + + /// + /// Visits + /// + public virtual void Visit(IOpenApiExtension openApiExtension) + { + } + + /// + /// Visits list of + /// + public virtual void Visit(IList example) + { + } + + /// + /// Visits a dictionary of server variables + /// + public virtual void Visit(IDictionary serverVariables) + { + } + + /// + /// Visits a dictionary of encodings + /// + /// + public virtual void Visit(IDictionary encodings) + { + } + + /// + /// Visits IOpenApiReferenceable instances that are references and not in components + /// + /// referenced object + public virtual void Visit(IOpenApiReferenceable referenceable) + { + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiWalker.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiWalker.cs new file mode 100644 index 000000000000..cda7648fd491 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -0,0 +1,1169 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Services +{ + /// + /// The walker to visit multiple Open API elements. + /// + internal class OpenApiWalker + { + private readonly OpenApiVisitorBase _visitor; + private readonly Stack _schemaLoop = new(); + private readonly Stack _pathItemLoop = new(); + + /// + /// Initializes the class. + /// + public OpenApiWalker(OpenApiVisitorBase visitor) + { + _visitor = visitor; + } + + /// + /// Visits list of and child objects + /// + /// OpenApiDocument to be walked + public void Walk(OpenApiDocument doc) + { + if (doc == null) + { + return; + } + + _schemaLoop.Clear(); + _pathItemLoop.Clear(); + + _visitor.Visit(doc); + + Walk(OpenApiConstants.Info, () => Walk(doc.Info)); + Walk(OpenApiConstants.Servers, () => Walk(doc.Servers)); + Walk(OpenApiConstants.Paths, () => Walk(doc.Paths)); + Walk(OpenApiConstants.Components, () => Walk(doc.Components)); + Walk(OpenApiConstants.Security, () => Walk(doc.SecurityRequirements)); + Walk(OpenApiConstants.ExternalDocs, () => Walk(doc.ExternalDocs)); + Walk(OpenApiConstants.Tags, () => Walk(doc.Tags)); + Walk(doc as IOpenApiExtensible); + } + + /// + /// Visits list of and child objects + /// + internal void Walk(IList tags) + { + if (tags == null) + { + return; + } + + _visitor.Visit(tags); + + // Visit tags + if (tags != null) + { + for (var i = 0; i < tags.Count; i++) + { + Walk(i.ToString(), () => Walk(tags[i])); + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiExternalDocs externalDocs) + { + if (externalDocs == null) + { + return; + } + + _visitor.Visit(externalDocs); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiComponents components) + { + if (components == null) + { + return; + } + + _visitor.Visit(components); + + if (components == null) + { + return; + } + + Walk(OpenApiConstants.Schemas, () => + { + if (components.Schemas != null) + { + foreach (var item in components.Schemas) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(OpenApiConstants.SecuritySchemes, () => + { + if (components.SecuritySchemes != null) + { + foreach (var item in components.SecuritySchemes) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(OpenApiConstants.Callbacks, () => + { + if (components.Callbacks != null) + { + foreach (var item in components.Callbacks) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(OpenApiConstants.Parameters, () => + { + if (components.Parameters != null) + { + foreach (var item in components.Parameters) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(OpenApiConstants.Examples, () => + { + if (components.Examples != null) + { + foreach (var item in components.Examples) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(OpenApiConstants.Headers, () => + { + if (components.Headers != null) + { + foreach (var item in components.Headers) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(OpenApiConstants.Links, () => + { + if (components.Links != null) + { + foreach (var item in components.Links) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(OpenApiConstants.RequestBodies, () => + { + if (components.RequestBodies != null) + { + foreach (var item in components.RequestBodies) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(OpenApiConstants.Responses, () => + { + if (components.Responses != null) + { + foreach (var item in components.Responses) + { + Walk(item.Key, () => Walk(item.Value, isComponent: true)); + } + } + }); + + Walk(components as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiPaths paths) + { + if (paths == null) + { + return; + } + + _visitor.Visit(paths); + + // Visit Paths + if (paths != null) + { + foreach (var pathItem in paths) + { + _visitor.CurrentKeys.Path = pathItem.Key; + Walk(pathItem.Key, () => Walk(pathItem.Value));// JSON Pointer uses ~1 as an escape character for / + _visitor.CurrentKeys.Path = null; + } + } + + } + + /// + /// Visits list of and child objects + /// + internal void Walk(IList servers) + { + if (servers == null) + { + return; + } + + _visitor.Visit(servers); + + // Visit Servers + if (servers != null) + { + for (var i = 0; i < servers.Count; i++) + { + Walk(i.ToString(), () => Walk(servers[i])); + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiInfo info) + { + if (info == null) + { + return; + } + + _visitor.Visit(info); + if (info != null) + { + Walk(OpenApiConstants.Contact, () => Walk(info.Contact)); + Walk(OpenApiConstants.License, () => Walk(info.License)); + } + Walk(info as IOpenApiExtensible); + } + + /// + /// Visits dictionary of extensions + /// + internal void Walk(IOpenApiExtensible openApiExtensible) + { + if (openApiExtensible == null) + { + return; + } + + _visitor.Visit(openApiExtensible); + + if (openApiExtensible.Extensions != null) + { + foreach (var item in openApiExtensible.Extensions) + { + _visitor.CurrentKeys.Extension = item.Key; + Walk(item.Key, () => Walk(item.Value)); + _visitor.CurrentKeys.Extension = null; + } + } + } + + /// + /// Visits + /// + internal void Walk(IOpenApiExtension extension) + { + if (extension == null) + { + return; + } + + _visitor.Visit(extension); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiLicense license) + { + if (license == null) + { + return; + } + + _visitor.Visit(license); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiContact contact) + { + if (contact == null) + { + return; + } + + _visitor.Visit(contact); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiCallback callback, bool isComponent = false) + { + if (callback == null || ProcessAsReference(callback, isComponent)) + { + return; + } + + _visitor.Visit(callback); + + if (callback != null) + { + foreach (var item in callback.PathItems) + { + _visitor.CurrentKeys.Callback = item.Key.ToString(); + var pathItem = item.Value; + Walk(item.Key.ToString(), () => Walk(pathItem)); + _visitor.CurrentKeys.Callback = null; + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiTag tag) + { + if (tag == null || ProcessAsReference(tag)) + { + return; + } + + _visitor.Visit(tag); + _visitor.Visit(tag.ExternalDocs); + _visitor.Visit(tag as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiServer server) + { + if (server == null) + { + return; + } + + _visitor.Visit(server); + Walk(OpenApiConstants.Variables, () => Walk(server.Variables)); + _visitor.Visit(server as IOpenApiExtensible); + } + + /// + /// Visits dictionary of + /// + internal void Walk(IDictionary serverVariables) + { + if (serverVariables == null) + { + return; + } + + _visitor.Visit(serverVariables); + + if (serverVariables != null) + { + foreach (var variable in serverVariables) + { + _visitor.CurrentKeys.ServerVariable = variable.Key; + Walk(variable.Key, () => Walk(variable.Value)); + _visitor.CurrentKeys.ServerVariable = null; + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiServerVariable serverVariable) + { + if (serverVariable == null) + { + return; + } + + _visitor.Visit(serverVariable); + _visitor.Visit(serverVariable as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiPathItem pathItem) + { + if (pathItem == null) + { + return; + } + + if (_pathItemLoop.Contains(pathItem)) + { + return; // Loop detected, this pathItem has already been walked. + } + else + { + _pathItemLoop.Push(pathItem); + } + + _visitor.Visit(pathItem); + + // The path may be a reference + if (pathItem != null && !ProcessAsReference(pathItem)) + { + Walk(OpenApiConstants.Parameters, () => Walk(pathItem.Parameters)); + Walk(pathItem.Operations); + } + _visitor.Visit(pathItem as IOpenApiExtensible); + + _pathItemLoop.Pop(); + } + + /// + /// Visits dictionary of + /// + internal void Walk(IDictionary operations) + { + if (operations == null) + { + return; + } + + _visitor.Visit(operations); + if (operations != null) + { + foreach (var operation in operations) + { + _visitor.CurrentKeys.Operation = operation.Key; + Walk(operation.Key.GetDisplayName(), () => Walk(operation.Value)); + _visitor.CurrentKeys.Operation = null; + } + } + } + + /// + /// Visits and child objects + /// + /// + internal void Walk(OpenApiOperation operation) + { + if (operation == null) + { + return; + } + + _visitor.Visit(operation); + + Walk(OpenApiConstants.Parameters, () => Walk(operation.Parameters)); + Walk(OpenApiConstants.RequestBody, () => Walk(operation.RequestBody)); + Walk(OpenApiConstants.Responses, () => Walk(operation.Responses)); + Walk(OpenApiConstants.Callbacks, () => Walk(operation.Callbacks)); + Walk(OpenApiConstants.Tags, () => Walk(operation.Tags)); + Walk(OpenApiConstants.Security, () => Walk(operation.Security)); + Walk(operation as IOpenApiExtensible); + } + + /// + /// Visits list of + /// + internal void Walk(IList securityRequirements) + { + if (securityRequirements == null) + { + return; + } + + _visitor.Visit(securityRequirements); + + if (securityRequirements != null) + { + for (var i = 0; i < securityRequirements.Count; i++) + { + Walk(i.ToString(), () => Walk(securityRequirements[i])); + } + } + } + + /// + /// Visits list of + /// + internal void Walk(IList parameters) + { + if (parameters == null) + { + return; + } + + _visitor.Visit(parameters); + + if (parameters != null) + { + for (var i = 0; i < parameters.Count; i++) + { + Walk(i.ToString(), () => Walk(parameters[i])); + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiParameter parameter, bool isComponent = false) + { + if (parameter == null || ProcessAsReference(parameter, isComponent)) + { + return; + } + + _visitor.Visit(parameter); + Walk(OpenApiConstants.Schema, () => Walk(parameter.Schema)); + Walk(OpenApiConstants.Content, () => Walk(parameter.Content)); + Walk(OpenApiConstants.Examples, () => Walk(parameter.Examples)); + + Walk(parameter as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiResponses responses) + { + if (responses == null) + { + return; + } + + _visitor.Visit(responses); + + if (responses != null) + { + foreach (var response in responses) + { + _visitor.CurrentKeys.Response = response.Key; + Walk(response.Key, () => Walk(response.Value)); + _visitor.CurrentKeys.Response = null; + } + } + Walk(responses as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiResponse response, bool isComponent = false) + { + if (response == null || ProcessAsReference(response, isComponent)) + { + return; + } + + _visitor.Visit(response); + Walk(OpenApiConstants.Content, () => Walk(response.Content)); + Walk(OpenApiConstants.Links, () => Walk(response.Links)); + Walk(OpenApiConstants.Headers, () => Walk(response.Headers)); + Walk(response as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiRequestBody requestBody, bool isComponent = false) + { + if (requestBody == null || ProcessAsReference(requestBody, isComponent)) + { + return; + } + + _visitor.Visit(requestBody); + + if (requestBody is {Content: not null}) + { + Walk(OpenApiConstants.Content, () => Walk(requestBody.Content)); + } + Walk(requestBody as IOpenApiExtensible); + } + + /// + /// Visits dictionary of + /// + internal void Walk(IDictionary headers) + { + if (headers == null) + { + return; + } + + _visitor.Visit(headers); + if (headers != null) + { + foreach (var header in headers) + { + _visitor.CurrentKeys.Header = header.Key; + Walk(header.Key, () => Walk(header.Value)); + _visitor.CurrentKeys.Header = null; + } + } + } + + /// + /// Visits dictionary of + /// + internal void Walk(IDictionary callbacks) + { + if (callbacks == null) + { + return; + } + + _visitor.Visit(callbacks); + if (callbacks != null) + { + foreach (var callback in callbacks) + { + _visitor.CurrentKeys.Callback = callback.Key; + Walk(callback.Key, () => Walk(callback.Value)); + _visitor.CurrentKeys.Callback = null; + } + } + } + + /// + /// Visits dictionary of + /// + internal void Walk(IDictionary content) + { + if (content == null) + { + return; + } + + _visitor.Visit(content); + if (content != null) + { + foreach (var mediaType in content) + { + _visitor.CurrentKeys.Content = mediaType.Key; + Walk(mediaType.Key, () => Walk(mediaType.Value)); + _visitor.CurrentKeys.Content = null; + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiMediaType mediaType) + { + if (mediaType == null) + { + return; + } + + _visitor.Visit(mediaType); + + Walk(OpenApiConstants.Example, () => Walk(mediaType.Examples)); + Walk(OpenApiConstants.Schema, () => Walk(mediaType.Schema)); + Walk(OpenApiConstants.Encoding, () => Walk(mediaType.Encoding)); + Walk(mediaType as IOpenApiExtensible); + } + + /// + /// Visits dictionary of + /// + internal void Walk(IDictionary encodings) + { + if (encodings == null) + { + return; + } + + _visitor.Visit(encodings); + + if (encodings != null) + { + foreach (var item in encodings) + { + _visitor.CurrentKeys.Encoding = item.Key; + Walk(item.Key, () => Walk(item.Value)); + _visitor.CurrentKeys.Encoding = null; + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiEncoding encoding) + { + if (encoding == null) + { + return; + } + + _visitor.Visit(encoding); + + if (encoding.Headers != null) + { + Walk(encoding.Headers); + } + Walk(encoding as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiSchema schema, bool isComponent = false) + { + if (schema == null || ProcessAsReference(schema, isComponent)) + { + return; + } + + if (_schemaLoop.Contains(schema)) + { + return; // Loop detected, this schema has already been walked. + } + else + { + _schemaLoop.Push(schema); + } + + _visitor.Visit(schema); + + if (schema.Items != null) + { + Walk("items", () => Walk(schema.Items)); + } + + if (schema.Not != null) + { + Walk("not", () => Walk(schema.Not)); + } + + if (schema.AllOf != null) + { + Walk("allOf", () => Walk(schema.AllOf)); + } + + if (schema.AnyOf != null) + { + Walk("anyOf", () => Walk(schema.AnyOf)); + } + + if (schema.OneOf != null) + { + Walk("oneOf", () => Walk(schema.OneOf)); + } + + if (schema.Properties != null) + { + Walk("properties", () => + { + foreach (var item in schema.Properties) + { + Walk(item.Key, () => Walk(item.Value)); + } + }); + } + + if (schema.AdditionalProperties != null) + { + Walk("additionalProperties", () => Walk(schema.AdditionalProperties)); + } + + Walk(OpenApiConstants.ExternalDocs, () => Walk(schema.ExternalDocs)); + + Walk(schema as IOpenApiExtensible); + + _schemaLoop.Pop(); + } + + /// + /// Visits dictionary of + /// + internal void Walk(IDictionary examples) + { + if (examples == null) + { + return; + } + + _visitor.Visit(examples); + + if (examples != null) + { + foreach (var example in examples) + { + _visitor.CurrentKeys.Example = example.Key; + Walk(example.Key, () => Walk(example.Value)); + _visitor.CurrentKeys.Example = null; + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(IOpenApiAny example) + { + if (example == null) + { + return; + } + + _visitor.Visit(example); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiExample example, bool isComponent = false) + { + if (example == null || ProcessAsReference(example, isComponent)) + { + return; + } + + _visitor.Visit(example); + Walk(example as IOpenApiExtensible); + } + + /// + /// Visits the list of and child objects + /// + internal void Walk(IList examples) + { + if (examples == null) + { + return; + } + + _visitor.Visit(examples); + + // Visit Examples + if (examples != null) + { + for (var i = 0; i < examples.Count; i++) + { + Walk(i.ToString(), () => Walk(examples[i])); + } + } + } + + /// + /// Visits a list of and child objects + /// + internal void Walk(IList schemas) + { + if (schemas == null) + { + return; + } + + // Visit Schemas + if (schemas != null) + { + for (var i = 0; i < schemas.Count; i++) + { + Walk(i.ToString(), () => Walk(schemas[i])); + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiOAuthFlows flows) + { + if (flows == null) + { + return; + } + _visitor.Visit(flows); + Walk(flows as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiOAuthFlow oAuthFlow) + { + if (oAuthFlow == null) + { + return; + } + + _visitor.Visit(oAuthFlow); + Walk(oAuthFlow as IOpenApiExtensible); + } + + /// + /// Visits dictionary of and child objects + /// + internal void Walk(IDictionary links) + { + if (links == null) + { + return; + } + + _visitor.Visit(links); + + if (links != null) + { + foreach (var item in links) + { + _visitor.CurrentKeys.Link = item.Key; + Walk(item.Key, () => Walk(item.Value)); + _visitor.CurrentKeys.Link = null; + } + } + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiLink link, bool isComponent = false) + { + if (link == null || ProcessAsReference(link, isComponent)) + { + return; + } + + _visitor.Visit(link); + Walk(OpenApiConstants.Server, () => Walk(link.Server)); + Walk(link as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiHeader header, bool isComponent = false) + { + if (header == null || ProcessAsReference(header, isComponent)) + { + return; + } + + _visitor.Visit(header); + Walk(OpenApiConstants.Content, () => Walk(header.Content)); + Walk(OpenApiConstants.Example, () => Walk(header.Example)); + Walk(OpenApiConstants.Examples, () => Walk(header.Examples)); + Walk(OpenApiConstants.Schema, () => Walk(header.Schema)); + Walk(header as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiSecurityRequirement securityRequirement) + { + if (securityRequirement == null) + { + return; + } + + _visitor.Visit(securityRequirement); + Walk(securityRequirement as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(OpenApiSecurityScheme securityScheme, bool isComponent = false) + { + if (securityScheme == null || ProcessAsReference(securityScheme, isComponent)) + { + return; + } + + _visitor.Visit(securityScheme); + Walk(securityScheme as IOpenApiExtensible); + } + + /// + /// Visits and child objects + /// + internal void Walk(IOpenApiReferenceable referenceable) + { + _visitor.Visit(referenceable); + } + + /// + /// Dispatcher method that enables using a single method to walk the model + /// starting from any + /// + internal void Walk(IOpenApiElement element) + { + if (element == null) + { + return; + } + + switch (element) + { + case OpenApiDocument e: Walk(e); break; + case OpenApiLicense e: Walk(e); break; + case OpenApiInfo e: Walk(e); break; + case OpenApiComponents e: Walk(e); break; + case OpenApiContact e: Walk(e); break; + case OpenApiCallback e: Walk(e); break; + case OpenApiEncoding e: Walk(e); break; + case OpenApiExample e: Walk(e); break; + case IDictionary e: Walk(e); break; + case OpenApiExternalDocs e: Walk(e); break; + case OpenApiHeader e: Walk(e); break; + case OpenApiLink e: Walk(e); break; + case IDictionary e: Walk(e); break; + case OpenApiMediaType e: Walk(e); break; + case OpenApiOAuthFlows e: Walk(e); break; + case OpenApiOAuthFlow e: Walk(e); break; + case OpenApiOperation e: Walk(e); break; + case OpenApiParameter e: Walk(e); break; + case OpenApiPaths e: Walk(e); break; + case OpenApiRequestBody e: Walk(e); break; + case OpenApiResponse e: Walk(e); break; + case OpenApiSchema e: Walk(e); break; + case OpenApiSecurityRequirement e: Walk(e); break; + case OpenApiSecurityScheme e: Walk(e); break; + case OpenApiServer e: Walk(e); break; + case OpenApiServerVariable e: Walk(e); break; + case OpenApiTag e: Walk(e); break; + case IList e: Walk(e); break; + case IOpenApiExtensible e: Walk(e); break; + case IOpenApiExtension e: Walk(e); break; + } + } + + /// + /// Adds a segment to the context path to enable pointing to the current location in the document + /// + /// An identifier for the context. + /// An action that walks objects within the context. + private void Walk(string context, Action walk) + { + _visitor.Enter(context.Replace("/", "~1")); + walk(); + _visitor.Exit(); + } + + /// + /// Identify if an element is just a reference to a component, or an actual component + /// + private bool ProcessAsReference(IOpenApiReferenceable referenceable, bool isComponent = false) + { + var isReference = referenceable.Reference != null && + (!isComponent || referenceable.UnresolvedReference); + if (isReference) + { + Walk(referenceable); + } + return isReference; + } + } + + /// + /// Object containing contextual information based on where the walker is currently referencing in an OpenApiDocument + /// + internal class CurrentKeys + { + /// + /// Current Path key + /// + public string Path { get; set; } + + /// + /// Current Operation Type + /// + public OperationType? Operation { get; set; } + + /// + /// Current Response Status Code + /// + public string Response { get; set; } + + /// + /// Current Content Media Type + /// + public string Content { get; set; } + + /// + /// Current Callback Key + /// + public string Callback { get; set; } + + /// + /// Current Link Key + /// + public string Link { get; set; } + + /// + /// Current Header Key + /// + public string Header { get; internal set; } + + /// + /// Current Encoding Key + /// + public string Encoding { get; internal set; } + + /// + /// Current Example Key + /// + public string Example { get; internal set; } + + /// + /// Current Extension Key + /// + public string Extension { get; internal set; } + + /// + /// Current ServerVariable + /// + public string ServerVariable { get; internal set; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiWorkspace.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiWorkspace.cs new file mode 100644 index 000000000000..f705284657d4 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Services/OpenApiWorkspace.cs @@ -0,0 +1,152 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.IO; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Extensions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Services +{ + /// + /// Contains a set of OpenApi documents and document fragments that reference each other + /// + internal class OpenApiWorkspace + { + private Dictionary _documents = new(); + private Dictionary _fragments = new(); + private Dictionary _artifacts = new(); + + /// + /// A list of OpenApiDocuments contained in the workspace + /// + public IEnumerable Documents { + get { + return _documents.Values; + } + } + + /// + /// A list of document fragments that are contained in the workspace + /// + public IEnumerable Fragments { get; } + + /// + /// The base location from where all relative references are resolved + /// + public Uri BaseUrl { get; } + + /// + /// A list of document fragments that are contained in the workspace + /// + public IEnumerable Artifacts { get; } + + /// + /// Initialize workspace pointing to a base URL to allow resolving relative document locations. Use a file:// url to point to a folder + /// + /// + public OpenApiWorkspace(Uri baseUrl) + { + BaseUrl = baseUrl; + } + + /// + /// Initialize workspace using current directory as the default location. + /// + public OpenApiWorkspace() + { + BaseUrl = new("file://" + Environment.CurrentDirectory + $"{Path.DirectorySeparatorChar}" ); + } + + /// + /// Initializes a copy of an object + /// + public OpenApiWorkspace(OpenApiWorkspace workspace){} + + /// + /// Verify if workspace contains a document based on its URL. + /// + /// A relative or absolute URL of the file. Use file:// for folder locations. + /// Returns true if a matching document is found. + public bool Contains(string location) + { + var key = ToLocationUrl(location); + return _documents.ContainsKey(key) || _fragments.ContainsKey(key) || _artifacts.ContainsKey(key); + } + + /// + /// Add an OpenApiDocument to the workspace. + /// + /// + /// + public void AddDocument(string location, OpenApiDocument document) + { + document.Workspace = this; + _documents.Add(ToLocationUrl(location), document); + } + + /// + /// Adds a fragment of an OpenApiDocument to the workspace. + /// + /// + /// + /// Not sure how this is going to work. Does the reference just point to the fragment as a whole, or do we need to + /// to be able to point into the fragment. Keeping it private until we figure it out. + /// + public void AddFragment(string location, IOpenApiReferenceable fragment) + { + _fragments.Add(ToLocationUrl(location), fragment); + } + + /// + /// Add a stream based artifact to the workspace. Useful for images, examples, alternative schemas. + /// + /// + /// + public void AddArtifact(string location, Stream artifact) + { + _artifacts.Add(ToLocationUrl(location), artifact); + } + + /// + /// Returns the target of an OpenApiReference from within the workspace. + /// + /// An instance of an OpenApiReference + /// + public IOpenApiReferenceable ResolveReference(OpenApiReference reference) + { + if (_documents.TryGetValue(new(BaseUrl, reference.ExternalResource), out var doc)) + { + return doc.ResolveReference(reference, false); + } + else if (_fragments.TryGetValue(new(BaseUrl, reference.ExternalResource), out var fragment)) + { + var jsonPointer = new JsonPointer($"/{reference.Id ?? string.Empty}"); + return fragment.ResolveReference(jsonPointer); + } + return null; + } + + /// + /// + /// + /// + /// + public Stream GetArtifact(string location) + { + return _artifacts[ToLocationUrl(location)]; + } + + private Uri ToLocationUrl(string location) + { + return new(BaseUrl, location); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Utils.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Utils.cs new file mode 100644 index 000000000000..3ac8526ecbb9 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Utils.cs @@ -0,0 +1,46 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Runtime.CompilerServices; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi +{ + /// + /// Utilities methods + /// + internal static class Utils + { + /// + /// Check whether the input argument value is null or not. + /// + /// The input value type. + /// The input value. + /// The input parameter name. + /// The input value. + internal static T CheckArgumentNull( + T value, + [CallerArgumentExpression("value")] string parameterName = "") + { + return value ?? throw new ArgumentNullException(parameterName, $"Value cannot be null: {parameterName}"); + } + + /// + /// Check whether the input string value is null or empty. + /// + /// The input string value. + /// The input parameter name. + /// The input value. + internal static string CheckArgumentNullOrEmpty( + string value, + [CallerArgumentExpression(nameof(value))] string parameterName = "") + { + return string.IsNullOrWhiteSpace(value) ? throw new ArgumentNullException(parameterName, $"Value cannot be null or empty: {parameterName}") : value; + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/IOpenApiWriter.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/IOpenApiWriter.cs new file mode 100644 index 000000000000..92a33ac18987 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/IOpenApiWriter.cs @@ -0,0 +1,81 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Interface for writing Open API documentation. + /// + internal interface IOpenApiWriter + { + /// + /// Write the start object. + /// + void WriteStartObject(); + + /// + /// Write the end object. + /// + void WriteEndObject(); + + /// + /// Write the start array. + /// + void WriteStartArray(); + + /// + /// Write the end array. + /// + void WriteEndArray(); + + /// + /// Write the property name. + /// + void WritePropertyName(string name); + + /// + /// Write the string value. + /// + void WriteValue(string value); + + /// + /// Write the decimal value. + /// + void WriteValue(decimal value); + + /// + /// Write the int value. + /// + void WriteValue(int value); + + /// + /// Write the boolean value. + /// + void WriteValue(bool value); + + /// + /// Write the null value. + /// + void WriteNull(); + + /// + /// Write the raw content value. + /// + void WriteRaw(string value); + + /// + /// Write the object value. + /// + void WriteValue(object value); + + /// + /// Flush the writer. + /// + void Flush(); + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs new file mode 100644 index 000000000000..04fa73af75cd --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs @@ -0,0 +1,272 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.IO; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// JSON Writer. + /// + internal class OpenApiJsonWriter : OpenApiWriterBase + { + /// + /// Initializes a new instance of the class. + /// + /// The text writer. + public OpenApiJsonWriter(TextWriter textWriter) : base(textWriter, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The text writer. + /// Settings for controlling how the OpenAPI document will be written out. + public OpenApiJsonWriter(TextWriter textWriter, OpenApiJsonWriterSettings settings) : base(textWriter, settings) + { + _produceTerseOutput = settings.Terse; + } + + /// + /// Initializes a new instance of the class. + /// + /// The text writer. + /// Settings for controlling how the OpenAPI document will be written out. + /// Setting for allowing the JSON emitted to be in terse format. + public OpenApiJsonWriter(TextWriter textWriter, OpenApiWriterSettings settings, bool terseOutput = false) : base(textWriter, settings) + { + _produceTerseOutput = terseOutput; + } + + /// + /// Indicates whether or not the produced document will be written in a compact or pretty fashion. + /// + private readonly bool _produceTerseOutput; + + /// + /// Base Indentation Level. + /// This denotes how many indentations are needed for the property in the base object. + /// + protected override int BaseIndentation => 1; + + /// + /// Write JSON start object. + /// + public override void WriteStartObject() + { + var previousScope = CurrentScope(); + + var currentScope = StartScope(ScopeType.Object); + + if (previousScope is {Type: ScopeType.Array}) + { + currentScope.IsInArray = true; + + if (previousScope.ObjectCount != 1) + { + Writer.Write(WriterConstants.ArrayElementSeparator); + } + + WriteLine(); + WriteIndentation(); + } + + Writer.Write(WriterConstants.StartObjectScope); + + IncreaseIndentation(); + } + + /// + /// Write JSON end object. + /// + public override void WriteEndObject() + { + var currentScope = EndScope(ScopeType.Object); + if (currentScope.ObjectCount != 0) + { + WriteLine(); + DecreaseIndentation(); + WriteIndentation(); + } + else + { + if (!_produceTerseOutput) + { + Writer.Write(WriterConstants.WhiteSpaceForEmptyObject); + } + DecreaseIndentation(); + } + + Writer.Write(WriterConstants.EndObjectScope); + } + + /// + /// Write JSON start array. + /// + public override void WriteStartArray() + { + var previousScope = CurrentScope(); + + var currentScope = StartScope(ScopeType.Array); + + if (previousScope is {Type: ScopeType.Array}) + { + currentScope.IsInArray = true; + + if (previousScope.ObjectCount != 1) + { + Writer.Write(WriterConstants.ArrayElementSeparator); + } + + WriteLine(); + WriteIndentation(); + } + + Writer.Write(WriterConstants.StartArrayScope); + IncreaseIndentation(); + } + + /// + /// Write JSON end array. + /// + public override void WriteEndArray() + { + var current = EndScope(ScopeType.Array); + if (current.ObjectCount != 0) + { + WriteLine(); + DecreaseIndentation(); + WriteIndentation(); + } + else + { + Writer.Write(WriterConstants.WhiteSpaceForEmptyArray); + DecreaseIndentation(); + } + + Writer.Write(WriterConstants.EndArrayScope); + } + + /// + /// Write property name. + /// + /// The property name. + /// public override void WritePropertyName(string name) + public override void WritePropertyName(string name) + { + VerifyCanWritePropertyName(name); + + var currentScope = CurrentScope(); + if (currentScope.ObjectCount != 0) + { + Writer.Write(WriterConstants.ObjectMemberSeparator); + } + + WriteLine(); + + currentScope.ObjectCount++; + + WriteIndentation(); + + name = name.GetJsonCompatibleString(); + + Writer.Write(name); + + Writer.Write(WriterConstants.NameValueSeparator); + + if (!_produceTerseOutput) + { + Writer.Write(WriterConstants.NameValueSeparatorWhiteSpaceSuffix); + } + } + + /// + /// Write string value. + /// + /// The string value. + public override void WriteValue(string value) + { + WriteValueSeparator(); + + value = value.GetJsonCompatibleString(); + + Writer.Write(value); + } + + /// + /// Write null value. + /// + public override void WriteNull() + { + WriteValueSeparator(); + + Writer.Write("null"); + } + + /// + /// Writes a separator of a value if it's needed for the next value to be written. + /// + protected override void WriteValueSeparator() + { + if (Scopes.Count == 0) + { + return; + } + + var currentScope = Scopes.Peek(); + + if (currentScope.Type == ScopeType.Array) + { + if (currentScope.ObjectCount != 0) + { + Writer.Write(WriterConstants.ArrayElementSeparator); + } + + WriteLine(); + WriteIndentation(); + currentScope.ObjectCount++; + } + } + + /// + /// Writes the content raw value. + /// + public override void WriteRaw(string value) + { + WriteValueSeparator(); + Writer.Write(value); + } + + /// + /// Write the indentation. + /// + public override void WriteIndentation() + { + if (_produceTerseOutput) + { + return; + } + + base.WriteIndentation(); + } + + /// + /// Writes a line terminator to the text string or stream. + /// + private void WriteLine() + { + if (_produceTerseOutput) + { + return; + } + + Writer.WriteLine(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiJsonWriterSettings.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiJsonWriterSettings.cs new file mode 100644 index 000000000000..8173ef4fe448 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiJsonWriterSettings.cs @@ -0,0 +1,24 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Configuration settings to control how OpenAPI Json documents are written + /// + internal class OpenApiJsonWriterSettings : OpenApiWriterSettings + { + /// + /// Initializes a new instance of the class. + /// + public OpenApiJsonWriterSettings() + { } + + /// + /// Indicates whether or not the produced document will be written in a compact or pretty fashion. + /// + public bool Terse { get; set; } = false; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs new file mode 100644 index 000000000000..d1f8d7abde13 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs @@ -0,0 +1,110 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Any; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Extensions methods for writing the + /// + internal static class OpenApiWriterAnyExtensions + { + /// + /// Write the specification extensions + /// + /// The Open API writer. + /// The specification extensions. + /// Version of the OpenAPI specification that that will be output. + public static void WriteExtensions(this IOpenApiWriter writer, IDictionary extensions, OpenApiSpecVersion specVersion) + { + Utils.CheckArgumentNull(writer); + + if (extensions != null) + { + foreach (var item in extensions) + { + writer.WritePropertyName(item.Key); + item.Value.Write(writer, specVersion); + } + } + } + + /// + /// Write the value. + /// + /// The Open API Any type. + /// The Open API writer. + /// The Any value + public static void WriteAny(this IOpenApiWriter writer, T any) where T : IOpenApiAny + { + Utils.CheckArgumentNull(writer); + + if (any == null) + { + writer.WriteNull(); + return; + } + + switch (any.AnyType) + { + case AnyType.Array: // Array + writer.WriteArray(any as OpenApiArray); + break; + + case AnyType.Object: // Object + writer.WriteObject(any as OpenApiObject); + break; + + case AnyType.Primitive: // Primitive + writer.WritePrimitive(any as IOpenApiPrimitive); + break; + + case AnyType.Null: // null + writer.WriteNull(); + break; + + default: + break; + } + } + + private static void WriteArray(this IOpenApiWriter writer, OpenApiArray array) + { + writer.WriteStartArray(); + + foreach (var item in array) + { + writer.WriteAny(item); + } + + writer.WriteEndArray(); + } + + private static void WriteObject(this IOpenApiWriter writer, OpenApiObject entity) + { + writer.WriteStartObject(); + + foreach (var item in entity) + { + writer.WritePropertyName(item.Key); + writer.WriteAny(item.Value); + } + + writer.WriteEndObject(); + } + + private static void WritePrimitive(this IOpenApiWriter writer, IOpenApiPrimitive primitive) + { + // The Spec version is meaning for the Any type, so it's ok to use the latest one. + primitive.Write(writer, OpenApiSpecVersion.OpenApi3_0); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs new file mode 100644 index 000000000000..3d6c1a528633 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs @@ -0,0 +1,414 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.IO; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Exceptions; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Properties; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Base class for Open API writer. + /// + internal abstract class OpenApiWriterBase : IOpenApiWriter + { + /// + /// Settings for controlling how the OpenAPI document will be written out. + /// + public OpenApiWriterSettings Settings { get; set; } + + /// + /// The indentation string to prepend to each line for each indentation level. + /// + protected const string IndentationString = " "; + + /// + /// Scope of the Open API element - object, array, property. + /// + protected readonly Stack Scopes; + + /// + /// Number which specifies the level of indentation. + /// + private int _indentLevel; + + /// + /// Initializes a new instance of the class. + /// + /// The text writer. + public OpenApiWriterBase(TextWriter textWriter) : this(textWriter, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + public OpenApiWriterBase(TextWriter textWriter, OpenApiWriterSettings settings) + { + Writer = textWriter; + Writer.NewLine = "\n"; + + Scopes = new(); + if (settings == null) + { + settings = new(); + } + Settings = settings; + } + + /// + /// Base Indentation Level. + /// This denotes how many indentations are needed for the property in the base object. + /// + protected abstract int BaseIndentation { get; } + + /// + /// The text writer. + /// + protected TextWriter Writer { get; } + + /// + /// Write start object. + /// + public abstract void WriteStartObject(); + + /// + /// Write end object. + /// + public abstract void WriteEndObject(); + + /// + /// Write start array. + /// + public abstract void WriteStartArray(); + + /// + /// Write end array. + /// + public abstract void WriteEndArray(); + + /// + /// Write the start property. + /// + public abstract void WritePropertyName(string name); + + /// + /// Writes a separator of a value if it's needed for the next value to be written. + /// + protected abstract void WriteValueSeparator(); + + /// + /// Write null value. + /// + public abstract void WriteNull(); + + /// + /// Write content raw value. + /// + public abstract void WriteRaw(string value); + + /// + /// Flush the writer. + /// + public void Flush() + { + Writer.Flush(); + } + + /// + /// Write string value. + /// + /// The string value. + public abstract void WriteValue(string value); + + /// + /// Write float value. + /// + /// The float value. + public virtual void WriteValue(float value) + { + WriteValueSeparator(); + Writer.Write(value); + } + + /// + /// Write double value. + /// + /// The double value. + public virtual void WriteValue(double value) + { + WriteValueSeparator(); + Writer.Write(value); + } + + /// + /// Write decimal value. + /// + /// The decimal value. + public virtual void WriteValue(decimal value) + { + WriteValueSeparator(); + Writer.Write(value); + } + + /// + /// Write integer value. + /// + /// The integer value. + public virtual void WriteValue(int value) + { + WriteValueSeparator(); + Writer.Write(value); + } + + /// + /// Write long value. + /// + /// The long value. + public virtual void WriteValue(long value) + { + WriteValueSeparator(); + Writer.Write(value); + } + + /// + /// Write DateTime value. + /// + /// The DateTime value. + public virtual void WriteValue(DateTime value) + { + this.WriteValue(value.ToString("o")); + } + + /// + /// Write DateTimeOffset value. + /// + /// The DateTimeOffset value. + public virtual void WriteValue(DateTimeOffset value) + { + this.WriteValue(value.ToString("o")); + } + + /// + /// Write boolean value. + /// + /// The boolean value. + public virtual void WriteValue(bool value) + { + WriteValueSeparator(); + Writer.Write(value.ToString().ToLower()); + } + + /// + /// Write object value. + /// + /// The object value. + public virtual void WriteValue(object value) + { + if (value == null) + { + WriteNull(); + return; + } + + var type = value.GetType(); + + if (type == typeof(string)) + { + WriteValue((string)(value)); + } + else if (type == typeof(int) || type == typeof(int?)) + { + WriteValue((int)value); + } + else if (type == typeof(long) || type == typeof(long?)) + { + WriteValue((long)value); + } + else if (type == typeof(bool) || type == typeof(bool?)) + { + WriteValue((bool)value); + } + else if (type == typeof(float) || type == typeof(float?)) + { + WriteValue((float)value); + } + else if (type == typeof(double) || type == typeof(double?)) + { + WriteValue((double)value); + } + else if (type == typeof(decimal) || type == typeof(decimal?)) + { + WriteValue((decimal)value); + } + else if (type == typeof(DateTime) || type == typeof(DateTime?)) + { + WriteValue((DateTime)value); + } + else if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?)) + { + WriteValue((DateTimeOffset)value); + } + else + { + throw new OpenApiWriterException(string.Format(SRResource.OpenApiUnsupportedValueType, type.FullName)); + } + } + + /// + /// Increases the level of indentation applied to the output. + /// + public virtual void IncreaseIndentation() + { + _indentLevel++; + } + + /// + /// Decreases the level of indentation applied to the output. + /// + public virtual void DecreaseIndentation() + { + if (_indentLevel == 0) + { + throw new OpenApiWriterException(SRResource.IndentationLevelInvalid); + } + + if (_indentLevel < 1) + { + _indentLevel = 0; + } + else + { + _indentLevel--; + } + } + + /// + /// Write the indentation. + /// + public virtual void WriteIndentation() + { + for (var i = 0; i < (BaseIndentation + _indentLevel - 1); i++) + { + Writer.Write(IndentationString); + } + } + + /// + /// Get current scope. + /// + /// + protected Scope CurrentScope() + { + return Scopes.Count == 0 ? null : Scopes.Peek(); + } + + /// + /// Start the scope given the scope type. + /// + /// The scope type to start. + protected Scope StartScope(ScopeType type) + { + if (Scopes.Count != 0) + { + var currentScope = Scopes.Peek(); + + currentScope.ObjectCount++; + } + + var scope = new Scope(type); + Scopes.Push(scope); + return scope; + } + + /// + /// End the scope of the given scope type. + /// + /// + /// + protected Scope EndScope(ScopeType type) + { + if (Scopes.Count == 0) + { + throw new OpenApiWriterException(SRResource.ScopeMustBePresentToEnd); + } + + if (Scopes.Peek().Type != type) + { + throw new OpenApiWriterException( + string.Format( + SRResource.ScopeToEndHasIncorrectType, + type, + Scopes.Peek().Type)); + } + + return Scopes.Pop(); + } + + /// + /// Whether the current scope is the top level (outermost) scope. + /// + protected bool IsTopLevelScope() + { + return Scopes.Count == 1; + } + + /// + /// Whether the current scope is an object scope. + /// + protected bool IsObjectScope() + { + return IsScopeType(ScopeType.Object); + } + + /// + /// Whether the current scope is an array scope. + /// + /// + protected bool IsArrayScope() + { + return IsScopeType(ScopeType.Array); + } + + private bool IsScopeType(ScopeType type) + { + if (Scopes.Count == 0) + { + return false; + } + + return Scopes.Peek().Type == type; + } + + /// + /// Verifies whether a property name can be written based on whether + /// the property name is a valid string and whether the current scope is an object scope. + /// + /// property name + protected void VerifyCanWritePropertyName(string name) + { + Utils.CheckArgumentNull(name); + + if (Scopes.Count == 0) + { + throw new OpenApiWriterException( + string.Format(SRResource.ActiveScopeNeededForPropertyNameWriting, name)); + } + + if (Scopes.Peek().Type != ScopeType.Object) + { + throw new OpenApiWriterException( + string.Format(SRResource.ObjectScopeNeededForPropertyNameWriting, name)); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs new file mode 100644 index 000000000000..e2acb840603e --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs @@ -0,0 +1,408 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Interfaces; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Extension methods for writing Open API documentation. + /// + internal static class OpenApiWriterExtensions + { + /// + /// Write a string property. + /// + /// The writer. + /// The property name. + /// The property value. + public static void WriteProperty(this IOpenApiWriter writer, string name, string value) + { + if (value == null) + { + return; + } + + Utils.CheckArgumentNullOrEmpty(name); + writer.WritePropertyName(name); + writer.WriteValue(value); + } + + /// + /// Write required string property. + /// + /// The writer. + /// The property name. + /// The property value. + public static void WriteRequiredProperty(this IOpenApiWriter writer, string name, string value) + { + Utils.CheckArgumentNullOrEmpty(name); + writer.WritePropertyName(name); + if (value == null) + { + writer.WriteNull(); + } + else + { + writer.WriteValue(value); + } + } + + /// + /// Write a boolean property. + /// + /// The writer. + /// The property name. + /// The property value. + /// The default boolean value. + public static void WriteProperty(this IOpenApiWriter writer, string name, bool value, bool defaultValue = false) + { + if (value == defaultValue) + { + return; + } + + Utils.CheckArgumentNullOrEmpty(name); + writer.WritePropertyName(name); + writer.WriteValue(value); + } + + /// + /// Write a boolean property. + /// + /// The writer. + /// The property name. + /// The property value. + /// The default boolean value. + public static void WriteProperty( + this IOpenApiWriter writer, + string name, + bool? value, + bool defaultValue = false) + { + if (value == null || value.Value == defaultValue) + { + return; + } + + Utils.CheckArgumentNullOrEmpty(name); + writer.WritePropertyName(name); + writer.WriteValue(value.Value); + } + + /// + /// Write a primitive property. + /// + /// The writer. + /// The property name. + /// The property value. + public static void WriteProperty(this IOpenApiWriter writer, string name, T? value) + where T : struct + { + if (value == null) + { + return; + } + + writer.WriteProperty(name, value.Value); + } + + /// + /// Write a string/number property. + /// + /// The writer. + /// The property name. + /// The property value. + public static void WriteProperty(this IOpenApiWriter writer, string name, T value) + where T : struct + { + Utils.CheckArgumentNullOrEmpty(name); + writer.WritePropertyName(name); + writer.WriteValue(value); + } + + /// + /// Write the optional Open API object/element. + /// + /// The Open API element type. + /// The Open API writer. + /// The property name. + /// The property value. + /// The property value writer action. + public static void WriteOptionalObject( + this IOpenApiWriter writer, + string name, + T value, + Action action) + where T : IOpenApiElement + { + if (value != null) + { + if (value is IEnumerable values && !values.GetEnumerator().MoveNext()) + { + return; // Don't render optional empty collections + } + + writer.WriteRequiredObject(name, value, action); + } + } + + /// + /// Write the required Open API object/element. + /// + /// The Open API element type. + /// The Open API writer. + /// The property name. + /// The property value. + /// The property value writer action. + public static void WriteRequiredObject( + this IOpenApiWriter writer, + string name, + T value, + Action action) + where T : IOpenApiElement + { + Utils.CheckArgumentNull(action); + + writer.WritePropertyName(name); + if (value != null) + { + action(writer, value); + } + else + { + writer.WriteStartObject(); + writer.WriteEndObject(); + } + } + + /// + /// Write the optional of collection string. + /// + /// The Open API writer. + /// The property name. + /// The collection values. + /// The collection string writer action. + public static void WriteOptionalCollection( + this IOpenApiWriter writer, + string name, + IEnumerable elements, + Action action) + { + if (elements != null && elements.Any()) + { + writer.WriteCollectionInternal(name, elements, action); + } + } + + /// + /// Write the optional Open API object/element collection. + /// + /// The Open API element type. + /// The Open API writer. + /// The property name. + /// The collection values. + /// The collection element writer action. + public static void WriteOptionalCollection( + this IOpenApiWriter writer, + string name, + IEnumerable elements, + Action action) + where T : IOpenApiElement + { + if (elements != null && elements.Any()) + { + writer.WriteCollectionInternal(name, elements, action); + } + } + + /// + /// Write the required Open API object/element collection. + /// + /// The Open API element type. + /// The Open API writer. + /// The property name. + /// The collection values. + /// The collection element writer action. + public static void WriteRequiredCollection( + this IOpenApiWriter writer, + string name, + IEnumerable elements, + Action action) + where T : IOpenApiElement + { + writer.WriteCollectionInternal(name, elements, action); + } + + /// + /// Write the optional Open API element map (string to string mapping). + /// + /// The Open API writer. + /// The property name. + /// The map values. + /// The map element writer action. + public static void WriteOptionalMap( + this IOpenApiWriter writer, + string name, + IDictionary elements, + Action action) + { + if (elements != null && elements.Any()) + { + writer.WriteMapInternal(name, elements, action); + } + } + + /// + /// Write the required Open API element map (string to string mapping). + /// + /// The Open API writer. + /// The property name. + /// The map values. + /// The map element writer action. + public static void WriteRequiredMap( + this IOpenApiWriter writer, + string name, + IDictionary elements, + Action action) + { + writer.WriteMapInternal(name, elements, action); + } + + /// + /// Write the optional Open API element map. + /// + /// The Open API element type. + /// The Open API writer. + /// The property name. + /// The map values. + /// The map element writer action with writer and value as input. + public static void WriteOptionalMap( + this IOpenApiWriter writer, + string name, + IDictionary elements, + Action action) + where T : IOpenApiElement + { + if (elements != null && elements.Any()) + { + writer.WriteMapInternal(name, elements, action); + } + } + + /// + /// Write the optional Open API element map. + /// + /// The Open API element type. + /// The Open API writer. + /// The property name. + /// The map values. + /// The map element writer action with writer, key, and value as input. + public static void WriteOptionalMap( + this IOpenApiWriter writer, + string name, + IDictionary elements, + Action action) + where T : IOpenApiElement + { + if (elements != null && elements.Any()) + { + writer.WriteMapInternal(name, elements, action); + } + } + + /// + /// Write the required Open API element map. + /// + /// The Open API element type. + /// The Open API writer. + /// The property name. + /// The map values. + /// The map element writer action. + public static void WriteRequiredMap( + this IOpenApiWriter writer, + string name, + IDictionary elements, + Action action) + where T : IOpenApiElement + { + writer.WriteMapInternal(name, elements, action); + } + + private static void WriteCollectionInternal( + this IOpenApiWriter writer, + string name, + IEnumerable elements, + Action action) + { + Utils.CheckArgumentNull(action); + + writer.WritePropertyName(name); + writer.WriteStartArray(); + if (elements != null) + { + foreach (var item in elements) + { + if (item != null) + { + action(writer, item); + } + else + { + writer.WriteNull(); + } + } + } + + writer.WriteEndArray(); + } + + private static void WriteMapInternal( + this IOpenApiWriter writer, + string name, + IDictionary elements, + Action action) + { + WriteMapInternal(writer, name, elements, (w, _, s) => action(w, s)); + } + + private static void WriteMapInternal( + this IOpenApiWriter writer, + string name, + IDictionary elements, + Action action) + { + Utils.CheckArgumentNull(action); + + writer.WritePropertyName(name); + writer.WriteStartObject(); + + if (elements != null) + { + foreach (var item in elements) + { + writer.WritePropertyName(item.Key); + if (item.Value != null) + { + action(writer, item.Key, item.Value); + } + else + { + writer.WriteNull(); + } + } + } + + writer.WriteEndObject(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs new file mode 100644 index 000000000000..f1976b7df818 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs @@ -0,0 +1,83 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 + +using System; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Models; +using Datadog.Trace.Vendors.Microsoft.OpenApi.Services; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Indicates if and when the writer should convert references into complete object renderings + /// + [Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] + internal enum ReferenceInlineSetting + { + /// + /// Render all references as $ref. + /// + DoNotInlineReferences, + /// + /// Render all local references as inline objects + /// + InlineLocalReferences, + /// + /// Render all references as inline objects. + /// + InlineAllReferences + } + + /// + /// Configuration settings to control how OpenAPI documents are written + /// + internal class OpenApiWriterSettings + { + [Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] + private ReferenceInlineSetting referenceInline = ReferenceInlineSetting.DoNotInlineReferences; + + internal LoopDetector LoopDetector { get; } = new(); + /// + /// Indicates how references in the source document should be handled. + /// + [Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] + public ReferenceInlineSetting ReferenceInline { + get { return referenceInline; } + set { + referenceInline = value; + switch(referenceInline) + { + case ReferenceInlineSetting.DoNotInlineReferences: + InlineLocalReferences = false; + InlineExternalReferences = false; + break; + case ReferenceInlineSetting.InlineLocalReferences: + InlineLocalReferences = true; + InlineExternalReferences = false; + break; + case ReferenceInlineSetting.InlineAllReferences: + InlineLocalReferences = true; + InlineExternalReferences = true; + break; + } + } + } + /// + /// Indicates if local references should be rendered as an inline object + /// + public bool InlineLocalReferences { get; set; } + + /// + /// Indicates if external references should be rendered as an inline object + /// + public bool InlineExternalReferences { get; set; } + + internal bool ShouldInlineReference(OpenApiReference reference) + { + return (reference.IsLocal && InlineLocalReferences) + || (reference.IsExternal && InlineExternalReferences); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/Scope.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/Scope.cs new file mode 100644 index 000000000000..4ec136b1698a --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/Scope.cs @@ -0,0 +1,61 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Various scope types for Open API writer. + /// + internal enum ScopeType + { + /// + /// Object scope. + /// + Object = 0, + + /// + /// Array scope. + /// + Array = 1, + } + + /// + /// Class representing scope information. + /// + internal sealed class Scope + { + /// + /// The type of the scope. + /// + private readonly ScopeType _type; + + /// + /// Constructor. + /// + /// The type of the scope. + public Scope(ScopeType type) + { + this._type = type; + } + + /// + /// Get/Set the object count for this scope. + /// + public int ObjectCount { get; set; } + + /// + /// Gets the scope type for this scope. + /// + public ScopeType Type { get => _type; } + + /// + /// Get/Set the whether it is in previous array scope. + /// + public bool IsInArray { get; set; } = false; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs new file mode 100644 index 000000000000..04f4a8c96ade --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs @@ -0,0 +1,210 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Extensions class for strings to handle special characters. + /// + internal static class SpecialCharacterStringExtensions + { + // Plain style strings cannot start with indicators. + // http://www.yaml.org/spec/1.2/spec.html#indicator// + private static readonly HashSet _yamlIndicators = new() + { + "-", + "?", + ":", + ",", + "{", + "}", + "[", + "]", + "&", + "*", + "#", + "?", + "|", + "-", + ">", + "!", + "%", + "@", + "`", + "'", + "\"" + }; + + // Plain style strings cannot contain these character combinations. + // http://www.yaml.org/spec/1.2/spec.html#style/flow/plain + private static readonly HashSet _yamlPlainStringForbiddenCombinations = new() + { + ": ", + " #", + + // These are technically forbidden only inside flow collections, but + // for the sake of simplicity, we will never allow them in our generated plain string. + "[", + "]", + "{", + "}", + "," + }; + + // Plain style strings cannot end with these characters. + // http://www.yaml.org/spec/1.2/spec.html#style/flow/plain + private static readonly HashSet _yamlPlainStringForbiddenTerminals = new() + { + ":" + }; + + // Double-quoted strings are needed for these non-printable control characters. + // http://www.yaml.org/spec/1.2/spec.html#style/flow/double-quoted + private static readonly Dictionary _yamlControlCharacterCharReplacements = new() + { + {'\0', "\\0"}, + {'\x01', "\\x01"}, + {'\x02', "\\x02"}, + {'\x03', "\\x03"}, + {'\x04', "\\x04"}, + {'\x05', "\\x05"}, + {'\x06', "\\x06"}, + {'\a', "\\a"}, + {'\b', "\\b"}, + {'\t', "\\t"}, + {'\n', "\\n"}, + {'\v', "\\v"}, + {'\f', "\\f"}, + {'\r', "\\r"}, + {'\x0e', "\\x0e"}, + {'\x0f', "\\x0f"}, + {'\x10', "\\x10"}, + {'\x11', "\\x11"}, + {'\x12', "\\x12"}, + {'\x13', "\\x13"}, + {'\x14', "\\x14"}, + {'\x15', "\\x15"}, + {'\x16', "\\x16"}, + {'\x17', "\\x17"}, + {'\x18', "\\x18"}, + {'\x19', "\\x19"}, + {'\x1a', "\\x1a"}, + {'\x1b', "\\x1b"}, + {'\x1c', "\\x1c"}, + {'\x1d', "\\x1d"}, + {'\x1e', "\\x1e"}, + {'\x1f', "\\x1f"}, + }; + + private static readonly Dictionary _yamlControlCharacterStringReplacements = _yamlControlCharacterCharReplacements + .ToDictionary(x => x.Key.ToString(), x => x.Value); + + /// + /// Escapes all special characters and put the string in quotes if necessary to + /// get a YAML-compatible string. + /// + internal static string GetYamlCompatibleString(this string input) + { + switch (input) + { + // If string is an empty string, wrap it in quote to ensure it is not recognized as null. + case "": + return "''"; + // If string is the word null, wrap it in quote to ensure it is not recognized as empty scalar null. + case "null": + return "'null'"; + // If string is the letter ~, wrap it in quote to ensure it is not recognized as empty scalar null. + case "~": + return "'~'"; + } + + // If string includes a control character, wrapping in double quote is required. + if (input.Any(c => _yamlControlCharacterCharReplacements.ContainsKey(c))) + { + // Replace the backslash first, so that the new backslashes created by other Replaces are not duplicated. + input = input.Replace("\\", "\\\\"); + + // Escape the double quotes. + input = input.Replace("\"", "\\\""); + + // Escape all the control characters. + foreach (var replacement in _yamlControlCharacterStringReplacements) + { + input = input.Replace(replacement.Key, replacement.Value); + } + + return $"\"{input}\""; + } + + // If string + // 1) includes a character forbidden in plain string, + // 2) starts with an indicator, OR + // 3) has trailing/leading white spaces, + // wrap the string in single quote. + // http://www.yaml.org/spec/1.2/spec.html#style/flow/plain + if (_yamlPlainStringForbiddenCombinations.Any(fc => input.Contains(fc)) || + _yamlIndicators.Any(i => input.StartsWith(i)) || + _yamlPlainStringForbiddenTerminals.Any(i => input.EndsWith(i)) || + input.Trim() != input) + { + // Escape single quotes with two single quotes. + input = input.Replace("'", "''"); + + return $"'{input}'"; + } + + // If string can be mistaken as a number, c-style hexadecimal notation, a boolean, or a timestamp, + // wrap it in quote to indicate that this is indeed a string, not a number, c-style hexadecimal notation, a boolean, or a timestamp + if (decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out _) || + IsHexadecimalNotation(input) || + bool.TryParse(input, out _) || + DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) + { + return $"'{input}'"; + } + + return input; + } + + /// + /// Handles control characters and backslashes and adds double quotes + /// to get JSON-compatible string. + /// + internal static string GetJsonCompatibleString(this string value) + { + if (value == null) + { + return "null"; + } + + // Show the control characters as strings + // http://json.org/ + + // Replace the backslash first, so that the new backslashes created by other Replaces are not duplicated. + value = value.Replace("\\", "\\\\") + .Replace("\b", "\\b") + .Replace("\f", "\\f") + .Replace("\n", "\\n") + .Replace("\r", "\\r") + .Replace("\t", "\\t") + .Replace("\"", "\\\""); + + return $"\"{value}\""; + } + + internal static bool IsHexadecimalNotation(string input) + { + return input.StartsWith("0x") && int.TryParse(input.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _); + } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/WriterConstants.cs b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/WriterConstants.cs new file mode 100644 index 000000000000..2de7896d1410 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/Writers/WriterConstants.cs @@ -0,0 +1,129 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendoredCode tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, CS1591, CS1573, CS8018, SYSLIB0011, SYSLIB0023, SYSLIB0032 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +namespace Datadog.Trace.Vendors.Microsoft.OpenApi.Writers +{ + /// + /// Constants for the writer. + /// + internal static class WriterConstants + { + /// + /// JSON datetime format. + /// + internal const string ODataDateTimeFormat = @"\/Date({0})\/"; + + /// + /// JSON datetime offset format. + /// + internal const string ODataDateTimeOffsetFormat = @"\/Date({0}{1}{2:D4})\/"; + + /// + /// A plus sign for the date time offset format. + /// + internal const string ODataDateTimeOffsetPlusSign = "+"; + + /// + /// The true value literal. + /// + internal const string JsonTrueLiteral = "true"; + + /// + /// The false value literal. + /// + internal const string JsonFalseLiteral = "false"; + + /// + /// The null value literal. + /// + internal const string JsonNullLiteral = "null"; + + /// + /// Character which starts the object scope. + /// + internal const string StartObjectScope = "{"; + + /// + /// Character which ends the object scope. + /// + internal const string EndObjectScope = "}"; + + /// + /// Character which starts the array scope. + /// + internal const string StartArrayScope = "["; + + /// + /// Character which ends the array scope. + /// + internal const string EndArrayScope = "]"; + + /// + /// "(" Json Padding Function scope open parens. + /// + internal const string StartPaddingFunctionScope = "("; + + /// + /// ")" Json Padding Function scope close parens. + /// + internal const string EndPaddingFunctionScope = ")"; + + /// + /// The separator between object members. + /// + internal const string ObjectMemberSeparator = ","; + + /// + /// The separator between array elements. + /// + internal const string ArrayElementSeparator = ","; + + /// + /// The separator between the name and the value. + /// + internal const string NameValueSeparator = ":"; + + /// + /// The white space postfixing + /// when producing pretty content. + /// + internal const string NameValueSeparatorWhiteSpaceSuffix = " "; + + /// + /// The white space for empty object + /// + internal const string WhiteSpaceForEmptyObject = " "; + + /// + /// The white space for empty array + /// + internal const string WhiteSpaceForEmptyArray = " "; + + /// + /// The prefix of array item + /// + internal const string PrefixOfArrayItem = "- "; + + /// + /// The white space for indent + /// + internal const string WhiteSpaceForIndent = " "; + + /// + /// Empty object + /// + /// To indicate empty object in YAML. + internal const string EmptyObject = "{ }"; + + /// + /// Empty array + /// + /// To indicate empty array in YAML. + internal const string EmptyArray = "[ ]"; + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/_last_downloaded_source_url.txt b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/_last_downloaded_source_url.txt new file mode 100644 index 000000000000..b0d3ba897ed2 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Microsoft.OpenApi/_last_downloaded_source_url.txt @@ -0,0 +1 @@ +https://github.com/microsoft/OpenAPI.NET/archive/1.6.23.zip \ No newline at end of file