fix(translate): serve Translate over smithy-rpc-v2-cbor (#8563)

This commit is contained in:
James Netherton authored and GitHub committed 2026-11-16 07:22:38 -04:00
1 parent e8f5a696a8
commit 8ec2c184f1
4 files changed
+121 -2

No files matched your search

@@ -18,6 +18,7 @@ import io.floci.aws.services.marketplace.MarketplaceEntitlementController;
import io.floci.aws.services.sns.SnsJsonHandler;
import io.floci.aws.services.sqs.SqsJsonHandler;
import io.floci.aws.services.stepfunctions.StepFunctionsJsonHandler;
import io.floci.aws.services.translate.TranslateJsonHandler;
import io.smallrye.common.annotation.RunOnVirtualThread;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
@@ -72,6 +73,7 @@ public class AwsJsonCborController {
private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler;
private final MarketplaceEntitlementController marketplaceEntitlementController;
private final EventBridgeV2Handler eventBridgeV2Handler;
private final TranslateJsonHandler translateJsonHandler;
@Inject
public AwsJsonCborController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -83,7 +85,8 @@ public class AwsJsonCborController {
StepFunctionsJsonHandler sfnJsonHandler,
CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler,
MarketplaceEntitlementController marketplaceEntitlementController,
EventBridgeV2Handler eventBridgeV2Handler) {
EventBridgeV2Handler eventBridgeV2Handler,
TranslateJsonHandler translateJsonHandler) {
this.objectMapper = objectMapper;
this.catalog = catalog;
this.regionResolver = regionResolver;
@@ -96,6 +99,7 @@ public class AwsJsonCborController {
this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler;
this.marketplaceEntitlementController = marketplaceEntitlementController;
this.eventBridgeV2Handler = eventBridgeV2Handler;
this.translateJsonHandler = translateJsonHandler;
}
@@ -179,6 +183,10 @@ public class AwsJsonCborController {
gen.writeEndArray();
} else if (numberIsTimestamp && node.isNumber()) {
writeCborTimestamp(gen, node, legacyDialect);
} else if (node.isBinary()) {
// A blob member (e.g. Translate's TranslatedDocument.Content) is a CBOR byte
// string on the wire, never base64 text.
gen.writeBinary(node.binaryValue());
} else if (node.isTextual()) {
gen.writeString(node.textValue());
} else if (node.isDouble() || node.isFloat()) {
@@ -519,6 +527,7 @@ public class AwsJsonCborController {
case "monitoring" -> cloudWatchMetricsJsonHandler.handle(operation, request, region);
case "marketplace" -> marketplaceEntitlementController.handle(operation, request, region);
case "eventsv2" -> eventBridgeV2Handler.handle(operation, request, region);
case "translate" -> translateJsonHandler.handleCbor(operation, request, region);
default -> null;
};
}
@@ -1,11 +1,15 @@
package io.floci.aws.services.translate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.BinaryNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsErrorResponse;
import io.floci.aws.core.common.AwsException;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.util.Base64;
/**
* JSON 1.1 handler for Amazon Translate API operations.
* Dispatches X-Amz-Target: AWSShineFrontendService_20170701.* actions to {@link TranslateService}.
@@ -33,7 +37,7 @@ public class TranslateJsonHandler {
getStringField(request, "SourceLanguageCode"),
getStringField(request, "TargetLanguageCode"));
case "TranslateDocument" -> translateService.translateDocument(
getNestedStringField(request, "Document", "Content"),
getNestedBlobField(request, "Document", "Content"),
getNestedStringField(request, "Document", "ContentType"),
getStringField(request, "SourceLanguageCode"),
getStringField(request, "TargetLanguageCode"));
@@ -45,6 +49,24 @@ public class TranslateJsonHandler {
.build();
};
}
/**
* Dispatches Translate actions received over smithy-rpc-v2-cbor. Requests go through
* {@link #handle}, which already accepts a CBOR byte string for blob members; on the
* way back, the blob {@code TranslatedDocument.Content} (base64 text in JSON 1.1) is
* turned into raw bytes so the CBOR serializer emits it as a byte string.
*/
public Response handleCbor(String action, JsonNode request, String region) {
Response response = handle(action, request, region);
if ("TranslateDocument".equals(action) && response.getEntity() instanceof ObjectNode root) {
JsonNode document = root.get("TranslatedDocument");
if (document instanceof ObjectNode documentNode && documentNode.path("Content").isTextual()) {
byte[] bytes = Base64.getDecoder().decode(documentNode.get("Content").textValue());
documentNode.set("Content", BinaryNode.valueOf(bytes));
}
}
return response;
}
/**
* Extracts a string-typed field. A present-but-wrong-typed value is a shape/marshalling
* mismatch caught at the protocol layer before operation-specific validation, matching
@@ -62,6 +84,23 @@ public class TranslateJsonHandler {
}
return value.asText();
}
/**
* Extracts a blob field nested one level under {@code parent} (e.g. Document.Content) as
* base64 text. JSON 1.1 carries a blob as a base64 string; the CBOR protocols carry it as
* a byte string, which decodes to a binary node and is re-encoded here, so the service
* sees the same base64 form either way (as {@code KinesisJsonHandler} does for Data).
*/
private String getNestedBlobField(JsonNode node, String parent, String field) {
JsonNode parentNode = node == null ? null : node.get(parent);
if (parentNode != null && parentNode.isObject()) {
JsonNode value = parentNode.get(field);
if (value instanceof BinaryNode binary) {
return Base64.getEncoder().encodeToString(binary.binaryValue());
}
}
return getNestedStringField(node, parent, field);
}
/** {@link #getStringField} for a field nested one level under {@code parent} (e.g. Document.Content). */
private String getNestedStringField(JsonNode node, String parent, String field) {
JsonNode parentNode = node == null ? null : node.get(parent);
@@ -2,11 +2,13 @@ package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -284,4 +286,19 @@ class AwsJsonCborSerializerTest {
private static boolean contains(byte[] bytes, byte target) {
return indexOf(bytes, target) >= 0;
}
@Test
void binaryNodeIsWrittenAsCborByteStringInBothDialects() throws Exception {
byte[] blob = {0x00, 0x01, (byte) 0xFF, 'a', 'b'};
ObjectNode node = jsonMapper.createObjectNode();
node.putObject("TranslatedDocument").put("Content", blob);
for (byte[] encoded : new byte[][] {
AwsJsonCborController.nodeToSmithyCbor(node),
AwsJsonCborController.nodeToLegacyCbor(node)}) {
JsonNode content = cborMapper.readTree(encoded).path("TranslatedDocument").path("Content");
assertTrue(content.isBinary(), "blob must be a CBOR byte string (major type 2), not text");
assertArrayEquals(blob, content.binaryValue());
}
}
}
@@ -2,6 +2,7 @@ package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
@@ -186,4 +187,57 @@ class SmithyRpcV2RoutingIntegrationTest {
.statusCode(200)
.contentType("application/x-amz-cbor-1.1");
}
@Test
void translateRoutesViaTargetPrefixServiceName() throws Exception {
byte[] response = given()
.contentType("application/cbor")
.accept("application/cbor")
.header("smithy-protocol", "rpc-v2-cbor")
.body(CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.readTree("""
{"Text":"Ciao","SourceLanguageCode":"it","TargetLanguageCode":"de"}
""")))
.when()
.post("/service/AWSShineFrontendService_20170701/operation/TranslateText")
.then()
.statusCode(200)
.header("smithy-protocol", equalTo("rpc-v2-cbor"))
.contentType("application/cbor")
.extract().asByteArray();
assertThat(CBOR_MAPPER.readTree(response)
.path("TranslatedText").asText(), equalTo("Ciao"));
}
@Test
void translateDocumentRoundTripsContentAsCborByteString() throws Exception {
// Non-UTF-8 bytes included on purpose: Document.Content is a blob, not text.
byte[] document = {'H', 'e', 'l', 'l', 'o', ' ', (byte) 0xC3, (byte) 0xA9, 0x00, (byte) 0xFF, '\n'};
ObjectNode request = JSON_MAPPER.createObjectNode();
request.putObject("Document")
.put("Content", document)
.put("ContentType", "text/plain");
request.put("SourceLanguageCode", "en");
request.put("TargetLanguageCode", "es");
byte[] response = given()
.contentType("application/cbor")
.accept("application/cbor")
.header("smithy-protocol", "rpc-v2-cbor")
.body(CBOR_MAPPER.writeValueAsBytes(request))
.when()
.post("/service/AWSShineFrontendService_20170701/operation/TranslateDocument")
.then()
.statusCode(200)
.header("smithy-protocol", equalTo("rpc-v2-cbor"))
.contentType("application/cbor")
.extract().asByteArray();
JsonNode decoded = CBOR_MAPPER.readTree(response);
JsonNode content = decoded.path("TranslatedDocument").path("Content");
assertThat(content.isBinary(), equalTo(true));
assertThat(content.binaryValue(), equalTo(document));
assertThat(decoded.path("SourceLanguageCode").asText(), equalTo("en"));
assertThat(decoded.path("TargetLanguageCode").asText(), equalTo("es"));
}
}