From f1cf5f8dbbbaff117a8205f71ba7001ca71c71f7 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 12 Nov 2026 12:53:29 -0500 Subject: [PATCH 1/5] feat(http-client-java): consume TCGC LRO operation ID metadata Generate a read-only getOperationId() on long-running poll-result models, populated from the @lroOperationId monitor-body property and/or the polling URL path parameter. Add Spector e2e tests for lro/operation-id. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- ...va-tcgc-lro-metadata-2026-10-12-17-55-0.md | 12 ++ .../emitter/src/code-model-builder.ts | 45 ++++- .../src/common/long-running-metadata.ts | 16 ++ .../codemodel/CodeModelCustomConstructor.java | 7 + .../model/codemodel/LongRunningMetadata.java | 19 ++ .../LongRunningOperationIdMetadata.java | 84 +++++++++ .../model/extensionmodel/XmsExtensions.java | 20 ++ .../generator/core/mapper/ModelMapper.java | 6 + .../core/mapper/PollingMetadata.java | 34 +++- .../core/model/clientmodel/ClientModel.java | 33 +++- .../core/template/ModelTemplate.java | 102 +++++++++++ .../generator/core/util/ClientModelUtil.java | 23 +++ .../resources/OperationIdPollingStrategy.java | 166 +++++++++++++++++ .../SyncOperationIdPollingStrategy.java | 78 ++++++++ .../implementation/OperationIdClientImpl.java | 74 ++++---- .../OperationIdPollingStrategy.java | 172 ++++++++++++++++++ .../SyncOperationIdPollingStrategy.java | 84 +++++++++ .../models/DocumentAnalysisStatus.java | 22 +++ .../operationid/models/TranslationStatus.java | 10 + .../models/TranslationWithPathStatus.java | 24 +++ ...nerator-core-lro-operationid_metadata.json | 2 +- .../lro/operationid/OperationIdTests.java | 74 ++++++++ .../http/client/generator/TypeSpecPlugin.java | 10 + 23 files changed, 1077 insertions(+), 40 deletions(-) create mode 100644 .chronus/changes/java-tcgc-lro-metadata-2026-10-12-17-55-0.md create mode 100644 packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/extension/model/codemodel/LongRunningOperationIdMetadata.java create mode 100644 packages/http-client-java/generator/http-client-generator-core/src/main/resources/OperationIdPollingStrategy.java create mode 100644 packages/http-client-java/generator/http-client-generator-core/src/main/resources/SyncOperationIdPollingStrategy.java create mode 100644 packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategy.java create mode 100644 packages/http-client-java/generator/http-client-generator-test/src/main/java/azure/clientgenerator/core/lro/operationid/implementation/SyncOperationIdPollingStrategy.java create mode 100644 packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/operationid/OperationIdTests.java 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..e392697bfb8 --- /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" +--- + +Support the LRO operation ID from `@lroOperationId`. Poll-result models now have a read-only `getOperationId()` method. It returns the operation ID from the status monitor response body when it is there, and otherwise from the polling URL. Polling still uses the complete polling URL. Status values from `@lroStatusMetadata` are available on the typed poll result. + +```java +SyncPoller poller = client.beginAnalyze(); +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 d07b34b8d75..26ef86b37aa 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, SdkModelPropertyType, SdkModelType, @@ -80,7 +81,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 } from "./common/operation.js"; import { @@ -1547,12 +1551,23 @@ 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 ?? {}; + pollingSchema.extensions["x-ms-lro-operation-id"] = { ...operationId }; + } + } + op.lroMetadata = createLongRunningMetadata( true, pollingSchema, finalSchema, pollingStrategy, finalResultPropertySerializedName, + operationId, ); return op.lroMetadata; } @@ -1560,6 +1575,34 @@ 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 statusMonitorOperation = + statusMonitorStep?.kind === "nextOperationReference" + ? statusMonitorStep.target.operation + : statusMonitorStep?.operation; + if (statusMonitorOperation) { + operationId.pathTemplate = statusMonitorOperation.path; + operationId.pathParameterSerializedName = selection.pathParameter.serializedName; + } + } 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], + ); + } + } + 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..1a21d3b6ca6 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,25 @@ 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; + /** 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 +28,7 @@ export function createLongRunningMetadata( finalResultType?: Schema, pollingStrategy?: Metadata, finalResultPropertySerializedName?: string, + operationId?: LongRunningOperationIdMetadata, ): LongRunningMetadata { return { longRunning, @@ -21,5 +36,6 @@ export function createLongRunningMetadata( finalResultType, pollingStrategy, finalResultPropertySerializedName, + 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/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 64191eaf686..4a5395c785c 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 @@ -368,6 +368,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..575a18d081a --- /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,84 @@ +// 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 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 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; + } +} 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 72104af163f..02b1ef4fc73 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 @@ -352,6 +352,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..3a1bd1c47d2 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,21 @@ 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 operationIdPollingStrategy = String.format("new %s.%s<>(%s, %s, %s)", packageName, + ClientModelUtil.OPERATION_ID_POLLING_STRATEGY, pollingStrategy, pathTemplateArg, pathParameterArg); + final String syncOperationIdPollingStrategy = String.format("new %s.%s<>(%s, %s, %s)", packageName, + ClientModelUtil.SYNC_OPERATION_ID_POLLING_STRATEGY, syncPollingStrategy, pathTemplateArg, + pathParameterArg); + return new MethodPollingDetails(operationIdPollingStrategy, syncOperationIdPollingStrategy, pollResultType, + finalResultType, pollIntervalInSeconds); + } return new MethodPollingDetails(pollingStrategy, syncPollingStrategy, pollResultType, finalResultType, pollIntervalInSeconds); } @@ -236,8 +254,14 @@ 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 + = settings.isAzureV1() && !settings.isFluent() && pollingSettings.getPollResultType() == null + ? 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/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 c77ad5e04a8..210d2b81eaf 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; + // Set of non-final properties that are set on access. // This pattern is used as when the ClientModel is initialized the ModelMapper may not have mapped all models // related to the one being initialized. When that happens some properties may not be set correctly. For example, @@ -173,6 +179,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, @@ -180,7 +187,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) { + ApiMetadata apiMetadata, LongRunningOperationIdMetadata lroOperationId) { this.packageName = packageKeyword; this.name = name; this.fullName = packageName + "." + name; @@ -204,6 +211,7 @@ protected ClientModel(String packageKeyword, String name, List imports, this.implementationDetails = implementationDetails; this.usedInXml = usedInXml; this.apiMetadata = apiMetadata; + this.lroOperationId = lroOperationId; this.serializationFormats = serializationFormats; } @@ -216,6 +224,15 @@ public ApiMetadata getApiMetadata() { return apiMetadata; } + /** + * 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. * @@ -685,6 +702,7 @@ public static class Builder { private boolean usedInXml; private ApiMetadata apiMetadata = new ApiMetadata.Builder().build(); private Set serializationFormats = Set.of(); + private LongRunningOperationIdMetadata lroOperationId; /** * Sets the package that this model class belongs to. @@ -900,6 +918,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. * @@ -920,7 +949,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); + usedInXml, serializationFormats, apiMetadata, 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 304df325851..896d5c80cf3 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 @@ -3,6 +3,7 @@ package com.microsoft.typespec.http.client.generator.core.template; +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.implementation.ClientModelPropertiesManager; import com.microsoft.typespec.http.client.generator.core.implementation.PolymorphicDiscriminatorHandler; @@ -60,6 +61,9 @@ public class ModelTemplate implements IJavaTemplate { private static final String MISSING_SCHEMA = "MISSING·SCHEMA"; private static final ModelTemplate INSTANCE = new ModelTemplate(); + private static final String LRO_OPERATION_ID_FIELD_NAME = "operationId"; + private static final String LRO_OPERATION_ID_GETTER_NAME = "getOperationId"; + private static final String LRO_OPERATION_ID_PROPERTY_VALUE_NAME = "propertyValue"; protected ModelTemplate() { } @@ -255,6 +259,8 @@ public final void write(ClientModel model, JavaFile javaFile) { } } + addLroOperationIdAccessors(classBlock, model); + if (settings.getClientFlattenAnnotationTarget() == JavaSettings.ClientFlattenAnnotationTarget.NONE) { // reference to properties from flattened client model for (ClientModelPropertyReference propertyReference : propertyReferences) { @@ -484,6 +490,12 @@ private void addImports(Set imports, ClientModel model, JavaSettings set model.addImportsTo(imports, settings); + // add long-running operation ID related imports + if (getLroOperationId(model) != null && getLroOperationId(model).hasPathSource()) { + imports.add(settings.getPackage(settings.getImplementationSubpackage()) + "." + + ClientModelUtil.OPERATION_ID_POLLING_STRATEGY); + } + // add Json merge patch related imports if (ClientModelUtil.isJsonMergePatchModel(model, settings)) { imports.add(settings.getPackage(settings.getImplementationSubpackage()) + "." @@ -1520,4 +1532,94 @@ private void addJsonMergePatchRelatedPropertyAndAccessors(JavaClass classBlock, staticBlock.line("});"); }); } + + /** + * Gets the sources of the long-running operation ID, if the model can generate the "getOperationId" method. + *

+ * The method is not generated, if the model already has a property named "operationId" or a "getOperationId" + * method. + * + * @param model the model. + * @return the sources of the long-running operation ID, or null. + */ + private static LongRunningOperationIdMetadata getLroOperationId(ClientModel model) { + final LongRunningOperationIdMetadata lroOperationId = model.getLroOperationId(); + if (lroOperationId == null) { + return null; + } + final boolean conflict + = Stream.concat(model.getProperties().stream(), ClientModelUtil.getParentProperties(model).stream()) + .anyMatch(p -> LRO_OPERATION_ID_FIELD_NAME.equals(p.getName()) + || LRO_OPERATION_ID_GETTER_NAME.equals(p.getGetterName())); + return conflict ? null : lroOperationId; + } + + private static ClientModelProperty getLroOperationIdProperty(ClientModel model, + LongRunningOperationIdMetadata lroOperationId) { + if (lroOperationId.getPropertySerializedName() == null) { + return null; + } + return Stream.concat(model.getProperties().stream(), ClientModelUtil.getParentProperties(model).stream()) + .filter(p -> lroOperationId.getPropertySerializedName().equals(p.getSerializedName()) + && ClassType.STRING.equals(p.getClientType())) + .findFirst() + .orElse(null); + } + + /** + * Adds the "getOperationId" method, and the accessor for OperationIdPollingStrategy to set the operation ID from + * the polling URL. + * + * @param classBlock the class block. + * @param model the model. + */ + private void addLroOperationIdAccessors(JavaClass classBlock, ClientModel model) { + final LongRunningOperationIdMetadata lroOperationId = getLroOperationId(model); + if (lroOperationId == null) { + return; + } + final ClientModelProperty property = getLroOperationIdProperty(model, lroOperationId); + final boolean hasPathSource = lroOperationId.hasPathSource(); + if (property == null && !hasPathSource) { + return; + } + + if (hasPathSource) { + classBlock.blockComment("The ID of the long-running operation, from the polling URL."); + addGeneratedAnnotation(classBlock); + classBlock.privateMemberVariable("String " + LRO_OPERATION_ID_FIELD_NAME); + + classBlock.staticBlock(staticBlock -> staticBlock.line(ClientModelUtil.OPERATION_ID_POLLING_STRATEGY + + ".setOperationIdAccessor(" + model.getName() + ".class, (model, " + LRO_OPERATION_ID_FIELD_NAME + + ") -> model." + LRO_OPERATION_ID_FIELD_NAME + " = " + LRO_OPERATION_ID_FIELD_NAME + ");")); + } + + 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."); + }); + addGeneratedAnnotation(classBlock); + classBlock.publicMethod("String " + LRO_OPERATION_ID_GETTER_NAME + "()", methodBlock -> { + if (property != null && hasPathSource) { + methodBlock.line( + "String " + LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " = this." + property.getGetterName() + "();"); + methodBlock.methodReturn(LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " != null ? " + + LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " : this." + LRO_OPERATION_ID_FIELD_NAME); + } else if (property != null) { + methodBlock.methodReturn("this." + property.getGetterName() + "()"); + } else { + methodBlock.methodReturn("this." + LRO_OPERATION_ID_FIELD_NAME); + } + }); + } } 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..065380b3a08 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 @@ -67,6 +67,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 +836,27 @@ 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()); + } + /** * 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..02053c5e99f --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/resources/OperationIdPollingStrategy.java @@ -0,0 +1,166 @@ +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_KEYS = { "Operation-Location", "Azure-AsyncOperation", "Location" }; + private static final Map, BiConsumer> ACCESSORS = new ConcurrentHashMap<>(); + + private final PollingStrategy pollingStrategy; + private final Pattern pathPattern; + + /** + * 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. + */ + public OperationIdPollingStrategy(PollingStrategy pollingStrategy, String pathTemplate, + String pathParameterName) { + this.pollingStrategy = Objects.requireNonNull(pollingStrategy, "'pollingStrategy' cannot be null."); + this.pathPattern = createPathPattern(pathTemplate, pathParameterName); + } + + /** + * 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) { + 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; + } + BiConsumer accessor = ACCESSORS.get(value.getClass()); + if (accessor == null) { + return pollResponse; + } + for (String key : POLLING_URL_KEYS) { + String operationId = getOperationId(pollingContext.getData(key), pathPattern); + if (operationId != null) { + accessor.accept(value, operationId); + break; + } + } + return pollResponse; + } + + 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..fc317b42c3e --- /dev/null +++ b/packages/http-client-java/generator/http-client-generator-core/src/main/resources/SyncOperationIdPollingStrategy.java @@ -0,0 +1,78 @@ +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; + + /** + * 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. + */ + public SyncOperationIdPollingStrategy(SyncPollingStrategy pollingStrategy, String pathTemplate, + String pathParameterName) { + this.pollingStrategy = Objects.requireNonNull(pollingStrategy, "'pollingStrategy' cannot be null."); + this.pathPattern = OperationIdPollingStrategy.createPathPattern(pathTemplate, pathParameterName); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean canPoll(Response initialResponse) { + return pollingStrategy.canPoll(initialResponse); + } + + /** + * {@inheritDoc} + */ + @Override + public PollResponse onInitialResponse(Response response, PollingContext pollingContext, + TypeReference pollResponseType) { + 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/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..64a7c12f3ca 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"), 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"), TypeReference.createInstance(DocumentAnalysisStatus.class), TypeReference.createInstance(DocumentAnalysisResult.class)); } @@ -778,14 +784,16 @@ 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"), TypeReference.createInstance(TranslationWithPathStatus.class), TypeReference.createInstance(TranslationResult.class)); } @@ -805,14 +813,16 @@ 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"), 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..faccdcf8bfe --- /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,172 @@ +// 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_KEYS = { "Operation-Location", "Azure-AsyncOperation", "Location" }; + private static final Map, BiConsumer> ACCESSORS = new ConcurrentHashMap<>(); + + private final PollingStrategy pollingStrategy; + private final Pattern pathPattern; + + /** + * 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. + */ + public OperationIdPollingStrategy(PollingStrategy pollingStrategy, String pathTemplate, + String pathParameterName) { + this.pollingStrategy = Objects.requireNonNull(pollingStrategy, "'pollingStrategy' cannot be null."); + this.pathPattern = createPathPattern(pathTemplate, pathParameterName); + } + + /** + * 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) { + 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; + } + BiConsumer accessor = ACCESSORS.get(value.getClass()); + if (accessor == null) { + return pollResponse; + } + for (String key : POLLING_URL_KEYS) { + String operationId = getOperationId(pollingContext.getData(key), pathPattern); + if (operationId != null) { + accessor.accept(value, operationId); + break; + } + } + return pollResponse; + } + + 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..c0e52b811fd --- /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,84 @@ +// 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; + + /** + * 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. + */ + public SyncOperationIdPollingStrategy(SyncPollingStrategy pollingStrategy, String pathTemplate, + String pathParameterName) { + this.pollingStrategy = Objects.requireNonNull(pollingStrategy, "'pollingStrategy' cannot be null."); + this.pathPattern = OperationIdPollingStrategy.createPathPattern(pathTemplate, pathParameterName); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean canPoll(Response initialResponse) { + return pollingStrategy.canPoll(initialResponse); + } + + /** + * {@inheritDoc} + */ + @Override + public PollResponse onInitialResponse(Response response, PollingContext pollingContext, + TypeReference pollResponseType) { + 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..26c7a99098d 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; @@ -59,6 +60,27 @@ public DocumentAnalysisResult getResult() { return this.result; } + /* + * The ID of the long-running operation, from the polling URL. + */ + @Generated + private String operationId; + + static { + OperationIdPollingStrategy.setOperationIdAccessor(DocumentAnalysisStatus.class, + (model, operationId) -> model.operationId = operationId); + } + + /** + * Get the ID of the long-running operation, from the polling URL. + * + * @return the ID of the long-running operation. + */ + @Generated + public String getOperationId() { + return this.operationId; + } + /** * {@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..c343f65d1bf 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,16 @@ 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. + */ + @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..faa38f397b0 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; @@ -77,6 +78,29 @@ public TranslationResult getResult() { return this.result; } + /* + * The ID of the long-running operation, from the polling URL. + */ + @Generated + private String operationId; + + static { + OperationIdPollingStrategy.setOperationIdAccessor(TranslationWithPathStatus.class, + (model, operationId) -> model.operationId = operationId); + } + + /** + * 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. + */ + @Generated + public String getOperationId() { + String propertyValue = this.getId(); + return propertyValue != null ? propertyValue : this.operationId; + } + /** * {@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/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..bdfd6831266 --- /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,74 @@ +// 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.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/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 d8541e4e369..84f6eb2d2b1 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 @@ -162,6 +162,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 From 45e7b9d74227fa96b87260979a1125b0285edc5b Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Mon, 16 Nov 2026 12:55:56 -0500 Subject: [PATCH 2/5] fix(http-client-java): avoid initializing unused LRO schemas Compare the poll result with the cached schema rather than invoking its lazy getter, preserving existing LRO model output. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/http-client-java/emitter/src/code-model-builder.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 26ef86b37aa..96a6f9404f2 100644 --- a/packages/http-client-java/emitter/src/code-model-builder.ts +++ b/packages/http-client-java/emitter/src/code-model-builder.ts @@ -1553,7 +1553,7 @@ 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) { + if (pollingSchema && pollingSchema !== this._pollResultSchema) { operationId = this.processLroOperationIdMetadata(lroMetadata); if (operationId) { pollingSchema.extensions = pollingSchema.extensions ?? {}; From 910a6e413803b85a76c8d0a8c23fb91ad8c76e59 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Wed, 18 Nov 2026 11:27:23 -0500 Subject: [PATCH 3/5] fix(java): address LRO operation ID review feedback Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- ...va-tcgc-lro-metadata-2026-10-12-17-55-0.md | 4 +- .../emitter/src/code-model-builder.ts | 62 ++++++++++-- .../src/common/long-running-metadata.ts | 2 + .../emitter/test/code-model.test.ts | 49 ++++++++++ .../test/fixtures/lro-operation-id.tsp | 56 +++++++++++ .../LongRunningOperationIdMetadata.java | 21 +++- .../core/mapper/PollingMetadata.java | 14 +-- .../core/mapper/ProxyMethodMapper.java | 2 +- .../core/template/ModelTemplate.java | 91 ++++++++++++----- .../generator/core/util/ClientModelUtil.java | 16 +++ .../resources/OperationIdPollingStrategy.java | 31 ++++-- .../SyncOperationIdPollingStrategy.java | 6 +- .../LroOperationIdModelTemplateTests.java | 93 ++++++++++++++++++ .../implementation/OperationIdClientImpl.java | 10 +- .../OperationIdPollingStrategy.java | 31 ++++-- .../SyncOperationIdPollingStrategy.java | 6 +- .../models/DocumentAnalysisStatus.java | 27 ++--- .../operationid/models/TranslationStatus.java | 3 +- .../models/TranslationWithPathStatus.java | 27 ++--- .../core/lro/metadata/MetadataTests.java | 6 +- .../lro/operationid/OperationIdTests.java | 7 +- .../OperationIdPollingStrategyTests.java | 98 +++++++++++++++++++ .../http/client/generator/TypeSpecPlugin.java | 45 +++++++++ 23 files changed, 615 insertions(+), 92 deletions(-) create mode 100644 packages/http-client-java/emitter/test/fixtures/lro-operation-id.tsp create mode 100644 packages/http-client-java/generator/http-client-generator-core/src/test/java/com/microsoft/typespec/http/client/generator/core/template/LroOperationIdModelTemplateTests.java create mode 100644 packages/http-client-java/generator/http-client-generator-test/src/test/java/azure/clientgenerator/core/lro/operationid/implementation/OperationIdPollingStrategyTests.java 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 index e392697bfb8..50d5f2d6aa5 100644 --- 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 @@ -4,9 +4,9 @@ packages: - "@typespec/http-client-java" --- -Support the LRO operation ID from `@lroOperationId`. Poll-result models now have a read-only `getOperationId()` method. It returns the operation ID from the status monitor response body when it is there, and otherwise from the polling URL. Polling still uses the complete polling URL. Status values from `@lroStatusMetadata` are available on the typed poll result. +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(); +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 b859796d9c3..3cca8ab6719 100644 --- a/packages/http-client-java/emitter/src/code-model-builder.ts +++ b/packages/http-client-java/emitter/src/code-model-builder.ts @@ -66,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"; @@ -1796,7 +1796,26 @@ export class CodeModelBuilder { operationId = this.processLroOperationIdMetadata(lroMetadata); if (operationId) { pollingSchema.extensions = pollingSchema.extensions ?? {}; - pollingSchema.extensions["x-ms-lro-operation-id"] = { ...operationId }; + 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, + }; } } @@ -1824,19 +1843,50 @@ export class CodeModelBuilder { for (const selection of lroMetadata.operationId) { if (selection.kind === "path") { const statusMonitorStep = lroMetadata.statusMonitorStep; - const statusMonitorOperation = + const selectedLink = statusMonitorStep?.kind === "nextOperationReference" - ? statusMonitorStep.target.operation - : statusMonitorStep?.operation; - if (statusMonitorOperation) { + ? 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; 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 1a21d3b6ca6..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 @@ -9,6 +9,8 @@ export interface LongRunningOperationIdMetadata { 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; } 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..e82edcc8957 --- /dev/null +++ b/packages/http-client-java/emitter/test/fixtures/lro-operation-id.tsp @@ -0,0 +1,56 @@ +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/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 index 575a18d081a..ac7df68c611 100644 --- 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 @@ -11,6 +11,7 @@ public class LongRunningOperationIdMetadata { private String pathTemplate; private String pathParameterSerializedName; + private String pollingHeaderName; private String propertySerializedName; /** @@ -55,6 +56,24 @@ 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. * @@ -79,6 +98,6 @@ public void setPropertySerializedName(String propertySerializedName) { * @return whether the operation ID is extracted from the path of the polling URL. */ public boolean hasPathSource() { - return pathTemplate != null && pathParameterSerializedName != null; + 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/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 3a1bd1c47d2..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 @@ -97,11 +97,13 @@ MethodPollingDetails asMethodPollingDetails() { final String pathTemplateArg = ClassType.STRING.defaultValueExpression(operationId.getPathTemplate()); final String pathParameterArg = ClassType.STRING.defaultValueExpression(operationId.getPathParameterSerializedName()); - final String operationIdPollingStrategy = String.format("new %s.%s<>(%s, %s, %s)", packageName, - ClientModelUtil.OPERATION_ID_POLLING_STRATEGY, pollingStrategy, pathTemplateArg, pathParameterArg); - final String syncOperationIdPollingStrategy = String.format("new %s.%s<>(%s, %s, %s)", packageName, + 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); + pathParameterArg, headerArg); return new MethodPollingDetails(operationIdPollingStrategy, syncOperationIdPollingStrategy, pollResultType, finalResultType, pollIntervalInSeconds); } @@ -256,9 +258,7 @@ private static PollingMetadata create(LongRunningMetadata lroMetadata, PollingSe // The operation ID is only populated on the poll result model generated from TypeSpec, for azure-core. final LongRunningOperationIdMetadata operationId - = settings.isAzureV1() && !settings.isFluent() && pollingSettings.getPollResultType() == null - ? lroMetadata.getOperationId() - : null; + = ClientModelUtil.supportsLroOperationId(settings, pollingSettings) ? lroMetadata.getOperationId() : null; return new PollingMetadata(pollingStrategy, syncPollingStrategy, pollResultType, finalResultType, pollingSettings.getPollIntervalInSeconds(), httpMethod, 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/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 50794049de8..1193fb5572b 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 @@ -3,8 +3,10 @@ package com.microsoft.typespec.http.client.generator.core.template; +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.implementation.ClientModelPropertiesManager; import com.microsoft.typespec.http.client.generator.core.implementation.PolymorphicDiscriminatorHandler; import com.microsoft.typespec.http.client.generator.core.model.clientmodel.Annotation; @@ -53,6 +55,7 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.slf4j.Logger; /** * Writes a ClientModel to a JavaFile. @@ -61,7 +64,8 @@ public class ModelTemplate implements IJavaTemplate { private static final String MISSING_SCHEMA = "MISSING·SCHEMA"; private static final ModelTemplate INSTANCE = new ModelTemplate(); - private static final String LRO_OPERATION_ID_FIELD_NAME = "operationId"; + private static final Logger LOGGER = new PluginLogger(Javagen.getPluginInstance(), ModelTemplate.class); + private static final String LRO_OPERATION_ID_FIELD_NAME = "lroOperationId"; private static final String LRO_OPERATION_ID_GETTER_NAME = "getOperationId"; private static final String LRO_OPERATION_ID_PROPERTY_VALUE_NAME = "propertyValue"; @@ -158,6 +162,7 @@ public final void write(ClientModel model, JavaFile javaFile) { // properties addProperties(propertiesManager, classBlock); + addLroOperationIdField(classBlock, model); // add jsonMergePatch related properties and accessors if (ClientModelUtil.isJsonMergePatchModel(model, settings)) { @@ -180,7 +185,23 @@ public final void write(ClientModel model, JavaFile javaFile) { if (!property.isPolymorphicDiscriminator() || PolymorphicDiscriminatorHandler.generateGetter(model, property, settings)) { - generateGetterJavadoc(classBlock, property); + LongRunningOperationIdMetadata metadata = getLroOperationId(model); + boolean usesOperationIdFallback = metadata != null + && metadata.hasPathSource() + && property == getLroOperationIdProperty(model, metadata) + && LRO_OPERATION_ID_GETTER_NAME.equals(property.getGetterName()) + && ClassType.STRING.equals(propertyWireType); + if (usesOperationIdFallback) { + 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."); + }); + } else { + generateGetterJavadoc(classBlock, property); + } addGeneratedAnnotation(classBlock); if (property.isAdditionalProperties() && !settings.isStreamStyleSerialization()) { classBlock.annotation("JsonAnyGetter"); @@ -195,9 +216,15 @@ 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 (usesOperationIdFallback) { + methodBlock.methodReturn("this." + property.getName() + " != null ? this." + + property.getName() + " : this." + LRO_OPERATION_ID_FIELD_NAME); + } else { + addGetterMethod(propertyWireType, propertyClientType, property, treatAsXml, methodBlock, + settings); + } + }); } if (ClientModelUtil.needsPublicSetter(property, settings) && !immutableModel) { @@ -1539,10 +1566,7 @@ private void addJsonMergePatchRelatedPropertyAndAccessors(JavaClass classBlock, } /** - * Gets the sources of the long-running operation ID, if the model can generate the "getOperationId" method. - *

- * The method is not generated, if the model already has a property named "operationId" or a "getOperationId" - * method. + * Gets the sources of the long-running operation ID, if the model can generate the accessor. * * @param model the model. * @return the sources of the long-running operation ID, or null. @@ -1554,8 +1578,11 @@ private static LongRunningOperationIdMetadata getLroOperationId(ClientModel mode } final boolean conflict = Stream.concat(model.getProperties().stream(), ClientModelUtil.getParentProperties(model).stream()) - .anyMatch(p -> LRO_OPERATION_ID_FIELD_NAME.equals(p.getName()) - || LRO_OPERATION_ID_GETTER_NAME.equals(p.getGetterName())); + .anyMatch(p -> (lroOperationId.hasPathSource() && LRO_OPERATION_ID_FIELD_NAME.equals(p.getName())) + || (LRO_OPERATION_ID_GETTER_NAME.equals(p.getGetterName()) + && (!Objects.equals(lroOperationId.getPropertySerializedName(), p.getSerializedName()) + || !ClassType.STRING.equals(p.getClientType()) + || !ClassType.STRING.equals(p.getWireType())))); return conflict ? null : lroOperationId; } @@ -1581,22 +1608,27 @@ private static ClientModelProperty getLroOperationIdProperty(ClientModel model, private void addLroOperationIdAccessors(JavaClass classBlock, ClientModel model) { final LongRunningOperationIdMetadata lroOperationId = getLroOperationId(model); if (lroOperationId == 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 = getLroOperationIdProperty(model, lroOperationId); final boolean hasPathSource = lroOperationId.hasPathSource(); + if (lroOperationId.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.", + lroOperationId.getPropertySerializedName(), model.getName()); + } if (property == null && !hasPathSource) { return; } - if (hasPathSource) { - classBlock.blockComment("The ID of the long-running operation, from the polling URL."); - addGeneratedAnnotation(classBlock); - classBlock.privateMemberVariable("String " + LRO_OPERATION_ID_FIELD_NAME); - - classBlock.staticBlock(staticBlock -> staticBlock.line(ClientModelUtil.OPERATION_ID_POLLING_STRATEGY - + ".setOperationIdAccessor(" + model.getName() + ".class, (model, " + LRO_OPERATION_ID_FIELD_NAME - + ") -> model." + LRO_OPERATION_ID_FIELD_NAME + " = " + LRO_OPERATION_ID_FIELD_NAME + ");")); + boolean usesExistingGetter = property != null && LRO_OPERATION_ID_GETTER_NAME.equals(property.getGetterName()); + if (usesExistingGetter && (!hasPathSource || model.getProperties().contains(property))) { + return; } final String description; @@ -1611,13 +1643,14 @@ private void addLroOperationIdAccessors(JavaClass classBlock, ClientModel model) } classBlock.javadocComment(comment -> { comment.description(description); - comment.methodReturns("the ID of the long-running operation."); + 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(classBlock); classBlock.publicMethod("String " + LRO_OPERATION_ID_GETTER_NAME + "()", methodBlock -> { if (property != null && hasPathSource) { - methodBlock.line( - "String " + LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " = this." + property.getGetterName() + "();"); + methodBlock.line("String " + LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " = " + + (usesExistingGetter ? "super." : "this.") + property.getGetterName() + "();"); methodBlock.methodReturn(LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " != null ? " + LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " : this." + LRO_OPERATION_ID_FIELD_NAME); } else if (property != null) { @@ -1627,4 +1660,18 @@ private void addLroOperationIdAccessors(JavaClass classBlock, ClientModel model) } }); } + + private void addLroOperationIdField(JavaClass classBlock, ClientModel model) { + LongRunningOperationIdMetadata metadata = getLroOperationId(model); + if (metadata == null || !metadata.hasPathSource()) { + return; + } + classBlock.javadocComment(comment -> comment + .description("The operation ID from the polling URL, set by the polling strategy after deserialization.")); + addGeneratedAnnotation(classBlock); + classBlock.privateMemberVariable("String " + LRO_OPERATION_ID_FIELD_NAME); + classBlock.staticBlock(staticBlock -> staticBlock + .line(ClientModelUtil.OPERATION_ID_POLLING_STRATEGY + ".setOperationIdAccessor(" + model.getName() + + ".class, (model, operationId) -> model." + LRO_OPERATION_ID_FIELD_NAME + " = operationId);")); + } } 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 065380b3a08..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; @@ -846,6 +847,7 @@ public static boolean requireOperationIdPollingStrategy(CodeModel codeModel) { if (CoreUtils.isNullOrEmpty(codeModel.getClients())) { return false; } + return codeModel.getClients() .stream() .filter(client -> client.getOperationGroups() != null) @@ -857,6 +859,20 @@ public static boolean requireOperationIdPollingStrategy(CodeModel codeModel) { && 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 index 02053c5e99f..4b3e7e78d31 100644 --- 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 @@ -26,11 +26,12 @@ * @param the type of the final result object to deserialize into */ public final class OperationIdPollingStrategy implements PollingStrategy { - private static final String[] POLLING_URL_KEYS = { "Operation-Location", "Azure-AsyncOperation", "Location" }; + 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. @@ -38,11 +39,13 @@ public final class OperationIdPollingStrategy implements PollingStrategy pollingStrategy, String pathTemplate, - String pathParameterName) { + 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."); } /** @@ -71,6 +74,7 @@ public Mono canPoll(Response initialResponse) { @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)); } @@ -126,20 +130,29 @@ static PollResponse setOperationId(PollResponse pollResponse, PollingC if (value == null) { return pollResponse; } - BiConsumer accessor = ACCESSORS.get(value.getClass()); + Class valueType = value.getClass(); + BiConsumer accessor = null; + while (valueType != null && accessor == null) { + accessor = ACCESSORS.get(valueType); + valueType = valueType.getSuperclass(); + } if (accessor == null) { return pollResponse; } - for (String key : POLLING_URL_KEYS) { - String operationId = getOperationId(pollingContext.getData(key), pathPattern); - if (operationId != null) { - accessor.accept(value, operationId); - break; - } + 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; 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 index fc317b42c3e..4f4867d328b 100644 --- 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 @@ -19,6 +19,7 @@ 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. @@ -26,11 +27,13 @@ public final class SyncOperationIdPollingStrategy implements SyncPollingSt * @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 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."); } /** @@ -47,6 +50,7 @@ public boolean canPoll(Response initialResponse) { @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); } 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 64a7c12f3ca..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 @@ -396,7 +396,7 @@ public PollerFlux beginAnalyzeWi .setServiceVersion(this.getServiceVersion().getVersion()), "result"), "/azure/client-generator-core/lro/operation-id/documentModels/{modelId}/analyzeResults/{resultId}", - "resultId"), + "resultId", "operation-location"), TypeReference.createInstance(DocumentAnalysisStatus.class), TypeReference.createInstance(DocumentAnalysisResult.class)); } @@ -426,7 +426,7 @@ public SyncPoller beginAnalyzeWi .setServiceVersion(this.getServiceVersion().getVersion()), "result"), "/azure/client-generator-core/lro/operation-id/documentModels/{modelId}/analyzeResults/{resultId}", - "resultId"), + "resultId", "operation-location"), TypeReference.createInstance(DocumentAnalysisStatus.class), TypeReference.createInstance(DocumentAnalysisResult.class)); } @@ -793,7 +793,8 @@ private Response startTranslationWithPathWithResponse(RequestOptions reque : Context.NONE) .setServiceVersion(this.getServiceVersion().getVersion()), "result"), - "/azure/client-generator-core/lro/operation-id/translations/operations/{operationId}", "operationId"), + "/azure/client-generator-core/lro/operation-id/translations/operations/{operationId}", "operationId", + "operation-location"), TypeReference.createInstance(TranslationWithPathStatus.class), TypeReference.createInstance(TranslationResult.class)); } @@ -822,7 +823,8 @@ private Response startTranslationWithPathWithResponse(RequestOptions reque : Context.NONE) .setServiceVersion(this.getServiceVersion().getVersion()), "result"), - "/azure/client-generator-core/lro/operation-id/translations/operations/{operationId}", "operationId"), + "/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 index faccdcf8bfe..cfea5102f8a 100644 --- 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 @@ -32,11 +32,12 @@ * @param the type of the final result object to deserialize into */ public final class OperationIdPollingStrategy implements PollingStrategy { - private static final String[] POLLING_URL_KEYS = { "Operation-Location", "Azure-AsyncOperation", "Location" }; + 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. @@ -44,11 +45,13 @@ public final class OperationIdPollingStrategy implements PollingStrategy pollingStrategy, String pathTemplate, - String pathParameterName) { + 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."); } /** @@ -77,6 +80,7 @@ public Mono canPoll(Response initialResponse) { @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)); } @@ -132,20 +136,29 @@ static PollResponse setOperationId(PollResponse pollResponse, PollingC if (value == null) { return pollResponse; } - BiConsumer accessor = ACCESSORS.get(value.getClass()); + Class valueType = value.getClass(); + BiConsumer accessor = null; + while (valueType != null && accessor == null) { + accessor = ACCESSORS.get(valueType); + valueType = valueType.getSuperclass(); + } if (accessor == null) { return pollResponse; } - for (String key : POLLING_URL_KEYS) { - String operationId = getOperationId(pollingContext.getData(key), pathPattern); - if (operationId != null) { - accessor.accept(value, operationId); - break; - } + 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; 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 index c0e52b811fd..35a740d214f 100644 --- 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 @@ -25,6 +25,7 @@ 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. @@ -32,11 +33,13 @@ public final class SyncOperationIdPollingStrategy implements SyncPollingSt * @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 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."); } /** @@ -53,6 +56,7 @@ public boolean canPoll(Response initialResponse) { @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); } 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 26c7a99098d..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 @@ -30,6 +30,17 @@ public final class DocumentAnalysisStatus implements JsonSerializable model.lroOperationId = operationId); + } + /** * Creates an instance of DocumentAnalysisStatus class. * @@ -60,25 +71,15 @@ public DocumentAnalysisResult getResult() { return this.result; } - /* - * The ID of the long-running operation, from the polling URL. - */ - @Generated - private String operationId; - - static { - OperationIdPollingStrategy.setOperationIdAccessor(DocumentAnalysisStatus.class, - (model, operationId) -> model.operationId = operationId); - } - /** * Get the ID of the long-running operation, from the polling URL. * - * @return the ID of the long-running operation. + * @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.operationId; + return this.lroOperationId; } /** 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 c343f65d1bf..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 @@ -80,7 +80,8 @@ public TranslationResult getResult() { /** * Get the ID of the long-running operation, from the {@code id} property. * - * @return the ID of the long-running operation. + * @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() { 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 faa38f397b0..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 @@ -36,6 +36,17 @@ public final class TranslationWithPathStatus implements JsonSerializable model.lroOperationId = operationId); + } + /** * Creates an instance of TranslationWithPathStatus class. * @@ -78,27 +89,17 @@ public TranslationResult getResult() { return this.result; } - /* - * The ID of the long-running operation, from the polling URL. - */ - @Generated - private String operationId; - - static { - OperationIdPollingStrategy.setOperationIdAccessor(TranslationWithPathStatus.class, - (model, operationId) -> model.operationId = operationId); - } - /** * 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. + * @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.operationId; + return propertyValue != null ? propertyValue : this.lroOperationId; } /** 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 index bdfd6831266..63dda6f46da 100644 --- 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 @@ -66,7 +66,12 @@ public void testStartTranslationWithPath() { OperationIdClient client = new OperationIdClientBuilder().buildClient(); SyncPoller poller = client.beginStartTranslationWithPath(); - PollResponse response = poller.waitForCompletion(); + 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 2bcc94177e6..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); From 646738f0213d7ab6dc0f05eec7c27643b8be9636 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Wed, 18 Nov 2026 11:33:15 -0500 Subject: [PATCH 4/5] style(java): format LRO test fixture Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../http-client-java/emitter/test/fixtures/lro-operation-id.tsp | 1 + 1 file changed, 1 insertion(+) 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 index e82edcc8957..9cff2a442b5 100644 --- a/packages/http-client-java/emitter/test/fixtures/lro-operation-id.tsp +++ b/packages/http-client-java/emitter/test/fixtures/lro-operation-id.tsp @@ -31,6 +31,7 @@ op analyze(): Azure.Core.Foundations.AcceptedResponse & model CombinedStatus { @lroOperationId id: string; + status: Azure.Core.Foundations.OperationState; result?: Result; } From dbd7cbaf50c28385ae28551f054af4f267c1c731 Mon Sep 17 00:00:00 2001 From: Weidong Xu Date: Thu, 19 Nov 2026 23:25:38 +0800 Subject: [PATCH 5/5] refactor(http-client-java): isolate LRO operation ID model generation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b9420119-96ca-4665-8899-a2a907c1efec --- .../core/template/ModelTemplate.java | 152 +------------ .../util/LroOperationIdModelHelper.java | 213 ++++++++++++++++++ 2 files changed, 220 insertions(+), 145 deletions(-) create mode 100644 packages/http-client-java/generator/http-client-generator-core/src/main/java/com/microsoft/typespec/http/client/generator/core/template/util/LroOperationIdModelHelper.java 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 1193fb5572b..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 @@ -3,10 +3,7 @@ package com.microsoft.typespec.http.client.generator.core.template; -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.implementation.ClientModelPropertiesManager; import com.microsoft.typespec.http.client.generator.core.implementation.PolymorphicDiscriminatorHandler; import com.microsoft.typespec.http.client.generator.core.model.clientmodel.Annotation; @@ -30,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; @@ -55,7 +53,6 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.slf4j.Logger; /** * Writes a ClientModel to a JavaFile. @@ -64,10 +61,6 @@ public class ModelTemplate implements IJavaTemplate { private static final String MISSING_SCHEMA = "MISSING·SCHEMA"; private static final ModelTemplate INSTANCE = new ModelTemplate(); - private static final Logger LOGGER = new PluginLogger(Javagen.getPluginInstance(), ModelTemplate.class); - private static final String LRO_OPERATION_ID_FIELD_NAME = "lroOperationId"; - private static final String LRO_OPERATION_ID_GETTER_NAME = "getOperationId"; - private static final String LRO_OPERATION_ID_PROPERTY_VALUE_NAME = "propertyValue"; protected ModelTemplate() { } @@ -90,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)); @@ -162,7 +157,7 @@ public final void write(ClientModel model, JavaFile javaFile) { // properties addProperties(propertiesManager, classBlock); - addLroOperationIdField(classBlock, model); + lroOperationId.addField(classBlock); // add jsonMergePatch related properties and accessors if (ClientModelUtil.isJsonMergePatchModel(model, settings)) { @@ -185,21 +180,7 @@ public final void write(ClientModel model, JavaFile javaFile) { if (!property.isPolymorphicDiscriminator() || PolymorphicDiscriminatorHandler.generateGetter(model, property, settings)) { - LongRunningOperationIdMetadata metadata = getLroOperationId(model); - boolean usesOperationIdFallback = metadata != null - && metadata.hasPathSource() - && property == getLroOperationIdProperty(model, metadata) - && LRO_OPERATION_ID_GETTER_NAME.equals(property.getGetterName()) - && ClassType.STRING.equals(propertyWireType); - if (usesOperationIdFallback) { - 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."); - }); - } else { + if (!lroOperationId.writeGetterJavadoc(classBlock, property)) { generateGetterJavadoc(classBlock, property); } addGeneratedAnnotation(classBlock); @@ -217,10 +198,7 @@ public final void write(ClientModel model, JavaFile javaFile) { ExperimentalAnnotationUtil.write(classBlock, property.getApiMetadata()); classBlock.method(methodVisibility, null, propertyClientType + " " + getGetterName(model, property) + "()", methodBlock -> { - if (usesOperationIdFallback) { - methodBlock.methodReturn("this." + property.getName() + " != null ? this." - + property.getName() + " : this." + LRO_OPERATION_ID_FIELD_NAME); - } else { + if (!lroOperationId.writeGetterBody(methodBlock, property)) { addGetterMethod(propertyWireType, propertyClientType, property, treatAsXml, methodBlock, settings); } @@ -291,7 +269,7 @@ public final void write(ClientModel model, JavaFile javaFile) { } } - addLroOperationIdAccessors(classBlock, model); + lroOperationId.addAccessors(classBlock); if (settings.getClientFlattenAnnotationTarget() == JavaSettings.ClientFlattenAnnotationTarget.NONE) { // reference to properties from flattened client model @@ -522,12 +500,6 @@ private void addImports(Set imports, ClientModel model, JavaSettings set model.addImportsTo(imports, settings); - // add long-running operation ID related imports - if (getLroOperationId(model) != null && getLroOperationId(model).hasPathSource()) { - imports.add(settings.getPackage(settings.getImplementationSubpackage()) + "." - + ClientModelUtil.OPERATION_ID_POLLING_STRATEGY); - } - // add Json merge patch related imports if (ClientModelUtil.isJsonMergePatchModel(model, settings)) { imports.add(settings.getPackage(settings.getImplementationSubpackage()) + "." @@ -1564,114 +1536,4 @@ private void addJsonMergePatchRelatedPropertyAndAccessors(JavaClass classBlock, staticBlock.line("});"); }); } - - /** - * Gets the sources of the long-running operation ID, if the model can generate the accessor. - * - * @param model the model. - * @return the sources of the long-running operation ID, or null. - */ - private static LongRunningOperationIdMetadata getLroOperationId(ClientModel model) { - final LongRunningOperationIdMetadata lroOperationId = model.getLroOperationId(); - if (lroOperationId == null) { - return null; - } - final boolean conflict - = Stream.concat(model.getProperties().stream(), ClientModelUtil.getParentProperties(model).stream()) - .anyMatch(p -> (lroOperationId.hasPathSource() && LRO_OPERATION_ID_FIELD_NAME.equals(p.getName())) - || (LRO_OPERATION_ID_GETTER_NAME.equals(p.getGetterName()) - && (!Objects.equals(lroOperationId.getPropertySerializedName(), p.getSerializedName()) - || !ClassType.STRING.equals(p.getClientType()) - || !ClassType.STRING.equals(p.getWireType())))); - return conflict ? null : lroOperationId; - } - - private static ClientModelProperty getLroOperationIdProperty(ClientModel model, - LongRunningOperationIdMetadata lroOperationId) { - if (lroOperationId.getPropertySerializedName() == null) { - return null; - } - return Stream.concat(model.getProperties().stream(), ClientModelUtil.getParentProperties(model).stream()) - .filter(p -> lroOperationId.getPropertySerializedName().equals(p.getSerializedName()) - && ClassType.STRING.equals(p.getClientType())) - .findFirst() - .orElse(null); - } - - /** - * Adds the "getOperationId" method, and the accessor for OperationIdPollingStrategy to set the operation ID from - * the polling URL. - * - * @param classBlock the class block. - * @param model the model. - */ - private void addLroOperationIdAccessors(JavaClass classBlock, ClientModel model) { - final LongRunningOperationIdMetadata lroOperationId = getLroOperationId(model); - if (lroOperationId == 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 = getLroOperationIdProperty(model, lroOperationId); - final boolean hasPathSource = lroOperationId.hasPathSource(); - if (lroOperationId.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.", - lroOperationId.getPropertySerializedName(), model.getName()); - } - if (property == null && !hasPathSource) { - return; - } - - boolean usesExistingGetter = property != null && LRO_OPERATION_ID_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(classBlock); - classBlock.publicMethod("String " + LRO_OPERATION_ID_GETTER_NAME + "()", methodBlock -> { - if (property != null && hasPathSource) { - methodBlock.line("String " + LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " = " - + (usesExistingGetter ? "super." : "this.") + property.getGetterName() + "();"); - methodBlock.methodReturn(LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " != null ? " - + LRO_OPERATION_ID_PROPERTY_VALUE_NAME + " : this." + LRO_OPERATION_ID_FIELD_NAME); - } else if (property != null) { - methodBlock.methodReturn("this." + property.getGetterName() + "()"); - } else { - methodBlock.methodReturn("this." + LRO_OPERATION_ID_FIELD_NAME); - } - }); - } - - private void addLroOperationIdField(JavaClass classBlock, ClientModel model) { - LongRunningOperationIdMetadata metadata = getLroOperationId(model); - if (metadata == null || !metadata.hasPathSource()) { - return; - } - classBlock.javadocComment(comment -> comment - .description("The operation ID from the polling URL, set by the polling strategy after deserialization.")); - addGeneratedAnnotation(classBlock); - classBlock.privateMemberVariable("String " + LRO_OPERATION_ID_FIELD_NAME); - classBlock.staticBlock(staticBlock -> staticBlock - .line(ClientModelUtil.OPERATION_ID_POLLING_STRATEGY + ".setOperationIdAccessor(" + model.getName() - + ".class, (model, operationId) -> model." + LRO_OPERATION_ID_FIELD_NAME + " = operationId);")); - } } 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()); + } +}