From 980282a0138f94ba7ca37e98569a6c4df482521c Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 12 Nov 2026 12:30:25 -0500 Subject: [PATCH] feat(http-client-csharp): preserve shared LRO metadata Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../dotnet-shared-lro-metadata-2026-11-12.md | 7 ++ .../emitter/src/lib/operation-converter.ts | 58 ++++++++++- .../emitter/src/lib/type-converter.ts | 9 +- .../emitter/src/type/input-service-method.ts | 31 +++++- .../test/Unit/operation-converter.test.ts | 85 ++++++++++++++++ .../InputLongRunningServiceMetadata.cs | 15 +++ .../InputTypes/InputLroOperationIdMetadata.cs | 10 ++ .../InputLroOperationIdPathMetadata.cs | 20 ++++ .../InputLroOperationIdPropertyMetadata.cs | 19 ++++ .../src/InputTypes/InputLroStatusMetadata.cs | 24 +++++ .../src/InputTypes/InputOperationLink.cs | 17 ++++ ...nputLongRunningServiceMetadataConverter.cs | 11 ++- .../InputLroOperationIdMetadataConverter.cs | 56 +++++++++++ .../InputLroStatusMetadataConverter.cs | 40 ++++++++ .../InputOperationLinkConverter.cs | 39 ++++++++ .../Serialization/TypeSpecSerialization.cs | 3 + .../test/TypeSpecInputConverterTests.cs | 96 +++++++++++++++++++ 17 files changed, 530 insertions(+), 10 deletions(-) create mode 100644 .chronus/changes/dotnet-shared-lro-metadata-2026-11-12.md create mode 100644 packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdMetadata.cs create mode 100644 packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPathMetadata.cs create mode 100644 packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPropertyMetadata.cs create mode 100644 packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroStatusMetadata.cs create mode 100644 packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputOperationLink.cs create mode 100644 packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroOperationIdMetadataConverter.cs create mode 100644 packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroStatusMetadataConverter.cs create mode 100644 packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputOperationLinkConverter.cs diff --git a/.chronus/changes/dotnet-shared-lro-metadata-2026-11-12.md b/.chronus/changes/dotnet-shared-lro-metadata-2026-11-12.md new file mode 100644 index 00000000000..931ed137101 --- /dev/null +++ b/.chronus/changes/dotnet-shared-lro-metadata-2026-11-12.md @@ -0,0 +1,7 @@ +--- +changeKind: internal +packages: + - "@typespec/http-client-csharp" +--- + +Preserve TCGC `@lroStatusMetadata` selections, typed `propertySegments`, and ordered `@lroOperationId` sources in the shared .NET input model for Azure generator consumption. Existing generated clients remain unchanged when this metadata is absent. diff --git a/packages/http-client-csharp/emitter/src/lib/operation-converter.ts b/packages/http-client-csharp/emitter/src/lib/operation-converter.ts index 4ecca8158a9..cf935c6635c 100644 --- a/packages/http-client-csharp/emitter/src/lib/operation-converter.ts +++ b/packages/http-client-csharp/emitter/src/lib/operation-converter.ts @@ -41,6 +41,7 @@ import { } from "@typespec/compiler"; import { unsafe_getEventDefinitions } from "@typespec/events/experimental"; import type { HttpStatusCodeRange } from "@typespec/http"; +import { getHeaderFieldName } from "@typespec/http"; import { isTerminalEvent } from "@typespec/sse"; import type { CSharpEmitterContext } from "../sdk-context.js"; import { collectionFormatToDelimMap } from "../type/collection-format.js"; @@ -54,6 +55,7 @@ import type { InputLongRunningPagingServiceMethod, InputLongRunningServiceMetadata, InputLongRunningServiceMethod, + InputLroOperationIdMetadata, InputNextLink, InputPagingServiceMetadata, InputPagingServiceMethod, @@ -79,7 +81,7 @@ import { getExternalDocs } from "./decorators.js"; import { fromSdkHttpExamples } from "./example-converter.js"; import { getExperimentalDetails } from "./experimental.js"; import { createDiagnostic } from "./lib.js"; -import { fromSdkType } from "./type-converter.js"; +import { fromSdkModelProperty, fromSdkType } from "./type-converter.js"; import { getClientNamespaceString, isReadOnly } from "./utils.js"; export function fromSdkServiceMethod( @@ -726,6 +728,58 @@ function loadLongRunningMetadata( ): [InputLongRunningServiceMetadata, readonly Diagnostic[]] { const diagnostics = createDiagnosticCollector(); + const metadata = method.lroMetadata; + const statusMetadata = metadata.statusMetadata?.length + ? metadata.statusMetadata.map((entry) => ({ + property: diagnostics.pipe(fromSdkModelProperty(sdkContext, entry.property)), + propertySegments: entry.propertySegments.map((property) => + diagnostics.pipe(fromSdkModelProperty(sdkContext, property)), + ), + })) + : undefined; + const operationId = metadata.operationId?.length + ? metadata.operationId.map((entry): InputLroOperationIdMetadata => { + if (entry.kind === "property") { + return { + kind: "property", + property: diagnostics.pipe(fromSdkModelProperty(sdkContext, entry.property)), + propertySegments: entry.propertySegments.map((property) => + diagnostics.pipe(fromSdkModelProperty(sdkContext, property)), + ), + }; + } + const step = metadata.statusMonitorStep; + const operation = + step?.kind === "nextOperationReference" ? step.target.operation : step?.operation; + compilerAssert(operation, "An LRO operation ID path requires a linked polling operation."); + const parameter = diagnostics.pipe( + fromParameter(sdkContext, entry.pathParameter, method.apiVersions), + ); + compilerAssert( + parameter?.kind === "path", + "An LRO operation ID requires a path parameter.", + ); + const sourceProperty = diagnostics.pipe( + fromSdkModelProperty(sdkContext, entry.source.property), + ); + if (entry.source.location === "ResponseHeader" && entry.source.property.__raw) { + sourceProperty.serializedName = getHeaderFieldName( + sdkContext.program, + entry.source.property.__raw, + ); + } + return { + kind: "path", + source: { + location: entry.source.location, + property: sourceProperty, + }, + pathParameter: parameter, + path: operation.path, + }; + }) + : undefined; + return diagnostics.wrap({ finalStateVia: convertLroFinalStateVia(method.lroMetadata.finalStateVia), finalResponse: { @@ -740,6 +794,8 @@ function loadLongRunningMetadata( : undefined, } as OperationResponse, resultPath: method.lroMetadata.finalResultPath, + statusMetadata, + operationId, }); } diff --git a/packages/http-client-csharp/emitter/src/lib/type-converter.ts b/packages/http-client-csharp/emitter/src/lib/type-converter.ts index 22fdaac29fd..96cdc9c1a73 100644 --- a/packages/http-client-csharp/emitter/src/lib/type-converter.ts +++ b/packages/http-client-csharp/emitter/src/lib/type-converter.ts @@ -286,13 +286,12 @@ function fromSdkModelType( return diagnostics.wrap(inputModelType); } -function fromSdkModelProperty( +export function fromSdkModelProperty( sdkContext: CSharpEmitterContext, sdkProperty: SdkModelPropertyType, - sdkModel: SdkModelType, -): [InputModelProperty | undefined, readonly Diagnostic[]] { + sdkModel?: SdkModelType, +): [InputModelProperty, readonly Diagnostic[]] { const diagnostics = createDiagnosticCollector(); - // TODO -- this returns undefined because some properties we do not support yet. let property = sdkContext.__typeCache.properties.get(sdkProperty) as InputModelProperty | undefined; if (property) { @@ -316,7 +315,7 @@ function fromSdkModelProperty( ? getDeprecated(sdkContext.program, sdkProperty.__raw) : undefined, type: diagnostics.pipe( - fromSdkType(sdkContext, sdkProperty.type, sdkProperty, sdkModel.namespace), + fromSdkType(sdkContext, sdkProperty.type, sdkProperty, sdkModel?.namespace), ), optional: sdkProperty.optional, readOnly: isReadOnly(sdkProperty), diff --git a/packages/http-client-csharp/emitter/src/type/input-service-method.ts b/packages/http-client-csharp/emitter/src/type/input-service-method.ts index 26c49336197..d568bfeef48 100644 --- a/packages/http-client-csharp/emitter/src/type/input-service-method.ts +++ b/packages/http-client-csharp/emitter/src/type/input-service-method.ts @@ -2,7 +2,13 @@ // Licensed under the MIT License. See License.txt in the project root for license information. import type { InputOperation } from "./input-operation.js"; -import type { InputMethodParameter, InputParameter, InputType } from "./input-type.js"; +import type { + InputMethodParameter, + InputModelProperty, + InputParameter, + InputPathParameter, + InputType, +} from "./input-type.js"; import type { OperationFinalStateVia } from "./operation-final-state-via.js"; import type { OperationResponse } from "./operation-response.js"; import type { ResponseLocation } from "./response-location.js"; @@ -75,8 +81,31 @@ export interface InputLongRunningServiceMetadata { finalStateVia: OperationFinalStateVia; finalResponse: OperationResponse; resultPath?: string; + statusMetadata?: InputLroStatusMetadata[]; + operationId?: InputLroOperationIdMetadata[]; } +export interface InputLroStatusMetadata { + property: InputModelProperty; + propertySegments: InputModelProperty[]; +} + +export type InputLroOperationIdMetadata = + | { + kind: "path"; + source: { + location: "ResponseHeader" | "ResponseBody" | "Self"; + property: InputModelProperty; + }; + pathParameter: InputPathParameter; + path: string; + } + | { + kind: "property"; + property: InputModelProperty; + propertySegments: InputModelProperty[]; + }; + export interface InputLongRunningPagingServiceMethod extends InputServiceMethodBase { kind: "lropaging"; lroMetadata: InputLongRunningServiceMetadata; diff --git a/packages/http-client-csharp/emitter/test/Unit/operation-converter.test.ts b/packages/http-client-csharp/emitter/test/Unit/operation-converter.test.ts index 86f691376fd..307eb113a70 100644 --- a/packages/http-client-csharp/emitter/test/Unit/operation-converter.test.ts +++ b/packages/http-client-csharp/emitter/test/Unit/operation-converter.test.ts @@ -19,6 +19,91 @@ describe("Operation Converter", () => { runner = await createEmitterTestHost(); }); + it.each([true, false])("preserves selected LRO metadata: %s", async (selected) => { + const program = await typeSpecCompile( + ` + model Result { value: string; } + model Usage { tokens: int32; } + enum OperationState { Running, Succeeded, Failed, Canceled } + model MonitorBase { + ${selected ? '@lroStatusMetadata @clientName("usageDetails")' : ""} + @encodedName("application/json", "usage_details") + usage?: Usage; + } + model Monitor extends MonitorBase { + ${selected ? "@lroOperationId" : ""} + @encodedName("application/json", "operation_id") + id: string; + @lroStatus status: OperationState; + @lroResult result?: Result; + } + @get @route("/jobs/{jobId}") + op getStatus(${selected ? "@lroOperationId" : ""} @path jobId: string): Monitor; + @pollingOperation(getStatus) + @post @route("/jobs") + op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: url; + }; + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + strictEqual(program.diagnostics.filter((d) => d.severity === "error").length, 0); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const [root, diagnostics] = createModel(sdkContext); + deepStrictEqual(diagnostics, []); + const method = root.clients[0].methods.find((m) => m.name === "begin"); + ok(method?.kind === "lro"); + const metadata = method.lroMetadata; + const serialized = JSON.parse(serializeCodeModel(sdkContext, root)); + const serializedMetadata = serialized.clients[0].methods.find( + (m: { name: string }) => m.name === "begin", + ).lroMetadata; + if (!selected) { + strictEqual(serializedMetadata.statusMetadata, undefined); + strictEqual(serializedMetadata.operationId, undefined); + return; + } + + const base = root.models.find((m) => m.name === "MonitorBase")!; + const monitor = root.models.find((m) => m.name === "Monitor")!; + const usage = base.properties.find((p) => p.name === "usageDetails")!; + strictEqual(metadata.statusMetadata?.[0].property, usage); + deepStrictEqual(metadata.statusMetadata[0].propertySegments, [usage]); + strictEqual(usage.serializedName, "usage_details"); + strictEqual(usage.optional, true); + deepStrictEqual( + metadata.operationId?.map((id) => id.kind), + ["path", "property"], + ); + const path = metadata.operationId[0]; + ok(path.kind === "path"); + strictEqual(path.path, "/jobs/{jobId}"); + strictEqual(path.source.location, "ResponseHeader"); + strictEqual(path.source.property.serializedName, "Operation-Location"); + deepStrictEqual( + path.pathParameter, + root.clients[0].methods + .find((m) => m.name === "getStatus")! + .operation.parameters.find((p) => p.name === "jobId"), + ); + const body = metadata.operationId[1]; + ok(body.kind === "property"); + strictEqual( + body.property, + monitor.properties.find((p) => p.name === "id"), + ); + deepStrictEqual(body.propertySegments, [body.property]); + strictEqual(body.property.serializedName, "operation_id"); + ok(serializedMetadata.statusMetadata[0].property.$ref); + deepStrictEqual(serializedMetadata.statusMetadata[0].propertySegments, [ + serializedMetadata.statusMetadata[0].property, + ]); + ok(serializedMetadata.operationId[0].pathParameter.$id); + ok(serializedMetadata.operationId[1].property.$ref); + }); + it.each([undefined, "", 'Use "read" instead.\nSee C:\\sdk.'])( "preserves operation deprecation metadata: %s", async (message) => { diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLongRunningServiceMetadata.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLongRunningServiceMetadata.cs index 143bac7cb69..7b558e60493 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLongRunningServiceMetadata.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLongRunningServiceMetadata.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System.Collections.Generic; using System.Linq; namespace Microsoft.TypeSpec.Generator.Input @@ -8,10 +9,22 @@ namespace Microsoft.TypeSpec.Generator.Input public sealed class InputLongRunningServiceMetadata { public InputLongRunningServiceMetadata(int finalStateVia, InputOperationResponse finalResponse, string? resultPath) + : this(finalStateVia, finalResponse, resultPath, [], []) + { + } + + public InputLongRunningServiceMetadata( + int finalStateVia, + InputOperationResponse finalResponse, + string? resultPath, + IReadOnlyList statusMetadata, + IReadOnlyList operationId) { FinalStateVia = finalStateVia; FinalResponse = finalResponse; ResultPath = resultPath; + StatusMetadata = statusMetadata; + OperationId = operationId; } public InputLongRunningServiceMetadata() : this(1, new InputOperationResponse(), null) { } @@ -19,6 +32,8 @@ public InputLongRunningServiceMetadata(int finalStateVia, InputOperationResponse public int FinalStateVia { get; } public InputOperationResponse FinalResponse { get; } public string? ResultPath { get; } + public IReadOnlyList StatusMetadata { get; } + public IReadOnlyList OperationId { get; } /// /// Meaningful return type of the long running operation. diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdMetadata.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdMetadata.cs new file mode 100644 index 00000000000..7c51aa0fb4f --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdMetadata.cs @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Microsoft.TypeSpec.Generator.Input +{ + public abstract class InputLroOperationIdMetadata + { + private protected InputLroOperationIdMetadata() { } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPathMetadata.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPathMetadata.cs new file mode 100644 index 00000000000..043df1982fb --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPathMetadata.cs @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Microsoft.TypeSpec.Generator.Input +{ + public sealed class InputLroOperationIdPathMetadata : InputLroOperationIdMetadata + { + public InputLroOperationIdPathMetadata(InputOperationLink source, InputPathParameter pathParameter, string path) + { + Source = source; + PathParameter = pathParameter; + Path = path; + } + + public InputOperationLink Source { get; } + public InputPathParameter PathParameter { get; } + /// The linked polling operation's route template, not the polling URL received at runtime. + public string Path { get; } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPropertyMetadata.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPropertyMetadata.cs new file mode 100644 index 00000000000..4b27c482491 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPropertyMetadata.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace Microsoft.TypeSpec.Generator.Input +{ + public sealed class InputLroOperationIdPropertyMetadata : InputLroOperationIdMetadata + { + public InputLroOperationIdPropertyMetadata(InputModelProperty property, IReadOnlyList propertySegments) + { + Property = property; + PropertySegments = propertySegments; + } + + public InputModelProperty Property { get; } + public IReadOnlyList PropertySegments { get; } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroStatusMetadata.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroStatusMetadata.cs new file mode 100644 index 00000000000..b0aedc0dbb4 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroStatusMetadata.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace Microsoft.TypeSpec.Generator.Input +{ + /// + /// Auxiliary values selected from the latest received status-monitor response, including failed or canceled responses. + /// Values are not persisted in continuation tokens and may be absent until a response is received. + /// + public sealed class InputLroStatusMetadata + { + public InputLroStatusMetadata(InputModelProperty property, IReadOnlyList propertySegments) + { + Property = property; + PropertySegments = propertySegments; + } + + public InputModelProperty Property { get; } + /// Typed property path rooted at the status-monitor response model. + public IReadOnlyList PropertySegments { get; } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputOperationLink.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputOperationLink.cs new file mode 100644 index 00000000000..180a5a02b83 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputOperationLink.cs @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Microsoft.TypeSpec.Generator.Input +{ + public sealed class InputOperationLink + { + public InputOperationLink(string location, InputModelProperty property) + { + Location = location; + Property = property; + } + + public string Location { get; } + public InputModelProperty Property { get; } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLongRunningServiceMetadataConverter.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLongRunningServiceMetadataConverter.cs index 4c7d6bf9d36..cc0ae622905 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLongRunningServiceMetadataConverter.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLongRunningServiceMetadataConverter.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; @@ -29,19 +30,23 @@ private InputLongRunningServiceMetadata CreateOperationLongRunning(ref Utf8JsonR int finalStateVia = default; InputOperationResponse? finalResponse = null; string? resultPath = null; + IReadOnlyList? statusMetadata = null; + IReadOnlyList? operationId = null; while (reader.TokenType != JsonTokenType.EndObject) { var isKnownProperty = reader.TryReadInt32("finalStateVia", ref finalStateVia) || reader.TryReadComplexType("finalResponse", options, ref finalResponse) - || reader.TryReadString("resultPath", ref resultPath); + || reader.TryReadString("resultPath", ref resultPath) + || reader.TryReadComplexType("statusMetadata", options, ref statusMetadata) + || reader.TryReadComplexType("operationId", options, ref operationId); if (!isKnownProperty) { - continue; + reader.SkipProperty(); } } - var result = new InputLongRunningServiceMetadata(finalStateVia, finalResponse ?? new InputOperationResponse(), resultPath); + var result = new InputLongRunningServiceMetadata(finalStateVia, finalResponse ?? new InputOperationResponse(), resultPath, statusMetadata ?? [], operationId ?? []); return result; } diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroOperationIdMetadataConverter.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroOperationIdMetadataConverter.cs new file mode 100644 index 00000000000..46066e6b012 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroOperationIdMetadataConverter.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Microsoft.TypeSpec.Generator.Input +{ + internal sealed class InputLroOperationIdMetadataConverter : JsonConverter + { + public override InputLroOperationIdMetadata Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.StartObject) + { + reader.Read(); + } + + string? kind = null; + string? path = null; + InputOperationLink? source = null; + InputPathParameter? pathParameter = null; + InputModelProperty? property = null; + IReadOnlyList? propertySegments = null; + while (reader.TokenType != JsonTokenType.EndObject) + { + var isKnownProperty = reader.TryReadString("kind", ref kind) + || reader.TryReadString("path", ref path) + || reader.TryReadComplexType("source", options, ref source) + || reader.TryReadComplexType("pathParameter", options, ref pathParameter) + || reader.TryReadComplexType("property", options, ref property) + || reader.TryReadComplexType("propertySegments", options, ref propertySegments); + if (!isKnownProperty) + { + reader.SkipProperty(); + } + } + + return kind switch + { + "path" => new InputLroOperationIdPathMetadata( + source ?? throw new JsonException("LRO operation ID path must have a source."), + pathParameter ?? throw new JsonException("LRO operation ID path must have a path parameter."), + path ?? throw new JsonException("LRO operation ID path must have a polling path.")), + "property" => new InputLroOperationIdPropertyMetadata( + property ?? throw new JsonException("LRO operation ID must have a property."), + propertySegments is { Count: > 0 } ? propertySegments : throw new JsonException("LRO operation ID must have property segments.")), + _ => throw new JsonException($"Unknown LRO operation ID kind '{kind}'.") + }; + } + + public override void Write(Utf8JsonWriter writer, InputLroOperationIdMetadata value, JsonSerializerOptions options) + => throw new NotSupportedException("Writing not supported"); + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroStatusMetadataConverter.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroStatusMetadataConverter.cs new file mode 100644 index 00000000000..2aa2c38eb8d --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroStatusMetadataConverter.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Microsoft.TypeSpec.Generator.Input +{ + internal sealed class InputLroStatusMetadataConverter : JsonConverter + { + public override InputLroStatusMetadata Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.StartObject) + { + reader.Read(); + } + + InputModelProperty? property = null; + IReadOnlyList? propertySegments = null; + while (reader.TokenType != JsonTokenType.EndObject) + { + var isKnownProperty = reader.TryReadComplexType("property", options, ref property) + || reader.TryReadComplexType("propertySegments", options, ref propertySegments); + if (!isKnownProperty) + { + reader.SkipProperty(); + } + } + + return new InputLroStatusMetadata( + property ?? throw new JsonException("LRO status metadata must have a property."), + propertySegments is { Count: > 0 } ? propertySegments : throw new JsonException("LRO status metadata must have property segments.")); + } + + public override void Write(Utf8JsonWriter writer, InputLroStatusMetadata value, JsonSerializerOptions options) + => throw new NotSupportedException("Writing not supported"); + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputOperationLinkConverter.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputOperationLinkConverter.cs new file mode 100644 index 00000000000..2efe9916b5d --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputOperationLinkConverter.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Microsoft.TypeSpec.Generator.Input +{ + internal sealed class InputOperationLinkConverter : JsonConverter + { + public override InputOperationLink Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.StartObject) + { + reader.Read(); + } + + string? location = null; + InputModelProperty? property = null; + while (reader.TokenType != JsonTokenType.EndObject) + { + var isKnownProperty = reader.TryReadString("location", ref location) + || reader.TryReadComplexType("property", options, ref property); + if (!isKnownProperty) + { + reader.SkipProperty(); + } + } + + return new InputOperationLink( + location is "ResponseHeader" or "ResponseBody" or "Self" ? location : throw new JsonException("LRO operation link must have a valid location."), + property ?? throw new JsonException("LRO operation link must have a property.")); + } + + public override void Write(Utf8JsonWriter writer, InputOperationLink value, JsonSerializerOptions options) + => throw new NotSupportedException("Writing not supported"); + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/TypeSpecSerialization.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/TypeSpecSerialization.cs index 37ff8f1cf97..101f74f7772 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/TypeSpecSerialization.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/TypeSpecSerialization.cs @@ -63,6 +63,9 @@ public static class TypeSpecSerialization new InputPagingServiceMetadataConverter(), new InputLongRunningServiceMethodConverter(referenceHandler), new InputLongRunningServiceMetadataConverter(), + new InputLroStatusMetadataConverter(), + new InputLroOperationIdMetadataConverter(), + new InputOperationLinkConverter(), new InputLongRunningPagingServiceMethodConverter(referenceHandler), new InputServiceMethodResponseConverter(), new InputPropertyConverter(referenceHandler), diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TypeSpecInputConverterTests.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TypeSpecInputConverterTests.cs index 9d47ecca8ac..c8715d1d9a2 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TypeSpecInputConverterTests.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TypeSpecInputConverterTests.cs @@ -10,6 +10,102 @@ namespace Microsoft.TypeSpec.Generator.Input.Tests { public class TypeSpecInputConverterTests { + [TestCase(true)] + [TestCase(false)] + public void LoadsLongRunningMetadata(bool selected) + { + var json = $$""" + { + "finalStateVia": 1, + "resultPath": "result", + "futureProperty": { "nested": [1, 2] } + {{(selected ? """ + ,"statusMetadata": [{ + "property": { + "$id": "usage", "kind": "property", "name": "usageDetails", + "serializedName": "usage_details", "optional": true, + "type": { "$id": "string", "kind": "string", "name": "string" } + }, + "propertySegments": [{ "$ref": "usage" }] + }], + "operationId": [{ + "$id": "pathId", "kind": "path", "path": "/jobs/{jobId}", + "source": { + "location": "ResponseHeader", + "property": { + "$id": "link", "kind": "property", "name": "location", + "serializedName": "Operation-Location", "type": { "$ref": "string" } + } + }, + "pathParameter": { + "$id": "jobId", "kind": "path", "name": "jobId", "serializedName": "jobId", + "type": { "$ref": "string" }, "scope": "method" + } + }, { + "$id": "bodyId", "kind": "property", + "property": { "$ref": "usage" }, + "propertySegments": [{ "$ref": "usage" }] + }] + """ : "")}} + } + """; + var input = TypeSpecSerialization.Deserialize($$""" + { + "name": "Test", + "clients": [{ + "$id": "client", "name": "TestClient", + "methods": [{ + "$id": "method", "kind": "lro", "name": "begin", + "crossLanguageDefinitionId": "Test.begin", + "operation": { + "$id": "operation", "name": "begin", "httpMethod": "POST", + "crossLanguageDefinitionId": "Test.begin", + "uri": "https://example.com", "path": "/jobs" + }, + "response": {}, "lroMetadata": {{json}} + }] + }] + } + """)!; + var metadata = ((InputLongRunningServiceMethod)input.RootClients.Single().Methods.Single()).LongRunningServiceMetadata; + + Assert.AreEqual(1, metadata.FinalStateVia); + Assert.AreEqual("result", metadata.ResultPath); + if (!selected) + { + Assert.IsEmpty(metadata.StatusMetadata); + Assert.IsEmpty(metadata.OperationId); + return; + } + + var status = metadata.StatusMetadata.Single(); + Assert.AreSame(status.Property, status.PropertySegments.Single()); + Assert.AreEqual("usageDetails", status.Property.Name); + Assert.AreEqual("usage_details", status.Property.SerializedName); + Assert.IsFalse(status.Property.IsRequired); + Assert.AreEqual(2, metadata.OperationId.Count); + var path = (InputLroOperationIdPathMetadata)metadata.OperationId[0]; + Assert.AreEqual("/jobs/{jobId}", path.Path); + Assert.AreEqual("ResponseHeader", path.Source.Location); + Assert.AreEqual("Operation-Location", path.Source.Property.SerializedName); + Assert.AreEqual("jobId", path.PathParameter.SerializedName); + var body = (InputLroOperationIdPropertyMetadata)metadata.OperationId[1]; + Assert.AreSame(status.Property, body.Property); + Assert.AreSame(body.Property, body.PropertySegments.Single()); + } + + [TestCase("""{"kind":"future"}""")] + [TestCase("""{"kind":"property","propertySegments":[]}""")] + [TestCase("""{"kind":"path","path":"/jobs/{id}"}""")] + public void RejectsInvalidLongRunningOperationId(string json) + { + var options = new JsonSerializerOptions + { + Converters = { new InputLroOperationIdMetadataConverter() } + }; + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + [Test] public void LoadsContinuationTokenMarker( [Values("query", "header", "path", "body", "method", "endpoint")] string kind,