diff --git a/.chronus/changes/java-tcgc-lro-metadata-2026-10-12-17-55-0.md b/.chronus/changes/java-tcgc-lro-metadata-2026-10-12-17-55-0.md new file mode 100644 index 00000000000..50d5f2d6aa5 --- /dev/null +++ b/.chronus/changes/java-tcgc-lro-metadata-2026-10-12-17-55-0.md @@ -0,0 +1,12 @@ +--- +changeKind: feature +packages: + - "@typespec/http-client-java" +--- + +Expose the LRO operation ID selected by `@lroOperationId` on supported typed poll-result models via `getOperationId()`. The poll-result model is available once a status response with a body is received; its body property takes precedence over the polling URL path. Polling continues to use the complete polling URL. + +```java +SyncPoller poller = client.beginAnalyze("document-1"); +String operationId = poller.poll().getValue().getOperationId(); +``` diff --git a/packages/http-client-java/emitter/src/code-model-builder.ts b/packages/http-client-java/emitter/src/code-model-builder.ts index 58a4d04e221..3cca8ab6719 100644 --- a/packages/http-client-java/emitter/src/code-model-builder.ts +++ b/packages/http-client-java/emitter/src/code-model-builder.ts @@ -17,6 +17,7 @@ import type { SdkHttpOperation, SdkHttpResponse, SdkLroPagingServiceMethod, + SdkLroServiceMetadata, SdkLroServiceMethod, SdkMethodResponse, SdkModelPropertyType, @@ -65,7 +66,7 @@ import { } from "@typespec/compiler"; import { $ } from "@typespec/compiler/typekit"; import type { Authentication, HttpStatusCodeRange, HttpStatusCodesEntry } from "@typespec/http"; -import { Visibility, getAuthentication } from "@typespec/http"; +import { Visibility, getAuthentication, getHeaderFieldName } from "@typespec/http"; import type {} from "@typespec/http-client/typekit"; import { getSegment } from "@typespec/rest"; import { getAddedOnVersions } from "@typespec/versioning"; @@ -83,7 +84,10 @@ import { } from "./common/client.js"; import type { CodeModel } from "./common/code-model.js"; import { addGlobalParameter, createCodeModel } from "./common/code-model.js"; -import type { LongRunningMetadata } from "./common/long-running-metadata.js"; +import type { + LongRunningMetadata, + LongRunningOperationIdMetadata, +} from "./common/long-running-metadata.js"; import { createLongRunningMetadata } from "./common/long-running-metadata.js"; import type { Operation as CodeModelOperation, Request, SseMetadata } from "./common/operation.js"; import { @@ -1786,12 +1790,42 @@ export class CodeModelBuilder { } } + // operation ID, only for poll result model (not the PollOperationDetails, which already has it) + let operationId: LongRunningOperationIdMetadata | undefined = undefined; + if (pollingSchema && pollingSchema !== this._pollResultSchema) { + operationId = this.processLroOperationIdMetadata(lroMetadata); + if (operationId) { + pollingSchema.extensions = pollingSchema.extensions ?? {}; + const previous = pollingSchema.extensions["x-ms-lro-operation-id"] as + LongRunningOperationIdMetadata | undefined; + if ( + previous?.propertySerializedName && + operationId.propertySerializedName && + previous.propertySerializedName !== operationId.propertySerializedName + ) { + reportDiagnostic(this.program, { + code: "generator-error", + format: { + errorMessage: + "Long-running operations using the same status model select different operation ID properties.", + }, + target: lroMetadata.operation.__raw?.operation ?? NoTarget, + }); + } + pollingSchema.extensions["x-ms-lro-operation-id"] = { + ...operationId, + ...previous, + }; + } + } + op.lroMetadata = createLongRunningMetadata( true, pollingSchema, finalSchema, pollingStrategy, finalResultPropertySerializedName, + operationId, ); return op.lroMetadata; } @@ -1799,6 +1833,65 @@ export class CodeModelBuilder { return createLongRunningMetadata(false); } + private processLroOperationIdMetadata( + lroMetadata: SdkLroServiceMetadata, + ): LongRunningOperationIdMetadata | undefined { + if (!lroMetadata.operationId || lroMetadata.operationId.length === 0) { + return undefined; + } + const operationId: LongRunningOperationIdMetadata = {}; + for (const selection of lroMetadata.operationId) { + if (selection.kind === "path") { + const statusMonitorStep = lroMetadata.statusMonitorStep; + const selectedLink = + statusMonitorStep?.kind === "nextOperationReference" + ? statusMonitorStep.target.link + : statusMonitorStep?.target; + const statusMonitorOperation = + selectedLink === selection.source + ? statusMonitorStep?.kind === "nextOperationReference" + ? statusMonitorStep.target.operation + : statusMonitorStep?.operation + : undefined; + const source = selection.source; + const header = source.property.__raw; + if ( + statusMonitorOperation && + source.location === "ResponseHeader" && + header && + statusMonitorOperation.path.includes(`{${selection.pathParameter.serializedName}}`) + ) { + operationId.pathTemplate = statusMonitorOperation.path; + operationId.pathParameterSerializedName = selection.pathParameter.serializedName; + operationId.pollingHeaderName = getHeaderFieldName(this.program, header).toLowerCase(); + } else { + reportDiagnostic(this.program, { + code: "generator-warning", + format: { + warningMessage: + "Cannot expose the long-running operation ID from the selected polling URL: its header or status-monitor path could not be resolved.", + }, + target: selection.pathParameter.__raw ?? NoTarget, + }); + } + } else if (selection.kind === "property" && selection.propertySegments.length === 1) { + // nested property is not supported, TCGC currently only provides a single segment + operationId.propertySerializedName = getPropertySerializedName( + selection.propertySegments[0], + ); + } else if (selection.kind === "property") { + reportDiagnostic(this.program, { + code: "generator-warning", + format: { + warningMessage: "Nested long-running operation ID properties are not supported.", + }, + target: selection.property.__raw ?? NoTarget, + }); + } + } + return operationId.pathTemplate || operationId.propertySerializedName ? operationId : undefined; + } + private processRouteForLongRunning(op: CodeModelOperation, lroMetadata: LongRunningMetadata) { if (lroMetadata.longRunning) { op.extensions = op.extensions ?? {}; diff --git a/packages/http-client-java/emitter/src/common/long-running-metadata.ts b/packages/http-client-java/emitter/src/common/long-running-metadata.ts index 6b6936db462..ff7c1aa3972 100644 --- a/packages/http-client-java/emitter/src/common/long-running-metadata.ts +++ b/packages/http-client-java/emitter/src/common/long-running-metadata.ts @@ -1,11 +1,27 @@ import type { Metadata, Schema } from "./schemas/model.js"; +/** + * Server-issued LRO operation ID sources selected by `@lroOperationId`. + * The polling URL path parameter is used until the status-monitor body property is available. + */ +export interface LongRunningOperationIdMetadata { + /** Route template of the status-monitor operation, used to extract the path parameter from the polling URL. */ + pathTemplate?: string; + /** Name of the path parameter in "pathTemplate". */ + pathParameterSerializedName?: string; + /** Name of the response header containing the polling URL. */ + pollingHeaderName?: string; + /** Serialized name of the status-monitor response property. */ + propertySerializedName?: string; +} + export interface LongRunningMetadata { longRunning: boolean; pollResultType?: Schema; finalResultType?: Schema; pollingStrategy?: Metadata; finalResultPropertySerializedName?: string; + operationId?: LongRunningOperationIdMetadata; } export function createLongRunningMetadata( @@ -14,6 +30,7 @@ export function createLongRunningMetadata( finalResultType?: Schema, pollingStrategy?: Metadata, finalResultPropertySerializedName?: string, + operationId?: LongRunningOperationIdMetadata, ): LongRunningMetadata { return { longRunning, @@ -21,5 +38,6 @@ export function createLongRunningMetadata( finalResultType, pollingStrategy, finalResultPropertySerializedName, + operationId, }; } diff --git a/packages/http-client-java/emitter/test/code-model.test.ts b/packages/http-client-java/emitter/test/code-model.test.ts index cb3cc438a1d..8603f13f16d 100644 --- a/packages/http-client-java/emitter/test/code-model.test.ts +++ b/packages/http-client-java/emitter/test/code-model.test.ts @@ -153,6 +153,55 @@ describe("ARM internal access", () => { }); }); +describe("LRO operation ID metadata", () => { + it("uses the selected polling link and preserves both operation ID sources", async () => { + const program = await compile( + NodeHost, + fileURLToPath(new URL("./fixtures/lro-operation-id.tsp", import.meta.url)), + { noEmit: true }, + ); + expectDiagnosticEmpty(program.diagnostics); + const model = await new CodeModelBuilder(program, { + program, + emitterOutputDir: "/code-model-test-output", + options: { flavor: "azure", "dev-options": {} }, + perf: { + startTimer: () => ({ end: () => 0 }), + time: (_label, callback) => callback(), + timeAsync: (_label, callback) => callback(), + report: () => {}, + }, + }).build(); + expectDiagnosticEmpty(program.diagnostics); + const operations = model.clients.flatMap((client) => + client.operationGroups.flatMap((group) => group.operations ?? []), + ); + const path = operations.find((operation) => operation.operationId === "analyze")!; + const both = operations.find( + (operation) => operation.operationId === "startTranslationWithPath", + )!; + const body = operations.find((operation) => operation.operationId === "startBodyOnly")!; + expect(path.lroMetadata?.operationId).toMatchObject({ + pathParameterSerializedName: "resultId", + pollingHeaderName: "operation-location", + }); + expect(both.lroMetadata?.operationId).toMatchObject({ + pathParameterSerializedName: "operationId", + propertySerializedName: "id", + pollingHeaderName: "operation-location", + }); + expect(both.lroMetadata?.pollResultType?.extensions?.["x-ms-lro-operation-id"]).toMatchObject({ + pathParameterSerializedName: "operationId", + propertySerializedName: "id", + }); + expect(body.lroMetadata?.operationId).toMatchObject({ propertySerializedName: "id" }); + expect(body.lroMetadata?.pollResultType?.extensions?.["x-ms-lro-operation-id"]).toMatchObject({ + pathParameterSerializedName: "operationId", + propertySerializedName: "id", + }); + }); +}); + describe("advanced versioning", () => { it.each([true, false])("preserves parameter additions only when enabled=%s", async (enabled) => { const program = await compile( diff --git a/packages/http-client-java/emitter/test/fixtures/lro-operation-id.tsp b/packages/http-client-java/emitter/test/fixtures/lro-operation-id.tsp new file mode 100644 index 00000000000..9cff2a442b5 --- /dev/null +++ b/packages/http-client-java/emitter/test/fixtures/lro-operation-id.tsp @@ -0,0 +1,57 @@ +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-client-generator-core"; + +using TypeSpec.Http; +using Azure.Core; +using Azure.ClientGenerator.Core; + +@service +@route("/lro") +namespace LroOperationIdTest; + +model Result { + value: string; +} + +model PathStatus { + status: Azure.Core.Foundations.OperationState; + result?: Result; +} + +@get +@route("/path/{resultId}") +op getPathStatus(@lroOperationId @path resultId: string): PathStatus; + +@post +@route("/analyze") +@pollingOperation(getPathStatus) +op analyze(): Azure.Core.Foundations.AcceptedResponse & + Azure.Core.Foundations.LongRunningStatusLocation; + +model CombinedStatus { + @lroOperationId + id: string; + + status: Azure.Core.Foundations.OperationState; + result?: Result; +} + +@get +@route("/combined/{operationId}") +op getCombinedStatus(@lroOperationId @path operationId: string): CombinedStatus; + +@post +@route("/start") +@pollingOperation(getCombinedStatus) +op startTranslationWithPath(): Azure.Core.Foundations.AcceptedResponse & + Azure.Core.Foundations.LongRunningStatusLocation; + +@get +@route("/body-only") +op getBodyOnlyStatus(): CombinedStatus; + +@post +@route("/start-body-only") +@pollingOperation(getBodyOnlyStatus) +op startBodyOnly(): Azure.Core.Foundations.AcceptedResponse & + Azure.Core.Foundations.LongRunningStatusLocation; diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/CodeModelCustomConstructor.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/CodeModelCustomConstructor.java index 8beb6e167bc..4bcb6e5ca54 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/CodeModelCustomConstructor.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/CodeModelCustomConstructor.java @@ -380,6 +380,13 @@ protected Object constructJavaBean2ndStep(MappingNode mappingNode, Object object new ScalarNode(keyNode.getTag(), "xmsArmIdDetails", keyNode.getStartMark(), keyNode.getEndMark(), keyNode.getScalarStyle()), extension.getValueNode())); + } else if ("x-ms-lro-operation-id".equals(keyNode.getValue())) { + actualValues + .add( + new NodeTuple( + new ScalarNode(keyNode.getTag(), "xmsLroOperationId", + keyNode.getStartMark(), keyNode.getEndMark(), keyNode.getScalarStyle()), + extension.getValueNode())); } else if ("x-ms-secret".equals(keyNode.getValue())) { actualValues.add( new NodeTuple(new ScalarNode(keyNode.getTag(), "xmsSecret", keyNode.getStartMark(), diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/LongRunningMetadata.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/LongRunningMetadata.java index ac2d944537d..16e2550fc98 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/LongRunningMetadata.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/LongRunningMetadata.java @@ -11,6 +11,7 @@ public class LongRunningMetadata { private Schema finalResultType; private Metadata pollingStrategy; private String finalResultPropertySerializedName; + private LongRunningOperationIdMetadata operationId; /** * Creates a new instance of the LongRunningMetadata class. @@ -89,4 +90,22 @@ public String getFinalResultPropertySerializedName() { public void setFinalResultPropertySerializedName(String finalResultPropertySerializedName) { this.finalResultPropertySerializedName = finalResultPropertySerializedName; } + + /** + * Gets the sources of the operation ID. + * + * @return the sources of the operation ID. + */ + public LongRunningOperationIdMetadata getOperationId() { + return operationId; + } + + /** + * Sets the sources of the operation ID. + * + * @param operationId the sources of the operation ID. + */ + public void setOperationId(LongRunningOperationIdMetadata operationId) { + this.operationId = operationId; + } } diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/LongRunningOperationIdMetadata.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/LongRunningOperationIdMetadata.java new file mode 100644 index 00000000000..ac7df68c611 --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/LongRunningOperationIdMetadata.java @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.typespec.http.client.generator.core.extension.model.codemodel; + +/** + * Represents the sources of the operation ID of a long-running operation. + *

+ * The path parameter in the polling URL is used until the property on the status monitor response is available. + */ +public class LongRunningOperationIdMetadata { + private String pathTemplate; + private String pathParameterSerializedName; + private String pollingHeaderName; + private String propertySerializedName; + + /** + * Creates a new instance of the LongRunningOperationIdMetadata class. + */ + public LongRunningOperationIdMetadata() { + } + + /** + * Gets the path template of the status monitor operation. + * + * @return the path template of the status monitor operation. + */ + public String getPathTemplate() { + return pathTemplate; + } + + /** + * Sets the path template of the status monitor operation. + * + * @param pathTemplate the path template of the status monitor operation. + */ + public void setPathTemplate(String pathTemplate) { + this.pathTemplate = pathTemplate; + } + + /** + * Gets the name of the path parameter that is the operation ID. + * + * @return the name of the path parameter that is the operation ID. + */ + public String getPathParameterSerializedName() { + return pathParameterSerializedName; + } + + /** + * Sets the name of the path parameter that is the operation ID. + * + * @param pathParameterSerializedName the name of the path parameter that is the operation ID. + */ + public void setPathParameterSerializedName(String pathParameterSerializedName) { + this.pathParameterSerializedName = pathParameterSerializedName; + } + + /** + * Gets the response header containing the polling URL. + * + * @return the polling URL header name. + */ + public String getPollingHeaderName() { + return pollingHeaderName; + } + + /** + * Sets the response header containing the polling URL. + * + * @param pollingHeaderName the polling URL header name. + */ + public void setPollingHeaderName(String pollingHeaderName) { + this.pollingHeaderName = pollingHeaderName; + } + + /** + * Gets the serialized name of the status monitor response property that is the operation ID. + * + * @return the serialized name of the status monitor response property that is the operation ID. + */ + public String getPropertySerializedName() { + return propertySerializedName; + } + + /** + * Sets the serialized name of the status monitor response property that is the operation ID. + * + * @param propertySerializedName the serialized name of the status monitor response property. + */ + public void setPropertySerializedName(String propertySerializedName) { + this.propertySerializedName = propertySerializedName; + } + + /** + * Whether the operation ID is extracted from the path of the polling URL. + * + * @return whether the operation ID is extracted from the path of the polling URL. + */ + public boolean hasPathSource() { + return pathTemplate != null && pathParameterSerializedName != null && pollingHeaderName != null; + } +} diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/extensionmodel/XmsExtensions.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/extensionmodel/XmsExtensions.java index 7c5e66fd22a..222763c504f 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/extensionmodel/XmsExtensions.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/extensionmodel/XmsExtensions.java @@ -3,6 +3,7 @@ package com.microsoft.typespec.http.client.generator.core.extension.model.extensionmodel; +import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.LongRunningOperationIdMetadata; import java.util.List; /** @@ -25,6 +26,7 @@ public class XmsExtensions { private XmsExamples xmsExamples; private Boolean xmsSecret; private List xmsVersioningAdded; + private LongRunningOperationIdMetadata xmsLroOperationId; /** * Creates a new instance of the XmsExtensions class. @@ -320,4 +322,22 @@ public List getXmsVersioningAdded() { public void setXmsVersioningAdded(List xmsVersioningAdded) { this.xmsVersioningAdded = xmsVersioningAdded; } + + /** + * Gets the sources of the long-running operation ID, for the status monitor model. + * + * @return the sources of the long-running operation ID. + */ + public LongRunningOperationIdMetadata getXmsLroOperationId() { + return xmsLroOperationId; + } + + /** + * Sets the sources of the long-running operation ID, for the status monitor model. + * + * @param xmsLroOperationId the sources of the long-running operation ID. + */ + public void setXmsLroOperationId(LongRunningOperationIdMetadata xmsLroOperationId) { + this.xmsLroOperationId = xmsLroOperationId; + } } diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/ModelMapper.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/ModelMapper.java index 27e247d6d37..e2c0cf1fbce 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/ModelMapper.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/ModelMapper.java @@ -371,6 +371,12 @@ public ClientModel map(ObjectSchema compositeType) { .crossLanguageDefinitionId(SchemaUtil.getCrossLanguageDefinitionId(compositeType)) .experimental(SchemaUtil.getExperimental(compositeType)) .build()); + if (settings.isAzureV1() + && !settings.isFluent() + && compositeType.getExtensions() != null + && compositeType.getExtensions().getXmsLroOperationId() != null) { + builder.lroOperationId(compositeType.getExtensions().getXmsLroOperationId()); + } result = builder.build(); diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/PollingMetadata.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/PollingMetadata.java index ac1d3b7692b..7f6f8f858af 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/PollingMetadata.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/PollingMetadata.java @@ -4,6 +4,7 @@ package com.microsoft.typespec.http.client.generator.core.mapper; import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.LongRunningMetadata; +import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.LongRunningOperationIdMetadata; import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.Operation; import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings; import com.microsoft.typespec.http.client.generator.core.extension.plugin.PollingSettings; @@ -14,6 +15,7 @@ import com.microsoft.typespec.http.client.generator.core.model.clientmodel.MethodPollingDetails; import com.microsoft.typespec.http.client.generator.core.model.clientmodel.PrimitiveType; import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ProxyMethod; +import com.microsoft.typespec.http.client.generator.core.util.ClientModelUtil; import com.microsoft.typespec.http.client.generator.core.util.MethodUtil; import io.clientcore.core.http.models.HttpMethod; @@ -28,6 +30,7 @@ final class PollingMetadata { private final IType finalResultType; private final int pollIntervalInSeconds; private final HttpMethod httpMethod; + private final LongRunningOperationIdMetadata operationId; /** * Creates long-running polling metadata for an {@link Operation}. @@ -56,7 +59,7 @@ static PollingMetadata create(Operation operation, ProxyMethod proxyMethod, ITyp if (settings.isFluent()) { return new PollingMetadata(pollingSettings.getPollingStrategy(), pollingSettings.getSyncPollingStrategy(), operationResponseType.asNullable(), - operationResponseType.asNullable(), pollingSettings.getPollIntervalInSeconds(), httpMethod); + operationResponseType.asNullable(), pollingSettings.getPollIntervalInSeconds(), httpMethod, null); } final IType pollResultType = getPollResultType(pollingSettings, operationResponseType); @@ -67,7 +70,7 @@ static PollingMetadata create(Operation operation, ProxyMethod proxyMethod, ITyp finalResultType = getFinalResultType(pollingSettings, operationResponseType); } return new PollingMetadata(pollingSettings.getPollingStrategy(), pollingSettings.getSyncPollingStrategy(), - pollResultType, finalResultType, pollingSettings.getPollIntervalInSeconds(), httpMethod); + pollResultType, finalResultType, pollingSettings.getPollIntervalInSeconds(), httpMethod, null); } else { // Create 'PollingMetadata' from TypeSpec long-running metadata. // Note: Only TypeSpec would have 'Operation::LongRunningMetadata' available. @@ -87,6 +90,23 @@ static PollingMetadata create(Operation operation, ProxyMethod proxyMethod, ITyp * @return the polling metadata. */ MethodPollingDetails asMethodPollingDetails() { + if (operationId != null && operationId.hasPathSource()) { + // Wrap the polling strategy to populate the operation ID on the poll result, from the polling URL. + final JavaSettings settings = JavaSettings.getInstance(); + final String packageName = settings.getPackage(settings.getImplementationSubpackage()); + final String pathTemplateArg = ClassType.STRING.defaultValueExpression(operationId.getPathTemplate()); + final String pathParameterArg + = ClassType.STRING.defaultValueExpression(operationId.getPathParameterSerializedName()); + final String headerArg = ClassType.STRING.defaultValueExpression(operationId.getPollingHeaderName()); + final String operationIdPollingStrategy = String.format("new %s.%s<>(%s, %s, %s, %s)", packageName, + ClientModelUtil.OPERATION_ID_POLLING_STRATEGY, pollingStrategy, pathTemplateArg, pathParameterArg, + headerArg); + final String syncOperationIdPollingStrategy = String.format("new %s.%s<>(%s, %s, %s, %s)", packageName, + ClientModelUtil.SYNC_OPERATION_ID_POLLING_STRATEGY, syncPollingStrategy, pathTemplateArg, + pathParameterArg, headerArg); + return new MethodPollingDetails(operationIdPollingStrategy, syncOperationIdPollingStrategy, pollResultType, + finalResultType, pollIntervalInSeconds); + } return new MethodPollingDetails(pollingStrategy, syncPollingStrategy, pollResultType, finalResultType, pollIntervalInSeconds); } @@ -236,8 +256,12 @@ private static PollingMetadata create(LongRunningMetadata lroMetadata, PollingSe syncPollingStrategy = pollingSettings.getSyncPollingStrategy(); } + // The operation ID is only populated on the poll result model generated from TypeSpec, for azure-core. + final LongRunningOperationIdMetadata operationId + = ClientModelUtil.supportsLroOperationId(settings, pollingSettings) ? lroMetadata.getOperationId() : null; + return new PollingMetadata(pollingStrategy, syncPollingStrategy, pollResultType, finalResultType, - pollingSettings.getPollIntervalInSeconds(), httpMethod); + pollingSettings.getPollIntervalInSeconds(), httpMethod, operationId); } private static IType createTypeFromModelName(String modelName) { @@ -257,12 +281,14 @@ private static IType createTypeFromModelName(String modelName) { } private PollingMetadata(String pollingStrategy, String syncPollingStrategy, IType pollResultType, - IType finalResultType, int pollIntervalInSeconds, HttpMethod httpMethod) { + IType finalResultType, int pollIntervalInSeconds, HttpMethod httpMethod, + LongRunningOperationIdMetadata operationId) { this.pollResultType = pollResultType; this.finalResultType = finalResultType; this.pollingStrategy = pollingStrategy; this.syncPollingStrategy = syncPollingStrategy; this.pollIntervalInSeconds = pollIntervalInSeconds; this.httpMethod = httpMethod; + this.operationId = operationId; } } diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/ProxyMethodMapper.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/ProxyMethodMapper.java index a1685ba1433..21c63bf6e1e 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/ProxyMethodMapper.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/mapper/ProxyMethodMapper.java @@ -104,7 +104,7 @@ public Map> map(Operation operation) { * @param settings the settings that may use to resolve the operation id. * @return the operation id. */ - private String getOperationId(Operation operation, JavaSettings settings) { + public String getOperationId(Operation operation, JavaSettings settings) { if (!CoreUtils.isNullOrEmpty(operation.getOperationId())) { return operation.getOperationId(); } diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/model/clientmodel/ClientModel.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/model/clientmodel/ClientModel.java index eb3b0c9c909..104451cb51f 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/model/clientmodel/ClientModel.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/model/clientmodel/ClientModel.java @@ -3,6 +3,7 @@ package com.microsoft.typespec.http.client.generator.core.model.clientmodel; +import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.LongRunningOperationIdMetadata; import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings; import com.microsoft.typespec.http.client.generator.core.util.ClientModelUtil; import com.microsoft.typespec.http.client.generator.core.util.ExperimentalAnnotationUtil; @@ -128,6 +129,11 @@ public class ClientModel { */ private final ApiMetadata apiMetadata; + /** + * The sources of the long-running operation ID, if this model is the poll result of a long-running operation. + */ + private final LongRunningOperationIdMetadata lroOperationId; + private final SseModelMetadata sseMetadata; // Set of non-final properties that are set on access. @@ -175,6 +181,7 @@ public class ClientModel { * @param implementationDetails The implementation details for the model. * @param usedInXml Whether the model is used in XML serialization. * @param apiMetadata The API metadata for the model. + * @param lroOperationId The sources of the long-running operation ID. */ protected ClientModel(String packageKeyword, String name, List imports, String description, boolean isPolymorphic, ClientModelProperty polymorphicDiscriminator, String polymorphicDiscriminatorName, @@ -182,7 +189,7 @@ protected ClientModel(String packageKeyword, String name, List imports, String xmlName, String xmlNamespace, List properties, List propertyReferences, IType modelType, boolean stronglyTypedHeader, ImplementationDetails implementationDetails, boolean usedInXml, Set serializationFormats, - ApiMetadata apiMetadata, SseModelMetadata sseMetadata) { + ApiMetadata apiMetadata, SseModelMetadata sseMetadata, LongRunningOperationIdMetadata lroOperationId) { this.packageName = packageKeyword; this.name = name; this.fullName = packageName + "." + name; @@ -206,6 +213,7 @@ protected ClientModel(String packageKeyword, String name, List imports, this.implementationDetails = implementationDetails; this.usedInXml = usedInXml; this.apiMetadata = apiMetadata; + this.lroOperationId = lroOperationId; this.serializationFormats = serializationFormats; this.sseMetadata = sseMetadata; } @@ -223,6 +231,15 @@ public SseModelMetadata getSseMetadata() { return sseMetadata; } + /** + * Gets the sources of the long-running operation ID, if this model is the poll result of a long-running operation. + * + * @return the sources of the long-running operation ID, or null. + */ + public LongRunningOperationIdMetadata getLroOperationId() { + return lroOperationId; + } + /** * Gets the package that this model class belongs to. * @@ -692,6 +709,7 @@ public static class Builder { private boolean usedInXml; private ApiMetadata apiMetadata = new ApiMetadata.Builder().build(); private Set serializationFormats = Set.of(); + private LongRunningOperationIdMetadata lroOperationId; private SseModelMetadata sseMetadata; /** @@ -908,6 +926,17 @@ public Builder apiMetadata(ApiMetadata apiMetadata) { return this; } + /** + * Sets the sources of the long-running operation ID. + * + * @param lroOperationId the sources of the long-running operation ID. + * @return the Builder itself + */ + public Builder lroOperationId(LongRunningOperationIdMetadata lroOperationId) { + this.lroOperationId = lroOperationId; + return this; + } + /** * Sets the Set of serialization format of this model. * @@ -933,7 +962,7 @@ public ClientModel build() { return new ClientModel(packageName, name, imports, description, isPolymorphic, polymorphicDiscriminator, polymorphicDiscriminatorName, serializedName, needsFlatten, parentModelName, derivedModels, xmlName, xmlNamespace, properties, propertyReferences, modelType, stronglyTypedHeader, implementationDetails, - usedInXml, serializationFormats, apiMetadata, sseMetadata); + usedInXml, serializationFormats, apiMetadata, sseMetadata, lroOperationId); } } } diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/template/ModelTemplate.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/template/ModelTemplate.java index 94be2674bc6..9c7237333b7 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/template/ModelTemplate.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/template/ModelTemplate.java @@ -27,6 +27,7 @@ import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaJavadocComment; import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaModifier; import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaVisibility; +import com.microsoft.typespec.http.client.generator.core.template.util.LroOperationIdModelHelper; import com.microsoft.typespec.http.client.generator.core.template.util.ModelTemplateHeaderHelper; import com.microsoft.typespec.http.client.generator.core.util.ClientModelUtil; import com.microsoft.typespec.http.client.generator.core.util.ExperimentalAnnotationUtil; @@ -82,9 +83,11 @@ public final void write(ClientModel model, JavaFile javaFile) { JavaSettings settings = JavaSettings.getInstance(); ClientModelPropertiesManager propertiesManager = new ClientModelPropertiesManager(model, settings); + LroOperationIdModelHelper lroOperationId = new LroOperationIdModelHelper(model, this::addGeneratedAnnotation); Set imports = settings.isStreamStyleSerialization() ? new StreamStyleImports() : new LinkedHashSet<>(); addImports(imports, model, settings); + lroOperationId.addImports(imports, settings); List propertyReferences = this.getClientModelPropertyReferences(model); propertyReferences.forEach(p -> p.addImportsTo(imports, false)); @@ -154,6 +157,7 @@ public final void write(ClientModel model, JavaFile javaFile) { // properties addProperties(propertiesManager, classBlock); + lroOperationId.addField(classBlock); // add jsonMergePatch related properties and accessors if (ClientModelUtil.isJsonMergePatchModel(model, settings)) { @@ -176,7 +180,9 @@ public final void write(ClientModel model, JavaFile javaFile) { if (!property.isPolymorphicDiscriminator() || PolymorphicDiscriminatorHandler.generateGetter(model, property, settings)) { - generateGetterJavadoc(classBlock, property); + if (!lroOperationId.writeGetterJavadoc(classBlock, property)) { + generateGetterJavadoc(classBlock, property); + } addGeneratedAnnotation(classBlock); if (property.isAdditionalProperties() && !settings.isStreamStyleSerialization()) { classBlock.annotation("JsonAnyGetter"); @@ -191,9 +197,12 @@ public final void write(ClientModel model, JavaFile javaFile) { } ExperimentalAnnotationUtil.write(classBlock, property.getApiMetadata()); classBlock.method(methodVisibility, null, - propertyClientType + " " + getGetterName(model, property) + "()", - methodBlock -> addGetterMethod(propertyWireType, propertyClientType, property, treatAsXml, - methodBlock, settings)); + propertyClientType + " " + getGetterName(model, property) + "()", methodBlock -> { + if (!lroOperationId.writeGetterBody(methodBlock, property)) { + addGetterMethod(propertyWireType, propertyClientType, property, treatAsXml, methodBlock, + settings); + } + }); } if (ClientModelUtil.needsPublicSetter(property, settings) && !immutableModel) { @@ -260,6 +269,8 @@ public final void write(ClientModel model, JavaFile javaFile) { } } + lroOperationId.addAccessors(classBlock); + if (settings.getClientFlattenAnnotationTarget() == JavaSettings.ClientFlattenAnnotationTarget.NONE) { // reference to properties from flattened client model for (ClientModelPropertyReference propertyReference : propertyReferences) { diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/template/util/LroOperationIdModelHelper.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/template/util/LroOperationIdModelHelper.java new file mode 100644 index 00000000000..a27aa0050e1 --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/template/util/LroOperationIdModelHelper.java @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.typespec.http.client.generator.core.template.util; + +import com.microsoft.typespec.http.client.generator.core.Javagen; +import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.LongRunningOperationIdMetadata; +import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings; +import com.microsoft.typespec.http.client.generator.core.extension.plugin.PluginLogger; +import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClassType; +import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClientModel; +import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClientModelProperty; +import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaBlock; +import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaClass; +import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaContext; +import com.microsoft.typespec.http.client.generator.core.util.ClientModelUtil; +import java.util.Objects; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Stream; +import org.slf4j.Logger; + +/** + * Generates LRO operation ID state and accessors on status-monitor models. + */ +public final class LroOperationIdModelHelper { + private static final Logger LOGGER = new PluginLogger(Javagen.getPluginInstance(), LroOperationIdModelHelper.class); + private static final String FIELD_NAME = "lroOperationId"; + private static final String GETTER_NAME = "getOperationId"; + private static final String PROPERTY_VALUE_NAME = "propertyValue"; + + private final ClientModel model; + private final LongRunningOperationIdMetadata metadata; + private final ClientModelProperty operationIdProperty; + private final Consumer addGeneratedAnnotation; + + /** + * Creates a helper for the model's operation ID, if supported. + * + * @param model the status-monitor model. + * @param addGeneratedAnnotation writes the generated-code annotation. + */ + public LroOperationIdModelHelper(ClientModel model, Consumer addGeneratedAnnotation) { + this.model = model; + this.metadata = resolveMetadata(model); + this.operationIdProperty = metadata == null ? null : resolveProperty(model, metadata); + this.addGeneratedAnnotation = addGeneratedAnnotation; + } + + /** + * Adds imports needed to populate an operation ID from the polling URL. + * + * @param imports the model imports. + * @param settings the generator settings. + */ + public void addImports(Set imports, JavaSettings settings) { + if (hasPathSource()) { + imports.add(settings.getPackage(settings.getImplementationSubpackage()) + "." + + ClientModelUtil.OPERATION_ID_POLLING_STRATEGY); + } + } + + /** + * Adds the non-wire field and registers its internal setter. + * + * @param classBlock the model class. + */ + public void addField(JavaClass classBlock) { + if (!hasPathSource()) { + return; + } + classBlock.javadocComment(comment -> comment + .description("The operation ID from the polling URL, set by the polling strategy after deserialization.")); + addGeneratedAnnotation.accept(classBlock); + classBlock.privateMemberVariable("String " + FIELD_NAME); + classBlock.staticBlock( + staticBlock -> staticBlock.line(ClientModelUtil.OPERATION_ID_POLLING_STRATEGY + ".setOperationIdAccessor(" + + model.getName() + ".class, (model, operationId) -> model." + FIELD_NAME + " = operationId);")); + } + + /** + * Writes documentation when an existing property getter needs the polling URL fallback. + * + * @param classBlock the model class. + * @param property the property being generated. + * @return whether the getter documentation was written. + */ + public boolean writeGetterJavadoc(JavaClass classBlock, ClientModelProperty property) { + if (!usesPathFallback(property)) { + return false; + } + classBlock.javadocComment(comment -> { + comment.description("Get the operation ID from the status response, or from the polling URL " + + "if the property is absent."); + comment + .methodReturns("the operation ID, or null until a status response with a body has " + "been received."); + }); + return true; + } + + /** + * Writes the polling URL fallback for an existing operation ID getter. + * + * @param methodBlock the getter body. + * @param property the property being generated. + * @return whether the getter body was written. + */ + public boolean writeGetterBody(JavaBlock methodBlock, ClientModelProperty property) { + if (!usesPathFallback(property)) { + return false; + } + methodBlock.methodReturn( + "this." + property.getName() + " != null ? this." + property.getName() + " : this." + FIELD_NAME); + return true; + } + + /** + * Adds the operation ID accessor unless an existing property getter provides it. + * + * @param classBlock the model class. + */ + public void addAccessors(JavaClass classBlock) { + if (metadata == null) { + if (model.getLroOperationId() != null) { + LOGGER.warn("Cannot expose the long-running operation ID on model '{}': a property conflicts with " + + "the generated accessor or field.", model.getName()); + } + return; + } + final ClientModelProperty property = operationIdProperty; + final boolean hasPathSource = hasPathSource(); + if (metadata.getPropertySerializedName() != null && property == null) { + LOGGER.warn( + "Cannot expose the selected long-running operation ID property '{}' on model '{}': " + + "the property is missing or is not a String.", + metadata.getPropertySerializedName(), model.getName()); + } + if (property == null && !hasPathSource) { + return; + } + + boolean usesExistingGetter = property != null && GETTER_NAME.equals(property.getGetterName()); + if (usesExistingGetter && (!hasPathSource || model.getProperties().contains(property))) { + return; + } + + final String description; + if (property != null && hasPathSource) { + description = "Get the ID of the long-running operation, from the {@code " + property.getSerializedName() + + "} property, or from the polling URL if the property is absent."; + } else if (property != null) { + description = "Get the ID of the long-running operation, from the {@code " + property.getSerializedName() + + "} property."; + } else { + description = "Get the ID of the long-running operation, from the polling URL."; + } + classBlock.javadocComment(comment -> { + comment.description(description); + comment.methodReturns("the ID of the long-running operation, or null if unavailable. The poll result is " + + "available when a status response with a body has been received."); + }); + addGeneratedAnnotation.accept(classBlock); + classBlock.publicMethod("String " + GETTER_NAME + "()", methodBlock -> { + if (property != null && hasPathSource) { + methodBlock.line("String " + PROPERTY_VALUE_NAME + " = " + (usesExistingGetter ? "super." : "this.") + + property.getGetterName() + "();"); + methodBlock + .methodReturn(PROPERTY_VALUE_NAME + " != null ? " + PROPERTY_VALUE_NAME + " : this." + FIELD_NAME); + } else if (property != null) { + methodBlock.methodReturn("this." + property.getGetterName() + "()"); + } else { + methodBlock.methodReturn("this." + FIELD_NAME); + } + }); + } + + private boolean hasPathSource() { + return metadata != null && metadata.hasPathSource(); + } + + private boolean usesPathFallback(ClientModelProperty property) { + return hasPathSource() + && property == operationIdProperty + && GETTER_NAME.equals(property.getGetterName()) + && ClassType.STRING.equals(property.getWireType()); + } + + private static LongRunningOperationIdMetadata resolveMetadata(ClientModel model) { + final LongRunningOperationIdMetadata metadata = model.getLroOperationId(); + if (metadata == null) { + return null; + } + final boolean conflict + = properties(model).anyMatch(p -> (metadata.hasPathSource() && FIELD_NAME.equals(p.getName())) + || (GETTER_NAME.equals(p.getGetterName()) + && (!Objects.equals(metadata.getPropertySerializedName(), p.getSerializedName()) + || !ClassType.STRING.equals(p.getClientType()) + || !ClassType.STRING.equals(p.getWireType())))); + return conflict ? null : metadata; + } + + private static ClientModelProperty resolveProperty(ClientModel model, LongRunningOperationIdMetadata metadata) { + if (metadata.getPropertySerializedName() == null) { + return null; + } + return properties(model).filter(p -> metadata.getPropertySerializedName().equals(p.getSerializedName()) + && ClassType.STRING.equals(p.getClientType())).findFirst().orElse(null); + } + + private static Stream properties(ClientModel model) { + return Stream.concat(model.getProperties().stream(), ClientModelUtil.getParentProperties(model).stream()); + } +} diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/util/ClientModelUtil.java b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/util/ClientModelUtil.java index 16c2086ed60..30978eead4c 100644 --- a/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/util/ClientModelUtil.java +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/util/ClientModelUtil.java @@ -12,6 +12,7 @@ import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.OperationGroup; import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.Parameter; import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings; +import com.microsoft.typespec.http.client.generator.core.extension.plugin.PollingSettings; import com.microsoft.typespec.http.client.generator.core.mapper.Mappers; import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ApiMetadata; import com.microsoft.typespec.http.client.generator.core.model.clientmodel.AsyncSyncClient; @@ -67,6 +68,8 @@ public class ClientModelUtil { public static final String OPERATION_LOCATION_POLLING_STRATEGY = "OperationLocationPollingStrategy"; public static final String SYNC_OPERATION_LOCATION_POLLING_STRATEGY = "SyncOperationLocationPollingStrategy"; + public static final String OPERATION_ID_POLLING_STRATEGY = "OperationIdPollingStrategy"; + public static final String SYNC_OPERATION_ID_POLLING_STRATEGY = "SyncOperationIdPollingStrategy"; public static final String POLLING_UTILS = "PollingUtils"; public static final String CLIENT_CORE_POLLING_UTILS = "ClientCorePollingUtils"; public static final String CLIENT_CORE_OPERATION_LOCATION_POLLING_STRATEGY @@ -834,6 +837,42 @@ public static boolean requireOperationLocationPollingStrategy(CodeModel codeMode return false; } + /** + * Checks whether any long-running operation extracts the operation ID from the path of the polling URL. + * + * @param codeModel the code model. + * @return whether OperationIdPollingStrategy is required. + */ + public static boolean requireOperationIdPollingStrategy(CodeModel codeModel) { + if (CoreUtils.isNullOrEmpty(codeModel.getClients())) { + return false; + } + + return codeModel.getClients() + .stream() + .filter(client -> client.getOperationGroups() != null) + .flatMap(client -> client.getOperationGroups().stream()) + .filter(og -> og.getOperations() != null) + .flatMap(og -> og.getOperations().stream()) + .anyMatch(operation -> operation.getLroMetadata() != null + && operation.getLroMetadata().getOperationId() != null + && operation.getLroMetadata().getOperationId().hasPathSource()); + } + + /** + * Whether an operation uses its generated status model for long-running operation ID metadata. + * + * @param settings the generator settings. + * @param pollingSettings the operation's polling settings. + * @return whether the generated status model can expose operation ID metadata. + */ + public static boolean supportsLroOperationId(JavaSettings settings, PollingSettings pollingSettings) { + return settings.isAzureV1() + && !settings.isFluent() + && pollingSettings != null + && pollingSettings.getPollResultType() == null; + } + /** * Checks if the model defines the property. * diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/resources/OperationIdPollingStrategy.java b/packages/http-client-java/generator/http-client-generator-core/src/main/resources/OperationIdPollingStrategy.java new file mode 100644 index 00000000000..4b3e7e78d31 --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/resources/OperationIdPollingStrategy.java @@ -0,0 +1,179 @@ +import com.azure.core.http.rest.Response; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.PollingContext; +import com.azure.core.util.polling.PollingStrategy; +import com.azure.core.util.serializer.TypeReference; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import reactor.core.publisher.Mono; + +// DO NOT modify this helper class + +/** + * Implements a polling strategy that populates the operation ID on the poll result, from the polling URL. + *

+ * The polling is delegated to the wrapped polling strategy, which keeps using the complete polling URL. + * + * @param the type of the response type from a polling call + * @param the type of the final result object to deserialize into + */ +public final class OperationIdPollingStrategy implements PollingStrategy { + private static final String POLLING_URL_KEY = OperationIdPollingStrategy.class.getName() + ".pollingUrl"; + private static final Map, BiConsumer> ACCESSORS = new ConcurrentHashMap<>(); + + private final PollingStrategy pollingStrategy; + private final Pattern pathPattern; + private final String pollingHeaderName; + + /** + * Creates an instance of the polling strategy. + * + * @param pollingStrategy the polling strategy to delegate to. + * @param pathTemplate the path template of the status monitor operation. + * @param pathParameterName the name of the path parameter that is the operation ID. + * @param pollingHeaderName the response header containing the polling URL. + */ + public OperationIdPollingStrategy(PollingStrategy pollingStrategy, String pathTemplate, + String pathParameterName, String pollingHeaderName) { + this.pollingStrategy = Objects.requireNonNull(pollingStrategy, "'pollingStrategy' cannot be null."); + this.pathPattern = createPathPattern(pathTemplate, pathParameterName); + this.pollingHeaderName = Objects.requireNonNull(pollingHeaderName, "'pollingHeaderName' cannot be null."); + } + + /** + * Registers the accessor that sets the operation ID on the poll result. + * + * @param clazz the class of the poll result. + * @param accessor the accessor that sets the operation ID. + * @param the type of the poll result. + */ + @SuppressWarnings("unchecked") + public static void setOperationIdAccessor(Class clazz, BiConsumer accessor) { + ACCESSORS.put(clazz, (BiConsumer) accessor); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono canPoll(Response initialResponse) { + return pollingStrategy.canPoll(initialResponse); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono> onInitialResponse(Response response, PollingContext pollingContext, + TypeReference pollResponseType) { + savePollingUrl(response, pollingContext, pollingHeaderName); + return pollingStrategy.onInitialResponse(response, pollingContext, pollResponseType) + .map(pollResponse -> setOperationId(pollResponse, pollingContext, pathPattern)); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono> poll(PollingContext pollingContext, TypeReference pollResponseType) { + return pollingStrategy.poll(pollingContext, pollResponseType) + .map(pollResponse -> setOperationId(pollResponse, pollingContext, pathPattern)); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono getResult(PollingContext pollingContext, TypeReference resultType) { + return pollingStrategy.getResult(pollingContext, resultType); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono cancel(PollingContext pollingContext, PollResponse initialResponse) { + return pollingStrategy.cancel(pollingContext, initialResponse); + } + + static Pattern createPathPattern(String pathTemplate, String pathParameterName) { + StringBuilder regex = new StringBuilder(); + Matcher matcher = Pattern.compile("\\{([^}]+)}").matcher(pathTemplate); + int index = 0; + boolean found = false; + while (matcher.find()) { + regex.append(Pattern.quote(pathTemplate.substring(index, matcher.start()))); + String name = matcher.group(1).replaceAll("^[+#./;?&]|\\*$", ""); + if (!found && name.equals(pathParameterName)) { + regex.append("([^/]+)"); + found = true; + } else { + regex.append("[^/]+"); + } + index = matcher.end(); + } + regex.append(Pattern.quote(pathTemplate.substring(index))); + return Pattern.compile(regex + "/?$"); + } + + static PollResponse setOperationId(PollResponse pollResponse, PollingContext pollingContext, + Pattern pathPattern) { + T value = pollResponse == null ? null : pollResponse.getValue(); + if (value == null) { + return pollResponse; + } + Class valueType = value.getClass(); + BiConsumer accessor = null; + while (valueType != null && accessor == null) { + accessor = ACCESSORS.get(valueType); + valueType = valueType.getSuperclass(); + } + if (accessor == null) { + return pollResponse; + } + String operationId = getOperationId(pollingContext.getData(POLLING_URL_KEY), pathPattern); + if (operationId != null) { + accessor.accept(value, operationId); + } + return pollResponse; + } + + static void savePollingUrl(Response response, PollingContext pollingContext, String pollingHeaderName) { + String pollingUrl = response.getHeaders().getValue(pollingHeaderName); + if (pollingUrl != null) { + pollingContext.setData(POLLING_URL_KEY, pollingUrl); + } + } + + private static String getOperationId(String pollingUrl, Pattern pathPattern) { + if (pollingUrl == null || pollingUrl.isEmpty()) { + return null; + } + String path; + try { + path = URI.create(pollingUrl).getRawPath(); + } catch (IllegalArgumentException e) { + path = pollingUrl; + } + if (path == null) { + return null; + } + Matcher matcher = pathPattern.matcher(path); + if (!matcher.find() || matcher.groupCount() < 1 || matcher.group(1) == null) { + return null; + } + try { + return URLDecoder.decode(matcher.group(1).replace("+", "%2B"), StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + return matcher.group(1); + } + } +} diff --git a/packages/http-client-java/generator/http-client-generator-core/src/main/resources/SyncOperationIdPollingStrategy.java b/packages/http-client-java/generator/http-client-generator-core/src/main/resources/SyncOperationIdPollingStrategy.java new file mode 100644 index 00000000000..4f4867d328b --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/resources/SyncOperationIdPollingStrategy.java @@ -0,0 +1,82 @@ +import com.azure.core.http.rest.Response; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.PollingContext; +import com.azure.core.util.polling.SyncPollingStrategy; +import com.azure.core.util.serializer.TypeReference; +import java.util.Objects; +import java.util.regex.Pattern; + +// DO NOT modify this helper class + +/** + * Implements a synchronous polling strategy that populates the operation ID on the poll result, from the polling URL. + *

+ * The polling is delegated to the wrapped polling strategy, which keeps using the complete polling URL. + * + * @param the type of the response type from a polling call + * @param the type of the final result object to deserialize into + */ +public final class SyncOperationIdPollingStrategy implements SyncPollingStrategy { + private final SyncPollingStrategy pollingStrategy; + private final Pattern pathPattern; + private final String pollingHeaderName; + + /** + * Creates an instance of the polling strategy. + * + * @param pollingStrategy the polling strategy to delegate to. + * @param pathTemplate the path template of the status monitor operation. + * @param pathParameterName the name of the path parameter that is the operation ID. + * @param pollingHeaderName the response header containing the polling URL. + */ + public SyncOperationIdPollingStrategy(SyncPollingStrategy pollingStrategy, String pathTemplate, + String pathParameterName, String pollingHeaderName) { + this.pollingStrategy = Objects.requireNonNull(pollingStrategy, "'pollingStrategy' cannot be null."); + this.pathPattern = OperationIdPollingStrategy.createPathPattern(pathTemplate, pathParameterName); + this.pollingHeaderName = Objects.requireNonNull(pollingHeaderName, "'pollingHeaderName' cannot be null."); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean canPoll(Response initialResponse) { + return pollingStrategy.canPoll(initialResponse); + } + + /** + * {@inheritDoc} + */ + @Override + public PollResponse onInitialResponse(Response response, PollingContext pollingContext, + TypeReference pollResponseType) { + OperationIdPollingStrategy.savePollingUrl(response, pollingContext, pollingHeaderName); + return OperationIdPollingStrategy.setOperationId( + pollingStrategy.onInitialResponse(response, pollingContext, pollResponseType), pollingContext, pathPattern); + } + + /** + * {@inheritDoc} + */ + @Override + public PollResponse poll(PollingContext pollingContext, TypeReference pollResponseType) { + return OperationIdPollingStrategy.setOperationId(pollingStrategy.poll(pollingContext, pollResponseType), + pollingContext, pathPattern); + } + + /** + * {@inheritDoc} + */ + @Override + public U getResult(PollingContext pollingContext, TypeReference resultType) { + return pollingStrategy.getResult(pollingContext, resultType); + } + + /** + * {@inheritDoc} + */ + @Override + public T cancel(PollingContext pollingContext, PollResponse initialResponse) { + return pollingStrategy.cancel(pollingContext, initialResponse); + } +} diff --git a/packages/http-client-java/generator/http-client-generator-core/src/test/java/com/microsoft/typespec/http/client/generator/core/template/LroOperationIdModelTemplateTests.java b/packages/http-client-java/generator/http-client-generator-core/src/test/java/com/microsoft/typespec/http/client/generator/core/template/LroOperationIdModelTemplateTests.java new file mode 100644 index 00000000000..ecefc870699 --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-core/src/test/java/com/microsoft/typespec/http/client/generator/core/template/LroOperationIdModelTemplateTests.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.typespec.http.client.generator.core.template; + +import com.microsoft.typespec.http.client.generator.core.MockUnitJavagen; +import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.LongRunningOperationIdMetadata; +import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings; +import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClassType; +import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClientModel; +import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClientModelProperty; +import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClientModels; +import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaFile; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Isolated; + +@Isolated +public class LroOperationIdModelTemplateTests { + @AfterEach + public void restoreSettings() { + new MockUnitJavagen(); + JavaSettings.clear(); + } + + @Test + public void selectedExistingGetterFallsBackToPath() { + new MockUnitJavagen(); + JavaSettings.clear(); + ClientModel model = model("SelectedOperationId", List.of(property("operationId", ClassType.STRING)), null); + String source = render(model); + Assertions.assertTrue( + source.contains("return this.operationId != null ? this.operationId : this.lroOperationId;"), source); + Assertions.assertEquals(source.indexOf("String getOperationId()"), + source.lastIndexOf("String getOperationId()")); + } + + @Test + public void inheritedSelectedGetterFallsBackToPath() { + new MockUnitJavagen(); + JavaSettings.clear(); + ClientModel parent = new ClientModel.Builder().name("OperationIdParent") + .packageName("com.azure.mock.models") + .properties(List.of(property("operationId", ClassType.STRING))) + .build(); + ClientModels.getInstance().addModel(parent); + String source = render(model("OperationIdChild", List.of(), parent.getName())); + Assertions.assertTrue(source.contains("String propertyValue = super.getOperationId();"), source); + Assertions.assertTrue(source.contains("return propertyValue != null ? propertyValue : this.lroOperationId;"), + source); + } + + @Test + public void unsupportedOrConflictingPropertyDoesNotGenerateAnInvalidGetter() { + new MockUnitJavagen(); + JavaSettings.clear(); + String nonString = render(model("UuidOperationId", List.of(property("operationId", ClassType.UUID)), null)); + Assertions.assertFalse(nonString.contains("private String lroOperationId"), nonString); + String collision + = render(model("CollidingOperationId", List.of(property("lroOperationId", ClassType.STRING)), null)); + Assertions.assertFalse(collision.contains("setOperationIdAccessor"), collision); + } + + private static ClientModelProperty property(String name, ClassType type) { + return new ClientModelProperty.Builder().name(name) + .serializedName(name) + .wireType(type) + .clientType(type) + .build(); + } + + private static ClientModel model(String name, List properties, String parent) { + LongRunningOperationIdMetadata metadata = new LongRunningOperationIdMetadata(); + metadata.setPathTemplate("/operations/{id}"); + metadata.setPathParameterSerializedName("id"); + metadata.setPollingHeaderName("operation-location"); + metadata.setPropertySerializedName("operationId"); + return new ClientModel.Builder().name(name) + .packageName("com.azure.mock.models") + .properties(properties) + .parentModelName(parent) + .lroOperationId(metadata) + .build(); + } + + private static String render(ClientModel model) { + JavaFile file = new JavaFile(model.getName() + ".java"); + ModelTemplate.getInstance().write(model, file); + return file.getContents().toString(); + } +} diff --git a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdClientImpl.java b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdClientImpl.java index 3e5c34c2136..24c1e12f37e 100644 --- a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdClientImpl.java +++ b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdClientImpl.java @@ -386,14 +386,17 @@ private Response analyzeWithResponse(String modelId, RequestOptions reques public PollerFlux beginAnalyzeWithModelAsync(String modelId, RequestOptions requestOptions) { return PollerFlux.create(Duration.ofSeconds(1), () -> this.analyzeWithResponseAsync(modelId, requestOptions), - new azure.clientgenerator.core.lro.operationid.implementation.OperationLocationPollingStrategy<>( - new PollingStrategyOptions(this.getHttpPipeline()) - .setEndpoint("{endpoint}".replace("{endpoint}", this.getEndpoint())) - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion()), - "result"), + new azure.clientgenerator.core.lro.operationid.implementation.OperationIdPollingStrategy<>( + new azure.clientgenerator.core.lro.operationid.implementation.OperationLocationPollingStrategy<>( + new PollingStrategyOptions(this.getHttpPipeline()) + .setEndpoint("{endpoint}".replace("{endpoint}", this.getEndpoint())) + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion()), + "result"), + "/azure/client-generator-core/lro/operation-id/documentModels/{modelId}/analyzeResults/{resultId}", + "resultId", "operation-location"), TypeReference.createInstance(DocumentAnalysisStatus.class), TypeReference.createInstance(DocumentAnalysisResult.class)); } @@ -413,14 +416,17 @@ public PollerFlux beginAnalyzeWi public SyncPoller beginAnalyzeWithModel(String modelId, RequestOptions requestOptions) { return SyncPoller.createPoller(Duration.ofSeconds(1), () -> this.analyzeWithResponse(modelId, requestOptions), - new azure.clientgenerator.core.lro.operationid.implementation.SyncOperationLocationPollingStrategy<>( - new PollingStrategyOptions(this.getHttpPipeline()) - .setEndpoint("{endpoint}".replace("{endpoint}", this.getEndpoint())) - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion()), - "result"), + new azure.clientgenerator.core.lro.operationid.implementation.SyncOperationIdPollingStrategy<>( + new azure.clientgenerator.core.lro.operationid.implementation.SyncOperationLocationPollingStrategy<>( + new PollingStrategyOptions(this.getHttpPipeline()) + .setEndpoint("{endpoint}".replace("{endpoint}", this.getEndpoint())) + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion()), + "result"), + "/azure/client-generator-core/lro/operation-id/documentModels/{modelId}/analyzeResults/{resultId}", + "resultId", "operation-location"), TypeReference.createInstance(DocumentAnalysisStatus.class), TypeReference.createInstance(DocumentAnalysisResult.class)); } @@ -778,14 +784,17 @@ private Response startTranslationWithPathWithResponse(RequestOptions reque beginStartTranslationWithPathWithModelAsync(RequestOptions requestOptions) { return PollerFlux.create(Duration.ofSeconds(1), () -> this.startTranslationWithPathWithResponseAsync(requestOptions), - new azure.clientgenerator.core.lro.operationid.implementation.OperationLocationPollingStrategy<>( - new PollingStrategyOptions(this.getHttpPipeline()) - .setEndpoint("{endpoint}".replace("{endpoint}", this.getEndpoint())) - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion()), - "result"), + new azure.clientgenerator.core.lro.operationid.implementation.OperationIdPollingStrategy<>( + new azure.clientgenerator.core.lro.operationid.implementation.OperationLocationPollingStrategy<>( + new PollingStrategyOptions(this.getHttpPipeline()) + .setEndpoint("{endpoint}".replace("{endpoint}", this.getEndpoint())) + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion()), + "result"), + "/azure/client-generator-core/lro/operation-id/translations/operations/{operationId}", "operationId", + "operation-location"), TypeReference.createInstance(TranslationWithPathStatus.class), TypeReference.createInstance(TranslationResult.class)); } @@ -805,14 +814,17 @@ private Response startTranslationWithPathWithResponse(RequestOptions reque beginStartTranslationWithPathWithModel(RequestOptions requestOptions) { return SyncPoller.createPoller(Duration.ofSeconds(1), () -> this.startTranslationWithPathWithResponse(requestOptions), - new azure.clientgenerator.core.lro.operationid.implementation.SyncOperationLocationPollingStrategy<>( - new PollingStrategyOptions(this.getHttpPipeline()) - .setEndpoint("{endpoint}".replace("{endpoint}", this.getEndpoint())) - .setContext(requestOptions != null && requestOptions.getContext() != null - ? requestOptions.getContext() - : Context.NONE) - .setServiceVersion(this.getServiceVersion().getVersion()), - "result"), + new azure.clientgenerator.core.lro.operationid.implementation.SyncOperationIdPollingStrategy<>( + new azure.clientgenerator.core.lro.operationid.implementation.SyncOperationLocationPollingStrategy<>( + new PollingStrategyOptions(this.getHttpPipeline()) + .setEndpoint("{endpoint}".replace("{endpoint}", this.getEndpoint())) + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion()), + "result"), + "/azure/client-generator-core/lro/operation-id/translations/operations/{operationId}", "operationId", + "operation-location"), TypeReference.createInstance(TranslationWithPathStatus.class), TypeReference.createInstance(TranslationResult.class)); } diff --git a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategy.java b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategy.java new file mode 100644 index 00000000000..cfea5102f8a --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategy.java @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package azure.clientgenerator.core.lro.operationid.implementation; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.PollingContext; +import com.azure.core.util.polling.PollingStrategy; +import com.azure.core.util.serializer.TypeReference; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import reactor.core.publisher.Mono; + +// DO NOT modify this helper class + +/** + * Implements a polling strategy that populates the operation ID on the poll result, from the polling URL. + *

+ * The polling is delegated to the wrapped polling strategy, which keeps using the complete polling URL. + * + * @param the type of the response type from a polling call + * @param the type of the final result object to deserialize into + */ +public final class OperationIdPollingStrategy implements PollingStrategy { + private static final String POLLING_URL_KEY = OperationIdPollingStrategy.class.getName() + ".pollingUrl"; + private static final Map, BiConsumer> ACCESSORS = new ConcurrentHashMap<>(); + + private final PollingStrategy pollingStrategy; + private final Pattern pathPattern; + private final String pollingHeaderName; + + /** + * Creates an instance of the polling strategy. + * + * @param pollingStrategy the polling strategy to delegate to. + * @param pathTemplate the path template of the status monitor operation. + * @param pathParameterName the name of the path parameter that is the operation ID. + * @param pollingHeaderName the response header containing the polling URL. + */ + public OperationIdPollingStrategy(PollingStrategy pollingStrategy, String pathTemplate, + String pathParameterName, String pollingHeaderName) { + this.pollingStrategy = Objects.requireNonNull(pollingStrategy, "'pollingStrategy' cannot be null."); + this.pathPattern = createPathPattern(pathTemplate, pathParameterName); + this.pollingHeaderName = Objects.requireNonNull(pollingHeaderName, "'pollingHeaderName' cannot be null."); + } + + /** + * Registers the accessor that sets the operation ID on the poll result. + * + * @param clazz the class of the poll result. + * @param accessor the accessor that sets the operation ID. + * @param the type of the poll result. + */ + @SuppressWarnings("unchecked") + public static void setOperationIdAccessor(Class clazz, BiConsumer accessor) { + ACCESSORS.put(clazz, (BiConsumer) accessor); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono canPoll(Response initialResponse) { + return pollingStrategy.canPoll(initialResponse); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono> onInitialResponse(Response response, PollingContext pollingContext, + TypeReference pollResponseType) { + savePollingUrl(response, pollingContext, pollingHeaderName); + return pollingStrategy.onInitialResponse(response, pollingContext, pollResponseType) + .map(pollResponse -> setOperationId(pollResponse, pollingContext, pathPattern)); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono> poll(PollingContext pollingContext, TypeReference pollResponseType) { + return pollingStrategy.poll(pollingContext, pollResponseType) + .map(pollResponse -> setOperationId(pollResponse, pollingContext, pathPattern)); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono getResult(PollingContext pollingContext, TypeReference resultType) { + return pollingStrategy.getResult(pollingContext, resultType); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono cancel(PollingContext pollingContext, PollResponse initialResponse) { + return pollingStrategy.cancel(pollingContext, initialResponse); + } + + static Pattern createPathPattern(String pathTemplate, String pathParameterName) { + StringBuilder regex = new StringBuilder(); + Matcher matcher = Pattern.compile("\\{([^}]+)}").matcher(pathTemplate); + int index = 0; + boolean found = false; + while (matcher.find()) { + regex.append(Pattern.quote(pathTemplate.substring(index, matcher.start()))); + String name = matcher.group(1).replaceAll("^[+#./;?&]|\\*$", ""); + if (!found && name.equals(pathParameterName)) { + regex.append("([^/]+)"); + found = true; + } else { + regex.append("[^/]+"); + } + index = matcher.end(); + } + regex.append(Pattern.quote(pathTemplate.substring(index))); + return Pattern.compile(regex + "/?$"); + } + + static PollResponse setOperationId(PollResponse pollResponse, PollingContext pollingContext, + Pattern pathPattern) { + T value = pollResponse == null ? null : pollResponse.getValue(); + if (value == null) { + return pollResponse; + } + Class valueType = value.getClass(); + BiConsumer accessor = null; + while (valueType != null && accessor == null) { + accessor = ACCESSORS.get(valueType); + valueType = valueType.getSuperclass(); + } + if (accessor == null) { + return pollResponse; + } + String operationId = getOperationId(pollingContext.getData(POLLING_URL_KEY), pathPattern); + if (operationId != null) { + accessor.accept(value, operationId); + } + return pollResponse; + } + + static void savePollingUrl(Response response, PollingContext pollingContext, String pollingHeaderName) { + String pollingUrl = response.getHeaders().getValue(pollingHeaderName); + if (pollingUrl != null) { + pollingContext.setData(POLLING_URL_KEY, pollingUrl); + } + } + + private static String getOperationId(String pollingUrl, Pattern pathPattern) { + if (pollingUrl == null || pollingUrl.isEmpty()) { + return null; + } + String path; + try { + path = URI.create(pollingUrl).getRawPath(); + } catch (IllegalArgumentException e) { + path = pollingUrl; + } + if (path == null) { + return null; + } + Matcher matcher = pathPattern.matcher(path); + if (!matcher.find() || matcher.groupCount() < 1 || matcher.group(1) == null) { + return null; + } + try { + return URLDecoder.decode(matcher.group(1).replace("+", "%2B"), StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + return matcher.group(1); + } + } +} diff --git a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/SyncOperationIdPollingStrategy.java b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/SyncOperationIdPollingStrategy.java new file mode 100644 index 00000000000..35a740d214f --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/SyncOperationIdPollingStrategy.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package azure.clientgenerator.core.lro.operationid.implementation; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.PollingContext; +import com.azure.core.util.polling.SyncPollingStrategy; +import com.azure.core.util.serializer.TypeReference; +import java.util.Objects; +import java.util.regex.Pattern; + +// DO NOT modify this helper class + +/** + * Implements a synchronous polling strategy that populates the operation ID on the poll result, from the polling URL. + *

+ * The polling is delegated to the wrapped polling strategy, which keeps using the complete polling URL. + * + * @param the type of the response type from a polling call + * @param the type of the final result object to deserialize into + */ +public final class SyncOperationIdPollingStrategy implements SyncPollingStrategy { + private final SyncPollingStrategy pollingStrategy; + private final Pattern pathPattern; + private final String pollingHeaderName; + + /** + * Creates an instance of the polling strategy. + * + * @param pollingStrategy the polling strategy to delegate to. + * @param pathTemplate the path template of the status monitor operation. + * @param pathParameterName the name of the path parameter that is the operation ID. + * @param pollingHeaderName the response header containing the polling URL. + */ + public SyncOperationIdPollingStrategy(SyncPollingStrategy pollingStrategy, String pathTemplate, + String pathParameterName, String pollingHeaderName) { + this.pollingStrategy = Objects.requireNonNull(pollingStrategy, "'pollingStrategy' cannot be null."); + this.pathPattern = OperationIdPollingStrategy.createPathPattern(pathTemplate, pathParameterName); + this.pollingHeaderName = Objects.requireNonNull(pollingHeaderName, "'pollingHeaderName' cannot be null."); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean canPoll(Response initialResponse) { + return pollingStrategy.canPoll(initialResponse); + } + + /** + * {@inheritDoc} + */ + @Override + public PollResponse onInitialResponse(Response response, PollingContext pollingContext, + TypeReference pollResponseType) { + OperationIdPollingStrategy.savePollingUrl(response, pollingContext, pollingHeaderName); + return OperationIdPollingStrategy.setOperationId( + pollingStrategy.onInitialResponse(response, pollingContext, pollResponseType), pollingContext, pathPattern); + } + + /** + * {@inheritDoc} + */ + @Override + public PollResponse poll(PollingContext pollingContext, TypeReference pollResponseType) { + return OperationIdPollingStrategy.setOperationId(pollingStrategy.poll(pollingContext, pollResponseType), + pollingContext, pathPattern); + } + + /** + * {@inheritDoc} + */ + @Override + public U getResult(PollingContext pollingContext, TypeReference resultType) { + return pollingStrategy.getResult(pollingContext, resultType); + } + + /** + * {@inheritDoc} + */ + @Override + public T cancel(PollingContext pollingContext, PollResponse initialResponse) { + return pollingStrategy.cancel(pollingContext, initialResponse); + } +} diff --git a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/DocumentAnalysisStatus.java b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/DocumentAnalysisStatus.java index da02aa94129..65983674b20 100644 --- a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/DocumentAnalysisStatus.java +++ b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/DocumentAnalysisStatus.java @@ -4,6 +4,7 @@ package azure.clientgenerator.core.lro.operationid.models; +import azure.clientgenerator.core.lro.operationid.implementation.OperationIdPollingStrategy; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; @@ -29,6 +30,17 @@ public final class DocumentAnalysisStatus implements JsonSerializable model.lroOperationId = operationId); + } + /** * Creates an instance of DocumentAnalysisStatus class. * @@ -59,6 +71,17 @@ public DocumentAnalysisResult getResult() { return this.result; } + /** + * Get the ID of the long-running operation, from the polling URL. + * + * @return the ID of the long-running operation, or null if unavailable. The poll result is available when a status + * response with a body has been received. + */ + @Generated + public String getOperationId() { + return this.lroOperationId; + } + /** * {@inheritDoc} */ diff --git a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationStatus.java b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationStatus.java index 99f129eea9d..a7612d58d71 100644 --- a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationStatus.java +++ b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationStatus.java @@ -77,6 +77,17 @@ public TranslationResult getResult() { return this.result; } + /** + * Get the ID of the long-running operation, from the {@code id} property. + * + * @return the ID of the long-running operation, or null if unavailable. The poll result is available when a status + * response with a body has been received. + */ + @Generated + public String getOperationId() { + return this.getId(); + } + /** * {@inheritDoc} */ diff --git a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationWithPathStatus.java b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationWithPathStatus.java index 3dd174bbf55..e843a2c70bf 100644 --- a/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationWithPathStatus.java +++ b/packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationWithPathStatus.java @@ -4,6 +4,7 @@ package azure.clientgenerator.core.lro.operationid.models; +import azure.clientgenerator.core.lro.operationid.implementation.OperationIdPollingStrategy; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; @@ -35,6 +36,17 @@ public final class TranslationWithPathStatus implements JsonSerializable model.lroOperationId = operationId); + } + /** * Creates an instance of TranslationWithPathStatus class. * @@ -77,6 +89,19 @@ public TranslationResult getResult() { return this.result; } + /** + * Get the ID of the long-running operation, from the {@code id} property, or from the polling URL if the property + * is absent. + * + * @return the ID of the long-running operation, or null if unavailable. The poll result is available when a status + * response with a body has been received. + */ + @Generated + public String getOperationId() { + String propertyValue = this.getId(); + return propertyValue != null ? propertyValue : this.lroOperationId; + } + /** * {@inheritDoc} */ diff --git a/packages/http-client-java/generator/http-client-generator-test/src/main/resources/META-INF/azure-clientgenerator-core-lro-operationid_metadata.json b/packages/http-client-java/generator/http-client-generator-test/src/main/resources/META-INF/azure-clientgenerator-core-lro-operationid_metadata.json index 7a3ed50a58b..30ba08c615f 100644 --- a/packages/http-client-java/generator/http-client-generator-test/src/main/resources/META-INF/azure-clientgenerator-core-lro-operationid_metadata.json +++ b/packages/http-client-java/generator/http-client-generator-test/src/main/resources/META-INF/azure-clientgenerator-core-lro-operationid_metadata.json @@ -1 +1 @@ -{"flavor":"Azure","apiVersions":{"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId":"2022-12-01-preview"},"crossLanguagePackageId":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId","crossLanguageVersion":"5e57f9e18eff","crossLanguageDefinitions":{"azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginAnalyze":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.analyze","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginAnalyzeWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.analyze","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginStartTranslation":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslation","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginStartTranslationWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslation","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginStartTranslationWithPath":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslationWithPath","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginStartTranslationWithPathWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslationWithPath","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getDocumentAnalysisStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getDocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getDocumentAnalysisStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getDocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getTranslationStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getTranslationStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getTranslationWithPathStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationWithPathStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getTranslationWithPathStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationWithPathStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginAnalyze":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.analyze","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginAnalyzeWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.analyze","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginStartTranslation":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslation","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginStartTranslationWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslation","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginStartTranslationWithPath":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslationWithPath","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginStartTranslationWithPathWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslationWithPath","azure.clientgenerator.core.lro.operationid.OperationIdClient.getDocumentAnalysisStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getDocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getDocumentAnalysisStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getDocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getTranslationStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getTranslationStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getTranslationWithPathStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationWithPathStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getTranslationWithPathStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationWithPathStatus","azure.clientgenerator.core.lro.operationid.OperationIdClientBuilder":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId","azure.clientgenerator.core.lro.operationid.models.DocumentAnalysisResult":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.DocumentAnalysisResult","azure.clientgenerator.core.lro.operationid.models.DocumentAnalysisStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.DocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.models.OperationState":"Azure.Core.Foundations.OperationState","azure.clientgenerator.core.lro.operationid.models.TranslationResult":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.TranslationResult","azure.clientgenerator.core.lro.operationid.models.TranslationStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.TranslationStatus","azure.clientgenerator.core.lro.operationid.models.TranslationWithPathStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.TranslationWithPathStatus"},"generatedFiles":["src/main/java/azure/clientgenerator/core/lro/operationid/OperationIdAsyncClient.java","src/main/java/azure/clientgenerator/core/lro/operationid/OperationIdClient.java","src/main/java/azure/clientgenerator/core/lro/operationid/OperationIdClientBuilder.java","src/main/java/azure/clientgenerator/core/lro/operationid/OperationIdServiceVersion.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdClientImpl.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationLocationPollingStrategy.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/PollingUtils.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/SyncOperationLocationPollingStrategy.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/package-info.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/DocumentAnalysisResult.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/DocumentAnalysisStatus.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/OperationState.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationResult.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationStatus.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationWithPathStatus.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/package-info.java","src/main/java/azure/clientgenerator/core/lro/operationid/package-info.java","src/main/java/module-info.java"]} \ No newline at end of file +{"flavor":"Azure","apiVersions":{"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId":"2022-12-01-preview"},"crossLanguagePackageId":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId","crossLanguageVersion":"5e57f9e18eff","crossLanguageDefinitions":{"azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginAnalyze":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.analyze","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginAnalyzeWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.analyze","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginStartTranslation":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslation","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginStartTranslationWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslation","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginStartTranslationWithPath":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslationWithPath","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.beginStartTranslationWithPathWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslationWithPath","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getDocumentAnalysisStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getDocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getDocumentAnalysisStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getDocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getTranslationStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getTranslationStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getTranslationWithPathStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationWithPathStatus","azure.clientgenerator.core.lro.operationid.OperationIdAsyncClient.getTranslationWithPathStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationWithPathStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginAnalyze":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.analyze","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginAnalyzeWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.analyze","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginStartTranslation":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslation","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginStartTranslationWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslation","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginStartTranslationWithPath":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslationWithPath","azure.clientgenerator.core.lro.operationid.OperationIdClient.beginStartTranslationWithPathWithModel":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.startTranslationWithPath","azure.clientgenerator.core.lro.operationid.OperationIdClient.getDocumentAnalysisStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getDocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getDocumentAnalysisStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getDocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getTranslationStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getTranslationStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getTranslationWithPathStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationWithPathStatus","azure.clientgenerator.core.lro.operationid.OperationIdClient.getTranslationWithPathStatusWithResponse":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.getTranslationWithPathStatus","azure.clientgenerator.core.lro.operationid.OperationIdClientBuilder":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId","azure.clientgenerator.core.lro.operationid.models.DocumentAnalysisResult":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.DocumentAnalysisResult","azure.clientgenerator.core.lro.operationid.models.DocumentAnalysisStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.DocumentAnalysisStatus","azure.clientgenerator.core.lro.operationid.models.OperationState":"Azure.Core.Foundations.OperationState","azure.clientgenerator.core.lro.operationid.models.TranslationResult":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.TranslationResult","azure.clientgenerator.core.lro.operationid.models.TranslationStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.TranslationStatus","azure.clientgenerator.core.lro.operationid.models.TranslationWithPathStatus":"_Specs_.Azure.ClientGenerator.Core.Lro.OperationId.TranslationWithPathStatus"},"generatedFiles":["src/main/java/azure/clientgenerator/core/lro/operationid/OperationIdAsyncClient.java","src/main/java/azure/clientgenerator/core/lro/operationid/OperationIdClient.java","src/main/java/azure/clientgenerator/core/lro/operationid/OperationIdClientBuilder.java","src/main/java/azure/clientgenerator/core/lro/operationid/OperationIdServiceVersion.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdClientImpl.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategy.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationLocationPollingStrategy.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/PollingUtils.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/SyncOperationIdPollingStrategy.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/SyncOperationLocationPollingStrategy.java","src/main/java/azure/clientgenerator/core/lro/operationid/implementation/package-info.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/DocumentAnalysisResult.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/DocumentAnalysisStatus.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/OperationState.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationResult.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationStatus.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/TranslationWithPathStatus.java","src/main/java/azure/clientgenerator/core/lro/operationid/models/package-info.java","src/main/java/azure/clientgenerator/core/lro/operationid/package-info.java","src/main/java/module-info.java"]} \ No newline at end of file diff --git a/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/metadata/MetadataTests.java b/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/metadata/MetadataTests.java index 042176ebab4..7ed46c2c33b 100644 --- a/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/metadata/MetadataTests.java +++ b/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/metadata/MetadataTests.java @@ -22,7 +22,11 @@ public void testAnalyzeWithUsage() { MetadataClient client = new MetadataClientBuilder().buildClient(); SyncPoller poller = client.beginAnalyzeWithUsage("analyzer-1"); - PollResponse response = poller.waitForCompletion(); + PollResponse response = poller.poll(); + Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus()); + Assertions.assertEquals(Map.of("input", 10), response.getValue().getUsage().getTokens()); + + response = poller.waitForCompletion(); Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); Assertions.assertEquals("usage-123", response.getValue().getId()); Assertions.assertEquals(1, response.getValue().getUsage().getDocumentPagesBasic()); diff --git a/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/operationid/OperationIdTests.java b/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/operationid/OperationIdTests.java new file mode 100644 index 00000000000..63dda6f46da --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/operationid/OperationIdTests.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azure.clientgenerator.core.lro.operationid; + +import azure.clientgenerator.core.lro.operationid.models.DocumentAnalysisResult; +import azure.clientgenerator.core.lro.operationid.models.DocumentAnalysisStatus; +import azure.clientgenerator.core.lro.operationid.models.TranslationResult; +import azure.clientgenerator.core.lro.operationid.models.TranslationStatus; +import azure.clientgenerator.core.lro.operationid.models.TranslationWithPathStatus; +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +public class OperationIdTests { + @Test + public void testAnalyze() { + OperationIdClient client = new OperationIdClientBuilder().buildClient(); + SyncPoller poller = client.beginAnalyze("document-1"); + + // operation ID from the path parameter of the polling URL, while the operation is in progress + PollResponse response = poller.poll(); + Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus()); + Assertions.assertEquals("analysis-123", response.getValue().getOperationId()); + + response = poller.waitForCompletion(); + Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); + Assertions.assertEquals("analysis-123", response.getValue().getOperationId()); + Assertions.assertNotNull(poller.getFinalResult().getSummary()); + } + + @Test + public void testAnalyzeAsync() { + OperationIdAsyncClient client = new OperationIdClientBuilder().buildAsyncClient(); + AsyncPollResponse response + = client.beginAnalyze("document-1").last().block(); + + Assertions.assertNotNull(response); + Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); + Assertions.assertEquals("analysis-123", response.getValue().getOperationId()); + Assertions.assertNotNull(response.getFinalResult().block()); + } + + @Test + public void testStartTranslation() { + OperationIdClient client = new OperationIdClientBuilder().buildClient(); + SyncPoller poller = client.beginStartTranslation(); + + // operation ID from the "id" property of the status monitor response + PollResponse response = poller.waitForCompletion(); + Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); + Assertions.assertEquals("translation-123", response.getValue().getOperationId()); + Assertions.assertEquals(response.getValue().getId(), response.getValue().getOperationId()); + Assertions.assertNotNull(poller.getFinalResult()); + } + + // The Spector mock registers "translations:start" before "translations:start-with-path"; Express treats ":start" + // as a route parameter, so the start-with-path request is served by the "start" handler. + @Disabled("Spector mock route collision: 'translations:start' shadows 'translations:start-with-path'") + @Test + public void testStartTranslationWithPath() { + OperationIdClient client = new OperationIdClientBuilder().buildClient(); + SyncPoller poller = client.beginStartTranslationWithPath(); + + PollResponse response = poller.poll(); + Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus()); + Assertions.assertEquals("translation-456", response.getValue().getOperationId()); + Assertions.assertEquals(response.getValue().getId(), response.getValue().getOperationId()); + + response = poller.waitForCompletion(); + Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); + Assertions.assertEquals("translation-456", response.getValue().getOperationId()); + Assertions.assertNotNull(poller.getFinalResult()); + } +} diff --git a/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategyTests.java b/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategyTests.java new file mode 100644 index 00000000000..8a93e88dfec --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategyTests.java @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azure.clientgenerator.core.lro.operationid.implementation; + +import azure.clientgenerator.core.lro.operationid.models.TranslationWithPathStatus; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.rest.Response; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.PollingContext; +import com.azure.core.util.polling.PollingStrategy; +import com.azure.core.util.polling.SyncPollingStrategy; +import com.azure.core.util.serializer.TypeReference; +import com.azure.json.JsonProviders; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import reactor.core.publisher.Mono; + +public class OperationIdPollingStrategyTests { + static class Status { + String operationId; + } + + static class DerivedStatus extends Status { + } + + @Test + @SuppressWarnings("unchecked") + public void usesSelectedHeaderForPolymorphicPollResult() { + OperationIdPollingStrategy.setOperationIdAccessor(Status.class, (status, id) -> status.operationId = id); + SyncPollingStrategy delegate = Mockito.mock(SyncPollingStrategy.class); + PollingContext context = Mockito.mock(PollingContext.class); + Map data = new HashMap<>(); + Mockito.when(context.getData(Mockito.anyString())) + .thenAnswer(invocation -> data.get(invocation.getArgument(0))); + Mockito.when(context.setData(Mockito.anyString(), Mockito.anyString())).thenAnswer(invocation -> { + data.put(invocation.getArgument(0), invocation.getArgument(1)); + return context; + }); + Response initial = Mockito.mock(Response.class); + Mockito.when(initial.getHeaders()) + .thenReturn(new HttpHeaders().set("Operation-Location", "https://example.test/operations/wrong") + .set("Location", "https://example.test/operations/correct%2Bid?api-version=1")); + TypeReference type = new TypeReference() { + }; + PollResponse response = new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, new DerivedStatus()); + Mockito.when(delegate.onInitialResponse(initial, context, type)).thenReturn(response); + Mockito.when(delegate.poll(context, type)).thenReturn(response); + + SyncOperationIdPollingStrategy strategy + = new SyncOperationIdPollingStrategy<>(delegate, "/operations/{id}", "id", "location"); + Assertions.assertEquals("correct+id", + strategy.onInitialResponse(initial, context, type).getValue().operationId); + response.getValue().operationId = null; + Assertions.assertEquals("correct+id", strategy.poll(context, type).getValue().operationId); + } + + @Test + @SuppressWarnings("unchecked") + public void asyncPollUsesBodyThenPathAndRetainsSelectedUrl() throws IOException { + PollingStrategy delegate = Mockito.mock(PollingStrategy.class); + PollingContext context = Mockito.mock(PollingContext.class); + Map data = new HashMap<>(); + Mockito.when(context.getData(Mockito.anyString())) + .thenAnswer(invocation -> data.get(invocation.getArgument(0))); + Mockito.when(context.setData(Mockito.anyString(), Mockito.anyString())).thenAnswer(invocation -> { + data.put(invocation.getArgument(0), invocation.getArgument(1)); + return context; + }); + Response initial = Mockito.mock(Response.class); + Mockito.when(initial.getHeaders()) + .thenReturn(new HttpHeaders().set("Operation-Location", "https://example.test/operations/wrong") + .set("Location", "https://example.test/operations/path-id")); + TypeReference type = new TypeReference() { + }; + TranslationWithPathStatus withoutId + = TranslationWithPathStatus.fromJson(JsonProviders.createReader("{\"status\":\"Running\"}")); + TranslationWithPathStatus withId = TranslationWithPathStatus + .fromJson(JsonProviders.createReader("{\"id\":\"body-id\",\"status\":\"Failed\"}")); + Mockito.when(delegate.onInitialResponse(initial, context, type)) + .thenReturn(Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, null))); + Mockito.when(delegate.poll(context, type)) + .thenReturn(Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, withoutId)), + Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, withId))); + + OperationIdPollingStrategy strategy + = new OperationIdPollingStrategy<>(delegate, "/operations/{id}", "id", "location"); + Assertions.assertNull(strategy.onInitialResponse(initial, context, type).block().getValue()); + Assertions.assertEquals("path-id", strategy.poll(context, type).block().getValue().getOperationId()); + Assertions.assertEquals("body-id", strategy.poll(context, type).block().getValue().getOperationId()); + Mockito.verify(delegate, Mockito.times(2)).poll(context, type); + } +} diff --git a/packages/http-client-java/generator/http-client-generator/src/main/java/com/microsoft/typespec/http/client/generator/TypeSpecPlugin.java b/packages/http-client-java/generator/http-client-generator/src/main/java/com/microsoft/typespec/http/client/generator/TypeSpecPlugin.java index c85681e2f3b..27a5cf26c23 100644 --- a/packages/http-client-java/generator/http-client-generator/src/main/java/com/microsoft/typespec/http/client/generator/TypeSpecPlugin.java +++ b/packages/http-client-java/generator/http-client-generator/src/main/java/com/microsoft/typespec/http/client/generator/TypeSpecPlugin.java @@ -7,6 +7,8 @@ import com.microsoft.typespec.http.client.generator.core.extension.jsonrpc.Connection; import com.microsoft.typespec.http.client.generator.core.extension.model.Message; import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.CodeModel; +import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.LongRunningOperationIdMetadata; +import com.microsoft.typespec.http.client.generator.core.extension.model.codemodel.Schema; import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings; import com.microsoft.typespec.http.client.generator.core.mapper.Mappers; import com.microsoft.typespec.http.client.generator.core.model.clientmodel.AsyncSyncClient; @@ -33,6 +35,7 @@ import java.io.OutputStream; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -50,11 +53,53 @@ public class TypeSpecPlugin extends Javagen { public Client processClient(CodeModel codeModel) { // transform code model codeModel = new Transformer().transform(Preprocessor.convertOptionalConstantsToEnum(codeModel)); + filterLroOperationIdMetadata(codeModel); // map to client model return Mappers.getClientMapper().map(codeModel); } + private void filterLroOperationIdMetadata(CodeModel codeModel) { + JavaSettings settings = JavaSettings.getInstance(); + Map supported = new IdentityHashMap<>(); + if (codeModel.getClients() != null) { + codeModel.getClients() + .stream() + .filter(client -> client.getOperationGroups() != null) + .flatMap(client -> client.getOperationGroups().stream()) + .filter(group -> group.getOperations() != null) + .flatMap(group -> group.getOperations().stream()) + .filter(operation -> operation.getConvenienceApi() != null && operation.getLroMetadata() != null) + .filter(operation -> ClientModelUtil.supportsLroOperationId(settings, + settings.getPollingSettings(Mappers.getProxyMethodMapper().getOperationId(operation, settings)))) + .forEach(operation -> { + Schema schema = operation.getLroMetadata().getPollResultType(); + LongRunningOperationIdMetadata current = operation.getLroMetadata().getOperationId(); + if (schema == null || current == null) { + return; + } + LongRunningOperationIdMetadata merged + = supported.computeIfAbsent(schema, ignored -> new LongRunningOperationIdMetadata()); + if (current.hasPathSource() && !merged.hasPathSource()) { + merged.setPathTemplate(current.getPathTemplate()); + merged.setPathParameterSerializedName(current.getPathParameterSerializedName()); + merged.setPollingHeaderName(current.getPollingHeaderName()); + } + if (current.getPropertySerializedName() != null) { + merged.setPropertySerializedName(current.getPropertySerializedName()); + } + }); + } + if (codeModel.getSchemas() != null && codeModel.getSchemas().getObjects() != null) { + codeModel.getSchemas() + .getObjects() + .stream() + .filter( + schema -> schema.getExtensions() != null && schema.getExtensions().getXmsLroOperationId() != null) + .forEach(schema -> schema.getExtensions().setXmsLroOperationId(supported.get(schema))); + } + } + public JavaPackage processTemplates(CodeModel codeModel, Client client, JavaSettings settings) { JavaPackage javaPackage = super.writeToTemplates(codeModel, client, settings); @@ -179,6 +224,16 @@ protected void writeHelperClasses(Client client, CodeModel codeModel, JavaPackag } } + + // OperationIdPollingStrategy + if (JavaSettings.getInstance().isAzureV1() + && !JavaSettings.getInstance().isFluent() + && ClientModelUtil.requireOperationIdPollingStrategy(codeModel)) { + javaPackage.addJavaFromResources(settings.getPackage(settings.getImplementationSubpackage()), + ClientModelUtil.OPERATION_ID_POLLING_STRATEGY); + javaPackage.addJavaFromResources(settings.getPackage(settings.getImplementationSubpackage()), + ClientModelUtil.SYNC_OPERATION_ID_POLLING_STRATEGY); + } } @Override