com.turbospaces.gcp.pubsub.PubsubTransactionalRequest Maven / Gradle / Ivy
package com.turbospaces.gcp.pubsub;
import java.nio.file.Paths;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.lang3.concurrent.ConcurrentException;
import org.apache.commons.lang3.concurrent.LazyInitializer;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.turbospaces.api.facade.RequestWrapperFacade;
import com.turbospaces.common.PlatformUtil;
import com.turbospaces.dispatch.AbstractTransactionalRequest;
import com.turbospaces.executor.WorkUnit;
import api.v1.ObfuscatePrinter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PubsubTransactionalRequest extends AbstractTransactionalRequest {
private Date when;
public PubsubTransactionalRequest(Class reqType, RESP prototype, WorkUnit record, RequestWrapperFacade wrapper, CountDownLatch latch) {
super(prototype, record, wrapper, latch);
this.req = new LazyInitializer() {
@Override
protected REQ initialize() throws ConcurrentException {
Any body = wrapper.body();
try {
REQ unpack = body.unpack(reqType);
log.debug("unpack: {}", ObfuscatePrinter.shortDebugString(unpack.toBuilder()));
return unpack;
} catch (InvalidProtocolBufferException err) {
throw new ConcurrentException(err);
}
}
};
this.when = new Date(record.timestamp());
}
@Override
public REQ request() throws Exception {
return req.get();
}
@Override
public Date timestamp() {
return when;
}
@Override
public boolean ack() {
boolean success = super.ack();
if (success) {
PubsubWorkUnit unit = (PubsubWorkUnit) record;
unit.ack().whenComplete((result, ex) -> {
if (ex != null) {
log.error(ex.getMessage(), ex);
} else {
log.debug("acknowledged pubsub work unit: {}", unit);
}
});
}
return success;
}
@Override
public boolean nack() {
boolean success = super.nack();
if (success) {
PubsubWorkUnit unit = (PubsubWorkUnit) record;
unit.nack().whenComplete((result, ex) -> {
if (ex != null) {
log.error(ex.getMessage(), ex);
} else {
log.debug("negative acknowledged pubsub work unit: {}", unit);
}
});
}
return success;
}
public static String jdbcOp(T req, String... args) {
String typeUrl = PlatformUtil.toLowerUnderscore(req.getClass().getSimpleName());
return Paths.get(String.format("jdbc_%s", typeUrl), args).toString();
}
}