Skip to content
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

Add IT to check protocol migration works #243

Merged
merged 1 commit into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
/*
* Copyright 2024 LY Corporation
*
* LY Corporation 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:
*
* https://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 com.linecorp.decaton.processor;

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

import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import com.linecorp.decaton.client.DecatonClient;
import com.linecorp.decaton.client.kafka.PrintableAsciiStringSerializer;
import com.linecorp.decaton.processor.runtime.DecatonTask;
import com.linecorp.decaton.processor.runtime.DynamicProperty;
import com.linecorp.decaton.processor.runtime.ProcessorProperties;
import com.linecorp.decaton.processor.runtime.ProcessorSubscription;
import com.linecorp.decaton.processor.runtime.ProcessorsBuilder;
import com.linecorp.decaton.processor.runtime.RetryConfig;
import com.linecorp.decaton.processor.runtime.StaticPropertySupplier;
import com.linecorp.decaton.processor.runtime.TaskExtractor;
import com.linecorp.decaton.protobuf.ProtocolBuffersDeserializer;
import com.linecorp.decaton.protocol.Decaton.TaskMetadataProto;
import com.linecorp.decaton.protocol.Sample.HelloTask;
import com.linecorp.decaton.protocol.internal.DecatonInternal.DecatonTaskRequest;
import com.linecorp.decaton.testing.KafkaClusterExtension;
import com.linecorp.decaton.testing.TestUtils;

/*
* Integration tests to check Decaton 9.0.0 migration from older version,
* to check that protocol migration works correctly.
*/
public class ProtocolMigrationTest {
@RegisterExtension
public static KafkaClusterExtension rule = new KafkaClusterExtension();

private String topic;
private String retryTopic;

@BeforeEach
public void setUp() {
topic = rule.admin().createRandomTopic(3, 3);
retryTopic = topic + "-retry";
rule.admin().createTopic(retryTopic, 3, 3);
}

@AfterEach
public void tearDown() {
rule.admin().deleteTopics(true, topic, retryTopic);
}

/*
* Check if the migration works when DecatonClient is used.
*/
@Test
@Timeout(30)
public void testMigration_deserializer() throws Exception {
DynamicProperty<Boolean> retryTaskInLegacyFormat =
new DynamicProperty<>(ProcessorProperties.CONFIG_RETRY_TASK_IN_LEGACY_FORMAT);
retryTaskInLegacyFormat.set(true);
DynamicProperty<Boolean> legacyParseFallbackEnabled =
new DynamicProperty<>(ProcessorProperties.CONFIG_LEGACY_PARSE_FALLBACK_ENABLED);
legacyParseFallbackEnabled.set(true);

Set<HelloTask> produced = ConcurrentHashMap.newKeySet();
Set<HelloTask> processed = ConcurrentHashMap.newKeySet();
try (ProcessorSubscription ignored = TestUtils.subscription(
rule.bootstrapServers(),
builder -> {
builder.processorsBuilder(
ProcessorsBuilder.consuming(topic, new ProtocolBuffersDeserializer<>(HelloTask.parser()))
.thenProcess((context, task) -> {
// always retry once, to check that retry-feature works at every step
if (context.metadata().retryCount() == 0) {
context.retry();
} else {
processed.add(task);
}
}))
.addProperties(StaticPropertySupplier.of(retryTaskInLegacyFormat, legacyParseFallbackEnabled))
.enableRetry(RetryConfig.builder().backoff(Duration.ZERO).build());
});
Producer<String, HelloTask> legacyClient = TestUtils.producer(
rule.bootstrapServers(),
new PrintableAsciiStringSerializer(),
(topic, task) -> DecatonTaskRequest
.newBuilder()
.setMetadata(TaskMetadataProto.newBuilder()
.setTimestampMillis(System.currentTimeMillis())
.setSourceApplicationId("test-application")
.setSourceInstanceId("test-instance")
.build())
.setSerializedTask(ByteString.copyFrom(task.toByteArray()))
.build()
.toByteArray());
DecatonClient<HelloTask> client = TestUtils.client(topic, rule.bootstrapServers())) {

// step1: initial
for (int i = 0; i < 10; i++) {
HelloTask task = HelloTask.newBuilder().setName("hello1-" + i).build();
legacyClient.send(new ProducerRecord<>(topic, task));
produced.add(task);
}
// step2: migrate retry tasks to new format
retryTaskInLegacyFormat.set(false);
for (int i = 0; i < 10; i++) {
HelloTask task = HelloTask.newBuilder().setName("hello2-" + i).build();
legacyClient.send(new ProducerRecord<>(topic, task));
produced.add(task);
}
// step3: migrate decaton client to new format
for (int i = 0; i < 10; i++) {
HelloTask task = HelloTask.newBuilder().setName("hello3-" + i).build();
client.put(null, task);
produced.add(task);
}

// Before go to last step, we have to ensure that there are no legacy format task at all.
TestUtils.awaitCondition(
"all produced tasks should be processed",
() -> produced.equals(processed));

// step4: disable legacy parse fallback
legacyParseFallbackEnabled.set(false);
for (int i = 0; i < 10; i++) {
HelloTask task = HelloTask.newBuilder().setName("hello4-" + i).build();
client.put(null, task);
produced.add(task);
}

// Check if it works after legacy parse fallback is disabled
TestUtils.awaitCondition(
"all produced tasks should be processed",
() -> produced.equals(processed));
}
}

/*
* Check if the migration works when pure producer is used.
*/
@Test
@Timeout(30)
public void testMigration_taskExtractor() throws Exception {
DynamicProperty<Boolean> retryTaskInLegacyFormat =
new DynamicProperty<>(ProcessorProperties.CONFIG_RETRY_TASK_IN_LEGACY_FORMAT);
retryTaskInLegacyFormat.set(true);
DynamicProperty<Boolean> legacyParseFallbackEnabled =
new DynamicProperty<>(ProcessorProperties.CONFIG_LEGACY_PARSE_FALLBACK_ENABLED);
legacyParseFallbackEnabled.set(true);

Set<HelloTask> produced = ConcurrentHashMap.newKeySet();
Set<HelloTask> processed = ConcurrentHashMap.newKeySet();
try (ProcessorSubscription ignored = TestUtils.subscription(
rule.bootstrapServers(),
builder -> {
builder.processorsBuilder(
ProcessorsBuilder.consuming(topic, (TaskExtractor<HelloTask>) record -> {
try {
return new DecatonTask<>(
TaskMetadata.builder().build(),
HelloTask.parser().parseFrom(record.value()),
record.value());
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
})
.thenProcess((context, task) -> {
// always retry once, to check that retry-feature works at every step
if (context.metadata().retryCount() == 0) {
context.retry();
} else {
processed.add(task);
}
}))
.addProperties(StaticPropertySupplier.of(retryTaskInLegacyFormat, legacyParseFallbackEnabled))
.enableRetry(RetryConfig.builder().backoff(Duration.ZERO).build());
});
Producer<String, HelloTask> producer = TestUtils.producer(
rule.bootstrapServers(),
new PrintableAsciiStringSerializer(),
(topic, task) -> task.toByteArray())) {

// step1: initial
for (int i = 0; i < 10; i++) {
HelloTask task = HelloTask.newBuilder().setName("hello1-" + i).build();
producer.send(new ProducerRecord<>(topic, task));
produced.add(task);
}
// step2: migrate retry tasks to new format
retryTaskInLegacyFormat.set(false);
for (int i = 0; i < 10; i++) {
HelloTask task = HelloTask.newBuilder().setName("hello2-" + i).build();
producer.send(new ProducerRecord<>(topic, task));
produced.add(task);
}

// Before go to last step, we have to ensure that there are no legacy format task at all.
TestUtils.awaitCondition(
"all produced tasks should be processed",
() -> produced.equals(processed));

// step3: disable legacy parse fallback
legacyParseFallbackEnabled.set(false);
for (int i = 0; i < 10; i++) {
HelloTask task = HelloTask.newBuilder().setName("hello3-" + i).build();
producer.send(new ProducerRecord<>(topic, task));
produced.add(task);
}

// Check if it works after legacy parse fallback is disabled
TestUtils.awaitCondition(
"all produced tasks should be processed",
() -> produced.equals(processed));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -270,15 +270,15 @@ public void testRetryQueueingMigrateToHeader() throws Exception {
.propertySupplier(StaticPropertySupplier.of(
retryTaskInLegacyFormat,
Property.ofStatic(ProcessorProperties.CONFIG_LEGACY_PARSE_FALLBACK_ENABLED, true)))
.produceTasksWithHeaderMetadata(false)
.produceTasksInLegacyFormat(true)
.configureProcessorsBuilder(builder -> builder.thenProcess((ctx, task) -> {
if (ctx.metadata().retryCount() == 0) {
int cnt = processCount.incrementAndGet();
// Enable header-mode after 50 tasks are processed
// Disable header-mode after 50 tasks are processed
if (cnt < 50) {
ctx.retry();
} else if (cnt == 50) {
retryTaskInLegacyFormat.set(true);
retryTaskInLegacyFormat.set(false);
migrationLatch.countDown();
ctx.retry();
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public class ProcessorTestSuite {
private final TracingProvider tracingProvider;
private final Function<String, Producer<byte[], byte[]>> producerSupplier;
private final TaskExtractor<TestTask> customTaskExtractor;
private final boolean produceTasksWithHeaderMetadata;
private final boolean produceTasksInLegacyFormat;

private static final int DEFAULT_NUM_TASKS = 10000;
private static final int NUM_KEYS = 100;
Expand Down Expand Up @@ -187,9 +187,9 @@ public static class Builder {
*/
private TaskExtractor<TestTask> customTaskExtractor;
/**
* Specify whether to produce tasks with header metadata instead of DecatonTaskRequest format
* Specify whether to produce tasks in legacy DecatonTaskRequest format instead of header metadata
*/
private boolean produceTasksWithHeaderMetadata = true;
private boolean produceTasksInLegacyFormat = false;

/**
* Exclude semantics from assertion.
Expand Down Expand Up @@ -238,7 +238,7 @@ public ProcessorTestSuite build() {
tracingProvider,
producerSupplier,
customTaskExtractor,
produceTasksWithHeaderMetadata);
produceTasksInLegacyFormat);
}
}

Expand Down Expand Up @@ -436,16 +436,16 @@ private CompletableFuture<Map<TopicPartition, Long>> produceTasks(
.setSourceInstanceId("test-instance")
.build();
final ProducerRecord<byte[], byte[]> record;
if (produceTasksWithHeaderMetadata) {
record = new ProducerRecord<>(topic, null, taskMetadata.getTimestampMillis(), key, serializer.serialize(task));
TaskMetadataUtil.writeAsHeader(taskMetadata, record.headers());
} else {
if (produceTasksInLegacyFormat) {
DecatonTaskRequest request =
DecatonTaskRequest.newBuilder()
.setMetadata(taskMetadata)
.setSerializedTask(ByteString.copyFrom(serializer.serialize(task)))
.build();
record = new ProducerRecord<>(topic, null, taskMetadata.getTimestampMillis(), key, request.toByteArray());
} else {
record = new ProducerRecord<>(topic, null, taskMetadata.getTimestampMillis(), key, serializer.serialize(task));
TaskMetadataUtil.writeAsHeader(taskMetadata, record.headers());
}

CompletableFuture<RecordMetadata> future = new CompletableFuture<>();
Expand Down
Loading