use of io.netty.util.Timeout in project pulsar by yahoo.
the class ProducerImpl method connectionOpened.
@Override
void connectionOpened(final ClientCnx cnx) {
// we set the cnx reference before registering the producer on the cnx, so if the cnx breaks before creating the
// producer, it will try to grab a new cnx
setClientCnx(cnx);
cnx.registerProducer(producerId, this);
log.info("[{}] [{}] Creating producer on cnx {}", topic, producerName, cnx.ctx().channel());
long requestId = client.newRequestId();
cnx.sendRequestWithId(Commands.newProducer(topic, producerId, requestId, producerName), requestId).thenAccept(producerName -> {
synchronized (ProducerImpl.this) {
if (getState() == State.Closing || getState() == State.Closed) {
cnx.removeProducer(producerId);
cnx.channel().close();
return;
}
resetBackoff();
log.info("[{}] [{}] Created producer on cnx {}", topic, producerName, cnx.ctx().channel());
connectionId = cnx.ctx().channel().toString();
connectedSince = DATE_FORMAT.format(Instant.now());
if (this.producerName == null) {
this.producerName = producerName;
}
if (!producerCreatedFuture.isDone() && isBatchMessagingEnabled()) {
client.timer().newTimeout(batchMessageAndSendTask, conf.getBatchingMaxPublishDelayMs(), TimeUnit.MILLISECONDS);
}
resendMessages(cnx);
}
}).exceptionally((e) -> {
cnx.removeProducer(producerId);
if (getState() == State.Closing || getState() == State.Closed) {
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.channel().close();
return null;
}
log.error("[{}] [{}] Failed to create producer: {}", topic, producerName, e.getCause().getMessage());
if (e.getCause() instanceof PulsarClientException.ProducerBlockedQuotaExceededException) {
synchronized (this) {
log.warn("[{}] [{}] Topic backlog quota exceeded. Throwing Exception on producer.", topic, producerName);
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Pending messages: {}", topic, producerName, pendingMessages.size());
}
PulsarClientException bqe = new PulsarClientException.ProducerBlockedQuotaExceededException("Could not send pending messages as backlog exceeded");
failPendingMessages(cnx(), bqe);
}
} else if (e.getCause() instanceof PulsarClientException.ProducerBlockedQuotaExceededError) {
log.warn("[{}] [{}] Producer is blocked on creation because backlog exceeded on topic.", producerName, topic);
}
if (//
producerCreatedFuture.isDone() || (e.getCause() instanceof PulsarClientException && isRetriableError((PulsarClientException) e.getCause()) && System.currentTimeMillis() < createProducerTimeout)) {
// Either we had already created the producer once (producerCreatedFuture.isDone()) or we are
// still within the initial timeout budget and we are dealing with a retriable error
reconnectLater(e.getCause());
} else {
setState(State.Failed);
producerCreatedFuture.completeExceptionally(e.getCause());
client.cleanupProducer(this);
}
return null;
});
}
use of io.netty.util.Timeout in project pulsar by yahoo.
the class ProducerImpl method closeAsync.
@Override
public CompletableFuture<Void> closeAsync() {
if (getState() == State.Closing || getState() == State.Closed) {
return CompletableFuture.completedFuture(null);
}
if (!isConnected()) {
log.info("[{}] [{}] Closed Producer (not connected)", topic, producerName);
synchronized (this) {
setState(State.Closed);
client.cleanupProducer(this);
pendingMessages.forEach(msg -> {
msg.cmd.release();
msg.recycle();
});
pendingMessages.clear();
}
return CompletableFuture.completedFuture(null);
}
setState(State.Closing);
Timeout timeout = sendTimeout;
if (timeout != null) {
timeout.cancel();
}
timeout = stats.getStatTimeout();
if (timeout != null) {
timeout.cancel();
}
long requestId = client.newRequestId();
ByteBuf cmd = Commands.newCloseProducer(producerId, requestId);
CompletableFuture<Void> closeFuture = new CompletableFuture<>();
ClientCnx cnx = cnx();
cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
cnx.removeProducer(producerId);
if (exception == null || !cnx.ctx().channel().isActive()) {
// connection did break in the meantime. In any case, the producer is gone.
synchronized (ProducerImpl.this) {
log.info("[{}] [{}] Closed Producer", topic, producerName);
setState(State.Closed);
pendingMessages.forEach(msg -> {
msg.cmd.release();
msg.recycle();
});
pendingMessages.clear();
}
closeFuture.complete(null);
client.cleanupProducer(this);
} else {
closeFuture.completeExceptionally(exception);
}
return null;
});
return closeFuture;
}
use of io.netty.util.Timeout in project async-http-client by AsyncHttpClient.
the class TimeoutsHolder method startReadTimeout.
void startReadTimeout(ReadTimeoutTimerTask task) {
if (requestTimeout == null || (!requestTimeout.isExpired() && readTimeoutValue < (requestTimeoutMillisTime - unpreciseMillisTime()))) {
// only schedule a new readTimeout if the requestTimeout doesn't happen first
if (task == null) {
// first call triggered from outside (else is read timeout is re-scheduling itself)
task = new ReadTimeoutTimerTask(nettyResponseFuture, requestSender, this, readTimeoutValue);
}
Timeout readTimeout = newTimeout(task, readTimeoutValue);
this.readTimeout = readTimeout;
} else if (task != null) {
// read timeout couldn't re-scheduling itself, clean up
task.clean();
}
}
use of io.netty.util.Timeout in project pravega by pravega.
the class TimerWheelTimeoutService method pingTxn.
@Override
public PingTxnStatus pingTxn(final String scope, final String stream, final UUID txnId, int version, long lease) {
if (!this.isRunning()) {
return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.DISCONNECTED).build();
}
final String key = getKey(scope, stream, txnId);
Preconditions.checkState(map.containsKey(key), "Stream not found in the map");
final TxnData txnData = map.get(key);
if (txnData == null) {
throw new IllegalStateException(String.format("Transaction %s not added to timerWheelTimeoutService", txnId));
}
if (lease > maxLeaseValue || lease > txnData.getScaleGracePeriod()) {
return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.LEASE_TOO_LARGE).build();
}
if (lease + System.currentTimeMillis() > txnData.getMaxExecutionTimeExpiry()) {
return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.MAX_EXECUTION_TIME_EXCEEDED).build();
} else {
Timeout timeout = txnData.getTimeout();
boolean cancelSucceeded = timeout.cancel();
if (cancelSucceeded) {
TxnData newTxnData = txnData.updateLease(scope, stream, txnId, version, lease);
map.replace(key, txnData, newTxnData);
return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.OK).build();
} else {
// Cancellation may fail because timeout task (1) may be scheduled for execution, or (2) is executing.
throw new IllegalStateException(String.format("Failed updating timeout for transaction %s", txnId));
}
}
}
use of io.netty.util.Timeout in project web3sdk by FISCO-BCOS.
the class Service method asyncSendChannelMessage2.
public void asyncSendChannelMessage2(ChannelRequest request, ChannelResponseCallback2 callback) {
try {
logger.debug("处理链上链下请求: " + request.getMessageID());
callback.setService(this);
ChannelMessage2 channelMessage = new ChannelMessage2();
channelMessage.setSeq(request.getMessageID());
channelMessage.setResult(0);
// 链上链下请求0x30
channelMessage.setType((short) 0x30);
channelMessage.setData(request.getContent().getBytes());
channelMessage.setTopic(request.getToTopic());
try {
List<ConnectionInfo> fromConnectionInfos = new ArrayList<ConnectionInfo>();
// 设置发送节点
ChannelConnections fromChannelConnections = allChannelConnections.get(orgID);
if (fromChannelConnections == null) {
// 没有找到对应的链
// 返回错误
logger.error("没有找到本机构:{}", orgID);
throw new Exception("未找到本机构");
}
fromConnectionInfos.addAll(fromChannelConnections.getConnections());
logger.debug("发送机构:{} 节点数:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
callback.setFromChannelConnections(fromChannelConnections);
callback.setFromConnectionInfos(fromConnectionInfos);
// 设置消息内容
callback.setRequest(channelMessage);
seq2Callback.put(request.getMessageID(), callback);
if (request.getTimeout() > 0) {
final ChannelResponseCallback2 callbackInner = callback;
callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {
ChannelResponseCallback2 _callback = callbackInner;
@Override
public void run(Timeout timeout) throws Exception {
// 处理超时逻辑
_callback.onTimeout();
}
}, request.getTimeout(), TimeUnit.MILLISECONDS));
}
callback.retrySendMessage();
} catch (Exception e) {
logger.error("发送消息异常 消息未发出", e);
ChannelResponse response = new ChannelResponse();
response.setErrorCode(100);
response.setMessageID(request.getMessageID());
response.setErrorMessage(e.getMessage());
response.setContent("");
callback.onResponse(response);
return;
}
} catch (Exception e) {
logger.error("系统错误", e);
}
}
Aggregations