Skip to content

Commit 4a616b5

Browse files
committed
feat: add deterministic idempotency key generation with time bucket fallback
1 parent 2ee6f22 commit 4a616b5

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package org.apache.fineract.commands.service;
2+
3+
4+
import org.apache.fineract.commands.domain.CommandWrapper;
5+
import org.springframework.stereotype.Component;
6+
7+
import java.nio.charset.StandardCharsets;
8+
import java.security.MessageDigest;
9+
import java.util.Base64;
10+
11+
@Component
12+
public class DeterministicIdempotencyKeyGenerator {
13+
14+
private static final int BUCKET_MINUTES = 2;
15+
16+
public String generate(CommandWrapper wrapper) {
17+
String json = wrapper.getJson();
18+
19+
String normalizedPayload = normalize(json);
20+
21+
String bucket = currentTimeBucket();
22+
23+
String raw = normalizedPayload + "|" + bucket;
24+
25+
return sha256(raw);
26+
}
27+
28+
private String normalize(String json) {
29+
// IMPORTANT: make deterministic (order, spacing, etc.)
30+
return json.replaceAll("\\s+", "");
31+
}
32+
33+
private String currentTimeBucket() {
34+
long now = System.currentTimeMillis();
35+
long bucketMillis = BUCKET_MINUTES * 60 * 1000;
36+
long bucket = now / bucketMillis;
37+
return String.valueOf(bucket);
38+
}
39+
40+
private String sha256(String input) {
41+
try {
42+
MessageDigest digest = MessageDigest.getInstance("SHA-256");
43+
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
44+
return Base64.getEncoder().encodeToString(hash);
45+
} catch (Exception e) {
46+
throw new RuntimeException("Failed to generate idempotency key", e);
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)