Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# yaml-language-server: $schema=../../../../../fern-changes-yml.schema.json

- summary: |
Idempotency-key auto-generation is now driven by the IR (`SdkConfig.idempotencyKeyGeneration`)
instead of a per-generator config flag. When enabled, the SDK adds the configured idempotency
header on the configured HTTP methods unless the caller already supplied one. The header name
and eligible methods come from the IR, and generated output is unchanged when the feature is off.
type: feat
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import com.fern.java.client.generators.FileStreamGenerator;
import com.fern.java.client.generators.HttpResponseGenerator;
import com.fern.java.client.generators.ILoggerGenerator;
import com.fern.java.client.generators.IdempotencyUtilsGenerator;
import com.fern.java.client.generators.InferredAuthTokenSupplierGenerator;
import com.fern.java.client.generators.InputStreamRequestBodyGenerator;
import com.fern.java.client.generators.LogConfigGenerator;
Expand Down Expand Up @@ -383,6 +384,11 @@ public GeneratedRootClient generateClient(
ResponseBodyReaderGenerator responseBodyReaderGenerator = new ResponseBodyReaderGenerator(context);
this.addGeneratedFile(responseBodyReaderGenerator.generateFile());

if (context.getIr().getSdkConfig().getIdempotencyKeyGeneration().isPresent()) {
IdempotencyUtilsGenerator idempotencyUtilsGenerator = new IdempotencyUtilsGenerator(context);
this.addGeneratedFile(idempotencyUtilsGenerator.generateFile());
}

ClientOptionsGenerator clientOptionsGenerator =
new ClientOptionsGenerator(context, generatedEnvironmentsClass, generatedRequestOptions);
GeneratedClientOptions generatedClientOptions = clientOptionsGenerator.generateFile();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ public ClassName getMediaTypesClassName() {
return ClassName.get(getCorePackage(), "MediaTypes");
}

public ClassName getIdempotencyUtilsClassName() {
return ClassName.get(getCorePackage(), "IdempotencyUtils");
}

public ClassName getOkhttp3MediaTypeClassName() {
return ClassName.get("okhttp3", "MediaType");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* (c) Copyright 2023 Birch Solutions Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.fern.java.client.generators;

import com.fern.java.client.ClientGeneratorContext;
import com.fern.java.generators.AbstractFileGenerator;
import com.fern.java.output.GeneratedResourcesJavaFile;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public final class IdempotencyUtilsGenerator extends AbstractFileGenerator {

public IdempotencyUtilsGenerator(ClientGeneratorContext clientGeneratorContext) {
super(clientGeneratorContext.getPoetClassNameFactory().getIdempotencyUtilsClassName(), clientGeneratorContext);
}

@Override
public GeneratedResourcesJavaFile generateFile() {
try (InputStream is = IdempotencyUtilsGenerator.class.getResourceAsStream("/IdempotencyUtils.java")) {
String contents = new String(is.readAllBytes(), StandardCharsets.UTF_8);
return GeneratedResourcesJavaFile.builder()
.className(className)
.contents(contents)
.build();
} catch (IOException e) {
throw new RuntimeException("Failed to read IdempotencyUtils.java", e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.fern.ir.model.auth.AuthScope;
import com.fern.ir.model.environment.EnvironmentBaseUrlId;
import com.fern.ir.model.http.*;
import com.fern.ir.model.ir.IdempotencyKeyGeneration;
import com.fern.ir.model.types.*;
import com.fern.java.client.ClientGeneratorContext;
import com.fern.java.client.GeneratedClientOptions;
Expand Down Expand Up @@ -636,12 +637,16 @@ public Boolean _visitUnknown(Object unknownType) {
httpEndpoint.getMethod().toString(),
variables.getOkhttpRequestBodyName());
methodBody.addStatement(
"$L.headers($T.of(this.$L.$L(($T) null)))",
"$L.headers($T.of($L))",
"_requestBuilder",
ClassName.get("okhttp3", "Headers"),
clientOptionsField.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
clientGeneratorContext.getPoetClassNameFactory().getRequestOptionsClassName());
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of(
"this.$L.$L(($T) null)",
clientOptionsField.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
clientGeneratorContext
.getPoetClassNameFactory()
.getRequestOptionsClassName())));
methodBody.addStatement(
"$T $L = $L.build()",
ClassName.get("okhttp3", "Request"),
Expand Down Expand Up @@ -710,12 +715,16 @@ public Boolean _visitUnknown(Object unknownType) {
httpEndpoint.getMethod().toString(),
variables.getOkhttpRequestBodyName());
withMediaTypeBody.addStatement(
"$L.headers($T.of(this.$L.$L(($T) null)))",
"$L.headers($T.of($L))",
"_requestBuilder",
ClassName.get("okhttp3", "Headers"),
clientOptionsField.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
clientGeneratorContext.getPoetClassNameFactory().getRequestOptionsClassName());
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of(
"this.$L.$L(($T) null)",
clientOptionsField.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
clientGeneratorContext
.getPoetClassNameFactory()
.getRequestOptionsClassName())));
withMediaTypeBody.addStatement(
"$T $L = $L.build()",
ClassName.get("okhttp3", "Request"),
Expand Down Expand Up @@ -783,12 +792,14 @@ public Boolean _visitUnknown(Object unknownType) {
httpEndpoint.getMethod().toString(),
variables.getOkhttpRequestBodyName());
withRequestOptionsBody.addStatement(
"$L.headers($T.of(this.$L.$L($L)))",
"$L.headers($T.of($L))",
"_requestBuilder",
ClassName.get("okhttp3", "Headers"),
clientOptionsField.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME);
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of(
"this.$L.$L($L)",
clientOptionsField.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME)));
withRequestOptionsBody.addStatement(
"$T $L = $L.build()",
ClassName.get("okhttp3", "Request"),
Expand Down Expand Up @@ -848,12 +859,14 @@ public Boolean _visitUnknown(Object unknownType) {
httpEndpoint.getMethod().toString(),
variables.getOkhttpRequestBodyName());
withBothBody.addStatement(
"$L.headers($T.of(this.$L.$L($L)))",
"$L.headers($T.of($L))",
"_requestBuilder",
ClassName.get("okhttp3", "Headers"),
clientOptionsField.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME);
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of(
"this.$L.$L($L)",
clientOptionsField.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME)));
withBothBody.addStatement(
"$T $L = $L.build()",
ClassName.get("okhttp3", "Request"),
Expand Down Expand Up @@ -899,6 +912,38 @@ public final ParameterSpec requestOptionsParameterSpec() {
.build();
}

/**
* Returns the IR-configured idempotency-key auto-generation settings when they apply to this endpoint. Present only
* when the IR's {@code SdkConfig.idempotencyKeyGeneration} is set and this endpoint's HTTP method is one of the
* configured eligible methods.
*/
protected final Optional<IdempotencyKeyGeneration> idempotencyKeyGenerationForEndpoint() {
return clientGeneratorContext
.getIr()
.getSdkConfig()
.getIdempotencyKeyGeneration()
.filter(idempotencyKeyGeneration ->
idempotencyKeyGeneration.getMethods().contains(httpEndpoint.getMethod()));
}

/**
* Wraps a headers-map expression so that a freshly generated idempotency key is added when the map does not already
* contain one. A caller-provided value always wins. The header name and eligible HTTP methods come from the IR
* ({@code SdkConfig.idempotencyKeyGeneration}). When auto-generation does not apply, the original expression is
* returned unchanged so existing output is byte-identical.
*/
protected final CodeBlock maybeWrapHeadersWithIdempotencyKey(CodeBlock headersExpression) {
Optional<IdempotencyKeyGeneration> idempotencyKeyGeneration = idempotencyKeyGenerationForEndpoint();
if (idempotencyKeyGeneration.isEmpty()) {
return headersExpression;
}
return CodeBlock.of(
"$T.withGeneratedIdempotencyKey($L, $S)",
clientGeneratorContext.getPoetClassNameFactory().getIdempotencyUtilsClassName(),
headersExpression,
idempotencyKeyGeneration.get().getHeaderName());
}

protected final MethodSpec getEnvironmentToUrlMethod() {
if (generatedEnvironmentsClass.info() instanceof SingleUrlEnvironmentClass) {
return ((SingleUrlEnvironmentClass) generatedEnvironmentsClass.info()).getUrlMethod();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,19 @@ public CodeBlock getInitializeRequestCodeBlock(
}

if (clientGeneratorContext.isEndpointSecurity()) {
builder.add(".headers($T.of(_headers))\n", Headers.class);
builder.add(
".headers($T.of($L))\n",
Headers.class,
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of("_headers")));
} else {
builder.add(
".headers($T.of($L.$L($L)))\n",
".headers($T.of($L))\n",
Headers.class,
clientOptionsMember.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME);
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of(
"$L.$L($L)",
clientOptionsMember.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME)));
}
if (sendContentType) {
builder.add(".addHeader($S, $S)\n", AbstractEndpointWriter.CONTENT_TYPE_HEADER, contentType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,19 @@ public CodeBlock getInitializeRequestCodeBlock(
httpEndpoint.getMethod().toString(),
variables.getOkhttpRequestBodyName());
if (clientGeneratorContext.isEndpointSecurity()) {
builder.add(".headers($T.of(_headers))\n", Headers.class);
builder.add(
".headers($T.of($L))\n",
Headers.class,
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of("_headers")));
} else {
builder.add(
".headers($T.of($L.$L($L)))\n",
".headers($T.of($L))\n",
Headers.class,
clientOptionsMember.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME);
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of(
"$L.$L($L)",
clientOptionsMember.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME)));
}
if (sendContentType) {
sdkRequestBodyType.visit(new SdkRequestBodyType.Visitor<Void>() {
Expand Down Expand Up @@ -292,14 +297,19 @@ public BytesRequest _visitUnknown(Object unknownType) {
httpEndpoint.getMethod().toString(),
variables.getOkhttpRequestBodyName());
if (clientGeneratorContext.isEndpointSecurity()) {
builder.add(".headers($T.of(_headers))\n", Headers.class);
builder.add(
".headers($T.of($L))\n",
Headers.class,
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of("_headers")));
} else {
builder.add(
".headers($T.of($L.$L($L)))\n",
".headers($T.of($L))\n",
Headers.class,
clientOptionsMember.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME);
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of(
"$L.$L($L)",
clientOptionsMember.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME)));
}
if (sendContentType) {
builder.add(".addHeader($S, $S)\n", AbstractEndpointWriter.CONTENT_TYPE_HEADER, contentType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,14 +201,17 @@ public CodeBlock getInitializeRequestCodeBlock(
}
Optional<CodeBlock> maybeAcceptsHeader = AbstractEndpointWriter.maybeAcceptsHeader(httpEndpoint);
if (clientGeneratorContext.isEndpointSecurity()) {
requestBodyCodeBlock.add(".headers($T.of(_headers))", Headers.class);
requestBodyCodeBlock.add(
".headers($T.of($L))", Headers.class, maybeWrapHeadersWithIdempotencyKey(CodeBlock.of("_headers")));
} else {
requestBodyCodeBlock.add(
".headers($T.of($L.$L($L)))",
".headers($T.of($L))",
Headers.class,
clientOptionsMember.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME);
maybeWrapHeadersWithIdempotencyKey(CodeBlock.of(
"$L.$L($L)",
clientOptionsMember.name,
ClientOptionsGenerator.HEADERS_METHOD_NAME,
AbstractEndpointWriterVariableNameContext.REQUEST_OPTIONS_PARAMETER_NAME)));
}
if (sendContentType && !isFileUpload) {
requestBodyCodeBlock.add("\n.addHeader($S, $S)", AbstractEndpointWriter.CONTENT_TYPE_HEADER, contentType);
Expand Down
25 changes: 25 additions & 0 deletions generators/java/sdk/src/main/resources/IdempotencyUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* Utilities for auto-generating idempotency keys on mutating requests.
*
* <p>Only emitted when idempotency-key auto-generation is enabled in the IR
* ({@code SdkConfig.idempotencyKeyGeneration}).
*/
public final class IdempotencyUtils {

private IdempotencyUtils() {}

/**
* Returns a copy of {@code headers} with a freshly generated UUIDv4 value added under {@code headerName} when a
* value is not already present. A caller-provided value (whether from a declared idempotency header or the generic
* request-options header bag) always wins.
*/
public static Map<String, String> withGeneratedIdempotencyKey(Map<String, String> headers, String headerName) {
Map<String, String> result = new HashMap<>(headers);
result.putIfAbsent(headerName, UUID.randomUUID().toString());
return result;
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading