/*
 *
 * Copyright 2017 gRPC authors.
 *
 * 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 grpc

import (
	
	
	
	
	
	
	

	
	
	internalserviceconfig 
	
)

const maxInt = int(^uint(0) >> 1)

// MethodConfig defines the configuration recommended by the service providers for a
// particular method.
//
// Deprecated: Users should not use this struct. Service config should be received
// through name resolver, as specified here
// https://github.com/grpc/grpc/blob/master/doc/service_config.md
type MethodConfig = internalserviceconfig.MethodConfig

type lbConfig struct {
	name string
	cfg  serviceconfig.LoadBalancingConfig
}

// ServiceConfig is provided by the service provider and contains parameters for how
// clients that connect to the service should behave.
//
// Deprecated: Users should not use this struct. Service config should be received
// through name resolver, as specified here
// https://github.com/grpc/grpc/blob/master/doc/service_config.md
type ServiceConfig struct {
	serviceconfig.Config

	// LB is the load balancer the service providers recommends.  This is
	// deprecated; lbConfigs is preferred.  If lbConfig and LB are both present,
	// lbConfig will be used.
	LB *string

	// lbConfig is the service config's load balancing configuration.  If
	// lbConfig and LB are both present, lbConfig will be used.
	lbConfig *lbConfig

	// Methods contains a map for the methods in this service.  If there is an
	// exact match for a method (i.e. /service/method) in the map, use the
	// corresponding MethodConfig.  If there's no exact match, look for the
	// default config for the service (/service/) and use the corresponding
	// MethodConfig if it exists.  Otherwise, the method has no MethodConfig to
	// use.
	Methods map[string]MethodConfig

	// If a retryThrottlingPolicy is provided, gRPC will automatically throttle
	// retry attempts and hedged RPCs when the client’s ratio of failures to
	// successes exceeds a threshold.
	//
	// For each server name, the gRPC client will maintain a token_count which is
	// initially set to maxTokens, and can take values between 0 and maxTokens.
	//
	// Every outgoing RPC (regardless of service or method invoked) will change
	// token_count as follows:
	//
	//   - Every failed RPC will decrement the token_count by 1.
	//   - Every successful RPC will increment the token_count by tokenRatio.
	//
	// If token_count is less than or equal to maxTokens / 2, then RPCs will not
	// be retried and hedged RPCs will not be sent.
	retryThrottling *retryThrottlingPolicy
	// healthCheckConfig must be set as one of the requirement to enable LB channel
	// health check.
	healthCheckConfig *healthCheckConfig
	// rawJSONString stores service config json string that get parsed into
	// this service config struct.
	rawJSONString string
}

// healthCheckConfig defines the go-native version of the LB channel health check config.
type healthCheckConfig struct {
	// serviceName is the service name to use in the health-checking request.
	ServiceName string
}

type jsonRetryPolicy struct {
	MaxAttempts          int
	InitialBackoff       string
	MaxBackoff           string
	BackoffMultiplier    float64
	RetryableStatusCodes []codes.Code
}

// retryThrottlingPolicy defines the go-native version of the retry throttling
// policy defined by the service config here:
// https://github.com/grpc/proposal/blob/master/A6-client-retries.md#integration-with-service-config
type retryThrottlingPolicy struct {
	// The number of tokens starts at maxTokens. The token_count will always be
	// between 0 and maxTokens.
	//
	// This field is required and must be greater than zero.
	MaxTokens float64
	// The amount of tokens to add on each successful RPC. Typically this will
	// be some number between 0 and 1, e.g., 0.1.
	//
	// This field is required and must be greater than zero. Up to 3 decimal
	// places are supported.
	TokenRatio float64
}

func ( *string) (*time.Duration, error) {
	if  == nil {
		return nil, nil
	}
	if !strings.HasSuffix(*, "s") {
		return nil, fmt.Errorf("malformed duration %q", *)
	}
	 := strings.SplitN((*)[:len(*)-1], ".", 3)
	if len() > 2 {
		return nil, fmt.Errorf("malformed duration %q", *)
	}
	// hasDigits is set if either the whole or fractional part of the number is
	// present, since both are optional but one is required.
	 := false
	var  time.Duration
	if len([0]) > 0 {
		,  := strconv.ParseInt([0], 10, 32)
		if  != nil {
			return nil, fmt.Errorf("malformed duration %q: %v", *, )
		}
		 = time.Duration() * time.Second
		 = true
	}
	if len() == 2 && len([1]) > 0 {
		if len([1]) > 9 {
			return nil, fmt.Errorf("malformed duration %q", *)
		}
		,  := strconv.ParseInt([1], 10, 64)
		if  != nil {
			return nil, fmt.Errorf("malformed duration %q: %v", *, )
		}
		for  := 9;  > len([1]); -- {
			 *= 10
		}
		 += time.Duration()
		 = true
	}
	if ! {
		return nil, fmt.Errorf("malformed duration %q", *)
	}

	return &, nil
}

type jsonName struct {
	Service string
	Method  string
}

var (
	errDuplicatedName             = errors.New("duplicated name")
	errEmptyServiceNonEmptyMethod = errors.New("cannot combine empty 'service' and non-empty 'method'")
)

func ( jsonName) () (string, error) {
	if .Service == "" {
		if .Method != "" {
			return "", errEmptyServiceNonEmptyMethod
		}
		return "", nil
	}
	 := "/" + .Service + "/"
	if .Method != "" {
		 += .Method
	}
	return , nil
}

// TODO(lyuxuan): delete this struct after cleaning up old service config implementation.
type jsonMC struct {
	Name                    *[]jsonName
	WaitForReady            *bool
	Timeout                 *string
	MaxRequestMessageBytes  *int64
	MaxResponseMessageBytes *int64
	RetryPolicy             *jsonRetryPolicy
}

// TODO(lyuxuan): delete this struct after cleaning up old service config implementation.
type jsonSC struct {
	LoadBalancingPolicy *string
	LoadBalancingConfig *internalserviceconfig.BalancerConfig
	MethodConfig        *[]jsonMC
	RetryThrottling     *retryThrottlingPolicy
	HealthCheckConfig   *healthCheckConfig
}

func () {
	internal.ParseServiceConfig = parseServiceConfig
}
func ( string) *serviceconfig.ParseResult {
	if len() == 0 {
		return &serviceconfig.ParseResult{Err: fmt.Errorf("no JSON service config provided")}
	}
	var  jsonSC
	 := json.Unmarshal([]byte(), &)
	if  != nil {
		logger.Warningf("grpc: unmarshaling service config %s: %v", , )
		return &serviceconfig.ParseResult{Err: }
	}
	 := ServiceConfig{
		LB:                .LoadBalancingPolicy,
		Methods:           make(map[string]MethodConfig),
		retryThrottling:   .RetryThrottling,
		healthCheckConfig: .HealthCheckConfig,
		rawJSONString:     ,
	}
	if  := .LoadBalancingConfig;  != nil {
		.lbConfig = &lbConfig{
			name: .Name,
			cfg:  .Config,
		}
	}

	if .MethodConfig == nil {
		return &serviceconfig.ParseResult{Config: &}
	}

	 := map[string]struct{}{}
	for ,  := range *.MethodConfig {
		if .Name == nil {
			continue
		}
		,  := parseDuration(.Timeout)
		if  != nil {
			logger.Warningf("grpc: unmarshaling service config %s: %v", , )
			return &serviceconfig.ParseResult{Err: }
		}

		 := MethodConfig{
			WaitForReady: .WaitForReady,
			Timeout:      ,
		}
		if .RetryPolicy,  = convertRetryPolicy(.RetryPolicy);  != nil {
			logger.Warningf("grpc: unmarshaling service config %s: %v", , )
			return &serviceconfig.ParseResult{Err: }
		}
		if .MaxRequestMessageBytes != nil {
			if *.MaxRequestMessageBytes > int64(maxInt) {
				.MaxReqSize = newInt(maxInt)
			} else {
				.MaxReqSize = newInt(int(*.MaxRequestMessageBytes))
			}
		}
		if .MaxResponseMessageBytes != nil {
			if *.MaxResponseMessageBytes > int64(maxInt) {
				.MaxRespSize = newInt(maxInt)
			} else {
				.MaxRespSize = newInt(int(*.MaxResponseMessageBytes))
			}
		}
		for ,  := range *.Name {
			,  := .generatePath()
			if  != nil {
				logger.Warningf("grpc: error unmarshaling service config %s due to methodConfig[%d]: %v", , , )
				return &serviceconfig.ParseResult{Err: }
			}

			if ,  := [];  {
				 = errDuplicatedName
				logger.Warningf("grpc: error unmarshaling service config %s due to methodConfig[%d]: %v", , , )
				return &serviceconfig.ParseResult{Err: }
			}
			[] = struct{}{}
			.Methods[] = 
		}
	}

	if .retryThrottling != nil {
		if  := .retryThrottling.MaxTokens;  <= 0 ||  > 1000 {
			return &serviceconfig.ParseResult{Err: fmt.Errorf("invalid retry throttling config: maxTokens (%v) out of range (0, 1000]", )}
		}
		if  := .retryThrottling.TokenRatio;  <= 0 {
			return &serviceconfig.ParseResult{Err: fmt.Errorf("invalid retry throttling config: tokenRatio (%v) may not be negative", )}
		}
	}
	return &serviceconfig.ParseResult{Config: &}
}

func ( *jsonRetryPolicy) ( *internalserviceconfig.RetryPolicy,  error) {
	if  == nil {
		return nil, nil
	}
	,  := parseDuration(&.InitialBackoff)
	if  != nil {
		return nil, 
	}
	,  := parseDuration(&.MaxBackoff)
	if  != nil {
		return nil, 
	}

	if .MaxAttempts <= 1 ||
		* <= 0 ||
		* <= 0 ||
		.BackoffMultiplier <= 0 ||
		len(.RetryableStatusCodes) == 0 {
		logger.Warningf("grpc: ignoring retry policy %v due to illegal configuration", )
		return nil, nil
	}

	 := &internalserviceconfig.RetryPolicy{
		MaxAttempts:          .MaxAttempts,
		InitialBackoff:       *,
		MaxBackoff:           *,
		BackoffMultiplier:    .BackoffMultiplier,
		RetryableStatusCodes: make(map[codes.Code]bool),
	}
	if .MaxAttempts > 5 {
		// TODO(retry): Make the max maxAttempts configurable.
		.MaxAttempts = 5
	}
	for ,  := range .RetryableStatusCodes {
		.RetryableStatusCodes[] = true
	}
	return , nil
}

func (,  *int) *int {
	if * < * {
		return 
	}
	return 
}

func (,  *int,  int) *int {
	if  == nil &&  == nil {
		return &
	}
	if  != nil &&  != nil {
		return min(, )
	}
	if  != nil {
		return 
	}
	return 
}

func ( int) *int {
	return &
}

func () {
	internal.EqualServiceConfigForTesting = equalServiceConfig
}

// equalServiceConfig compares two configs. The rawJSONString field is ignored,
// because they may diff in white spaces.
//
// If any of them is NOT *ServiceConfig, return false.
func (,  serviceconfig.Config) bool {
	if  == nil &&  == nil {
		return true
	}
	,  := .(*ServiceConfig)
	if ! {
		return false
	}
	,  := .(*ServiceConfig)
	if ! {
		return false
	}
	 := .rawJSONString
	.rawJSONString = ""
	 := .rawJSONString
	.rawJSONString = ""
	defer func() {
		.rawJSONString = 
		.rawJSONString = 
	}()
	// Using reflect.DeepEqual instead of cmp.Equal because many balancer
	// configs are unexported, and cmp.Equal cannot compare unexported fields
	// from unexported structs.
	return reflect.DeepEqual(, )
}