-
Notifications
You must be signed in to change notification settings - Fork 2.5k
FINERACT-1420: Improve idempotency fallback using deterministic key generation #5674
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
Draft
elnafateh
wants to merge
1
commit into
apache:develop
Choose a base branch
from
elnafateh:develop
base: develop
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.
+550
−20
Draft
Changes from all commits
Commits
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
112 changes: 112 additions & 0 deletions
112
.../main/java/org/apache/fineract/commands/service/DeterministicIdempotencyKeyGenerator.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,112 @@ | ||
| /** | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you 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 org.apache.fineract.commands.service; | ||
|
|
||
| import com.fasterxml.jackson.core.JsonFactory; | ||
| import com.fasterxml.jackson.core.JsonParser; | ||
| import com.fasterxml.jackson.databind.JsonNode; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.fasterxml.jackson.databind.node.ArrayNode; | ||
| import com.fasterxml.jackson.databind.node.ObjectNode; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.security.MessageDigest; | ||
| import java.time.Instant; | ||
| import java.util.ArrayList; | ||
| import java.util.Base64; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Component | ||
| public class DeterministicIdempotencyKeyGenerator { | ||
|
|
||
| // Plain ObjectMapper for canonicalization — must NOT use the application ObjectMapper | ||
| // which has custom serializers/deserializers that cause failures on certain JSON payloads | ||
| private static final ObjectMapper CANONICAL_MAPPER; | ||
|
|
||
| static { | ||
| JsonFactory factory = new JsonFactory(); | ||
| factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); | ||
| CANONICAL_MAPPER = new ObjectMapper(factory); | ||
| } | ||
|
|
||
| public String generate(String json, String context) { | ||
|
|
||
| if (json == null || json.isBlank()) { | ||
| // Shouldn't reach here after resolver guard, but defensive fallback | ||
| return java.util.UUID.randomUUID().toString(); | ||
| } | ||
|
|
||
| String canonical = toCanonicalString(json); | ||
| String window = currentTimeWindow(); | ||
| return hash(canonical + ":" + context + ":" + window); | ||
| } | ||
|
|
||
| private String toCanonicalString(String json) { | ||
| try { | ||
| JsonNode node = CANONICAL_MAPPER.readTree(json); | ||
| JsonNode canonical = canonicalize(node); | ||
| return CANONICAL_MAPPER.writeValueAsString(canonical); | ||
| } catch (Exception e) { | ||
| throw new RuntimeException("Failed to canonicalize JSON", e); | ||
| } | ||
| } | ||
|
|
||
| private JsonNode canonicalize(JsonNode node) { | ||
| if (node.isObject()) { | ||
| ObjectNode sorted = CANONICAL_MAPPER.createObjectNode(); | ||
|
|
||
| List<String> fieldNames = new ArrayList<>(); | ||
| node.fieldNames().forEachRemaining(fieldNames::add); | ||
| Collections.sort(fieldNames); | ||
|
|
||
| for (String field : fieldNames) { | ||
| sorted.set(field, canonicalize(node.get(field))); // recursion to resolve nested obj | ||
| } | ||
|
|
||
| return sorted; | ||
| } | ||
|
|
||
| if (node.isArray()) { | ||
| ArrayNode arrayNode = CANONICAL_MAPPER.createArrayNode(); | ||
| for (JsonNode element : node) { | ||
| arrayNode.add(canonicalize(element)); // recursion inside array | ||
| } | ||
| return arrayNode; | ||
| } | ||
|
|
||
| return node; // primitives + null | ||
| } | ||
|
|
||
| private String hash(String input) { | ||
| try { | ||
| MessageDigest digest = MessageDigest.getInstance("SHA-256"); | ||
| byte[] hashed = digest.digest(input.getBytes(StandardCharsets.UTF_8)); | ||
| return Base64.getEncoder().encodeToString(hashed); | ||
| } catch (Exception e) { | ||
| throw new RuntimeException("Hashing failed", e); | ||
| } | ||
| } | ||
|
|
||
| private String currentTimeWindow() { | ||
| Instant now = Instant.now(); | ||
| long window = now.getEpochSecond() / (5 * 60); | ||
| return String.valueOf(window); | ||
| } | ||
| } | ||
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
78 changes: 78 additions & 0 deletions
78
...t/java/org/apache/fineract/commands/service/DeterministicIdempotencyKeyGeneratorTest.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,78 @@ | ||
| /** | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you 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 org.apache.fineract.commands.service; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertNotEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| class DeterministicIdempotencyKeyGeneratorTest { | ||
|
|
||
| private final DeterministicIdempotencyKeyGenerator underTest = new DeterministicIdempotencyKeyGenerator(); | ||
|
|
||
| @Test | ||
| void shouldGenerateSameKeyForSameInputAndContext() { | ||
| String json = "{\"b\":2,\"a\":1}"; | ||
| String context = "action:entity:/endpoint:client1"; | ||
|
|
||
| String key1 = underTest.generate(json, context); | ||
| String key2 = underTest.generate("{\"a\":1,\"b\":2}", context); | ||
|
|
||
| assertEquals(key1, key2); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldGenerateDifferentKeysForDifferentContext() { | ||
| String json = "{\"a\":1}"; | ||
|
|
||
| String key1 = underTest.generate(json, "context1"); | ||
| String key2 = underTest.generate(json, "context2"); | ||
|
|
||
| assertNotEquals(key1, key2); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldGenerateDifferentKeysForDifferentPayload() { | ||
| String context = "same-context"; | ||
|
|
||
| String key1 = underTest.generate("{\"a\":1}", context); | ||
| String key2 = underTest.generate("{\"a\":2}", context); | ||
|
|
||
| assertNotEquals(key1, key2); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldGenerateSameKeyWithinSameTimeWindow() { | ||
| String json = "{\"a\":1}"; | ||
| String context = "ctx"; | ||
|
|
||
| String key1 = underTest.generate(json, context); | ||
| String key2 = underTest.generate(json, context); | ||
|
|
||
| assertEquals(key1, key2); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldFailForInvalidJson() { | ||
| RuntimeException exception = assertThrows(RuntimeException.class, () -> underTest.generate("{invalid-json", "test-context")); | ||
| assertEquals("Failed to canonicalize JSON", exception.getMessage()); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
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.