1 /* 2 * Copyright 2018 The gRPC Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package io.grpc.internal; 18 19 import com.google.common.base.MoreObjects; 20 import com.google.common.base.Objects; 21 import com.google.common.collect.ImmutableSet; 22 import io.grpc.Status.Code; 23 import java.util.Collections; 24 import java.util.Set; 25 import javax.annotation.concurrent.Immutable; 26 27 /** 28 * Hedging policy data object. 29 */ 30 @Immutable 31 final class HedgingPolicy { 32 final int maxAttempts; 33 final long hedgingDelayNanos; 34 final Set<Code> nonFatalStatusCodes; 35 36 /** No hedging. */ 37 static final HedgingPolicy DEFAULT = 38 new HedgingPolicy(1, 0, Collections.<Code>emptySet()); 39 40 /** 41 * The caller is supposed to have validated the arguments and handled throwing exception or 42 * logging warnings already, so we avoid repeating args check here. 43 */ 44 HedgingPolicy(int maxAttempts, long hedgingDelayNanos, Set<Code> nonFatalStatusCodes) { 45 this.maxAttempts = maxAttempts; 46 this.hedgingDelayNanos = hedgingDelayNanos; 47 this.nonFatalStatusCodes = ImmutableSet.copyOf(nonFatalStatusCodes); 48 } 49 50 @Override 51 public boolean equals(Object other) { 52 if (this == other) { 53 return true; 54 } 55 if (other == null || getClass() != other.getClass()) { 56 return false; 57 } 58 HedgingPolicy that = (HedgingPolicy) other; 59 return maxAttempts == that.maxAttempts 60 && hedgingDelayNanos == that.hedgingDelayNanos 61 && Objects.equal(nonFatalStatusCodes, that.nonFatalStatusCodes); 62 } 63 64 @Override 65 public int hashCode() { 66 return Objects.hashCode(maxAttempts, hedgingDelayNanos, nonFatalStatusCodes); 67 } 68 69 @Override 70 public String toString() { 71 return MoreObjects.toStringHelper(this) 72 .add("maxAttempts", maxAttempts) 73 .add("hedgingDelayNanos", hedgingDelayNanos) 74 .add("nonFatalStatusCodes", nonFatalStatusCodes) 75 .toString(); 76 } 77 78 /** 79 * Provides the most suitable hedging policy for a call. 80 */ 81 interface Provider { 82 83 /** 84 * This method is used no more than once for each call. Never returns null. 85 */ 86 HedgingPolicy get(); 87 } 88 } 89