<commit_before>/*
 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hazelcast.client.spi.impl;

import com.hazelcast.client.ClientRequest;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.RetryableRequest;
import com.hazelcast.client.connection.nio.ClientConnection;
import com.hazelcast.client.spi.EventHandler;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstanceNotActiveException;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.nio.serialization.SerializationService;
import com.hazelcast.spi.Callback;
import com.hazelcast.spi.exception.TargetDisconnectedException;
import com.hazelcast.spi.exception.TargetNotMemberException;
import com.hazelcast.util.Clock;
import com.hazelcast.util.ExceptionUtil;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import static com.hazelcast.client.config.ClientProperties.PROP_HEARTBEAT_INTERVAL_DEFAULT;
import static com.hazelcast.client.config.ClientProperties.PROP_RETRY_COUNT_DEFAULT;
import static com.hazelcast.client.config.ClientProperties.PROP_RETRY_WAIT_TIME_DEFAULT;

public class ClientCallFuture<V> implements ICompletableFuture<V>, Callback {

    static final ILogger logger = Logger.getLogger(ClientCallFuture.class);

    private Object response;

    private final ClientRequest request;

    private final ClientExecutionServiceImpl executionService;

    private final ClientInvocationServiceImpl invocationService;

    private final SerializationService serializationService;

    private final EventHandler handler;

    public final int heartBeatInterval;
    public final int retryCount;
    public final int retryWaitTime;

    private AtomicInteger reSendCount = new AtomicInteger();

    private volatile ClientConnection connection;

    private List<ExecutionCallbackNode> callbackNodeList = new LinkedList<ExecutionCallbackNode>();

    public ClientCallFuture(HazelcastClient client, ClientRequest request, EventHandler handler) {
        int interval = client.clientProperties.HEARTBEAT_INTERVAL.getInteger();
        this.heartBeatInterval = interval > 0 ? interval : Integer.parseInt(PROP_HEARTBEAT_INTERVAL_DEFAULT);

        int retry = client.clientProperties.RETRY_COUNT.getInteger();
        this.retryCount = retry > 0 ? retry : Integer.parseInt(PROP_RETRY_COUNT_DEFAULT);

        int waitTime = client.clientProperties.RETRY_WAIT_TIME.getInteger();
        this.retryWaitTime = waitTime > 0 ? waitTime : Integer.parseInt(PROP_RETRY_WAIT_TIME_DEFAULT);


        this.invocationService = (ClientInvocationServiceImpl) client.getInvocationService();
        this.executionService = (ClientExecutionServiceImpl) client.getClientExecutionService();
        this.serializationService = client.getSerializationService();
        this.request = request;
        this.handler = handler;
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    public boolean isCancelled() {
        return false;
    }

    public boolean isDone() {
        return response != null;
    }

    public V get() throws InterruptedException, ExecutionException {
        try {
            return get(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ignored) {
            return null;
        }
    }

    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (response == null) {
            long waitMillis = unit.toMillis(timeout);
            if (waitMillis > 0) {
                synchronized (this) {
                    while (waitMillis > 0 && response == null) {
                        long start = Clock.currentTimeMillis();
                        this.wait(Math.min(heartBeatInterval, waitMillis));
                        long elapsed = Clock.currentTimeMillis() - start;
                        waitMillis -= elapsed;
                        if (!isConnectionHealthy(elapsed)) {
                            break;
                        }
                    }
                }
            }
        }
        return resolveResponse();
    }

    private boolean isConnectionHealthy(long elapsed) {
        if (elapsed >= heartBeatInterval) {
            return connection.isHeartBeating();
        }
        return true;
    }

    public void notify(Object response) {
        if (response == null) {
            throw new IllegalArgumentException("response can't be null");
        }
        if (response instanceof TargetNotMemberException) {
            if (resend()) {
                return;
            }
        }
        if (response instanceof TargetDisconnectedException || response instanceof HazelcastInstanceNotActiveException) {
            if (request instanceof RetryableRequest || invocationService.isRedoOperation()) {
                if (resend()) {
                    return;
                }
            }<commit_msg>Client retries if connection is not healthy(meaning its heartbeat is timed out). ClientCallFuture does not return null when timeout, rethrows the exception<commit_after>/*
 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hazelcast.client.spi.impl;

import com.hazelcast.client.ClientRequest;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.RetryableRequest;
import com.hazelcast.client.connection.nio.ClientConnection;
import com.hazelcast.client.spi.EventHandler;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstanceNotActiveException;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.nio.serialization.SerializationService;
import com.hazelcast.spi.Callback;
import com.hazelcast.spi.exception.TargetDisconnectedException;
import com.hazelcast.spi.exception.TargetNotMemberException;
import com.hazelcast.util.Clock;
import com.hazelcast.util.ExceptionUtil;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import static com.hazelcast.client.config.ClientProperties.PROP_HEARTBEAT_INTERVAL_DEFAULT;
import static com.hazelcast.client.config.ClientProperties.PROP_RETRY_COUNT_DEFAULT;
import static com.hazelcast.client.config.ClientProperties.PROP_RETRY_WAIT_TIME_DEFAULT;

public class ClientCallFuture<V> implements ICompletableFuture<V>, Callback {

    static final ILogger logger = Logger.getLogger(ClientCallFuture.class);

    private Object response;

    private final ClientRequest request;

    private final ClientExecutionServiceImpl executionService;

    private final ClientInvocationServiceImpl invocationService;

    private final SerializationService serializationService;

    private final EventHandler handler;

    public final int heartBeatInterval;
    public final int retryCount;
    public final int retryWaitTime;

    private AtomicInteger reSendCount = new AtomicInteger();

    private volatile ClientConnection connection;

    private List<ExecutionCallbackNode> callbackNodeList = new LinkedList<ExecutionCallbackNode>();

    public ClientCallFuture(HazelcastClient client, ClientRequest request, EventHandler handler) {
        int interval = client.clientProperties.HEARTBEAT_INTERVAL.getInteger();
        this.heartBeatInterval = interval > 0 ? interval : Integer.parseInt(PROP_HEARTBEAT_INTERVAL_DEFAULT);

        int retry = client.clientProperties.RETRY_COUNT.getInteger();
        this.retryCount = retry > 0 ? retry : Integer.parseInt(PROP_RETRY_COUNT_DEFAULT);

        int waitTime = client.clientProperties.RETRY_WAIT_TIME.getInteger();
        this.retryWaitTime = waitTime > 0 ? waitTime : Integer.parseInt(PROP_RETRY_WAIT_TIME_DEFAULT);


        this.invocationService = (ClientInvocationServiceImpl) client.getInvocationService();
        this.executionService = (ClientExecutionServiceImpl) client.getClientExecutionService();
        this.serializationService = client.getSerializationService();
        this.request = request;
        this.handler = handler;
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    public boolean isCancelled() {
        return false;
    }

    public boolean isDone() {
        return response != null;
    }

    public V get() throws InterruptedException, ExecutionException {
        try {
            return get(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (TimeoutException exception) {
            throw ExceptionUtil.rethrow(exception);
        }
    }

    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (response == null) {
            long waitMillis = unit.toMillis(timeout);
            if (waitMillis > 0) {
                synchronized (this) {
                    while (waitMillis > 0 && response == null) {
                        long start = Clock.currentTimeMillis();
                        this.wait(Math.min(heartBeatInterval, waitMillis));
                        long elapsed = Clock.currentTimeMillis() - start;
                        waitMillis -= elapsed;
                        if (!isConnectionHealthy(elapsed)) {
                            notify(new TargetDisconnectedException());
                        }
                    }
                }
            }
        }
        return resolveResponse();
    }

    private boolean isConnectionHealthy(long elapsed) {
        if (elapsed >= heartBeatInterval) {
            return connection.isHeartBeating();
        }
        return true;
    }

    public void notify(Object response) {
        if (response == null) {
            throw new IllegalArgumentException("response can't be null");
        }
        if (response instanceof TargetNotMemberException) {
            if (resend()) {
                return;
            }
        }
        if (response instanceof TargetDisconnectedException || response instanceof HazelcastInstanceNotActiveException) {
            if (request instanceof RetryableRequest || invocationService.isRedoOperation()) {
                if (resend()) {
                    return;
                }
            }
{'fraction_non_alphanumeric': 0.07744278354868676, 'fraction_numerical': 0.002871379106494384, 'mean_word_length': 3.10752688172043, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3637214', 'n_tokens_mistral': 3093, 'n_tokens_neox': 2996, 'n_words': 756}