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..c3988774801 100644 --- a/packages/http-client-csharp/emitter/src/lib/operation-converter.ts +++ b/packages/http-client-csharp/emitter/src/lib/operation-converter.ts @@ -30,6 +30,8 @@ import { isHttpMetadata, shouldGenerateConvenient, shouldGenerateProtocol, + updateUsageOrAccess, + UsageFlags, } from "@azure-tools/typespec-client-generator-core"; import type { Diagnostic, Union } from "@typespec/compiler"; import { @@ -54,6 +56,7 @@ import type { InputLongRunningPagingServiceMethod, InputLongRunningServiceMetadata, InputLongRunningServiceMethod, + InputLroStatusMetadata, InputNextLink, InputPagingServiceMetadata, InputPagingServiceMethod, @@ -65,6 +68,8 @@ import type { InputHeaderParameter, InputHttpParameter, InputMethodParameter, + InputModelProperty, + InputModelType, InputPathParameter, InputQueryParameter, InputStreamingType, @@ -725,6 +730,57 @@ function loadLongRunningMetadata( method: SdkLroServiceMethod | SdkLroPagingServiceMethod, ): [InputLongRunningServiceMetadata, readonly Diagnostic[]] { const diagnostics = createDiagnosticCollector(); + const metadata = method.lroMetadata; + + let pollingResponseModel: InputModelType | undefined; + let statusMetadata: InputLroStatusMetadata[] | undefined; + if (metadata.statusMetadata?.length) { + // Status metadata is read by deserializing the polling response with its generated deserializer, + // so the polling model graph must be emitted with JSON deserialization even when the polling + // operation itself is not exposed. + const pollingModel = metadata.pollingInfo.responseModel; + const outputTypes = new Set(); + diagnostics.pipe( + updateUsageOrAccess(sdkContext, UsageFlags.Output | UsageFlags.Json, pollingModel, { + seenTypes: outputTypes, + }), + ); + pollingResponseModel = diagnostics.pipe(fromSdkType(sdkContext, pollingModel)); + for (const type of outputTypes) { + const inputType = sdkContext.__typeCache.types.get(type); + if (inputType?.kind === "model" || inputType?.kind === "enum") { + inputType.usage |= UsageFlags.Output | UsageFlags.Json; + } + } + + statusMetadata = []; + for (const entry of metadata.statusMetadata) { + const property = sdkContext.__typeCache.properties.get(entry.property); + const propertySegments = entry.propertySegments.map((segment) => + sdkContext.__typeCache.properties.get(segment), + ); + if ( + property === undefined || + propertySegments.length === 0 || + propertySegments.some((segment) => segment === undefined) + ) { + diagnostics.add( + createDiagnostic({ + code: "general-error", + format: { + message: `Invalid LRO status metadata for '${method.name}': property '${entry.property.name}' is not a property of the polling response model '${pollingModel.name}'.`, + }, + target: method.__raw ?? NoTarget, + }), + ); + continue; + } + statusMetadata.push({ + property, + propertySegments: propertySegments as InputModelProperty[], + }); + } + } return diagnostics.wrap({ finalStateVia: convertLroFinalStateVia(method.lroMetadata.finalStateVia), @@ -740,6 +796,8 @@ function loadLongRunningMetadata( : undefined, } as OperationResponse, resultPath: method.lroMetadata.finalResultPath, + pollingResponseModel, + statusMetadata, }); } 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..7d98ab83105 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, + InputModelType, + InputParameter, + 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,6 +81,17 @@ export interface InputLongRunningServiceMetadata { finalStateVia: OperationFinalStateVia; finalResponse: OperationResponse; resultPath?: string; + /** The status-monitor (polling) response model. Present when `statusMetadata` is present. */ + pollingResponseModel?: InputModelType; + /** Values selected by `@lroStatusMetadata` from the latest status-monitor response. */ + statusMetadata?: InputLroStatusMetadata[]; +} + +export interface InputLroStatusMetadata { + /** The selected property of `pollingResponseModel` (or one of its base models). */ + property: InputModelProperty; + /** Property path from `pollingResponseModel` to the selected value. */ + propertySegments: InputModelProperty[]; } export interface InputLongRunningPagingServiceMethod extends InputServiceMethodBase { 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..cd36b1e2d86 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 @@ -1,9 +1,15 @@ import type { TestHost } from "@typespec/compiler/testing"; +import { UsageFlags } from "@azure-tools/typespec-client-generator-core"; import { deepStrictEqual, ok, strictEqual } from "assert"; +import { readFileSync } from "node:fs"; import { beforeEach, describe, it } from "vitest"; import { serializeCodeModel } from "../../src/code-model-writer.js"; import { createModel } from "../../src/lib/client-model-builder.js"; -import type { InputEnumType } from "../../src/type/input-type.js"; +import type { + InputLongRunningServiceMethod, + InputLroStatusMetadata, +} from "../../src/type/input-service-method.js"; +import type { InputEnumType, InputModelType } from "../../src/type/input-type.js"; import { RequestLocation } from "../../src/type/request-location.js"; import { createCSharpSdkContext, @@ -910,3 +916,199 @@ describe("Multipart convenience method generation", () => { strictEqual(diagnostic, undefined); }); }); + +// Source for generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroStatusMetadata/tspCodeModel.json. +const lroStatusMetadataFixtureSource = ` +import "@typespec/http"; +import "@typespec/rest"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-client-generator-core"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using Azure.Core; +using Azure.ClientGenerator.Core; + +@service +namespace LroFixture; + +model Statistics { + completed: int32; +} + +model BaseMonitor { + @lroStatusMetadata + @clientName("updatedAt") + @encodedName("application/json", "last_updated") + updated?: utcDateTime; +} + +model Monitor extends BaseMonitor { + @lroStatus + status: "Running" | "Succeeded" | "Failed" | "Canceled"; + + @lroResult + result?: string; + + @lroStatusMetadata + @clientName("progress") + @encodedName("application/json", "percent_complete") + percent?: int32; + + @lroStatusMetadata + statistics?: Statistics; +} + +@get +@route("/jobs/{jobId}/status") +op getStatus(@path jobId: string): Monitor; + +@post +@route("/jobs") +@pollingOperation(getStatus) +op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; +}; +`; + +describe("LRO status metadata", () => { + let runner: TestHost; + + beforeEach(async () => { + runner = await createEmitterTestHost(); + }); + + function getLroMethod(root: ReturnType[0]): InputLongRunningServiceMethod { + const method = root.clients[0].methods.find((m) => m.kind === "lro"); + ok(method); + return method as InputLongRunningServiceMethod; + } + + it("emits the fixture consumed by the C# deserializer", async () => { + runner.addTypeSpecFile("main.tsp", lroStatusMetadataFixtureSource); + await runner.compile("./", { noEmit: true }); + const sdkContext = await createCSharpSdkContext(createEmitterContext(runner.program)); + const [root, diagnostics] = createModel(sdkContext); + deepStrictEqual(diagnostics, []); + const actual = JSON.parse(serializeCodeModel(sdkContext, root)); + const expected = JSON.parse( + readFileSync( + new URL( + "../../../generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroStatusMetadata/tspCodeModel.json", + import.meta.url, + ), + "utf8", + ), + ); + deepStrictEqual(actual, expected); + }); + + it("references the polling model and its own properties in TCGC order", async () => { + runner.addTypeSpecFile("main.tsp", lroStatusMetadataFixtureSource); + await runner.compile("./", { noEmit: true }); + const sdkContext = await createCSharpSdkContext(createEmitterContext(runner.program)); + const [root] = createModel(sdkContext); + const metadata = getLroMethod(root).lroMetadata; + const monitor = root.models.find((m) => m.name === "Monitor"); + const baseMonitor = root.models.find((m) => m.name === "BaseMonitor"); + ok(monitor && baseMonitor); + strictEqual(metadata.pollingResponseModel, monitor); + const selections = metadata.statusMetadata as InputLroStatusMetadata[]; + deepStrictEqual( + selections.map((s) => s.property.name), + ["progress", "statistics", "updatedAt"], + ); + strictEqual( + selections[0].property, + monitor.properties.find((p) => p.name === "progress"), + ); + strictEqual(selections[2].property, baseMonitor.properties[0]); + for (const selection of selections) { + deepStrictEqual(selection.propertySegments, [selection.property]); + } + }); + + it("emits a polling model that is not exposed by a client method with JSON output usage", async () => { + const program = await typeSpecCompile( + ` + model Details { message: string; } + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroStatusMetadata mode?: "fast" | "slow"; + @lroStatusMetadata details?: Details; + } + @get @route("/jobs/{jobId}/status") + @scope("!csharp") + op getStatus(@path jobId: string): Monitor; + @post @route("/jobs") + @pollingOperation(getStatus) + op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + }; + `, + runner, + { IsTCGCNeeded: true, IsAzureCoreNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const [root, diagnostics] = createModel(sdkContext); + deepStrictEqual(diagnostics, []); + strictEqual(root.clients[0].methods.length, 1); + const metadata = getLroMethod(root).lroMetadata; + const monitor = root.models.find((m) => m.name === "Monitor") as InputModelType; + const details = root.models.find((m) => m.name === "Details") as InputModelType; + ok(monitor && details); + strictEqual(metadata.pollingResponseModel, monitor); + for (const type of [monitor, details]) { + strictEqual( + type.usage & (UsageFlags.Output | UsageFlags.Json), + UsageFlags.Output | UsageFlags.Json, + ); + } + const mode = metadata.statusMetadata?.[0].property.type as InputEnumType; + strictEqual(mode.kind, "enum"); + ok(root.enums.includes(mode)); + strictEqual( + mode.usage & (UsageFlags.Output | UsageFlags.Json), + UsageFlags.Output | UsageFlags.Json, + ); + + const serialized = JSON.parse(serializeCodeModel(sdkContext, root)); + const serializedMetadata = serialized.clients[0].methods[0].lroMetadata; + strictEqual(serializedMetadata.statusMetadata.length, 2); + ok(serializedMetadata.pollingResponseModel.$ref); + }); + + it("does not emit status metadata when no property is selected", async () => { + const program = await typeSpecCompile( + ` + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + details?: string; + } + @get @route("/jobs/{jobId}/status") + op getStatus(@path jobId: string): Monitor; + @post @route("/jobs") + @pollingOperation(getStatus) + op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + }; + `, + runner, + { IsTCGCNeeded: true, IsAzureCoreNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const [root] = createModel(sdkContext); + const metadata = getLroMethod(root).lroMetadata; + strictEqual(metadata.pollingResponseModel, undefined); + strictEqual(metadata.statusMetadata, undefined); + const serialized = JSON.parse(serializeCodeModel(sdkContext, root)); + const serializedMetadata = serialized.clients[0].methods.find( + (m: { kind: string }) => m.kind === "lro", + ).lroMetadata; + ok(!("pollingResponseModel" in serializedMetadata)); + ok(!("statusMetadata" in serializedMetadata)); + }); +}); 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..b0f21d88c53 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,18 @@ namespace Microsoft.TypeSpec.Generator.Input public sealed class InputLongRunningServiceMetadata { public InputLongRunningServiceMetadata(int finalStateVia, InputOperationResponse finalResponse, string? resultPath) + : this(finalStateVia, finalResponse, resultPath, null, []) + { + } + + public InputLongRunningServiceMetadata(int finalStateVia, InputOperationResponse finalResponse, string? resultPath, + InputModelType? pollingResponseModel, IReadOnlyList statusMetadata) { FinalStateVia = finalStateVia; FinalResponse = finalResponse; ResultPath = resultPath; + PollingResponseModel = pollingResponseModel; + StatusMetadata = statusMetadata; } public InputLongRunningServiceMetadata() : this(1, new InputOperationResponse(), null) { } @@ -20,6 +29,17 @@ public InputLongRunningServiceMetadata(int finalStateVia, InputOperationResponse public InputOperationResponse FinalResponse { get; } public string? ResultPath { get; } + /// + /// The status-monitor (polling) response model. Present when is not empty. + /// + public InputModelType? PollingResponseModel { get; } + + /// + /// Values selected by @lroStatusMetadata from the latest status-monitor response. + /// Each selection refers to a property of or one of its base models. + /// + public IReadOnlyList StatusMetadata { get; } + /// /// Meaningful return type of the long running operation. /// 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..f18cd243469 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroStatusMetadata.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; + +namespace Microsoft.TypeSpec.Generator.Input +{ + public sealed class InputLroStatusMetadata + { + public InputLroStatusMetadata(InputModelProperty property, IReadOnlyList propertySegments) + { + Property = property; + PropertySegments = propertySegments; + } + + public InputModelProperty Property { get; } + /// + /// Typed access path from the polling response model, not the final result. + /// + public IReadOnlyList PropertySegments { 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..c86011df515 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; + InputModelType? pollingResponseModel = null; + IReadOnlyList? statusMetadata = 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("pollingResponseModel", options, ref pollingResponseModel) + || reader.TryReadComplexType("statusMetadata", options, ref statusMetadata); if (!isKnownProperty) { - continue; + reader.SkipProperty(); } } - var result = new InputLongRunningServiceMetadata(finalStateVia, finalResponse ?? new InputOperationResponse(), resultPath); + var result = new InputLongRunningServiceMetadata(finalStateVia, finalResponse ?? new InputOperationResponse(), resultPath, pollingResponseModel, statusMetadata ?? []); return result; } 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..f84a416a620 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroStatusMetadataConverter.cs @@ -0,0 +1,39 @@ +// 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) + { + if (!reader.TryReadComplexType("property", options, ref property) + && !reader.TryReadComplexType("propertySegments", options, ref propertySegments)) + { + reader.SkipProperty(); + } + } + + return new InputLroStatusMetadata( + property ?? throw new JsonException("LRO status metadata must have a property."), + 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/TypeSpecSerialization.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/TypeSpecSerialization.cs index 37ff8f1cf97..813bee89a7b 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,7 @@ public static class TypeSpecSerialization new InputPagingServiceMetadataConverter(), new InputLongRunningServiceMethodConverter(referenceHandler), new InputLongRunningServiceMetadataConverter(), + new InputLroStatusMetadataConverter(), new InputLongRunningPagingServiceMethodConverter(referenceHandler), new InputServiceMethodResponseConverter(), new InputPropertyConverter(referenceHandler), diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/InputServiceMethodTests.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/InputServiceMethodTests.cs index d994b3342ba..84da25a2f19 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/InputServiceMethodTests.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/InputServiceMethodTests.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System.IO; +using System.Linq; +using System.Text.Json.Nodes; using Microsoft.TypeSpec.Generator.Tests.Common; using NUnit.Framework; @@ -20,5 +23,50 @@ public void CanUpdateServiceMethodName() Assert.AreEqual("UpdatedOperation", serviceMethod.Operation.Name); } + [Test] + public void LoadsEmittedLroStatusMetadata() + { + var directory = Helpers.GetAssetFileOrDirectoryPath(false); + var input = TypeSpecSerialization.Deserialize(File.ReadAllText(Path.Combine(directory, "tspCodeModel.json")))!; + var metadata = ((InputLongRunningServiceMethod)input.Clients.Single().Methods.Single(m => m.Name == "begin")) + .LongRunningServiceMetadata; + var monitor = input.Models.Single(m => m.Name == "Monitor"); + var baseMonitor = input.Models.Single(m => m.Name == "BaseMonitor"); + var statistics = input.Models.Single(m => m.Name == "Statistics"); + + Assert.AreSame(monitor, metadata.PollingResponseModel); + CollectionAssert.AreEqual(new[] { "progress", "statistics", "updatedAt" }, + metadata.StatusMetadata.Select(selection => selection.Property.Name)); + CollectionAssert.AreEqual(new[] { "percent_complete", "statistics", "last_updated" }, + metadata.StatusMetadata.Select(selection => selection.Property.SerializedName)); + Assert.AreSame(monitor.Properties.Single(p => p.Name == "progress"), metadata.StatusMetadata[0].Property); + Assert.AreSame(monitor.Properties.Single(p => p.Name == "statistics"), metadata.StatusMetadata[1].Property); + Assert.AreSame(statistics, metadata.StatusMetadata[1].Property.Type); + Assert.AreSame(baseMonitor.Properties.Single(p => p.Name == "updatedAt"), metadata.StatusMetadata[2].Property); + foreach (var selection in metadata.StatusMetadata) + { + Assert.AreSame(selection.Property, selection.PropertySegments.Single()); + } + } + + [Test] + public void LoadsLroMetadataWithoutStatusMetadataAndSkipsUnknownProperties() + { + var directory = Helpers.GetAssetFileOrDirectoryPath(false, method: nameof(LoadsEmittedLroStatusMetadata)); + var root = JsonNode.Parse(File.ReadAllText(Path.Combine(directory, "tspCodeModel.json")))!; + var lroMetadata = root["clients"]![0]!["methods"]!.AsArray() + .Single(m => (string?)m!["name"] == "begin")!["lroMetadata"]!.AsObject(); + lroMetadata.Remove("pollingResponseModel"); + lroMetadata.Remove("statusMetadata"); + lroMetadata.Insert(0, "futureMetadata", new JsonObject { ["value"] = new JsonArray(1, 2) }); + var json = root.ToJsonString(); + var input = TypeSpecSerialization.Deserialize(json)!; + var metadata = ((InputLongRunningServiceMethod)input.Clients.Single().Methods.Single(m => m.Name == "begin")) + .LongRunningServiceMetadata; + + Assert.IsNull(metadata.PollingResponseModel); + Assert.IsEmpty(metadata.StatusMetadata); + Assert.AreEqual(3, metadata.FinalStateVia); + } } } diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroStatusMetadata/tspCodeModel.json b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroStatusMetadata/tspCodeModel.json new file mode 100644 index 00000000000..f3a08ac99f7 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroStatusMetadata/tspCodeModel.json @@ -0,0 +1,620 @@ +{ + "name": "LroFixture", + "apiVersions": [], + "enums": [ + { + "$id": "1", + "kind": "enum", + "name": "MonitorStatus", + "apiVersions": [], + "crossLanguageDefinitionId": "LroFixture.Monitor.status.anonymous", + "valueType": { + "$id": "2", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "3", + "kind": "enumvalue", + "name": "Running", + "value": "Running", + "valueType": { + "$ref": "2" + }, + "enumType": { + "$ref": "1" + }, + "decorators": [], + "isExactName": false + }, + { + "$id": "4", + "kind": "enumvalue", + "name": "Succeeded", + "value": "Succeeded", + "valueType": { + "$ref": "2" + }, + "enumType": { + "$ref": "1" + }, + "decorators": [], + "isExactName": false + }, + { + "$id": "5", + "kind": "enumvalue", + "name": "Failed", + "value": "Failed", + "valueType": { + "$ref": "2" + }, + "enumType": { + "$ref": "1" + }, + "decorators": [], + "isExactName": false + }, + { + "$id": "6", + "kind": "enumvalue", + "name": "Canceled", + "value": "Canceled", + "valueType": { + "$ref": "2" + }, + "enumType": { + "$ref": "1" + }, + "decorators": [], + "isExactName": false + } + ], + "namespace": "LroFixture", + "isFixed": true, + "isFlags": false, + "usage": "Output,Json,LroPolling,LroFinalEnvelope", + "decorators": [], + "isExactName": false + } + ], + "constants": [ + { + "$id": "7", + "kind": "constant", + "name": "GetStatusAccept", + "namespace": "", + "usage": "None", + "valueType": { + "$id": "8", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [], + "isExactName": false + } + ], + "models": [ + { + "$id": "9", + "kind": "model", + "name": "Monitor", + "apiVersions": [], + "namespace": "LroFixture", + "crossLanguageDefinitionId": "LroFixture.Monitor", + "usage": "Output,Json,LroPolling,LroFinalEnvelope", + "decorators": [], + "serializationOptions": { + "json": { + "name": "Monitor" + } + }, + "isExactName": false, + "baseModel": { + "$id": "10", + "kind": "model", + "name": "BaseMonitor", + "apiVersions": [], + "namespace": "LroFixture", + "crossLanguageDefinitionId": "LroFixture.BaseMonitor", + "usage": "Output,Json,LroPolling,LroFinalEnvelope", + "decorators": [], + "serializationOptions": { + "json": { + "name": "BaseMonitor" + } + }, + "isExactName": false, + "properties": [ + { + "$id": "11", + "kind": "property", + "name": "updatedAt", + "originalName": "updated", + "apiVersions": [], + "serializedName": "last_updated", + "type": { + "$id": "12", + "kind": "utcDateTime", + "name": "utcDateTime", + "encode": "rfc3339", + "wireType": { + "$id": "13", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.utcDateTime", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture.BaseMonitor.updated", + "serializationOptions": { + "json": { + "name": "last_updated" + } + }, + "isHttpMetadata": false, + "isExactName": false + } + ] + }, + "properties": [ + { + "$id": "14", + "kind": "property", + "name": "status", + "apiVersions": [], + "serializedName": "status", + "type": { + "$ref": "1" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture.Monitor.status", + "serializationOptions": { + "json": { + "name": "status" + } + }, + "isHttpMetadata": false, + "isExactName": false + }, + { + "$id": "15", + "kind": "property", + "name": "result", + "apiVersions": [], + "serializedName": "result", + "type": { + "$id": "16", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture.Monitor.result", + "serializationOptions": { + "json": { + "name": "result" + } + }, + "isHttpMetadata": false, + "isExactName": false + }, + { + "$id": "17", + "kind": "property", + "name": "progress", + "originalName": "percent", + "apiVersions": [], + "serializedName": "percent_complete", + "type": { + "$id": "18", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture.Monitor.percent", + "serializationOptions": { + "json": { + "name": "percent_complete" + } + }, + "isHttpMetadata": false, + "isExactName": false + }, + { + "$id": "19", + "kind": "property", + "name": "statistics", + "apiVersions": [], + "serializedName": "statistics", + "type": { + "$id": "20", + "kind": "model", + "name": "Statistics", + "apiVersions": [], + "namespace": "LroFixture", + "crossLanguageDefinitionId": "LroFixture.Statistics", + "usage": "Output,Json,LroPolling,LroFinalEnvelope", + "decorators": [], + "serializationOptions": { + "json": { + "name": "Statistics" + } + }, + "isExactName": false, + "properties": [ + { + "$id": "21", + "kind": "property", + "name": "completed", + "apiVersions": [], + "serializedName": "completed", + "type": { + "$id": "22", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture.Statistics.completed", + "serializationOptions": { + "json": { + "name": "completed" + } + }, + "isHttpMetadata": false, + "isExactName": false + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture.Monitor.statistics", + "serializationOptions": { + "json": { + "name": "statistics" + } + }, + "isHttpMetadata": false, + "isExactName": false + } + ] + }, + { + "$ref": "20" + }, + { + "$ref": "10" + } + ], + "clients": [ + { + "$id": "23", + "kind": "client", + "name": "LroFixtureClient", + "isExactName": false, + "namespace": "LroFixture", + "methods": [ + { + "$id": "24", + "kind": "basic", + "name": "getStatus", + "isExactName": false, + "accessibility": "public", + "apiVersions": [], + "operation": { + "$id": "25", + "name": "getStatus", + "isExactName": false, + "accessibility": "public", + "parameters": [ + { + "$id": "26", + "kind": "path", + "name": "jobId", + "serializedName": "jobId", + "type": { + "$id": "27", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "isApiVersion": false, + "explode": false, + "style": "simple", + "allowReserved": false, + "skipUrlEncoding": false, + "optional": false, + "scope": "Method", + "decorators": [], + "readOnly": false, + "crossLanguageDefinitionId": "LroFixture.getStatus.jobId", + "methodParameterSegments": [ + { + "$id": "28", + "kind": "method", + "name": "jobId", + "serializedName": "jobId", + "type": { + "$id": "29", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "optional": false, + "scope": "Method", + "crossLanguageDefinitionId": "LroFixture.getStatus.jobId", + "readOnly": false, + "access": "public", + "decorators": [], + "isExactName": false + } + ], + "isExactName": false + }, + { + "$id": "30", + "kind": "header", + "name": "accept", + "serializedName": "Accept", + "type": { + "$ref": "7" + }, + "isApiVersion": false, + "optional": false, + "isContentType": false, + "scope": "Constant", + "readOnly": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture.getStatus.accept", + "methodParameterSegments": [ + { + "$id": "31", + "kind": "method", + "name": "accept", + "serializedName": "Accept", + "type": { + "$ref": "7" + }, + "location": "Header", + "isApiVersion": false, + "optional": false, + "scope": "Constant", + "crossLanguageDefinitionId": "LroFixture.getStatus.accept", + "readOnly": false, + "access": "public", + "decorators": [], + "isExactName": false + } + ], + "isExactName": false + } + ], + "responses": [ + { + "statusCodes": [200], + "bodyType": { + "$ref": "9" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": ["application/json"], + "serializationOptions": { + "json": { + "name": "" + } + } + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/jobs/{jobId}/status", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "LroFixture.getStatus", + "decorators": [], + "namespace": "LroFixture" + }, + "parameters": [ + { + "$ref": "28" + }, + { + "$ref": "31" + } + ], + "response": { + "type": { + "$ref": "9" + } + }, + "isOverride": false, + "generateConvenient": true, + "generateProtocol": true, + "crossLanguageDefinitionId": "LroFixture.getStatus" + }, + { + "$id": "32", + "kind": "lro", + "name": "begin", + "isExactName": false, + "accessibility": "public", + "apiVersions": [], + "operation": { + "$id": "33", + "name": "begin", + "isExactName": false, + "accessibility": "public", + "parameters": [], + "responses": [ + { + "statusCodes": [202], + "headers": [ + { + "name": "location", + "nameInResponse": "Operation-Location", + "type": { + "$id": "34", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "35", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + } + } + ], + "isErrorResponse": false, + "serializationOptions": {} + } + ], + "httpMethod": "POST", + "uri": "{endpoint}", + "path": "/jobs", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "LroFixture.begin", + "decorators": [], + "namespace": "LroFixture" + }, + "parameters": [], + "response": { + "type": { + "$id": "36", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "resultSegments": ["result"] + }, + "isOverride": false, + "generateConvenient": true, + "generateProtocol": true, + "crossLanguageDefinitionId": "LroFixture.begin", + "lroMetadata": { + "finalStateVia": 3, + "finalResponse": { + "statusCodes": [200], + "bodyType": { + "$ref": "9" + } + }, + "resultPath": "result", + "pollingResponseModel": { + "$ref": "9" + }, + "statusMetadata": [ + { + "property": { + "$ref": "17" + }, + "propertySegments": [ + { + "$ref": "17" + } + ] + }, + { + "property": { + "$ref": "19" + }, + "propertySegments": [ + { + "$ref": "19" + } + ] + }, + { + "property": { + "$ref": "11" + }, + "propertySegments": [ + { + "$ref": "11" + } + ] + } + ] + } + } + ], + "parameters": [ + { + "$id": "37", + "kind": "endpoint", + "name": "endpoint", + "serializedName": "endpoint", + "doc": "Service host", + "type": { + "$id": "38", + "kind": "url", + "name": "endpoint", + "crossLanguageDefinitionId": "TypeSpec.url" + }, + "isApiVersion": false, + "optional": false, + "scope": "Client", + "isEndpoint": true, + "serverUrlTemplate": "{endpoint}", + "skipUrlEncoding": false, + "readOnly": false, + "crossLanguageDefinitionId": "LroFixture.endpoint", + "isExactName": false + } + ], + "initializedBy": 1, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture", + "apiVersions": [], + "isMultiServiceClient": false + } + ] +}