Handles a snapshot request from a peer.

@return a future to be completed once the snapshot is complete
480248
private CompletableFuture<Void> handleSnapshot() {
    return Futures.allOf(partitions.values().stream()
        .map(partition -> partition.snapshot())
        .collect(Collectors.toList()))
        .thenApply(v -> null);
  }
245757
void handle(OngoingRequest ongoingRequest, RequestContext requestContext, Endpoint endpoint) {
    try {
      endpoint.invoke(requestContext)
          .whenComplete((message, throwable) -> {
            try {
              if (message != null) {
                ongoingRequest.reply(message);
              } else if (throwable != null) {
                // unwrap CompletionException
                if (throwable instanceof CompletionException) {
                  throwable = throwable.getCause();
                }
                handleException(throwable, ongoingRequest);
              } else {
                LOG.error(
                    "Both message and throwable null in EndpointInvocationHandler for request "
                    + ongoingRequest
                    + " - this shouldn't happen!");
                handleException(new IllegalStateException("Both message and throwable null"),
                                ongoingRequest);
              }
            } catch (Throwable t) {
              // don't try to respond here; just log the fact that responding failed.
              LOG.error("Exception caught when replying", t);
            }
          });
    } catch (Exception e) {
      handleException(e, ongoingRequest);
    }
  }
1242243
private CompletableFuture<HeartbeatResponse> handleHeartbeat(HeartbeatRequest request) {
    log.trace("Received {}", request);
    boolean newLeader = !Objects.equals(selectorManager.leader(), request.leader());
    selectorManager.resetAll(request.leader(), request.members());
    HeartbeatResponse response = HeartbeatResponse.builder()
        .withStatus(RaftResponse.Status.OK)
        .build();
    if (newLeader) {
      resetAllIndexes();
    }
    log.trace("Sending {}", response);
    return CompletableFuture.completedFuture(response);
  }
142317
private CompletableFuture<TableBucket> getNextBucket() {
        val fromBatch = getNextBucketFromExistingBatch();
        if (fromBatch != null) {
            return CompletableFuture.completedFuture(fromBatch);
        }

        val canContinue = new AtomicBoolean(true);
        return Futures.loop(canContinue::get, this::fetchNextTableBuckets, canContinue::set, this.executor)
                .thenApply(v -> getNextBucketFromExistingBatch());
    }
313596
private void executeStorageRead(Request request) {
        try {
            byte[] buffer = new byte[request.length];
            getHandle()
                    .thenComposeAsync(handle -> this.storage.read(handle, request.offset, buffer, 0, buffer.length, request.getTimeout()), this.executor)
                    .thenAcceptAsync(bytesRead -> request.complete(new ByteArraySegment(buffer, 0, bytesRead)), this.executor)
                    .whenComplete((r, ex) -> {
                        if (ex != null) {
                            request.fail(ex);
                        }

                        // Unregister the Request after every request fulfillment.
                        finalizeRequest(request);
                    });
        } catch (Throwable ex) {
            if (Exceptions.mustRethrow(ex)) {
                throw ex;
            }

            request.fail(ex);
            finalizeRequest(request);
        }
    }
1132179
public function getSnapshot(): Snapshot
    {
        try {
            $value = $this->apiClient->get($this->getUri());
        } catch (ApiException $e) {
            throw QueryException::fromApiException($e, $this);
        }

        if ($this->sorter) {
            $value = $this->sorter->modifyValue($value);
        }

        foreach ($this->filters as $filter) {
            $value = $filter->modifyValue($value);
        }

        return new Snapshot($this->reference, $value);
    }
546870
public Future<Void> processClientResponse(final Callable<ClientResponseImpl> response) {
        return m_es.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                try {
                    ClientResponseImpl resp = response.call();
                    long handle = resp.getClientHandle();
                    m_procedureCallbacks.remove(handle).clientCallback(resp);
                } catch (Exception e) {
                    SNAP_LOG.warn("Error when SnapshotDaemon invoked callback for a procedure invocation", e);
                    /*
                     * Don't think it is productive to propagate any exceptions here, Ideally
                     * they should be handled by the procedure callbacks
                     */
                }
                return null;
            }
        });
    }
1194835
@Override
    public void operationComplete(ChannelFuture future) throws Exception {
        // If a message has been sent out, cancel the timeout for starting a request.
        cancelTimeout();

        if (future.isSuccess()) {
            // The first write is always the first headers, so log that we finished our first transfer over the
            // wire.
            if (!loggedRequestFirstBytesTransferred) {
                logBuilder.requestFirstBytesTransferred();
                loggedRequestFirstBytesTransferred = true;
            }

            if (state == State.DONE) {
                // Successfully sent the request; schedule the response timeout.
                response.scheduleTimeout(ch.eventLoop());
            }

            // Request more messages regardless whether the state is DONE. It makes the producer have
            // a chance to produce the last call such as 'onComplete' and 'onError' when there are
            // no more messages it can produce.
            if (!isSubscriptionCompleted) {
                assert subscription != null;
                subscription.request(1);
            }
            return;
        }

        fail(future.cause());

        final Throwable cause = future.cause();
        if (!(cause instanceof ClosedPublisherException)) {
            final Channel ch = future.channel();
            Exceptions.logIfUnexpected(logger, ch, HttpSession.get(ch).protocol(), cause);
            ch.close();
        }
    }
724538
public Observable<Page<SnapshotInner>> listAsync() {
        return listWithServiceResponseAsync()
            .map(new Func1<ServiceResponse<Page<SnapshotInner>>, Page<SnapshotInner>>() {
                @Override
                public Page<SnapshotInner> call(ServiceResponse<Page<SnapshotInner>> response) {
                    return response.body();
                }
            });
    }
1319301
public CompletableFuture<Void> commitAsync() {
        if (this.messagingFactory == null) {
            CompletableFuture<Void> exceptionCompletion = new CompletableFuture<>();
            exceptionCompletion.completeExceptionally(new ServiceBusException(false, "MessagingFactory should not be null"));
            return exceptionCompletion;
        }

        return this.messagingFactory.endTransactionAsync(this, true);
    }
1194798
public CompletableFuture<OpenSessionResponse> openSession(OpenSessionRequest request) {
    CompletableFuture<OpenSessionResponse> future = new CompletableFuture<>();
    if (context.isCurrentContext()) {
      sendRequest(request, protocol::openSession, future);
    } else {
      context.execute(() -> sendRequest(request, protocol::openSession, future));
    }
    return future;
  }
966300
def handle_syncing(node, snapshots)
      reconcile(node)

      if node.syncing_with_master? && node.prohibits_stale_reads?
        logger.info("Node #{node} not ready yet, still syncing with master.")
        force_unavailable_slave(node)
      else
        # otherwise, we can use this node
        handle_available(node, snapshots)
      end
    end
619969
private CompletableFuture<Boolean> handleProbeRequest(ImmutableMember member) {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    swimScheduler.execute(() -> {
      LOGGER.trace("{} - Probing {}", localMember.id(), member);
      bootstrapService.getMessagingService().sendAndReceive(
          member.address(), MEMBERSHIP_PROBE, SERIALIZER.encode(Pair.of(localMember.copy(), member)), false, config.getProbeTimeout())
          .whenCompleteAsync((response, error) -> {
            if (error != null) {
              LOGGER.debug("{} - Failed to probe {}", localMember.id(), member);
              future.complete(false);
            } else {
              future.complete(true);
            }
          }, swimScheduler);
    });
    return future;
  }
415330
private Future<M> sync() {
        logger.debug("Synchronization of Remote[" + this + "] triggered...");
        try {
            validateInitialization();
            try {
                SyncTaskCallable syncCallable = new SyncTaskCallable();

                final Future<M> currentSyncTask = GlobalCachedExecutorService.submit(syncCallable);
                syncCallable.setRelatedFuture(currentSyncTask);
                return currentSyncTask;
            } catch (java.util.concurrent.RejectedExecutionException | NullPointerException ex) {
                throw new CouldNotPerformException("Could not request the current status.", ex);
            }
        } catch (CouldNotPerformException ex) {
            return FutureProcessor.canceledFuture(ex);
        }
    }
1119372
@Override
    public Future<M> requestData() {
        logger.debug(this + " requestData...");
        try {
            validateInitialization();
            synchronized (syncMonitor) {

                // Check if sync is in process.
                if (syncFuture != null && !syncFuture.isDone()) {

                    // Recover sync task if it was canceled for instance during remote reinitialization.
                    if (syncTask == null || syncTask.isDone()) {
                        syncTask = sync();
                    }
                    return syncFuture;
                } else {
                    // cleanup old sync task
                    if (syncTask != null && !syncTask.isDone()) {
                        syncTask.cancel(true);
                    }
                }

                // Create new sync process
                syncFuture = new CompletableFutureLite();
                syncTask = sync();
                return syncFuture;
            }
        } catch (CouldNotPerformException ex) {
            return FutureProcessor.canceledFuture(new CouldNotPerformException("Could not request data!", ex));
        }
    }
1076300
public CompletableFuture<QueryResponse> query(QueryRequest request) {
    CompletableFuture<QueryResponse> future = new CompletableFuture<>();
    if (context.isCurrentContext()) {
      sendRequest(request, protocol::query, future);
    } else {
      context.execute(() -> sendRequest(request, protocol::query, future));
    }
    return future;
  }
316907
def _future_completed(future):
    
    exc = future.exception()
    if exc:
        log.debug("Failed to run task on executor", exc_info=exc)