io.debezium.connector.spanner.task.PartitionOffsetProvider Maven / Gradle / Ivy
/*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.connector.spanner.task;
import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.apache.kafka.connect.storage.OffsetStorageReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.cloud.Timestamp;
import io.debezium.connector.spanner.SpannerPartition;
import io.debezium.connector.spanner.context.offset.PartitionOffset;
import io.debezium.connector.spanner.kafka.internal.model.PartitionState;
import io.debezium.connector.spanner.metrics.MetricsEventPublisher;
import io.debezium.connector.spanner.metrics.event.OffsetReceivingTimeMetricEvent;
/**
* Retrieves offsets from Kafka Connect
* and publishes appropriate metrics
*/
public class PartitionOffsetProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(PartitionOffsetProvider.class);
private final OffsetStorageReader offsetStorageReader;
private final MetricsEventPublisher metricsEventPublisher;
private final ExecutorService executor;
public PartitionOffsetProvider(OffsetStorageReader offsetStorageReader, MetricsEventPublisher metricsEventPublisher) {
this.offsetStorageReader = offsetStorageReader;
this.metricsEventPublisher = metricsEventPublisher;
this.executor = Executors.newCachedThreadPool();
}
public Timestamp getOffset(PartitionState token) {
Map spannerPartition = new SpannerPartition(token.getToken()).getSourcePartition();
Map result = retrieveOffsetMap(spannerPartition);
if (result == null) {
LOGGER.warn("Token {} returning start timestamp because no offset was retrieved", token);
return token.getStartTimestamp();
}
LOGGER.info("Successfully retrieved offset {} for token {}", result, token);
return PartitionOffset.extractOffset(result);
}
public Map getOffsetMap(PartitionState token) {
Map spannerPartition = new SpannerPartition(token.getToken()).getSourcePartition();
Map result = retrieveOffsetMap(spannerPartition);
if (result == null) {
return Map.of();
}
return (Map) result;
}
public Map getOffsets(Collection partitions) {
Instant startTime = Instant.now();
List