Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
addressing review comments
  • Loading branch information
ankitk-me committed Apr 25, 2024
commit d778b9e69db33d9890fd13cc29923a51f2e1a8be
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import io.aklivity.zilla.runtime.catalog.karapace.internal.config.KarapaceOptionsConfig;
import io.aklivity.zilla.runtime.engine.EngineContext;
Expand All @@ -26,19 +27,22 @@
public class KarapaceCatalogContext implements CatalogContext
{
private final EngineContext context;
private final ConcurrentHashMap<Integer, CompletableFuture<String>> cache;
private final ConcurrentMap<Integer, CompletableFuture<String>> cachedSchemas;
private final ConcurrentMap<Integer, CompletableFuture<CachedSchemaId>> cachedSchemaIds;

public KarapaceCatalogContext(
EngineContext context)
{
this.context = context;
this.cache = new ConcurrentHashMap<>();
this.cachedSchemas = new ConcurrentHashMap<>();
this.cachedSchemaIds = new ConcurrentHashMap<>();
}

@Override
public CatalogHandler attach(
CatalogConfig catalog)
{
return new KarapaceCatalogHandler(KarapaceOptionsConfig.class.cast(catalog.options), context, catalog.id, cache);
return new KarapaceCatalogHandler(KarapaceOptionsConfig.class.cast(catalog.options), context, catalog.id,
cachedSchemas, cachedSchemaIds);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.text.MessageFormat;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.zip.CRC32C;

Expand Down Expand Up @@ -57,13 +58,23 @@ public class KarapaceCatalogHandler implements CatalogHandler
private final long maxAgeMillis;
private final KarapaceEventContext event;
private final long catalogId;
private final ConcurrentHashMap<Integer, CompletableFuture<String>> cache;
private final ConcurrentMap<Integer, CompletableFuture<String>> cachedSchemas;
private final ConcurrentMap<Integer, CompletableFuture<CachedSchemaId>> cachedSchemaIds;

public KarapaceCatalogHandler(
KarapaceOptionsConfig config,
EngineContext context,
long catalogId)
{
this(config, context, catalogId, new ConcurrentHashMap<>(), new ConcurrentHashMap<>());
}

public KarapaceCatalogHandler(
KarapaceOptionsConfig config,
EngineContext context,
long catalogId,
ConcurrentHashMap<Integer, CompletableFuture<String>> cache)
ConcurrentMap<Integer, CompletableFuture<String>> cachedSchemas,
ConcurrentMap<Integer, CompletableFuture<CachedSchemaId>> cachedSchemaIds)
{
this.baseUrl = config.url;
this.client = HttpClient.newHttpClient();
Expand All @@ -74,7 +85,8 @@ public KarapaceCatalogHandler(
this.maxAgeMillis = config.maxAge.toMillis();
this.event = new KarapaceEventContext(context);
this.catalogId = catalogId;
this.cache = cache;
this.cachedSchemas = cachedSchemas;
this.cachedSchemaIds = cachedSchemaIds;
}

@Override
Expand All @@ -88,21 +100,27 @@ public String resolve(
}
else
{
CompletableFuture<String> future = cache.get(schemaId);
CompletableFuture<String> future = cachedSchemas.get(schemaId);
if (future == null)
{
future = CompletableFuture.supplyAsync(() ->
CompletableFuture<String> newFuture = new CompletableFuture<String>();
future = cachedSchemas.putIfAbsent(schemaId, newFuture);
if (future == null)
{
String response = sendHttpRequest(MessageFormat.format(SCHEMA_PATH, schemaId));
return response != null ? request.resolveSchemaResponse(response) : null;
});
newFuture = CompletableFuture.supplyAsync(() ->
{
String response = sendHttpRequest(MessageFormat.format(SCHEMA_PATH, schemaId));
return response != null ? request.resolveSchemaResponse(response) : null;
});
future = newFuture;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we can reassign newFuture here, as the value being lost is the one that already made it into the concurrent map, so if we reassign it then the one in the map would not be completed, agree?

}
}
assert future != null;
try
{
schema = future.get();
if (schema != null)
{
cache.put(schemaId, future);
schemas.put(schemaId, schema);
}
}
Expand All @@ -119,26 +137,80 @@ public int resolve(
String subject,
String version)
{
int schemaId;
int schemaId = NO_SCHEMA_ID;

int checkSum = generateCRC32C(subject, version);
if (schemaIds.containsKey(checkSum) &&
(System.currentTimeMillis() - schemaIds.get(checkSum).timestamp) < maxAgeMillis)
int schemaKey = generateCRC32C(subject, version);
if (schemaIds.containsKey(schemaKey) &&
(System.currentTimeMillis() - schemaIds.get(schemaKey).timestamp) < maxAgeMillis)
{
schemaId = schemaIds.get(checkSum).id;
schemaId = schemaIds.get(schemaKey).id;
}
else
{
String response = sendHttpRequest(MessageFormat.format(SUBJECT_VERSION_PATH, subject, version));
schemaId = response != null ? request.resolveResponse(response) : NO_SCHEMA_ID;
if (schemaId != NO_SCHEMA_ID)
CompletableFuture<CachedSchemaId> future = cachedSchemaIds.get(schemaKey);
if (future == null)
{
schemaIds.put(checkSum, new CachedSchemaId(System.currentTimeMillis(), schemaId));
CompletableFuture<CachedSchemaId> newFuture = new CompletableFuture<>();
future = cachedSchemaIds.putIfAbsent(schemaKey, newFuture);
if (future == null)
{
newFuture = CompletableFuture.supplyAsync(() ->
{
String response = sendHttpRequest(MessageFormat.format(SUBJECT_VERSION_PATH, subject, version));
return new CachedSchemaId(System.currentTimeMillis(),
response != null ? request.resolveResponse(response) : NO_SCHEMA_ID);
});
future = newFuture;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue here as above, agree?

}
}
else if (schemaIds.containsKey(checkSum))
assert future != null;
try
{
schemaId = schemaIds.get(checkSum).id;
CachedSchemaId cachedSchemaId = future.get();
schemaId = cachedSchemaId.id;
if (schemaId != NO_SCHEMA_ID && (System.currentTimeMillis() - cachedSchemaId.timestamp) < maxAgeMillis)
{
schemaIds.put(schemaKey, cachedSchemaId);
}
else
{
CompletableFuture<CachedSchemaId> newFuture =
cachedSchemaIds.computeIfPresent(schemaKey, (key, existingFuture) ->
{
if (existingFuture.isDone() || existingFuture.isCompletedExceptionally())
{
CompletableFuture<CachedSchemaId> id = CompletableFuture.supplyAsync(() ->
{
String response = sendHttpRequest(MessageFormat.format(SUBJECT_VERSION_PATH,
subject, version));
return new CachedSchemaId(System.currentTimeMillis(),
response != null ? request.resolveResponse(response) : NO_SCHEMA_ID);
});
return id;
}
else
{
return existingFuture;
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can perhaps simplify the logic by creating the candidate newFuture and calling:

CompletableFuture<> newFuture = new CompletableFuture<CachedSchemaId>();
CompletableFuture<> future = cachedSchemaIds.merge(schemaKey, newFuture, (v1, v2) -> v1 != null && !v1.isDone() ? v1 : v2);
if (future == newFuture)
{
    // send request
    // complete future
}
cachedSchemaId  = future.get();

cachedSchemaId = newFuture.get();
schemaId = cachedSchemaId.id;
if (schemaId != NO_SCHEMA_ID)
{
schemaIds.put(schemaKey, cachedSchemaId);
}
}
}
Comment on lines +139 to +270

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed to handle the case where remote access fails, but we can serve from (stale) cache instead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes.

catch (ExecutionException | InterruptedException e)
{
// TODO: log an event
}
}

if (schemaId == NO_SCHEMA_ID && schemaIds.containsKey(schemaKey))
{
schemaId = schemaIds.get(schemaKey).id;
// TODO: log an event to notify, that stale schemaId was returned
}
return schemaId;
}
Expand Down

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer this IT done via scripts not mocks.

Note: if using mocks then it is a unit test, not an integration test - unit tests with mocks are not stable after a refactor of the code as they also need to be changed, whereas integration tests remain stable, providing better confidence after changing implementation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be no need to drive any direct calls to KarapaceCatalogHandler via code and mocks.

Instead, this should be driven by test binding in zilla.yaml for the test. It may be necessary to add support for expected schema in test binding options so that it can verify the retrieved schema matches expectations.

Note: this would be for test binding only, as other bindings have no need to validate expectations.

Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import static org.mockito.Mockito.mock;

import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;

import org.agrona.DirectBuffer;
import org.agrona.concurrent.UnsafeBuffer;
Expand Down Expand Up @@ -73,7 +72,7 @@ public void shouldResolveSchemaViaSchemaId() throws Exception
"{\"name\":\"status\",\"type\":\"string\"}]," +
"\"name\":\"Event\",\"namespace\":\"io.aklivity.example\",\"type\":\"record\"}";

KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L, new ConcurrentHashMap<>());
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L);

String schema = catalog.resolve(9);

Expand All @@ -92,7 +91,7 @@ public void shouldResolveSchemaViaSubjectVersion() throws Exception
"{\"name\":\"status\",\"type\":\"string\"}]," +
"\"name\":\"Event\",\"namespace\":\"io.aklivity.example\",\"type\":\"record\"}";

KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L, new ConcurrentHashMap<>());
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L);

int schemaId = catalog.resolve("items-snapshots-value", "latest");

Expand All @@ -114,7 +113,7 @@ public void shouldResolveSchemaViaSchemaIdFromCache() throws Exception
"{\"name\":\"status\",\"type\":\"string\"}]," +
"\"name\":\"Event\",\"namespace\":\"io.aklivity.example\",\"type\":\"record\"}";

KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L, new ConcurrentHashMap<>());
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L);

catalog.resolve(9);

Expand All @@ -135,7 +134,7 @@ public void shouldResolveSchemaViaSubjectVersionFromCache() throws Exception
"{\"name\":\"status\",\"type\":\"string\"}]," +
"\"name\":\"Event\",\"namespace\":\"io.aklivity.example\",\"type\":\"record\"}";

KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L, new ConcurrentHashMap<>());
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L);

catalog.resolve(catalog.resolve("items-snapshots-value", "latest"));

Expand All @@ -153,15 +152,15 @@ public void shouldResolveSchemaViaSubjectVersionFromCache() throws Exception
@Test
public void shouldVerifyMaxPadding()
{
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L, new ConcurrentHashMap<>());
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L);

assertEquals(5, catalog.encodePadding());
}

@Test
public void shouldVerifyEncodedData()
{
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L, new ConcurrentHashMap<>());
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L);

DirectBuffer data = new UnsafeBuffer();

Expand All @@ -177,7 +176,7 @@ public void shouldVerifyEncodedData()
public void shouldResolveSchemaIdAndProcessData()
{

KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L, new ConcurrentHashMap<>());
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L);

DirectBuffer data = new UnsafeBuffer();

Expand All @@ -193,7 +192,7 @@ public void shouldResolveSchemaIdAndProcessData()
@Test
public void shouldResolveSchemaIdFromData()
{
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L, new ConcurrentHashMap<>());
KarapaceCatalogHandler catalog = new KarapaceCatalogHandler(config, context, 0L);

DirectBuffer data = new UnsafeBuffer();

Expand Down