-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Wrap JSON Parsing Errors as CosmosException
.
#47040
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jeet1995
wants to merge
9
commits into
Azure:main
Choose a base branch
from
jeet1995:CfpParsingErrorLoggingChanges
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
b9ec2ae
Adding logging for non-parseable documents.
jeet1995 15d0fb9
Adding logging for non-parseable documents.
jeet1995 0c53e0a
Adding tests.
jeet1995 2b57962
Refactor.
jeet1995 e39f20c
Update CHANGELOG.md
jeet1995 63f05ca
Modified tests.
jeet1995 da5ed46
Merge branch 'main' of github.com:jeet1995/azure-sdk-for-java into Cf…
jeet1995 c76d45a
Modified tests.
jeet1995 aebaba1
Fixing tests.
jeet1995 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
153 changes: 153 additions & 0 deletions
153
...re-cosmos-tests/src/test/java/com/azure/cosmos/implementation/MalformedResponseTests.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
package com.azure.cosmos.implementation; | ||
|
||
import com.azure.cosmos.CosmosAsyncClient; | ||
import com.azure.cosmos.CosmosAsyncContainer; | ||
import com.azure.cosmos.CosmosClientBuilder; | ||
import com.azure.cosmos.CosmosException; | ||
import com.azure.cosmos.TestObject; | ||
import com.azure.cosmos.models.PartitionKey; | ||
import com.azure.cosmos.rx.TestSuiteBase; | ||
import com.fasterxml.jackson.core.JsonParseException; | ||
import com.fasterxml.jackson.core.JsonProcessingException; | ||
import com.fasterxml.jackson.databind.JsonNode; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import org.testng.annotations.AfterSuite; | ||
import org.testng.annotations.BeforeSuite; | ||
import org.testng.annotations.Factory; | ||
import org.testng.annotations.Ignore; | ||
import org.testng.annotations.Test; | ||
|
||
import java.io.IOException; | ||
import java.lang.reflect.Field; | ||
|
||
import static org.assertj.core.api.Assertions.assertThat; | ||
import static org.assertj.core.api.Fail.fail; | ||
|
||
@Ignore("MalformedResponseTests is safe to run in isolation as it leverages Reflection to override the deserializer.") | ||
public class MalformedResponseTests extends TestSuiteBase { | ||
|
||
@Factory(dataProvider = "clientBuildersWithSessionConsistency") | ||
public MalformedResponseTests(CosmosClientBuilder clientBuilder) { | ||
super(clientBuilder); | ||
} | ||
|
||
@BeforeSuite(groups = {"emulator"}, alwaysRun = true) | ||
public void beforeSuite() { | ||
System.setProperty("COSMOS.CHARSET_DECODER_ERROR_ACTION_ON_MALFORMED_INPUT", "IGNORE"); | ||
super.beforeSuite(); | ||
} | ||
|
||
@Test(groups = { "emulator" }) | ||
public void validateCosmosExceptionThrownOnMalformedResponse() throws NoSuchFieldException, IllegalAccessException { | ||
|
||
CosmosAsyncClient cosmosAsyncClient = null; | ||
ObjectMapper originalMapper = null; | ||
|
||
try { | ||
cosmosAsyncClient = getClientBuilder() | ||
.key(TestConfigurations.MASTER_KEY) | ||
.endpoint(TestConfigurations.HOST) | ||
.buildAsyncClient(); | ||
CosmosAsyncContainer cosmosAsyncContainer = getSharedSinglePartitionCosmosContainer(cosmosAsyncClient); | ||
|
||
TestObject testObject = TestObject.create(); | ||
cosmosAsyncContainer.createItem(testObject).block(); | ||
|
||
Field field = Utils.class.getDeclaredField("simpleObjectMapper"); | ||
field.setAccessible(true); | ||
|
||
// Save original | ||
originalMapper = (ObjectMapper) field.get(null); | ||
|
||
// Create a bad ObjectMapper | ||
ObjectMapper badMapper = new FailingObjectMapper(); | ||
// Override | ||
field.set(null, badMapper); | ||
|
||
cosmosAsyncContainer.readItem(testObject.getId(), new PartitionKey(testObject.getMypk()), TestObject.class).block(); | ||
fail("The read operation should have failed"); | ||
} catch (CosmosException cosmosException) { | ||
validate(cosmosException); | ||
} catch (IllegalAccessException e) { | ||
fail("An IllegalAccessException shouldn't have occurred", e); | ||
} finally { | ||
// Restore original | ||
Field field = Utils.class.getDeclaredField("simpleObjectMapper"); | ||
field.setAccessible(true); | ||
field.set(null, originalMapper); | ||
field.setAccessible(false); | ||
} | ||
} | ||
|
||
@Test(groups = {"emulator"}) | ||
public void validateCosmosExceptionThrownOnMalformedResponseWhenFallbackDecoderSet() throws NoSuchFieldException, IllegalAccessException { | ||
|
||
CosmosAsyncClient cosmosAsyncClient = null; | ||
ObjectMapper originalMapper = null; | ||
|
||
try { | ||
|
||
cosmosAsyncClient = getClientBuilder() | ||
.key(TestConfigurations.MASTER_KEY) | ||
.endpoint(TestConfigurations.HOST) | ||
.buildAsyncClient(); | ||
CosmosAsyncContainer cosmosAsyncContainer = getSharedSinglePartitionCosmosContainer(cosmosAsyncClient); | ||
|
||
TestObject testObject = TestObject.create(); | ||
cosmosAsyncContainer.createItem(testObject).block(); | ||
|
||
Field field = Utils.class.getDeclaredField("simpleObjectMapper"); | ||
field.setAccessible(true); | ||
|
||
// Save original | ||
originalMapper = (ObjectMapper) field.get(null); | ||
|
||
// Create a bad ObjectMapper | ||
ObjectMapper badMapper = new FailingObjectMapper(); | ||
// Override | ||
field.set(null, badMapper); | ||
|
||
cosmosAsyncContainer.readItem(testObject.getId(), new PartitionKey(testObject.getMypk()), TestObject.class).block(); | ||
fail("The read operation should have failed"); | ||
} catch (CosmosException cosmosException) { | ||
validate(cosmosException); | ||
} catch (IllegalAccessException e) { | ||
fail("An IllegalAccessException shouldn't have occurred", e); | ||
} finally { | ||
// Restore original | ||
Field field = Utils.class.getDeclaredField("simpleObjectMapper"); | ||
field.setAccessible(true); | ||
field.set(null, originalMapper); | ||
field.setAccessible(false); | ||
} | ||
} | ||
|
||
private class FailingObjectMapper extends ObjectMapper { | ||
@Override | ||
public JsonNode readTree(byte[] bytes) throws IOException { | ||
throw new IOException("Simulated failure"); | ||
} | ||
|
||
@Override | ||
public JsonNode readTree(String content) throws JsonProcessingException { | ||
throw new JsonParseException("Simulated failure"); | ||
jeet1995 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
@AfterSuite(groups = {"emulator"}, alwaysRun = true) | ||
public void afterSuite() { | ||
System.setProperty("COSMOS.CHARSET_DECODER_ERROR_ACTION_ON_MALFORMED_INPUT", "IGNORE"); | ||
super.afterSuite(); | ||
} | ||
|
||
private static void validate(CosmosException cosmosException) { | ||
assertThat(cosmosException.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR); | ||
assertThat(cosmosException.getSubStatusCode()).isEqualTo(HttpConstants.SubStatusCodes.FAILED_TO_PARSE_SERVER_RESPONSE); | ||
assertThat(cosmosException.getDiagnostics()).isNotNull(); | ||
assertThat(cosmosException.getResponseHeaders()).isNotNull(); | ||
assertThat(cosmosException.getResponseHeaders()).isNotEmpty(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ | |
package com.azure.cosmos.implementation.directconnectivity; | ||
|
||
import com.azure.cosmos.implementation.Configs; | ||
import com.azure.cosmos.implementation.HttpConstants; | ||
import com.azure.cosmos.implementation.Utils; | ||
import com.fasterxml.jackson.databind.JsonNode; | ||
import io.netty.buffer.ByteBufInputStream; | ||
|
@@ -16,49 +17,79 @@ | |
import java.nio.charset.CharsetDecoder; | ||
import java.nio.charset.CodingErrorAction; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.Base64; | ||
import java.util.Map; | ||
|
||
public class JsonNodeStorePayload implements StorePayload<JsonNode> { | ||
private static final Logger logger = LoggerFactory.getLogger(JsonNodeStorePayload.class); | ||
private static final CharsetDecoder fallbackCharsetDecoder = getFallbackCharsetDecoder(); | ||
private final int responsePayloadSize; | ||
private final JsonNode jsonValue; | ||
|
||
public JsonNodeStorePayload(ByteBufInputStream bufferStream, int readableBytes) { | ||
public JsonNodeStorePayload(ByteBufInputStream bufferStream, int readableBytes, Map<String, String> responseHeaders) { | ||
if (readableBytes > 0) { | ||
this.responsePayloadSize = readableBytes; | ||
this.jsonValue = fromJson(bufferStream, readableBytes); | ||
this.jsonValue = fromJson(bufferStream, readableBytes, responseHeaders); | ||
} else { | ||
this.responsePayloadSize = 0; | ||
this.jsonValue = null; | ||
} | ||
} | ||
|
||
private static JsonNode fromJson(ByteBufInputStream bufferStream, int readableBytes) { | ||
private static JsonNode fromJson(ByteBufInputStream bufferStream, int readableBytes, Map<String, String> responseHeaders) { | ||
byte[] bytes = new byte[readableBytes]; | ||
try { | ||
bufferStream.read(bytes); | ||
return Utils.getSimpleObjectMapper().readTree(bytes); | ||
} catch (IOException e) { | ||
if (fallbackCharsetDecoder != null) { | ||
logger.warn("Unable to parse JSON, fallback to use customized charset decoder.", e); | ||
return fromJsonWithFallbackCharsetDecoder(bytes); | ||
return fromJsonWithFallbackCharsetDecoder(bytes, responseHeaders); | ||
jeet1995 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} else { | ||
throw new IllegalStateException("Unable to parse JSON.", e); | ||
|
||
if (Configs.isNonParseableDocumentLoggingEnabled()) { | ||
String documentSample = Base64.getEncoder().encodeToString(bytes); | ||
logger.error("Failed to parse JSON document. No customized charset decoder configured. Document in Base64 format: [" + documentSample + "]", e); | ||
} else { | ||
logger.error("Failed to parse JSON document. No customized charset decoder configured."); | ||
} | ||
|
||
IllegalStateException innerException = new IllegalStateException("Unable to parse JSON.", e); | ||
|
||
throw Utils.createCosmosException( | ||
HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Initially I was inclined to ask for changing this to 400 Bad Request - indicating that application is responsible for invalid json. That said, service should validate json validity before even storing it - so, 500 also seems reasonable. Worth discussing a bit more broadly IMO. |
||
HttpConstants.SubStatusCodes.FAILED_TO_PARSE_SERVER_RESPONSE, | ||
innerException, | ||
responseHeaders); | ||
} | ||
} | ||
} | ||
|
||
private static JsonNode fromJsonWithFallbackCharsetDecoder(byte[] bytes) { | ||
private static JsonNode fromJsonWithFallbackCharsetDecoder(byte[] bytes, Map<String, String> responseHeaders) { | ||
try { | ||
String sanitizedJson = fallbackCharsetDecoder.decode(ByteBuffer.wrap(bytes)).toString(); | ||
return Utils.getSimpleObjectMapper().readTree(sanitizedJson); | ||
} catch (IOException e) { | ||
throw new IllegalStateException( | ||
|
||
if (Configs.isNonParseableDocumentLoggingEnabled()) { | ||
String documentSample = Base64.getEncoder().encodeToString(bytes); | ||
logger.error("Failed to parse JSON document even after applying fallback charset decoder. Document in Base64 format: [" + documentSample + "]", e); | ||
jeet1995 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} else { | ||
logger.error("Failed to parse JSON document even after applying fallback charset decoder."); | ||
} | ||
|
||
Exception nestedException = new IllegalStateException( | ||
String.format( | ||
"Unable to parse JSON with fallback charset decoder[OnMalformedInput %s, OnUnmappedCharacter %s]", | ||
Configs.getCharsetDecoderErrorActionOnMalformedInput(), | ||
Configs.getCharsetDecoderErrorActionOnUnmappedCharacter()), | ||
e); | ||
|
||
throw Utils.createCosmosException( | ||
HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, | ||
HttpConstants.SubStatusCodes.FAILED_TO_PARSE_SERVER_RESPONSE, | ||
nestedException, | ||
responseHeaders); | ||
} | ||
} | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.