Skip to content
This repository has been archived by the owner on Mar 15, 2021. It is now read-only.

Commit

Permalink
Resize pubsub batches when they are above 10MB limit (#246)
Browse files Browse the repository at this point in the history
  • Loading branch information
lmuhlha authored Feb 25, 2021
1 parent 646f88e commit ef47556
Showing 1 changed file with 17 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.common.cache.Cache;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.inject.Inject;
import com.google.protobuf.ByteString;
Expand All @@ -42,6 +43,7 @@
import eu.toolchain.async.AsyncFramework;
import eu.toolchain.async.AsyncFuture;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
Expand All @@ -58,6 +60,9 @@
*/
public class PubsubPluginSink implements BatchablePluginSink {

// Pubsub publish request limit is 10MB
private final static double MAX_BATCH_SIZE_BYTES = 10_000_000.0;

private final Executor executorService = MoreExecutors.directExecutor();
@Inject
AsyncFramework async;
Expand Down Expand Up @@ -116,7 +121,18 @@ public AsyncFuture<Void> sendMetrics(Collection<Metric> metrics) {

try {
final ByteString m = ByteString.copyFrom(serializer.serialize(metrics, writeCache));
publishPubSub(m);

if (m.size() > MAX_BATCH_SIZE_BYTES) {
logger.debug("Above byte limit, resizing batch");
int times = (int)Math.ceil(m.size()/MAX_BATCH_SIZE_BYTES);
List<List<Metric>> collections = Lists.partition(new ArrayList<>(metrics), m.size()/times);
for (List<Metric> l: collections) {
final ByteString mResize = ByteString.copyFrom(serializer.serialize(l, writeCache));
publishPubSub(mResize);
}
} else {
publishPubSub(m);
}
} catch (Exception e) {
logger.error("Failed to serialize batch of metrics: ", e);
}
Expand Down

0 comments on commit ef47556

Please sign in to comment.