fix(glue): ignore Avro custom attributes in schema identity (#4692)

* fix(glue): ignore Avro custom attributes in schema identity

* fix(glue): preserve lookup across legacy duplicate schema versions

* fix(glue): synchronize schema definition lookups with deletion

* perf(glue): narrow definition lookup lock

* fix(glue): revalidate schema format during definition lookup

* fix(glue): scope Avro schema properties by type

* fix(glue): use modeled error for schema lookup retries
This commit is contained in:
XuJian authored and GitHub committed 2026-10-01 13:41:43 -04:00
1 parent 0c8d184854
commit c60da16c54
5 files changed
+543 -14

No files matched your search

@@ -43,6 +43,7 @@ public class GlueSchemaRegistryService {
private static final int DEFAULT_MAX_RESULTS = 100;
private static final int MAX_MAX_RESULTS = 100;
private static final int MAX_DELETE_SCHEMA_VERSIONS = 25;
private static final int MAX_LOOKUP_FORMAT_ATTEMPTS = 4;
private static final int MAX_SCHEMA_DEFINITION_LENGTH = 170_000;
private static final Set<String> DATA_FORMATS = Set.of("AVRO", "JSON", "PROTOBUF");
@@ -424,8 +425,15 @@ public class GlueSchemaRegistryService {
byNumber.remove(v);
if (hash != null) {
Map<String, String> hashIndex = versionByDefinitionHash.get(key);
if (hashIndex != null) {
hashIndex.remove(hash);
if (hashIndex != null && hashIndex.remove(hash, id)) {
for (String remainingId : byNumber.values()) {
SchemaVersion remaining = versionStore.get(remainingId).orElse(null);
if (remaining != null && hash.equals(canonicalHash(
remaining.getSchemaDefinition(), remaining.getDataFormat()))) {
hashIndex.putIfAbsent(hash, remainingId);
break;
}
}
}
}
if (v.equals(latestRemaining)) {
@@ -639,16 +647,31 @@ public class GlueSchemaRegistryService {
validateDefinitionRequired(definition);
Schema schema = resolveSchema(schemaId, region);
String schemaKey = schemaKey(schema.getRegistryName(), schema.getSchemaName());
String hash = canonicalHash(definition, schema.getDataFormat());
Map<String, String> hashIndex = versionByDefinitionHash.get(schemaKey);
String id = hashIndex != null ? hashIndex.get(hash) : null;
if (id == null) {
throw new AwsException("EntityNotFoundException",
"Schema version is not found. Definition not found in " + schemaKey, 400);
String dataFormat = schema.getDataFormat();
for (int attempt = 0; attempt < MAX_LOOKUP_FORMAT_ATTEMPTS; attempt++) {
String hash = canonicalHash(definition, dataFormat);
synchronized (this) {
String currentFormat = schemaStore.get(schemaKey)
.orElseThrow(() -> new AwsException("EntityNotFoundException",
"Schema is not found. " + schema.getRegistryName() + "/" + schema.getSchemaName(), 400))
.getDataFormat();
if (!dataFormat.equals(currentFormat)) {
dataFormat = currentFormat;
continue;
}
Map<String, String> hashIndex = versionByDefinitionHash.get(schemaKey);
String id = hashIndex != null ? hashIndex.get(hash) : null;
if (id == null) {
throw new AwsException("EntityNotFoundException",
"Schema version is not found. Definition not found in " + schemaKey, 400);
}
return versionStore.get(id)
.orElseThrow(() -> new AwsException("EntityNotFoundException",
"Schema version vanished: " + id, 400));
}
}
return versionStore.get(id)
.orElseThrow(() -> new AwsException("EntityNotFoundException",
"Schema version vanished: " + id, 400));
throw new AwsException("InternalServiceException",
"Schema format changed repeatedly during definition lookup: " + schemaKey, 500);
}
// ---- Helpers ---------------------------------------------------------
@@ -933,7 +956,7 @@ public class GlueSchemaRegistryService {
String hash = canonicalHash(version.getSchemaDefinition(), version.getDataFormat());
versionByDefinitionHash
.computeIfAbsent(schemaKey, k -> new ConcurrentHashMap<>())
.put(hash, version.getSchemaVersionId());
.putIfAbsent(hash, version.getSchemaVersionId());
}
private void rebuildVersionIndexes() {
@@ -943,7 +966,9 @@ public class GlueSchemaRegistryService {
for (Schema s : schemaStore.scan(k -> true)) {
arnToSchemaKey.put(s.getSchemaArn(), schemaKey(s.getRegistryName(), s.getSchemaName()));
}
for (SchemaVersion v : versionStore.scan(k -> true)) {
List<SchemaVersion> versions = new ArrayList<>(versionStore.scan(k -> true));
versions.sort(Comparator.comparing(SchemaVersion::getVersionNumber));
for (SchemaVersion v : versions) {
String schemaKey = arnToSchemaKey.get(v.getSchemaArn());
if (schemaKey == null) {
continue;
@@ -1,5 +1,10 @@
package io.github.hectorvent.floci.services.glue.schemaregistry;
import com.fasterxml.jackson.core.JsonProcessingException;
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 io.apicurio.registry.content.ContentHandle;
import io.apicurio.registry.content.canon.AvroContentCanonicalizer;
import io.apicurio.registry.content.canon.ContentCanonicalizer;
@@ -20,6 +25,7 @@ import io.apicurio.registry.rules.validity.ValidityLevel;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
@@ -28,6 +34,22 @@ import java.util.stream.Collectors;
*/
public final class SchemaCompatibilityChecker {
private static final ObjectMapper JSON = new ObjectMapper();
private static final Set<String> AVRO_RECORD_PROPERTIES = Set.of(
"type", "name", "namespace", "doc", "aliases", "fields", "logicalType", "precision", "scale");
private static final Set<String> AVRO_ENUM_PROPERTIES = Set.of(
"type", "name", "namespace", "doc", "aliases", "symbols", "default",
"logicalType", "precision", "scale");
private static final Set<String> AVRO_FIXED_PROPERTIES = Set.of(
"type", "name", "namespace", "doc", "aliases", "size", "logicalType", "precision", "scale");
private static final Set<String> AVRO_ARRAY_PROPERTIES = Set.of(
"type", "items", "default", "logicalType", "precision", "scale");
private static final Set<String> AVRO_MAP_PROPERTIES = Set.of(
"type", "values", "default", "logicalType", "precision", "scale");
private static final Set<String> AVRO_PRIMITIVE_PROPERTIES = Set.of("type", "logicalType", "precision", "scale");
private static final Set<String> AVRO_FIELD_PROPERTIES = Set.of(
"name", "type", "doc", "default", "order", "aliases");
public record Result(boolean compatible, String reason) {
public static Result ok() {
return new Result(true, null);
@@ -70,7 +92,46 @@ public final class SchemaCompatibilityChecker {
public static String canonicalize(String definition, String dataFormat) {
ContentCanonicalizer canon = canonicalizerFor(dataFormat);
ContentHandle handle = ContentHandle.create(definition);
return canon.canonicalize(handle, Map.of()).content();
String canonical = canon.canonicalize(handle, Map.of()).content();
if (!"AVRO".equals(dataFormat)) {
return canonical;
}
try {
JsonNode schema = JSON.readTree(canonical);
stripAvroCustomAttributes(schema);
return schema.toString();
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Unable to canonicalize AVRO schema", e);
}
}
private static void stripAvroCustomAttributes(JsonNode schema) {
if (schema instanceof ArrayNode union) {
for (JsonNode branch : union) {
stripAvroCustomAttributes(branch);
}
} else if (schema instanceof ObjectNode object) {
Set<String> properties = switch (object.path("type").asText()) {
case "record", "error" -> AVRO_RECORD_PROPERTIES;
case "enum" -> AVRO_ENUM_PROPERTIES;
case "fixed" -> AVRO_FIXED_PROPERTIES;
case "array" -> AVRO_ARRAY_PROPERTIES;
case "map" -> AVRO_MAP_PROPERTIES;
default -> AVRO_PRIMITIVE_PROPERTIES;
};
object.retain(properties);
stripAvroCustomAttributes(object.get("type"));
stripAvroCustomAttributes(object.get("items"));
stripAvroCustomAttributes(object.get("values"));
if (object.get("fields") instanceof ArrayNode fields) {
for (JsonNode field : fields) {
if (field instanceof ObjectNode fieldObject) {
fieldObject.retain(AVRO_FIELD_PROPERTIES);
stripAvroCustomAttributes(fieldObject.get("type"));
}
}
}
}
}
/**
@@ -35,6 +35,10 @@ class GlueSchemaRegistrySchemaIntegrationTest {
+ "\\\"fields\\\":[{\\\"name\\\":\\\"id\\\",\\\"type\\\":\\\"long\\\"},"
+ "{\\\"name\\\":\\\"email\\\",\\\"type\\\":\\\"string\\\"}]}";
private static final String AVRO_V1_WITH_CUSTOM_ATTRIBUTES = AVRO_V1
.replace("\\\"fields\\\"", "\\\"x-record\\\":\\\"custom\\\",\\\"fields\\\"")
.replace("\\\"type\\\":\\\"long\\\"", "\\\"type\\\":\\\"long\\\",\\\"x-field\\\":\\\"custom\\\"");
private static String createdSchemaVersionId;
@BeforeAll
@@ -233,4 +237,42 @@ class GlueSchemaRegistrySchemaIntegrationTest {
.statusCode(400)
.body("__type", equalTo("InvalidInputException"));
}
@Test
@Order(12)
void customAvroAttributesReuseExistingVersionForRegistrationAndLookup() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSGlue.RegisterSchemaVersion")
.body("{ \"SchemaId\": { \"RegistryName\": \"" + REGISTRY + "\", \"SchemaName\": \"" + SCHEMA + "\" },"
+ " \"SchemaDefinition\": \"" + AVRO_V1_WITH_CUSTOM_ATTRIBUTES + "\" }")
.when()
.post("/")
.then()
.statusCode(200)
.body("SchemaVersionId", equalTo(createdSchemaVersionId))
.body("VersionNumber", equalTo(1));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSGlue.GetSchemaByDefinition")
.body("{ \"SchemaId\": { \"RegistryName\": \"" + REGISTRY + "\", \"SchemaName\": \"" + SCHEMA + "\" },"
+ " \"SchemaDefinition\": \"" + AVRO_V1_WITH_CUSTOM_ATTRIBUTES + "\" }")
.when()
.post("/")
.then()
.statusCode(200)
.body("SchemaVersionId", equalTo(createdSchemaVersionId));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "AWSGlue.GetSchemaVersion")
.body("{ \"SchemaId\": { \"RegistryName\": \"" + REGISTRY + "\", \"SchemaName\": \"" + SCHEMA + "\" },"
+ " \"SchemaVersionNumber\": { \"LatestVersion\": true } }")
.when()
.post("/")
.then()
.statusCode(200)
.body("VersionNumber", equalTo(2));
}
}
@@ -11,8 +11,20 @@ import io.github.hectorvent.floci.services.glue.schemaregistry.model.SchemaVersi
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -20,6 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class GlueSchemaRegistryServiceTest {
@@ -378,6 +391,309 @@ class GlueSchemaRegistryServiceTest {
assertEquals(1L, same.getVersionNumber());
}
@Test
void recordLevelCustomAttributesReuseExistingVersionAndRemainDiscoverable() {
preCreateRegistry();
SchemaVersion first = service.createSchema(new RegistryId("reg", null),
"users", "AVRO", "BACKWARD", null, AVRO_V1, null, REGION).firstVersion();
SchemaId schemaId = new SchemaId("reg", "users", null);
for (String attribute : List.of("\"order\":\"descending\"", "\"default\":\"unused\"",
"\"symbols\":[\"IGNORED\"]", "\"size\":8")) {
String definition = AVRO_V1.replace("\"fields\"", attribute + ",\"fields\"");
assertEquals(first.getSchemaVersionId(),
service.registerSchemaVersion(schemaId, definition, REGION).getSchemaVersionId(), attribute);
assertEquals(first.getSchemaVersionId(),
service.getSchemaByDefinition(schemaId, definition, REGION).getSchemaVersionId(), attribute);
}
assertEquals(1, service.listSchemaVersions(schemaId, REGION).size());
}
@Test
void legacyAvroDuplicatesPreferEarliestVersionAndSurviveDeletion() {
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
InMemoryStorage<String, Registry> registryStore = new InMemoryStorage<>();
InMemoryStorage<String, Schema> schemaStore = new InMemoryStorage<>();
InMemoryStorage<String, SchemaVersion> versionStore = new InMemoryStorage<>() {
@Override
public List<SchemaVersion> scan(Predicate<String> keyFilter) {
List<SchemaVersion> versions = super.scan(keyFilter);
versions.sort((left, right) -> left.getVersionNumber().compareTo(right.getVersionNumber()));
return versions;
}
};
service = new GlueSchemaRegistryService(registryStore, schemaStore, versionStore,
new InMemoryStorage<>(), regionResolver);
service.createRegistry("reg", null, null, REGION);
SchemaVersion first = service.createSchema(new RegistryId("reg", null),
"users", "AVRO", "BACKWARD", null, AVRO_V1, null, REGION).firstVersion();
SchemaId schemaId = new SchemaId("reg", "users", null);
SchemaVersion second = service.registerSchemaVersion(schemaId, AVRO_V2_BACKWARD_OK, REGION);
String withCustomAttribute = AVRO_V1.replace("\"type\":\"long\"",
"\"type\":\"long\",\"x-field\":\"legacy\"");
second.setSchemaDefinition(withCustomAttribute);
versionStore.put(second.getSchemaVersionId(), second);
service = new GlueSchemaRegistryService(registryStore, schemaStore, versionStore,
new InMemoryStorage<>(), regionResolver);
service.afterCdiInit();
assertEquals(first.getSchemaVersionId(),
service.getSchemaByDefinition(schemaId, withCustomAttribute, REGION).getSchemaVersionId());
assertEquals(first.getSchemaVersionId(),
service.registerSchemaVersion(schemaId, withCustomAttribute, REGION).getSchemaVersionId());
service.updateSchema(schemaId, null, null, 2L, REGION);
assertNull(service.deleteSchemaVersions(schemaId, "1", REGION).get(0).errorCode());
assertEquals(second.getSchemaVersionId(),
service.getSchemaByDefinition(schemaId, AVRO_V1, REGION).getSchemaVersionId());
assertEquals(second.getSchemaVersionId(),
service.registerSchemaVersion(schemaId, AVRO_V1, REGION).getSchemaVersionId());
}
@Test
void lookupWaitsForLegacyDuplicateHashReplacement() throws Exception {
CountDownLatch replacementStarted = new CountDownLatch(1);
CountDownLatch finishReplacement = new CountDownLatch(1);
AtomicReference<String> replacementId = new AtomicReference<>();
AtomicReference<Thread> deletingThread = new AtomicReference<>();
OrderedVersionStore versionStore = new OrderedVersionStore() {
@Override
public Optional<SchemaVersion> get(String key) {
if (Thread.currentThread() == deletingThread.get() && key.equals(replacementId.get())) {
replacementStarted.countDown();
awaitRelease(finishReplacement);
}
return super.get(key);
}
};
LegacyAvroVersions versions = legacyAvroVersions(versionStore);
replacementId.set(versions.second().getSchemaVersionId());
service.updateSchema(versions.schemaId(), null, null, 2L, REGION);
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<List<GlueSchemaRegistryService.VersionDeletionResult>> deletion = pool.submit(() -> {
deletingThread.set(Thread.currentThread());
return service.deleteSchemaVersions(versions.schemaId(), "1", REGION);
});
assertTrue(replacementStarted.await(5, TimeUnit.SECONDS));
CountDownLatch lookupStarted = new CountDownLatch(1);
AtomicReference<Thread> lookupThread = new AtomicReference<>();
Future<SchemaVersion> lookup = pool.submit(() -> {
lookupThread.set(Thread.currentThread());
lookupStarted.countDown();
return service.getSchemaByDefinition(versions.schemaId(), AVRO_V1, REGION);
});
assertTrue(lookupStarted.await(5, TimeUnit.SECONDS));
assertBlockedOnService(lookupThread.get(), lookup);
finishReplacement.countDown();
assertNull(deletion.get(5, TimeUnit.SECONDS).get(0).errorCode());
assertEquals(versions.second().getSchemaVersionId(),
lookup.get(5, TimeUnit.SECONDS).getSchemaVersionId());
} finally {
finishReplacement.countDown();
pool.shutdownNow();
assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void deletionWaitsForLookupThatAlreadyReadLegacyVersionId() throws Exception {
CountDownLatch lookupReadingVersion = new CountDownLatch(1);
CountDownLatch finishLookup = new CountDownLatch(1);
AtomicReference<String> firstId = new AtomicReference<>();
AtomicReference<Thread> lookupThread = new AtomicReference<>();
OrderedVersionStore versionStore = new OrderedVersionStore() {
@Override
public Optional<SchemaVersion> get(String key) {
if (Thread.currentThread() == lookupThread.get() && key.equals(firstId.get())) {
lookupReadingVersion.countDown();
awaitRelease(finishLookup);
}
return super.get(key);
}
};
LegacyAvroVersions versions = legacyAvroVersions(versionStore);
firstId.set(versions.first().getSchemaVersionId());
service.updateSchema(versions.schemaId(), null, null, 2L, REGION);
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
Future<SchemaVersion> lookup = pool.submit(() -> {
lookupThread.set(Thread.currentThread());
return service.getSchemaByDefinition(versions.schemaId(), AVRO_V1, REGION);
});
assertTrue(lookupReadingVersion.await(5, TimeUnit.SECONDS));
CountDownLatch deletionStarted = new CountDownLatch(1);
AtomicReference<Thread> deletingThread = new AtomicReference<>();
Future<List<GlueSchemaRegistryService.VersionDeletionResult>> deletion = pool.submit(() -> {
deletingThread.set(Thread.currentThread());
deletionStarted.countDown();
return service.deleteSchemaVersions(versions.schemaId(), "1", REGION);
});
assertTrue(deletionStarted.await(5, TimeUnit.SECONDS));
assertBlockedOnService(deletingThread.get(), deletion);
finishLookup.countDown();
assertEquals(versions.first().getSchemaVersionId(),
lookup.get(5, TimeUnit.SECONDS).getSchemaVersionId());
assertNull(deletion.get(5, TimeUnit.SECONDS).get(0).errorCode());
assertEquals(versions.second().getSchemaVersionId(),
service.getSchemaByDefinition(versions.schemaId(), AVRO_V1, REGION).getSchemaVersionId());
} finally {
finishLookup.countDown();
pool.shutdownNow();
assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
@Test
void lookupRehashesAfterSchemaIsRecreatedWithDifferentFormat() throws Exception {
String definition = "{\"type\":\"string\",\"x-note\":\"both formats\"}";
assertTrue(service.checkSchemaVersionValidity("AVRO", definition).valid());
assertTrue(service.checkSchemaVersionValidity("JSON", definition).valid());
assertLookupFindsRecreatedSchema(definition, definition);
}
@Test
void lookupFindsDefinitionInvalidForOldFormatAfterRecreation() throws Exception {
String jsonDefinition = "{ \"type\": \"object\", \"properties\": { \"k\": { \"type\": \"string\" } } }";
assertFalse(service.checkSchemaVersionValidity("AVRO", jsonDefinition).valid());
assertTrue(service.checkSchemaVersionValidity("JSON", jsonDefinition).valid());
assertFalse(jsonDefinition.equals(SchemaCompatibilityChecker.canonicalize(jsonDefinition, "JSON")));
assertLookupFindsRecreatedSchema(AVRO_V1, jsonDefinition);
}
@Test
void lookupReportsInternalErrorWhenSchemaFormatKeepsChanging() {
String definition = "{\"type\":\"string\"}";
AtomicBoolean alternateFormat = new AtomicBoolean();
AtomicInteger reads = new AtomicInteger();
InMemoryStorage<String, Schema> schemaStore = new InMemoryStorage<>() {
@Override
public Optional<Schema> get(String key) {
Optional<Schema> schema = super.get(key);
if (alternateFormat.get() && schema.isPresent()) {
schema.get().setDataFormat(reads.getAndIncrement() % 2 == 0 ? "AVRO" : "JSON");
}
return schema;
}
};
service = new GlueSchemaRegistryService(new InMemoryStorage<>(), schemaStore,
new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, ACCOUNT_ID));
service.createRegistry("reg", null, null, REGION);
service.createSchema(new RegistryId("reg", null), "users", "AVRO", "NONE",
null, definition, null, REGION);
alternateFormat.set(true);
AwsException error = assertThrows(AwsException.class, () ->
service.getSchemaByDefinition(new SchemaId("reg", "users", null), definition, REGION));
assertEquals("InternalServiceException", error.getErrorCode());
assertEquals(500, error.getHttpStatus());
}
private void assertLookupFindsRecreatedSchema(String oldDefinition, String replacementDefinition) throws Exception {
CountDownLatch firstSchemaRead = new CountDownLatch(1);
CountDownLatch finishLookup = new CountDownLatch(1);
AtomicBoolean paused = new AtomicBoolean();
AtomicReference<Thread> lookupThread = new AtomicReference<>();
InMemoryStorage<String, Schema> schemaStore = new InMemoryStorage<>() {
@Override
public Optional<Schema> get(String key) {
Optional<Schema> schema = super.get(key);
if (Thread.currentThread() == lookupThread.get()
&& key.equals("reg:users") && paused.compareAndSet(false, true)) {
firstSchemaRead.countDown();
awaitRelease(finishLookup);
}
return schema;
}
};
service = new GlueSchemaRegistryService(new InMemoryStorage<>(), schemaStore,
new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, ACCOUNT_ID));
service.createRegistry("reg", null, null, REGION);
SchemaId schemaId = new SchemaId("reg", "users", null);
service.createSchema(new RegistryId("reg", null), "users", "AVRO", "BACKWARD",
null, oldDefinition, null, REGION);
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<SchemaVersion> lookup = pool.submit(() -> {
lookupThread.set(Thread.currentThread());
return service.getSchemaByDefinition(schemaId, replacementDefinition, REGION);
});
assertTrue(firstSchemaRead.await(5, TimeUnit.SECONDS));
service.deleteSchema(schemaId, REGION);
SchemaVersion replacement = service.createSchema(new RegistryId("reg", null),
"users", "JSON", "BACKWARD", null, replacementDefinition, null, REGION).firstVersion();
finishLookup.countDown();
assertEquals(replacement.getSchemaVersionId(), lookup.get(5, TimeUnit.SECONDS).getSchemaVersionId());
} finally {
finishLookup.countDown();
pool.shutdownNow();
assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
private LegacyAvroVersions legacyAvroVersions(OrderedVersionStore versionStore) {
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
InMemoryStorage<String, Registry> registryStore = new InMemoryStorage<>();
InMemoryStorage<String, Schema> schemaStore = new InMemoryStorage<>();
service = new GlueSchemaRegistryService(registryStore, schemaStore, versionStore,
new InMemoryStorage<>(), regionResolver);
service.createRegistry("reg", null, null, REGION);
SchemaVersion first = service.createSchema(new RegistryId("reg", null),
"users", "AVRO", "BACKWARD", null, AVRO_V1, null, REGION).firstVersion();
SchemaId schemaId = new SchemaId("reg", "users", null);
SchemaVersion second = service.registerSchemaVersion(schemaId, AVRO_V2_BACKWARD_OK, REGION);
String withCustomAttribute = AVRO_V1.replace("\"type\":\"long\"",
"\"type\":\"long\",\"x-field\":\"legacy\"");
second.setSchemaDefinition(withCustomAttribute);
versionStore.put(second.getSchemaVersionId(), second);
service = new GlueSchemaRegistryService(registryStore, schemaStore, versionStore,
new InMemoryStorage<>(), regionResolver);
service.afterCdiInit();
return new LegacyAvroVersions(schemaId, first, second);
}
private static void awaitRelease(CountDownLatch release) {
try {
assertTrue(release.await(10, TimeUnit.SECONDS));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError(e);
}
}
private void assertBlockedOnService(Thread worker, Future<?> task) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime() < deadline && !task.isDone()) {
ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(worker.threadId());
if (info != null && info.getThreadState() == Thread.State.BLOCKED
&& info.getLockInfo() != null
&& info.getLockInfo().getIdentityHashCode() == System.identityHashCode(service)) {
return;
}
Thread.sleep(10);
}
fail("Expected worker to block on the schema service monitor");
}
private record LegacyAvroVersions(SchemaId schemaId, SchemaVersion first, SchemaVersion second) {}
private static class OrderedVersionStore extends InMemoryStorage<String, SchemaVersion> {
@Override
public List<SchemaVersion> scan(Predicate<String> keyFilter) {
List<SchemaVersion> versions = super.scan(keyFilter);
versions.sort((left, right) -> left.getVersionNumber().compareTo(right.getVersionNumber()));
return versions;
}
}
@Test
void registerSchemaVersionWithDisabledCompatRejectsNewVersions() {
preCreateRegistry();
@@ -6,6 +6,7 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -162,6 +163,90 @@ class SchemaCompatibilityCheckerTest {
assertEquals(c1, c2);
}
@Test
void canonicalizeIgnoresAvroCustomAttributes() {
String withCustomAttributes = "{\"type\":\"record\",\"name\":\"User\",\"namespace\":\"x\","
+ "\"x-record\":{\"any\":true},\"fields\":[{\"name\":\"id\",\"type\":\"long\","
+ "\"x-field\":\"value\"}]}";
assertEquals(SchemaCompatibilityChecker.canonicalize(AVRO_V1, "AVRO"),
SchemaCompatibilityChecker.canonicalize(withCustomAttributes, "AVRO"));
}
@Test
void canonicalizeIgnoresAttributesThatAreNotStandardForRecords() {
String base = SchemaCompatibilityChecker.canonicalize(AVRO_V1, "AVRO");
for (String attribute : List.of("\"order\":\"descending\"", "\"default\":\"unused\"",
"\"symbols\":[\"IGNORED\"]", "\"size\":8")) {
String withAttribute = AVRO_V1.replace("\"fields\"", attribute + ",\"fields\"");
assertNull(SchemaCompatibilityChecker.validateDefinition(withAttribute, "AVRO"), attribute);
assertEquals(base, SchemaCompatibilityChecker.canonicalize(withAttribute, "AVRO"), attribute);
}
}
@Test
void canonicalizePreservesTypeSpecificAvroProperties() {
String fieldOrder = AVRO_V1.replace("\"type\":\"long\"",
"\"type\":\"long\",\"order\":\"descending\"");
String fieldDefault = AVRO_V1.replace("\"type\":\"long\"",
"\"type\":\"long\",\"default\":1");
assertNotEquals(SchemaCompatibilityChecker.canonicalize(AVRO_V1, "AVRO"),
SchemaCompatibilityChecker.canonicalize(fieldOrder, "AVRO"));
assertNotEquals(SchemaCompatibilityChecker.canonicalize(AVRO_V1, "AVRO"),
SchemaCompatibilityChecker.canonicalize(fieldDefault, "AVRO"));
String enumSchema = "{\"type\":\"enum\",\"name\":\"Status\",\"symbols\":[\"OPEN\",\"CLOSED\"]}";
String fixedSchema = "{\"type\":\"fixed\",\"name\":\"Id\",\"size\":8}";
assertNotEquals(SchemaCompatibilityChecker.canonicalize(enumSchema, "AVRO"),
SchemaCompatibilityChecker.canonicalize(enumSchema.replace("CLOSED", "PENDING"), "AVRO"));
assertNotEquals(SchemaCompatibilityChecker.canonicalize(fixedSchema, "AVRO"),
SchemaCompatibilityChecker.canonicalize(fixedSchema.replace("\"size\":8", "\"size\":16"), "AVRO"));
}
@Test
void canonicalizePreservesExistingLogicalAnnotationsOnComplexTypes() {
for (String schema : List.of(AVRO_V1,
"{\"type\":\"array\",\"items\":\"string\"}",
"{\"type\":\"map\",\"values\":\"string\"}",
"{\"type\":\"enum\",\"name\":\"Status\",\"symbols\":[\"OPEN\",\"CLOSED\"]}")) {
String annotated = schema.replaceFirst("\\{", "{\"logicalType\":\"custom\",");
assertNotEquals(SchemaCompatibilityChecker.canonicalize(schema, "AVRO"),
SchemaCompatibilityChecker.canonicalize(annotated, "AVRO"), schema);
}
String decimal = "{\"type\":\"bytes\",\"logicalType\":\"decimal\",\"precision\":4,\"scale\":2}";
assertNotEquals(SchemaCompatibilityChecker.canonicalize(decimal, "AVRO"),
SchemaCompatibilityChecker.canonicalize(decimal.replace("\"precision\":4", "\"precision\":5"), "AVRO"));
assertNotEquals(SchemaCompatibilityChecker.canonicalize(decimal, "AVRO"),
SchemaCompatibilityChecker.canonicalize(decimal.replace("\"scale\":2", "\"scale\":1"), "AVRO"));
}
@Test
void canonicalizePreservesExistingArrayAndMapDefaults() {
String array = "{\"type\":\"array\",\"items\":\"string\"}";
String map = "{\"type\":\"map\",\"values\":\"string\"}";
assertNotEquals(SchemaCompatibilityChecker.canonicalize(array, "AVRO"),
SchemaCompatibilityChecker.canonicalize(array.replace("\"items\"",
"\"default\":[],\"items\""), "AVRO"));
assertNotEquals(SchemaCompatibilityChecker.canonicalize(map, "AVRO"),
SchemaCompatibilityChecker.canonicalize(map.replace("\"values\"",
"\"default\":{},\"values\""), "AVRO"));
}
@Test
void canonicalizeIgnoresNestedAvroCustomAttributesButPreservesDefaults() {
String base = "{\"type\":\"record\",\"name\":\"Outer\",\"fields\":[{\"name\":\"inner\","
+ "\"type\":{\"type\":\"record\",\"name\":\"Inner\",\"fields\":[{\"name\":\"value\","
+ "\"type\":\"string\"}]},\"default\":{\"value\":\"one\"}}]}";
String withCustom = base.replace("\"name\":\"Inner\"", "\"name\":\"Inner\",\"x-record\":true")
.replace("\"name\":\"value\"", "\"name\":\"value\",\"x-field\":42");
String changedDefault = base.replace("\"value\":\"one\"", "\"value\":\"two\"");
assertEquals(SchemaCompatibilityChecker.canonicalize(base, "AVRO"),
SchemaCompatibilityChecker.canonicalize(withCustom, "AVRO"));
assertNotEquals(SchemaCompatibilityChecker.canonicalize(base, "AVRO"),
SchemaCompatibilityChecker.canonicalize(changedDefault, "AVRO"));
}
@Test
void validateDefinitionAcceptsValidAvro() {
assertNull(SchemaCompatibilityChecker.validateDefinition(AVRO_V1, "AVRO"));