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..917e018d491 100644 --- a/packages/http-client-csharp/emitter/src/lib/operation-converter.ts +++ b/packages/http-client-csharp/emitter/src/lib/operation-converter.ts @@ -27,6 +27,7 @@ import { getHttpOperationParameter, getParamAlias, getResponseAsBool, + getSdkModelWithDiagnostics, isHttpMetadata, shouldGenerateConvenient, shouldGenerateProtocol, @@ -38,9 +39,11 @@ import { getDeprecated, isErrorModel, NoTarget, + resolveEncodedName, } from "@typespec/compiler"; import { unsafe_getEventDefinitions } from "@typespec/events/experimental"; import type { HttpStatusCodeRange } from "@typespec/http"; +import { getHeaderFieldName, isBody, isBodyRoot } from "@typespec/http"; import { isTerminalEvent } from "@typespec/sse"; import type { CSharpEmitterContext } from "../sdk-context.js"; import { collectionFormatToDelimMap } from "../type/collection-format.js"; @@ -54,17 +57,21 @@ import type { InputLongRunningPagingServiceMethod, InputLongRunningServiceMetadata, InputLongRunningServiceMethod, + InputLroOperationIdMetadata, + InputLroOperationIdPropertyMetadata, InputNextLink, InputPagingServiceMetadata, InputPagingServiceMethod, InputServiceMethod, InputServiceMethodResponse, } from "../type/input-service-method.js"; +import { InputOperationLinkLocation } from "../type/input-service-method.js"; import type { InputBodyParameter, InputHeaderParameter, InputHttpParameter, InputMethodParameter, + InputModelProperty, InputPathParameter, InputQueryParameter, InputStreamingType, @@ -79,7 +86,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( @@ -135,7 +142,7 @@ export function fromSdkServiceMethod( ), ); lroServiceMethod.lroMetadata = diagnostics.pipe( - loadLongRunningMetadata(sdkContext, sdkMethod), + loadLongRunningMetadata(sdkContext, sdkMethod, rootApiVersions), ); method = lroServiceMethod; break; @@ -150,7 +157,7 @@ export function fromSdkServiceMethod( ), ); lroPagingMethod.lroMetadata = diagnostics.pipe( - loadLongRunningMetadata(sdkContext, sdkMethod), + loadLongRunningMetadata(sdkContext, sdkMethod, rootApiVersions), ); lroPagingMethod.pagingMetadata = diagnostics.pipe( loadPagingServiceMetadata(sdkContext, sdkMethod, rootApiVersions, uri, namespace), @@ -723,8 +730,172 @@ export function fromMethodParameter( function loadLongRunningMetadata( sdkContext: CSharpEmitterContext, method: SdkLroServiceMethod | SdkLroPagingServiceMethod, + rootApiVersions: string[], ): [InputLongRunningServiceMetadata, readonly Diagnostic[]] { const diagnostics = createDiagnosticCollector(); + const metadata = method.lroMetadata; + const step = metadata.statusMonitorStep; + const pollingOperation = + step?.kind === "nextOperationLink" ? step.operation : step?.target.operation; + let pollingMethod: SdkServiceMethod | undefined; + if (pollingOperation && metadata.operationId?.length) { + const pollingClient = sdkContext.getClientForOperation(pollingOperation.__raw.operation); + const clients = [...sdkContext.sdkPackage.clients]; + for (let index = 0; index < clients.length; index++) { + const client = clients[index]; + if (client.__raw === pollingClient) { + pollingMethod = client.methods.find( + (candidate) => candidate.operation.__raw.operation === pollingOperation.__raw.operation, + ); + break; + } + clients.push(...(client.children ?? [])); + } + } + const reportInvalidSelection = (message: string) => { + diagnostics.add( + createDiagnostic({ + code: "general-error", + format: { message: `Invalid LRO metadata for '${method.name}': ${message}` }, + target: method.__raw ?? NoTarget, + }), + ); + }; + + const convertProperty = (sdkProperty: SdkModelPropertyType) => { + const property = diagnostics.pipe( + fromSdkModelProperty(sdkContext, sdkProperty, metadata.pollingInfo.responseModel), + ); + // TCGC omits serialization options when the polling model is not otherwise emitted. + if (property && property.serializedName === undefined && sdkProperty.__raw) { + property.serializedName = resolveEncodedName( + sdkContext.program, + sdkProperty.__raw, + "application/json", + ); + } + return property; + }; + + const convertSelection = (entry: { + property: SdkModelPropertyType; + propertySegments: SdkModelPropertyType[]; + }): Pick | undefined => { + if (!entry.property || !entry.propertySegments?.length) { + reportInvalidSelection("a selected property must have a nonempty property path."); + return undefined; + } + + const property = convertProperty(entry.property); + if (!property) { + reportInvalidSelection("a selected property could not be converted."); + return undefined; + } + + const propertySegments: InputModelProperty[] = []; + for (const segment of entry.propertySegments) { + const converted = convertProperty(segment); + if (!converted) { + reportInvalidSelection("a selected property path could not be converted."); + return undefined; + } + propertySegments.push(converted); + } + return { property, propertySegments }; + }; + + const operationId: InputLroOperationIdMetadata[] = []; + for (const entry of metadata.operationId ?? []) { + if (entry.kind === "property") { + const selection = convertSelection(entry); + if (selection) { + operationId.push({ kind: "property", ...selection }); + } + continue; + } + + if (entry.kind !== "path") { + reportInvalidSelection("the operation ID has an unsupported selection kind."); + continue; + } + + if (!pollingOperation?.path || !entry.pathParameter || entry.pathParameter.kind !== "path") { + reportInvalidSelection( + "the operation ID requires a linked polling operation and path parameter.", + ); + continue; + } + + // TCGC constructs a separate polling operation for LRO metadata. Use the actual + // client method's parameter when it is exposed so its cached input is shared. + const sdkPollingOperation = pollingMethod?.operation ?? pollingOperation; + const sdkPathParameters = sdkPollingOperation.parameters.filter( + (parameter) => + parameter.kind === "path" && + parameter.crossLanguageDefinitionId === entry.pathParameter.crossLanguageDefinitionId, + ); + if (sdkPathParameters.length !== 1) { + reportInvalidSelection( + "the operation ID path parameter must uniquely match a polling operation parameter.", + ); + continue; + } + const pathParameter = diagnostics.pipe( + fromParameter(sdkContext, sdkPathParameters[0], rootApiVersions), + ); + if (!pathParameter || pathParameter.kind !== "path") { + reportInvalidSelection("the operation ID path parameter could not be converted."); + continue; + } + + if (!entry.source?.property) { + reportInvalidSelection("the operation ID polling link must have a source property."); + continue; + } + + const source = entry.source.property; + const rawSource = source.__raw; + if (!rawSource?.model) { + reportInvalidSelection("the operation ID polling link must have a source model property."); + continue; + } + + let location: InputOperationLinkLocation; + switch (entry.source.location) { + case "ResponseHeader": + location = InputOperationLinkLocation.ResponseHeader; + break; + case "ResponseBody": + location = + isBody(sdkContext.program, rawSource) || isBodyRoot(sdkContext.program, rawSource) + ? InputOperationLinkLocation.Self + : InputOperationLinkLocation.ResponseBody; + break; + case "Self": + location = InputOperationLinkLocation.Self; + break; + default: + reportInvalidSelection("the operation ID has an unsupported polling link location."); + continue; + } + + const sourceModel = diagnostics.pipe(getSdkModelWithDiagnostics(sdkContext, rawSource.model)); + const convertedSource = diagnostics.pipe(fromSdkModelProperty(sdkContext, source, sourceModel)); + if (!convertedSource) { + reportInvalidSelection("the operation ID polling link property could not be converted."); + continue; + } + const sourceProperty = + location === InputOperationLinkLocation.ResponseHeader + ? { ...convertedSource, serializedName: getHeaderFieldName(sdkContext.program, rawSource) } + : convertedSource; + operationId.push({ + kind: "path", + source: { location, property: sourceProperty }, + pathParameter, + pollingPath: pollingOperation.path, + }); + } return diagnostics.wrap({ finalStateVia: convertLroFinalStateVia(method.lroMetadata.finalStateVia), @@ -740,6 +911,7 @@ function loadLongRunningMetadata( : undefined, } as OperationResponse, resultPath: method.lroMetadata.finalResultPath, + operationId: metadata.operationId ? operationId : undefined, }); } 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 eea761b987b..64edc9275bd 100644 --- a/packages/http-client-csharp/emitter/src/lib/type-converter.ts +++ b/packages/http-client-csharp/emitter/src/lib/type-converter.ts @@ -288,7 +288,7 @@ function fromSdkModelType( return diagnostics.wrap(inputModelType); } -function fromSdkModelProperty( +export function fromSdkModelProperty( sdkContext: CSharpEmitterContext, sdkProperty: SdkModelPropertyType, sdkModel: SdkModelType, 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..ec527c430ae 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,37 @@ export interface InputLongRunningServiceMetadata { finalStateVia: OperationFinalStateVia; finalResponse: OperationResponse; resultPath?: string; + operationId?: InputLroOperationIdMetadata[]; } +export enum InputOperationLinkLocation { + Unknown = "Unknown", + ResponseHeader = "ResponseHeader", + ResponseBody = "ResponseBody", + Self = "Self", +} + +export interface InputOperationLink { + location: InputOperationLinkLocation; + property: InputModelProperty; +} + +export interface InputLroOperationIdPathMetadata { + kind: "path"; + source: InputOperationLink; + pathParameter: InputPathParameter; + pollingPath: string; +} + +export interface InputLroOperationIdPropertyMetadata { + kind: "property"; + property: InputModelProperty; + propertySegments: InputModelProperty[]; +} + +export type InputLroOperationIdMetadata = + InputLroOperationIdPathMetadata | InputLroOperationIdPropertyMetadata; + 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..0215e48794a 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,5 +1,6 @@ -import type { TestHost } from "@typespec/compiler/testing"; -import { deepStrictEqual, ok, strictEqual } from "assert"; +import { expectDiagnostics, type TestHost } from "@typespec/compiler/testing"; +import { deepStrictEqual, notStrictEqual, 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"; @@ -12,6 +13,50 @@ import { typeSpecCompile, } from "./utils/test-util.js"; +// Source for generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroMetadata/tspCodeModel.json. +const lroMetadataFixtureSource = ` +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 BaseMonitor { + @lroOperationId + @clientName("jobId") + @encodedName("application/json", "job_id") + id: string; +} + +model Monitor extends BaseMonitor { + @lroStatus + status: "Running" | "Succeeded" | "Failed" | "Canceled"; + + @lroResult + result?: string; +} + +@get +@route("/jobs/{jobId}/status") +op getStatus(@lroOperationId @path("jobId") id: string): Monitor; + +@post +@route("/jobs") +@access(Access.internal, "csharp") +@pollingOperation(getStatus) +op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; +}; +`; + describe("Operation Converter", () => { let runner: TestHost; @@ -19,6 +64,541 @@ describe("Operation Converter", () => { runner = await createEmitterTestHost(); }); + it("emits the LRO metadata fixture consumed by the C# deserializer", async () => { + const fixture = new URL( + "../../../generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroMetadata/", + import.meta.url, + ); + runner.addTypeSpecFile("main.tsp", lroMetadataFixtureSource); + 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("tspCodeModel.json", fixture), "utf8")); + deepStrictEqual(actual, expected); + }); + + it.each( + ["both", "body", "path", "none"].flatMap((selection) => + [true, false].map((pollingFirst) => ({ selection, pollingFirst })), + ), + )( + "preserves LRO selections: $selection, polling operation declared first: $pollingFirst", + async ({ selection, pollingFirst }) => { + const selected = selection !== "none"; + const pollingOperation = ` + @get @route("/jobs/{jobId}/status") + op getStatus( + ${["both", "path"].includes(selection) ? "@lroOperationId" : ""} + @path("jobId") id: string + ): Monitor; + `; + const startOperation = ` + @post @route("/jobs") + @pollingOperation(getStatus) + op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + }; + `; + const program = await typeSpecCompile( + ` + model BaseMonitor { + ${["both", "body"].includes(selection) ? "@lroOperationId" : ""} + @clientName("jobId") + @encodedName("application/json", "job_id") + id: string; + } + model Monitor extends BaseMonitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroResult result?: string; + } + ${pollingFirst ? `${pollingOperation}\n${startOperation}` : `${startOperation}\n${pollingOperation}`} + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + 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; + if (!selected) { + strictEqual(metadata.operationId, undefined); + strictEqual(serializeCodeModel(sdkContext, root).includes('"operationId"'), false); + return; + } + deepStrictEqual( + metadata.operationId?.map((entry) => entry.kind), + selection === "both" ? ["path", "property"] : [selection === "body" ? "property" : "path"], + ); + for (const entry of metadata.operationId!) { + if (entry.kind === "path") { + strictEqual(entry.pollingPath, "/jobs/{jobId}/status"); + strictEqual(entry.pathParameter.serializedName, "jobId"); + strictEqual( + entry.pathParameter, + root.clients[0].methods + .find((m) => m.name === "getStatus")! + .operation.parameters.find((p) => p.kind === "path"), + ); + strictEqual(entry.source.location, "ResponseHeader"); + strictEqual(entry.source.property.serializedName, "Operation-Location"); + const sdkMethod = sdkContext.sdkPackage.clients[0].methods.find( + (m) => m.name === "begin", + ); + ok(sdkMethod?.kind === "lro"); + const sdkPath = sdkMethod.lroMetadata.operationId?.find((id) => id.kind === "path"); + ok(sdkPath?.kind === "path"); + const cachedSourceProperty = sdkContext.__typeCache.properties.get( + sdkPath.source.property, + ); + ok(cachedSourceProperty); + strictEqual( + cachedSourceProperty.serializedName, + sdkPath.source.property.serializationOptions.json?.name ?? + sdkPath.source.property.serializationOptions.xml?.name ?? + sdkPath.source.property.serializationOptions.multipart?.name, + ); + notStrictEqual(entry.source.property, cachedSourceProperty); + } else { + strictEqual(entry.property.name, "jobId"); + strictEqual(entry.propertySegments[0], entry.property); + strictEqual(entry.property.serializedName, "job_id"); + strictEqual( + entry.property, + root.models + .find((m) => m.name === "BaseMonitor") + ?.properties.find((p) => p.name === "jobId"), + ); + } + } + const serialized = JSON.parse(serializeCodeModel(sdkContext, root)); + const serializedMetadata = serialized.clients[0].methods.find( + (m: { name: string }) => m.name === "begin", + ).lroMetadata; + deepStrictEqual( + serializedMetadata.operationId.map((entry: { kind: string }) => entry.kind), + metadata.operationId!.map((entry) => entry.kind), + ); + if (["both", "path"].includes(selection)) { + const serializedPath = serializedMetadata.operationId.find( + (entry: { kind: string }) => entry.kind === "path", + ).pathParameter; + const pollingMethod = root.clients[0].methods.find((m) => m.name === "getStatus")!; + const parameterIndex = pollingMethod.operation.parameters.findIndex( + (p) => p.kind === "path" && p.serializedName === "jobId", + ); + ok(parameterIndex >= 0); + const serializedPollingParameter = serialized.clients[0].methods.find( + (m: { name: string }) => m.name === "getStatus", + ).operation.parameters[parameterIndex]; + strictEqual( + serializedPath.$id ?? serializedPath.$ref, + serializedPollingParameter.$id ?? serializedPollingParameter.$ref, + ); + ok(serializedPath.$ref || serializedPollingParameter.$ref); + } + }, + ); + + it.each([ + "missing polling operation", + "missing path parameter", + "missing header source", + "unknown link location", + ])("reports a diagnostic for an LRO operation ID with %s", async (malformation) => { + const program = await typeSpecCompile( + ` + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroResult result?: string; + @lroOperationId id: string; + } + @get @route("/jobs/{jobId}/status") + op getStatus(@lroOperationId @path("jobId") id: string): Monitor; + @post @route("/jobs") @pollingOperation(getStatus) + op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + }; + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const sdkMethod = sdkContext.sdkPackage.clients[0].methods.find((m) => m.name === "begin"); + ok(sdkMethod?.kind === "lro"); + const path = sdkMethod.lroMetadata.operationId?.find((entry) => entry.kind === "path"); + ok(path?.kind === "path"); + switch (malformation) { + case "missing polling operation": + sdkMethod.lroMetadata.statusMonitorStep = undefined; + break; + case "missing path parameter": + path.pathParameter.crossLanguageDefinitionId = "missing.parameter"; + break; + case "missing header source": + path.source.property.__raw = undefined; + break; + case "unknown link location": + // Simulate an unrecognized location from a future TCGC version. + // @ts-expect-error The current TCGC type lists only known locations. + path.source.location = "FutureLocation"; + break; + } + const [root, diagnostics] = createModel(sdkContext); + const method = root.clients[0].methods.find((m) => m.name === "begin"); + ok(method?.kind === "lro"); + deepStrictEqual( + method.lroMetadata.operationId?.map((entry) => entry.kind), + ["property"], + ); + expectDiagnostics(diagnostics, { + severity: "error", + code: "@typespec/http-client-csharp/general-error", + message: /Invalid LRO metadata for 'begin': .*operation ID/, + }); + }); + + it("reports an empty operation ID property path without dropping valid selections", async () => { + const program = await typeSpecCompile( + ` + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroResult result?: string; + @lroOperationId id: string; + } + @get @route("/jobs/{jobId}/status") + op getStatus(@lroOperationId @path("jobId") id: string): Monitor; + @post @route("/jobs") @pollingOperation(getStatus) + op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + }; + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const sdkMethod = sdkContext.sdkPackage.clients[0].methods.find((m) => m.name === "begin"); + ok(sdkMethod?.kind === "lro"); + const sdkProperty = sdkMethod.lroMetadata.operationId?.find( + (entry) => entry.kind === "property", + ); + ok(sdkProperty?.kind === "property"); + sdkProperty.propertySegments = []; + + const [root, diagnostics] = createModel(sdkContext); + const method = root.clients[0].methods.find((m) => m.name === "begin"); + ok(method?.kind === "lro"); + deepStrictEqual( + method.lroMetadata.operationId?.map((entry) => entry.kind), + ["path"], + ); + expectDiagnostics(diagnostics, { + severity: "error", + code: "@typespec/http-client-csharp/general-error", + message: + "Invalid LRO metadata for 'begin': a selected property must have a nonempty property path.", + }); + }); + + it("shares the selected parameter with a polling operation in another client", async () => { + const program = await typeSpecCompile( + ` + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroResult result?: string; + } + interface Start { + @post @route("/jobs") @pollingOperation(Polling.getStatus) + begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + }; + } + interface Polling { + @get @route("/jobs/{jobId}/status") + getStatus(@lroOperationId @path("jobId") id: string): Monitor; + } + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const [root, diagnostics] = createModel(sdkContext); + deepStrictEqual(diagnostics, []); + const clients = [...root.clients]; + for (let index = 0; index < clients.length; index++) { + clients.push(...(clients[index].children ?? [])); + } + const methods = clients.flatMap((client) => client.methods); + const start = methods.find((method) => method.name === "begin"); + const poll = methods.find((method) => method.name === "getStatus"); + ok(start?.kind === "lro"); + ok(poll); + const path = start.lroMetadata.operationId?.find((entry) => entry.kind === "path"); + ok(path?.kind === "path"); + strictEqual( + path.pathParameter, + poll.operation.parameters.find((parameter) => parameter.kind === "path"), + ); + }); + + it("preserves a path selection when the polling operation is not exposed as a client method", async () => { + const program = await typeSpecCompile( + ` + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroResult result?: string; + } + @get @route("/jobs/{jobId}/status") + op getStatus(@lroOperationId @path("jobId") id: string): Monitor; + @post @route("/jobs") @pollingOperation(getStatus) + op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + }; + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const client = sdkContext.sdkPackage.clients[0]; + client.methods = client.methods.filter((method) => method.name !== "getStatus"); + + const [root, diagnostics] = createModel(sdkContext); + deepStrictEqual(diagnostics, []); + const method = root.clients[0].methods.find((m) => m.name === "begin"); + ok(method?.kind === "lro"); + const path = method.lroMetadata.operationId?.find((entry) => entry.kind === "path"); + ok(path?.kind === "path"); + strictEqual(path.pathParameter.serializedName, "jobId"); + strictEqual(path.pollingPath, "/jobs/{jobId}/status"); + }); + + it.each([ + { expansion: "{jobId}", style: "simple" }, + { expansion: "{.jobId}", style: "label" }, + { expansion: "{;jobId}", style: "matrix" }, + { expansion: "{/jobId}", style: "path" }, + { expansion: "{#jobId}", style: "fragment" }, + ])( + "preserves the $style style and shared identity of a spread polling ID", + async ({ expansion, style }) => { + const program = await typeSpecCompile( + ` + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroResult result?: string; + } + model PollingParameters { + @lroOperationId @path("jobId") id: string; + } + @get @route("/jobs${expansion}/status") + op getStatus(...PollingParameters): Monitor; + @post @route("/jobs") @pollingOperation(getStatus) + op begin(): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + }; + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const [root, diagnostics] = createModel(sdkContext); + deepStrictEqual(diagnostics, []); + const start = root.clients[0].methods.find((method) => method.name === "begin"); + const poll = root.clients[0].methods.find((method) => method.name === "getStatus"); + ok(start?.kind === "lro"); + ok(poll); + const selected = start.lroMetadata.operationId?.find((entry) => entry.kind === "path"); + ok(selected?.kind === "path"); + const parameter = poll.operation.parameters.find((parameter) => parameter.kind === "path"); + ok(parameter?.kind === "path"); + strictEqual(selected.pathParameter, parameter); + strictEqual(selected.pollingPath, "/jobs{jobId}/status"); + strictEqual(parameter.serializedName, "jobId"); + strictEqual(parameter.style, style); + + const serialized = JSON.parse(serializeCodeModel(sdkContext, root)); + const serializedStart = serialized.clients[0].methods.find( + (method: { name: string }) => method.name === "begin", + ); + const serializedPoll = serialized.clients[0].methods.find( + (method: { name: string }) => method.name === "getStatus", + ); + const serializedSelection = serializedStart.lroMetadata.operationId.find( + (entry: { kind: string }) => entry.kind === "path", + ); + const serializedParameter = serializedPoll.operation.parameters.find( + (entry: { kind: string }) => entry.kind === "path", + ); + strictEqual( + serializedSelection.pathParameter.$id ?? serializedSelection.pathParameter.$ref, + serializedParameter.$id ?? serializedParameter.$ref, + ); + ok(serializedSelection.pathParameter.$ref || serializedParameter.$ref); + strictEqual( + (serializedParameter.$ref ? serializedSelection.pathParameter : serializedParameter).style, + style, + ); + }, + ); + + it.each([true, false])( + "preserves an operation ID property from an unexposed polling model, path ID: %s", + async (hasPathId) => { + const program = await typeSpecCompile( + ` + model FinalResult { value: string; } + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroOperationId @encodedName("application/json", "job_id") jobId: string; + unrelated: [string, int32]; + } + @get @route("/jobs/{jobId}/status") + @convenientAPI(false, "csharp") + op getStatus(${hasPathId ? "@lroOperationId" : ""} @path("jobId") id: string): Monitor; + @get @route("/jobs/{jobId}") + @convenientAPI(false, "csharp") + op getResult(@path("jobId") id: string): FinalResult; + @client({ service: Azure.Csharp.Testing }) + interface PublicOperations { + @post @route("/jobs/{jobId}") @pollingOperation(getStatus) @finalOperation(getResult) + @useFinalStateVia("original-uri") + @convenientAPI(false, "csharp") + op begin(@path("jobId") id: string): { + @statusCode code: 202; + @pollingLocation @header("Operation-Location") location: ResourceLocation; + @finalLocation @header("Location") finalLocation: ResourceLocation; + }; + } + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const client = sdkContext.sdkPackage.clients[0]; + strictEqual( + client.methods.some((method) => method.name === "getStatus"), + false, + ); + strictEqual( + sdkContext.sdkPackage.models.some((model) => model.name === "Monitor"), + false, + ); + const [root, diagnostics] = createModel(sdkContext); + deepStrictEqual( + diagnostics.map((diagnostic) => diagnostic.code), + [], + ); + const method = root.clients[0].methods.find((m) => m.name === "begin"); + ok(method?.kind === "lro"); + deepStrictEqual( + method.lroMetadata.operationId?.map((entry) => entry.kind), + hasPathId ? ["path", "property"] : ["property"], + ); + strictEqual( + root.models.some((model) => model.name === "Monitor"), + false, + ); + const selection = method.lroMetadata.operationId?.find((entry) => entry.kind === "property"); + ok(selection?.kind === "property"); + strictEqual(selection.propertySegments[0], selection.property); + strictEqual(selection.property.serializedName, "job_id"); + const serialized = JSON.parse(serializeCodeModel(sdkContext, root)); + const serializedSelection = serialized.clients[0].methods + .find((m: { name: string }) => m.name === "begin") + .lroMetadata.operationId.find((entry: { kind: string }) => entry.kind === "property"); + strictEqual(serializedSelection.propertySegments[0].$ref, serializedSelection.property.$id); + }, + ); + + it.each([ + { + decorators: '@pollingLocation @header("Operation-Location")', + expectedLocation: "ResponseHeader", + expectedName: "Operation-Location", + }, + { + decorators: "@pollingLocation", + expectedLocation: "ResponseBody", + expectedName: "status_url", + }, + { + decorators: "@pollingLocation @body", + expectedLocation: "Self", + expectedName: undefined, + }, + { + decorators: "@pollingLocation @bodyRoot", + expectedLocation: "Self", + expectedName: undefined, + }, + ])( + "preserves a polling link in $expectedLocation without changing its source property", + async ({ decorators, expectedLocation, expectedName }) => { + const program = await typeSpecCompile( + ` + namespace Tracking { + model Monitor { + @lroStatus status: "Running" | "Succeeded" | "Failed" | "Canceled"; + @lroResult result?: string; + } + } + namespace Kickoff { + model StartResponse { + @statusCode code: 202; + ${decorators} + @encodedName("application/json", "status_url") + location: ResourceLocation; + } + } + @get @route("/jobs/{jobId}/status") + op getStatus(@lroOperationId @path("jobId") id: string): Tracking.Monitor; + @put @route("/jobs/{jobId}/status") + @useFinalStateVia("original-uri") + @pollingOperation(getStatus) + op begin(@path("jobId") id: string): Kickoff.StartResponse; + `, + runner, + { IsAzureCoreNeeded: true, IsTCGCNeeded: true }, + ); + const sdkContext = await createCSharpSdkContext(createEmitterContext(program)); + const sdkMethod = sdkContext.sdkPackage.clients[0].methods.find((m) => m.name === "begin"); + ok(sdkMethod?.kind === "lro"); + const sdkPath = sdkMethod.lroMetadata.operationId?.find((entry) => entry.kind === "path"); + ok(sdkPath?.kind === "path"); + + const [root, diagnostics] = createModel(sdkContext); + deepStrictEqual(diagnostics, []); + const method = root.clients[0].methods.find((m) => m.name === "begin"); + ok(method?.kind === "lro"); + const path = method.lroMetadata.operationId?.find((entry) => entry.kind === "path"); + ok(path?.kind === "path"); + strictEqual(path.source.location, expectedLocation); + strictEqual(path.source.property.serializedName, expectedName); + const cachedSource = sdkContext.__typeCache.properties.get(sdkPath.source.property); + ok(cachedSource); + strictEqual( + cachedSource.serializedName, + sdkPath.source.property.serializationOptions.json?.name ?? + sdkPath.source.property.serializationOptions.xml?.name ?? + sdkPath.source.property.serializationOptions.multipart?.name, + ); + if (expectedLocation === "ResponseHeader") { + notStrictEqual(path.source.property, cachedSource); + } else { + strictEqual(path.source.property, cachedSource); + } + }, + ); + 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..356c19fdfdd 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,17 @@ 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 operationId) { FinalStateVia = finalStateVia; FinalResponse = finalResponse; ResultPath = resultPath; + OperationId = operationId; } public InputLongRunningServiceMetadata() : this(1, new InputOperationResponse(), null) { } @@ -19,6 +27,11 @@ public InputLongRunningServiceMetadata(int finalStateVia, InputOperationResponse public int FinalStateVia { get; } public InputOperationResponse FinalResponse { get; } public string? ResultPath { get; } + /// + /// Server-issued ID sources in availability order: polling URL, then polling response body. + /// These selections do not replace the complete polling URL. + /// + 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..cadf3225d5f --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputLroOperationIdPathMetadata.cs @@ -0,0 +1,22 @@ +// 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 pollingPath) + { + Source = source; + PathParameter = pathParameter; + PollingPath = pollingPath; + } + + public InputOperationLink Source { get; } + public InputPathParameter PathParameter { get; } + /// + /// Modeled polling route used to locate the selected parameter in the complete polling URL. + /// + public string PollingPath { 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/InputOperationLink.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputOperationLink.cs new file mode 100644 index 00000000000..5999d68e595 --- /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(InputOperationLinkLocation location, InputModelProperty property) + { + Location = location; + Property = property; + } + + public InputOperationLinkLocation Location { get; } + public InputModelProperty Property { get; } + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputOperationLinkLocation.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputOperationLinkLocation.cs new file mode 100644 index 00000000000..fa95ee8eb6b --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputOperationLinkLocation.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Microsoft.TypeSpec.Generator.Input +{ + /// + /// Identifies where a polling operation link is found. + /// + public enum InputOperationLinkLocation + { + /// + /// The location is not recognized by this version of the input model. + /// + Unknown, + ResponseHeader, + ResponseBody, + Self, + } +} diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputPathParameter.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputPathParameter.cs index c3517cd9036..12744245b8b 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputPathParameter.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputPathParameter.cs @@ -30,6 +30,10 @@ public InputPathParameter( } public bool Explode { get; internal set; } + /// + /// The URI template expansion style, or when unavailable. + /// + public InputPathParameterStyle Style { get; internal set; } public bool AllowReserved { get; internal set; } public bool SkipUrlEncoding { get; internal set; } public string? ServerUrlTemplate { get; internal set; } diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputPathParameterStyle.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputPathParameterStyle.cs new file mode 100644 index 00000000000..4a9fe848511 --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/InputPathParameterStyle.cs @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Microsoft.TypeSpec.Generator.Input +{ + /// + /// Identifies the URI template expansion style of a path parameter. + /// + public enum InputPathParameterStyle + { + /// + /// The style is missing or not recognized by this version of the input model. + /// + Unknown, + Simple, + Label, + Matrix, + Path, + Fragment, + } +} 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..3d2b8402b6e 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,21 @@ private InputLongRunningServiceMetadata CreateOperationLongRunning(ref Utf8JsonR int finalStateVia = default; InputOperationResponse? finalResponse = null; string? resultPath = 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("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, 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..cbfcb7f11dd --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputLroOperationIdMetadataConverter.cs @@ -0,0 +1,55 @@ +// 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; + InputOperationLink? source = null; + InputPathParameter? pathParameter = null; + string? pollingPath = null; + InputModelProperty? property = null; + IReadOnlyList? propertySegments = null; + while (reader.TokenType != JsonTokenType.EndObject) + { + if (!reader.TryReadString("kind", ref kind) + && !reader.TryReadComplexType("source", options, ref source) + && !reader.TryReadComplexType("pathParameter", options, ref pathParameter) + && !reader.TryReadString("pollingPath", ref pollingPath) + && !reader.TryReadComplexType("property", options, ref property) + && !reader.TryReadComplexType("propertySegments", options, ref propertySegments)) + { + reader.SkipProperty(); + } + } + + return kind switch + { + "path" => new InputLroOperationIdPathMetadata( + source ?? throw new JsonException("Path operation ID must have a source."), + pathParameter ?? throw new JsonException("Path operation ID must have a path parameter."), + pollingPath ?? throw new JsonException("Path operation ID must have a polling path.")), + "property" => new InputLroOperationIdPropertyMetadata( + property ?? throw new JsonException("Property operation ID must have a property."), + propertySegments ?? throw new JsonException("Property 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/InputOperationLinkConverter.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputOperationLinkConverter.cs new file mode 100644 index 00000000000..fb2aa3e820b --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputOperationLinkConverter.cs @@ -0,0 +1,45 @@ +// 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) + { + if (!reader.TryReadString("location", ref location) + && !reader.TryReadComplexType("property", options, ref property)) + { + reader.SkipProperty(); + } + } + + if (location is null) + { + throw new JsonException("Operation link must have a location."); + } + var parsedLocation = Enum.TryParse(location, ignoreCase: true, out var value) && Enum.IsDefined(value) + ? value + : InputOperationLinkLocation.Unknown; + + return new InputOperationLink(parsedLocation, + property ?? throw new JsonException("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/InputPathParameterConverter.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputPathParameterConverter.cs index ab6e4c0956b..3f01656a510 100644 --- a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputPathParameterConverter.cs +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/src/InputTypes/Serialization/InputPathParameterConverter.cs @@ -64,6 +64,7 @@ internal static InputPathParameter ReadInputPathParameter(ref Utf8JsonReader rea bool isReadOnly = false; bool isOptional = false; string? access = null; + string? style = null; string? serverUrlTemplate = null; bool allowReserved = false; IReadOnlyList? decorators = null; @@ -88,6 +89,7 @@ internal static InputPathParameter ReadInputPathParameter(ref Utf8JsonReader rea || reader.TryReadComplexType("defaultValue", options, ref defaultValue) || reader.TryReadString("scope", ref scope) || reader.TryReadBoolean("explode", ref explode) + || reader.TryReadString("style", ref style) || reader.TryReadBoolean("skipUrlEncoding", ref skipUrlEncoding) || reader.TryReadComplexType("decorators", options, ref decorators) || reader.TryReadComplexType("methodParameterSegments", options, ref methodParameterSegments) @@ -115,6 +117,9 @@ internal static InputPathParameter ReadInputPathParameter(ref Utf8JsonReader rea parameter.DefaultValue = defaultValue; parameter.Scope = InputParameter.ParseScope(type, name, scope); parameter.Explode = explode; + parameter.Style = Enum.TryParse(style, ignoreCase: true, out var parsedStyle) && Enum.IsDefined(parsedStyle) + ? parsedStyle + : InputPathParameterStyle.Unknown; parameter.SkipUrlEncoding = skipUrlEncoding; parameter.MethodParameterSegments = methodParameterSegments; parameter.IsExactName = isExactName; 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..49761d08717 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,8 @@ public static class TypeSpecSerialization new InputPagingServiceMetadataConverter(), new InputLongRunningServiceMethodConverter(referenceHandler), new InputLongRunningServiceMetadataConverter(), + 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/InputServiceMethodTests.cs b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/InputServiceMethodTests.cs index d994b3342ba..c2bee9c8341 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; using Microsoft.TypeSpec.Generator.Tests.Common; using NUnit.Framework; @@ -8,6 +11,360 @@ namespace Microsoft.TypeSpec.Generator.Input.Tests { public class InputServiceMethodTests { + [Test] + public void LoadsEmittedLroMetadata() + { + var directory = Helpers.GetAssetFileOrDirectoryPath(false); + var input = TypeSpecSerialization.Deserialize(File.ReadAllText(Path.Combine(directory, "tspCodeModel.json")))!; + var methods = input.Clients.Single().Methods; + var polling = methods.Single(m => m.Name == "getStatus").Operation; + var metadata = ((InputLongRunningServiceMethod)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"); + Assert.AreSame(baseMonitor, monitor.BaseModel); + + Assert.AreEqual(2, metadata.OperationId.Count); + var path = (InputLroOperationIdPathMetadata)metadata.OperationId[0]; + var property = (InputLroOperationIdPropertyMetadata)metadata.OperationId[1]; + Assert.AreSame(polling.Parameters.Single(p => p.Name == "id"), path.PathParameter); + Assert.AreEqual("jobId", path.PathParameter.SerializedName); + Assert.AreEqual("/jobs/{jobId}/status", path.PollingPath); + Assert.AreEqual(InputOperationLinkLocation.ResponseHeader, path.Source.Location); + Assert.AreEqual("Operation-Location", path.Source.Property.SerializedName); + Assert.AreSame(baseMonitor.Properties.Single(p => p.Name == "jobId"), property.Property); + Assert.AreEqual("job_id", property.Property.SerializedName); + Assert.AreSame(property.Property, property.PropertySegments.Single()); + } + + [TestCase("simple", InputPathParameterStyle.Simple)] + [TestCase("label", InputPathParameterStyle.Label)] + [TestCase("matrix", InputPathParameterStyle.Matrix)] + [TestCase("path", InputPathParameterStyle.Path)] + [TestCase("fragment", InputPathParameterStyle.Fragment)] + [TestCase("future-style", InputPathParameterStyle.Unknown)] + [TestCase(null, InputPathParameterStyle.Unknown)] + public void LoadsPollingIdPathStyle(string? style, InputPathParameterStyle expected) + { + var directory = Helpers.GetAssetFileOrDirectoryPath(false, method: nameof(LoadsEmittedLroMetadata)); + var json = File.ReadAllText(Path.Combine(directory, "tspCodeModel.json")); + json = json.Replace("\"style\": \"simple\",", style == null ? "" : $"\"style\": \"{style}\","); + var input = TypeSpecSerialization.Deserialize(json)!; + var methods = input.Clients.Single().Methods; + var polling = methods.Single(m => m.Name == "getStatus").Operation; + var metadata = ((InputLongRunningServiceMethod)methods.Single(m => m.Name == "begin")) + .LongRunningServiceMetadata; + var selection = (InputLroOperationIdPathMetadata)metadata.OperationId[0]; + Assert.AreSame(polling.Parameters.Single(p => p.Name == "id"), selection.PathParameter); + Assert.AreEqual(expected, selection.PathParameter.Style); + } + + [TestCase("lro")] + [TestCase("lropaging")] + public void LoadsLongRunningMetadataWithTypedPathsAndOrderedIdSources(string methodKind) + { + var json = """ + { + "finalStateVia": 1, + "operationId": [{ + "kind": "path", + "source": { + "location": "ResponseHeader", + "property": { + "$id": "location", "name": "location", "serializedName": "Operation-Location", + "type": { "kind": "string" } + } + }, + "pathParameter": { + "$id": "parameter", "kind": "path", "name": "id", "serializedName": "jobId", + "type": { "kind": "string" }, "scope": "method" + }, + "pollingPath": "/jobs/{jobId}/status" + }, { + "kind": "property", + "property": { + "$id": "id", "name": "jobId", "serializedName": "job_id", + "type": { "kind": "string" } + }, + "propertySegments": [{ + "$id": "job", "name": "job", "serializedName": "job", + "type": { "kind": "string" } + }, { "$ref": "id" }] + }] + } + """; + var referenceHandler = new TypeSpecReferenceHandler(); + var options = new JsonSerializerOptions + { + Converters = + { + new InputLongRunningServiceMetadataConverter(), + new InputLroOperationIdMetadataConverter(), + new InputOperationLinkConverter(), + new InputModelPropertyConverter(referenceHandler), + new InputTypeConverter(referenceHandler), + new InputPrimitiveTypeConverter(referenceHandler), + new InputPathParameterConverter(referenceHandler), + new System.Text.Json.Serialization.JsonStringEnumConverter(JsonNamingPolicy.CamelCase), + } + }; + var metadata = JsonSerializer.Deserialize(json, options)!; + + Assert.AreEqual(2, metadata.OperationId.Count); + var path = (InputLroOperationIdPathMetadata)metadata.OperationId[0]; + Assert.AreEqual(InputOperationLinkLocation.ResponseHeader, path.Source.Location); + Assert.AreEqual("Operation-Location", path.Source.Property.SerializedName); + Assert.AreEqual("jobId", path.PathParameter.SerializedName); + Assert.AreEqual("/jobs/{jobId}/status", path.PollingPath); + var property = (InputLroOperationIdPropertyMetadata)metadata.OperationId[1]; + Assert.AreEqual("jobId", property.Property.Name); + Assert.AreEqual("job_id", property.Property.SerializedName); + CollectionAssert.AreEqual(new[] { "job", "job_id" }, property.PropertySegments.Select(p => p.SerializedName)); + Assert.AreSame(property.Property, property.PropertySegments[1]); + + var input = TypeSpecSerialization.Deserialize($$""" + { + "name": "Test", + "models": [{ + "$id": "monitor", "name": "Monitor", + "properties": [{ "$ref": "job" }, { "$ref": "id" }] + }], + "clients": [{ + "$id": "client", "name": "TestClient", + "methods": [{ + "$id": "begin", "kind": "{{methodKind}}", "name": "begin", + "crossLanguageDefinitionId": "Test.begin", + "operation": { + "$id": "operation", "name": "begin", "httpMethod": "POST", + "uri": "https://example.com", "path": "/jobs", + "crossLanguageDefinitionId": "Test.begin" + }, + "response": {}, + "pagingMetadata": { "itemPropertySegments": ["items"] }, + "lroMetadata": {{json}} + }] + }] + } + """)!; + var method = input.Clients.Single().Methods.Single(); + var registeredMetadata = method is InputLongRunningServiceMethod lro + ? lro.LongRunningServiceMetadata + : ((InputLongRunningPagingServiceMethod)method).LongRunningServiceMetadata; + var registeredProperty = (InputLroOperationIdPropertyMetadata)registeredMetadata.OperationId[1]; + Assert.AreSame(input.Models[0].Properties[0], registeredProperty.PropertySegments[0]); + Assert.AreSame(input.Models[0].Properties[1], registeredProperty.Property); + } + + [TestCase(true, true)] + [TestCase(false, true)] + [TestCase(true, false)] + [TestCase(false, false)] + public void ResolvesInheritedOperationIdAndPollingOperationReferences(bool pollingFirst, bool modelsFirst) + { + const string parameter = """ + { + "$id": "jobId", "kind": "path", "name": "id", "serializedName": "jobId", + "type": { "kind": "string" }, "scope": "method" + } + """; + const string reference = """{ "$ref": "jobId" }"""; + var pollingMethod = $$""" + { + "$id": "poll", "kind": "basic", "name": "getStatus", + "crossLanguageDefinitionId": "Test.getStatus", + "operation": { + "$id": "polling", "name": "getStatus", "httpMethod": "GET", + "uri": "https://example.com", "path": "/jobs/{jobId}/status", + "crossLanguageDefinitionId": "Test.getStatus", + "parameters": [{{(pollingFirst ? parameter : reference)}}] + }, + "response": {} + } + """; + var beginMethod = $$""" + { + "$id": "begin", "kind": "lro", "name": "begin", + "crossLanguageDefinitionId": "Test.begin", + "operation": { + "$id": "start", "name": "begin", "httpMethod": "POST", + "uri": "https://example.com", "path": "/jobs", + "crossLanguageDefinitionId": "Test.begin" + }, + "response": {}, + "lroMetadata": { + "finalStateVia": 1, + "operationId": [{ + "kind": "path", + "source": { "location": "ResponseBody", "property": { "$ref": "link" } }, + "pathParameter": {{(pollingFirst ? reference : parameter)}}, + "pollingPath": "/jobs/{jobId}/status" + }, { + "kind": "property", + "property": { "$ref": "inherited" }, + "propertySegments": [{ "$ref": "inherited" }] + }] + } + } + """; + var methodsJson = pollingFirst + ? $"{pollingMethod}, {beginMethod}" + : $"{beginMethod}, {pollingMethod}"; + const string modelsJson = """ + "models": [{ + "$id": "base", "name": "BaseMonitor", + "properties": [{ + "$id": "inherited", "name": "updated", "serializedName": "updated_at", + "type": { "kind": "string" } + }] + }, { + "$id": "monitor", "name": "Monitor", "baseModel": { "$ref": "base" }, + "properties": [] + }, { + "$id": "startResponse", "name": "StartResponse", + "properties": [{ + "$id": "link", "name": "location", "serializedName": "location", + "type": { "kind": "string" } + }] + }] + """; + var clientsJson = $$""" + "clients": [{ + "$id": "client", "name": "TestClient", + "methods": [{{methodsJson}}] + }] + """; + var input = TypeSpecSerialization.Deserialize($$""" + { + "name": "Test", + {{(modelsFirst ? $"{modelsJson}, {clientsJson}" : $"{clientsJson}, {modelsJson}")}} + } + """)!; + + var methods = input.Clients.Single().Methods; + var pollingOperation = methods.Single(m => m.Name == "getStatus").Operation; + var metadata = ((InputLongRunningServiceMethod)methods.Single(m => m.Name == "begin")) + .LongRunningServiceMetadata; + var path = (InputLroOperationIdPathMetadata)metadata.OperationId[0]; + var property = (InputLroOperationIdPropertyMetadata)metadata.OperationId[1]; + var baseModel = input.Models.Single(m => m.Name == "BaseMonitor"); + var monitor = input.Models.Single(m => m.Name == "Monitor"); + var startResponse = input.Models.Single(m => m.Name == "StartResponse"); + + Assert.AreSame(baseModel, monitor.BaseModel); + Assert.AreSame(baseModel.Properties[0], property.Property); + Assert.AreSame(baseModel.Properties[0], property.PropertySegments[0]); + Assert.AreSame(startResponse.Properties[0], path.Source.Property); + Assert.AreSame(pollingOperation.Parameters.Single(), path.PathParameter); + } + + [TestCase("ResponseHeader", InputOperationLinkLocation.ResponseHeader)] + [TestCase("ResponseBody", InputOperationLinkLocation.ResponseBody)] + [TestCase("Self", InputOperationLinkLocation.Self)] + [TestCase("FutureLocation", InputOperationLinkLocation.Unknown)] + public void LoadsOperationLinkLocations(string location, InputOperationLinkLocation expected) + { + var referenceHandler = new TypeSpecReferenceHandler(); + var options = new JsonSerializerOptions + { + Converters = + { + new InputOperationLinkConverter(), + new InputModelPropertyConverter(referenceHandler), + new InputTypeConverter(referenceHandler), + new InputPrimitiveTypeConverter(referenceHandler), + } + }; + var link = JsonSerializer.Deserialize($$""" + { + "location": "{{location}}", + "property": { "$id": "link", "name": "link", "type": { "kind": "string" } } + } + """, options)!; + + Assert.AreEqual(expected, link.Location); + } + + [TestCase("""{}""")] + [TestCase("""{ "location": null }""")] + public void RejectsOperationLinkWithoutLocation(string json) + { + var options = new JsonSerializerOptions + { + Converters = { new InputOperationLinkConverter() } + }; + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [TestCase("""{"kind":"future"}""")] + [TestCase("""{"kind":"path"}""")] + [TestCase("""{"kind":"property","propertySegments":[]}""")] + public void RejectsInvalidOperationIdMetadata(string json) + { + var options = new JsonSerializerOptions + { + Converters = { new InputLroOperationIdMetadataConverter() } + }; + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Test] + public void LoadsLegacyLongRunningMetadataWithoutSelections() + { + var options = new JsonSerializerOptions + { + Converters = { new InputLongRunningServiceMetadataConverter() } + }; + var metadata = JsonSerializer.Deserialize( + """{ "futureMetadata": { "values": [1, 2] }, "finalStateVia": 2, "resultPath": "result" }""", options)!; + + Assert.AreEqual(2, metadata.FinalStateVia); + Assert.AreEqual("result", metadata.ResultPath); + Assert.IsEmpty(metadata.OperationId); + Assert.IsEmpty(new InputLongRunningServiceMetadata().OperationId); + } + + [Test] + public void LoadsOperationIdPropertyFromUnemittedPollingModel() + { + var input = TypeSpecSerialization.Deserialize(""" + { + "name": "Test", + "models": [], + "clients": [{ + "$id": "client", "name": "TestClient", + "methods": [{ + "$id": "begin", "kind": "lro", "name": "begin", + "crossLanguageDefinitionId": "Test.begin", + "operation": { + "$id": "operation", "name": "begin", "httpMethod": "POST", + "uri": "https://example.com", "path": "/jobs", + "crossLanguageDefinitionId": "Test.begin" + }, + "response": {}, + "lroMetadata": { + "finalStateVia": 1, + "operationId": [{ + "kind": "property", + "property": { + "$id": "id", "name": "jobId", "serializedName": "job_id", + "type": { "kind": "string" } + }, + "propertySegments": [{ "$ref": "id" }] + }] + } + }] + }] + } + """)!; + var method = (InputLongRunningServiceMethod)input.Clients.Single().Methods.Single(); + var metadata = method.LongRunningServiceMetadata; + var selection = (InputLroOperationIdPropertyMetadata)metadata.OperationId.Single(); + + Assert.IsNull(selection.Property.EnclosingType); + Assert.AreEqual("job_id", selection.Property.SerializedName); + Assert.AreSame(selection.Property, selection.PropertySegments.Single()); + } + [Test] public void CanUpdateServiceMethodName() { diff --git a/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroMetadata/tspCodeModel.json b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroMetadata/tspCodeModel.json new file mode 100644 index 00000000000..8d6fd97c0fd --- /dev/null +++ b/packages/http-client-csharp/generator/Microsoft.TypeSpec.Generator.Input/test/TestData/InputServiceMethodTests/LoadsEmittedLroMetadata/tspCodeModel.json @@ -0,0 +1,546 @@ +{ + "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": "jobId", + "originalName": "id", + "apiVersions": [], + "serializedName": "job_id", + "type": { + "$id": "12", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture.BaseMonitor.id", + "serializationOptions": { + "json": { + "name": "job_id" + } + }, + "isHttpMetadata": false, + "isExactName": false + } + ] + }, + "properties": [ + { + "$id": "13", + "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": "14", + "kind": "property", + "name": "result", + "apiVersions": [], + "serializedName": "result", + "type": { + "$id": "15", + "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 + } + ] + }, + { + "$ref": "10" + } + ], + "clients": [ + { + "$id": "16", + "kind": "client", + "name": "LroFixtureClient", + "isExactName": false, + "namespace": "LroFixture", + "methods": [ + { + "$id": "17", + "kind": "basic", + "name": "getStatus", + "isExactName": false, + "accessibility": "public", + "apiVersions": [], + "operation": { + "$id": "18", + "name": "getStatus", + "isExactName": false, + "accessibility": "public", + "parameters": [ + { + "$id": "19", + "kind": "path", + "name": "id", + "serializedName": "jobId", + "type": { + "$id": "20", + "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.id", + "methodParameterSegments": [ + { + "$id": "21", + "kind": "method", + "name": "id", + "serializedName": "jobId", + "type": { + "$id": "22", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "optional": false, + "scope": "Method", + "crossLanguageDefinitionId": "LroFixture.getStatus.id", + "readOnly": false, + "access": "public", + "decorators": [], + "isExactName": false + } + ], + "isExactName": false + }, + { + "$id": "23", + "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": "24", + "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": "21" + }, + { + "$ref": "24" + } + ], + "response": { + "type": { + "$ref": "9" + } + }, + "isOverride": false, + "generateConvenient": true, + "generateProtocol": true, + "crossLanguageDefinitionId": "LroFixture.getStatus" + }, + { + "$id": "25", + "kind": "lro", + "name": "begin", + "isExactName": false, + "accessibility": "internal", + "apiVersions": [], + "operation": { + "$id": "26", + "name": "begin", + "isExactName": false, + "accessibility": "internal", + "parameters": [], + "responses": [ + { + "statusCodes": [ + 202 + ], + "headers": [ + { + "name": "location", + "nameInResponse": "Operation-Location", + "type": { + "$id": "27", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "28", + "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": "29", + "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", + "operationId": [ + { + "$id": "30", + "kind": "path", + "source": { + "location": "ResponseHeader", + "property": { + "$id": "31", + "kind": "property", + "name": "location", + "apiVersions": [], + "serializedName": "Operation-Location", + "type": { + "$id": "32", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "33", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "LroFixture..anonymous.location", + "serializationOptions": {}, + "isHttpMetadata": true, + "isExactName": false + } + }, + "pathParameter": { + "$ref": "19" + }, + "pollingPath": "/jobs/{jobId}/status" + }, + { + "$id": "34", + "kind": "property", + "property": { + "$ref": "11" + }, + "propertySegments": [ + { + "$ref": "11" + } + ] + } + ] + } + } + ], + "parameters": [ + { + "$id": "35", + "kind": "endpoint", + "name": "endpoint", + "serializedName": "endpoint", + "doc": "Service host", + "type": { + "$id": "36", + "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 + } + ] +}