Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .chronus/changes/java-tcgc-lro-metadata-2026-10-12-17-55-0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
changeKind: feature
packages:
- "@typespec/http-client-java"
---

Expose the LRO operation ID selected by `@lroOperationId` on supported typed poll-result models via `getOperationId()`. The poll-result model is available once a status response with a body is received; its body property takes precedence over the polling URL path. Polling continues to use the complete polling URL.

```java
SyncPoller<DocumentAnalysisStatus, DocumentAnalysisResult> poller = client.beginAnalyze("document-1");
String operationId = poller.poll().getValue().getOperationId();
```
97 changes: 95 additions & 2 deletions packages/http-client-java/emitter/src/code-model-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
SdkHttpOperation,
SdkHttpResponse,
SdkLroPagingServiceMethod,
SdkLroServiceMetadata,
SdkLroServiceMethod,
SdkMethodResponse,
SdkModelPropertyType,
Expand Down Expand Up @@ -65,7 +66,7 @@ import {
} from "@typespec/compiler";
import { $ } from "@typespec/compiler/typekit";
import type { Authentication, HttpStatusCodeRange, HttpStatusCodesEntry } from "@typespec/http";
import { Visibility, getAuthentication } from "@typespec/http";
import { Visibility, getAuthentication, getHeaderFieldName } from "@typespec/http";
import type {} from "@typespec/http-client/typekit";
import { getSegment } from "@typespec/rest";
import { getAddedOnVersions } from "@typespec/versioning";
Expand All @@ -83,7 +84,10 @@ import {
} from "./common/client.js";
import type { CodeModel } from "./common/code-model.js";
import { addGlobalParameter, createCodeModel } from "./common/code-model.js";
import type { LongRunningMetadata } from "./common/long-running-metadata.js";
import type {
LongRunningMetadata,
LongRunningOperationIdMetadata,
} from "./common/long-running-metadata.js";
import { createLongRunningMetadata } from "./common/long-running-metadata.js";
import type { Operation as CodeModelOperation, Request, SseMetadata } from "./common/operation.js";
import {
Expand Down Expand Up @@ -1786,19 +1790,108 @@ export class CodeModelBuilder {
}
}

// operation ID, only for poll result model (not the PollOperationDetails, which already has it)
let operationId: LongRunningOperationIdMetadata | undefined = undefined;
if (pollingSchema && pollingSchema !== this._pollResultSchema) {
operationId = this.processLroOperationIdMetadata(lroMetadata);
if (operationId) {
pollingSchema.extensions = pollingSchema.extensions ?? {};
const previous = pollingSchema.extensions["x-ms-lro-operation-id"] as
LongRunningOperationIdMetadata | undefined;
if (
previous?.propertySerializedName &&
operationId.propertySerializedName &&
previous.propertySerializedName !== operationId.propertySerializedName
) {
reportDiagnostic(this.program, {
code: "generator-error",
format: {
errorMessage:
"Long-running operations using the same status model select different operation ID properties.",
},
target: lroMetadata.operation.__raw?.operation ?? NoTarget,
});
}
pollingSchema.extensions["x-ms-lro-operation-id"] = {
...operationId,
...previous,
};
}
}

op.lroMetadata = createLongRunningMetadata(
true,
pollingSchema,
finalSchema,
pollingStrategy,
finalResultPropertySerializedName,
operationId,
);
return op.lroMetadata;
}

return createLongRunningMetadata(false);
}

private processLroOperationIdMetadata(
lroMetadata: SdkLroServiceMetadata,
): LongRunningOperationIdMetadata | undefined {
if (!lroMetadata.operationId || lroMetadata.operationId.length === 0) {
return undefined;
}
const operationId: LongRunningOperationIdMetadata = {};
for (const selection of lroMetadata.operationId) {
if (selection.kind === "path") {
const statusMonitorStep = lroMetadata.statusMonitorStep;
const selectedLink =
statusMonitorStep?.kind === "nextOperationReference"
? statusMonitorStep.target.link
: statusMonitorStep?.target;
const statusMonitorOperation =
selectedLink === selection.source
? statusMonitorStep?.kind === "nextOperationReference"
? statusMonitorStep.target.operation
: statusMonitorStep?.operation
: undefined;
const source = selection.source;
const header = source.property.__raw;
if (
statusMonitorOperation &&
source.location === "ResponseHeader" &&
header &&
statusMonitorOperation.path.includes(`{${selection.pathParameter.serializedName}}`)
) {
operationId.pathTemplate = statusMonitorOperation.path;
operationId.pathParameterSerializedName = selection.pathParameter.serializedName;
operationId.pollingHeaderName = getHeaderFieldName(this.program, header).toLowerCase();
} else {
reportDiagnostic(this.program, {
code: "generator-warning",
format: {
warningMessage:
"Cannot expose the long-running operation ID from the selected polling URL: its header or status-monitor path could not be resolved.",
},
target: selection.pathParameter.__raw ?? NoTarget,
});
}
} else if (selection.kind === "property" && selection.propertySegments.length === 1) {
// nested property is not supported, TCGC currently only provides a single segment
operationId.propertySerializedName = getPropertySerializedName(
selection.propertySegments[0],
);
} else if (selection.kind === "property") {
reportDiagnostic(this.program, {
code: "generator-warning",
format: {
warningMessage: "Nested long-running operation ID properties are not supported.",
},
target: selection.property.__raw ?? NoTarget,
});
}
}
return operationId.pathTemplate || operationId.propertySerializedName ? operationId : undefined;
}

private processRouteForLongRunning(op: CodeModelOperation, lroMetadata: LongRunningMetadata) {
if (lroMetadata.longRunning) {
op.extensions = op.extensions ?? {};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
import type { Metadata, Schema } from "./schemas/model.js";

/**
* Server-issued LRO operation ID sources selected by `@lroOperationId`.
* The polling URL path parameter is used until the status-monitor body property is available.
*/
export interface LongRunningOperationIdMetadata {
/** Route template of the status-monitor operation, used to extract the path parameter from the polling URL. */
pathTemplate?: string;
/** Name of the path parameter in "pathTemplate". */
pathParameterSerializedName?: string;
/** Name of the response header containing the polling URL. */
pollingHeaderName?: string;
/** Serialized name of the status-monitor response property. */
propertySerializedName?: string;
}

export interface LongRunningMetadata {
longRunning: boolean;
pollResultType?: Schema;
finalResultType?: Schema;
pollingStrategy?: Metadata;
finalResultPropertySerializedName?: string;
operationId?: LongRunningOperationIdMetadata;
}

export function createLongRunningMetadata(
Expand All @@ -14,12 +30,14 @@ export function createLongRunningMetadata(
finalResultType?: Schema,
pollingStrategy?: Metadata,
finalResultPropertySerializedName?: string,
operationId?: LongRunningOperationIdMetadata,
): LongRunningMetadata {
return {
longRunning,
pollResultType,
finalResultType,
pollingStrategy,
finalResultPropertySerializedName,
operationId,
};
}
49 changes: 49 additions & 0 deletions packages/http-client-java/emitter/test/code-model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import "@azure-tools/typespec-azure-core";
import "@azure-tools/typespec-client-generator-core";

using TypeSpec.Http;
using Azure.Core;
using Azure.ClientGenerator.Core;

@service
@route("/lro")
namespace LroOperationIdTest;

model Result {
value: string;
}

model PathStatus {
status: Azure.Core.Foundations.OperationState;
result?: Result;
}

@get
@route("/path/{resultId}")
op getPathStatus(@lroOperationId @path resultId: string): PathStatus;

@post
@route("/analyze")
@pollingOperation(getPathStatus)
op analyze(): Azure.Core.Foundations.AcceptedResponse &
Azure.Core.Foundations.LongRunningStatusLocation<PathStatus>;

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<CombinedStatus>;

@get
@route("/body-only")
op getBodyOnlyStatus(): CombinedStatus;

@post
@route("/start-body-only")
@pollingOperation(getBodyOnlyStatus)
op startBodyOnly(): Azure.Core.Foundations.AcceptedResponse &
Azure.Core.Foundations.LongRunningStatusLocation<CombinedStatus>;
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,13 @@ protected Object constructJavaBean2ndStep(MappingNode mappingNode, Object object
new ScalarNode(keyNode.getTag(), "xmsArmIdDetails", keyNode.getStartMark(),
keyNode.getEndMark(), keyNode.getScalarStyle()),
extension.getValueNode()));
} else if ("x-ms-lro-operation-id".equals(keyNode.getValue())) {
actualValues
.add(
new NodeTuple(
new ScalarNode(keyNode.getTag(), "xmsLroOperationId",
keyNode.getStartMark(), keyNode.getEndMark(), keyNode.getScalarStyle()),
extension.getValueNode()));
} else if ("x-ms-secret".equals(keyNode.getValue())) {
actualValues.add(
new NodeTuple(new ScalarNode(keyNode.getTag(), "xmsSecret", keyNode.getStartMark(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
}
Loading