github.com/cloudwego/kitex@v0.9.0/pkg/connpool/config.go (about)

     1  /*
     2   * Copyright 2021 CloudWeGo 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 connpool
    18  
    19  import "time"
    20  
    21  // IdleConfig contains idle configuration for long-connection pool.
    22  type IdleConfig struct {
    23  	MinIdlePerAddress int
    24  	MaxIdlePerAddress int
    25  	MaxIdleGlobal     int
    26  	MaxIdleTimeout    time.Duration
    27  }
    28  
    29  const (
    30  	defaultMaxIdleTimeout = 30 * time.Second
    31  	minMaxIdleTimeout     = 2 * time.Second
    32  	maxMinIdlePerAddress  = 5
    33  	defaultMaxIdleGlobal  = 1 << 20 // no limit
    34  )
    35  
    36  // CheckPoolConfig to check invalid param.
    37  // default MaxIdleTimeout = 30s, min value is 2s
    38  func CheckPoolConfig(config IdleConfig) *IdleConfig {
    39  	// idle timeout
    40  	if config.MaxIdleTimeout == 0 {
    41  		config.MaxIdleTimeout = defaultMaxIdleTimeout
    42  	} else if config.MaxIdleTimeout < minMaxIdleTimeout {
    43  		config.MaxIdleTimeout = minMaxIdleTimeout
    44  	}
    45  
    46  	// idlePerAddress
    47  	if config.MinIdlePerAddress < 0 {
    48  		config.MinIdlePerAddress = 0
    49  	}
    50  	if config.MinIdlePerAddress > maxMinIdlePerAddress {
    51  		config.MinIdlePerAddress = maxMinIdlePerAddress
    52  	}
    53  	if config.MaxIdlePerAddress <= 0 {
    54  		config.MaxIdlePerAddress = 1
    55  	}
    56  	if config.MaxIdlePerAddress < config.MinIdlePerAddress {
    57  		config.MaxIdlePerAddress = config.MinIdlePerAddress
    58  	}
    59  
    60  	// globalIdle
    61  	if config.MaxIdleGlobal <= 0 {
    62  		config.MaxIdleGlobal = defaultMaxIdleGlobal
    63  	} else if config.MaxIdleGlobal < config.MaxIdlePerAddress {
    64  		config.MaxIdleGlobal = config.MaxIdlePerAddress
    65  	}
    66  	return &config
    67  }