go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/sync/dispatcher/options_validate.go (about)

     1  // Copyright 2019 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package dispatcher
    16  
    17  import (
    18  	"context"
    19  	"time"
    20  
    21  	"golang.org/x/time/rate"
    22  
    23  	"go.chromium.org/luci/common/errors"
    24  )
    25  
    26  // normalize validates that Options is well formed and populates defaults which
    27  // are missing.
    28  func (o *Options) normalize(ctx context.Context) error {
    29  	if o.ItemSizeFunc == nil {
    30  		if o.Buffer.BatchSizeMax > 0 {
    31  			return errors.New("Buffer.BatchSizeMax > 0 but ItemSizerFunc == nil")
    32  		}
    33  	}
    34  
    35  	if o.ErrorFn == nil {
    36  		o.ErrorFn = defaultErrorFnFactory(ctx)
    37  	}
    38  	if o.DropFn == nil {
    39  		o.DropFn = defaultDropFnFactory(ctx, o.Buffer.FullBehavior)
    40  	}
    41  
    42  	if o.QPSLimit == nil {
    43  		o.QPSLimit = rate.NewLimiter(rate.Inf, 0)
    44  	}
    45  	if o.QPSLimit.Limit() != rate.Inf && o.QPSLimit.Burst() < 1 {
    46  		return errors.Reason(
    47  			"QPSLimit has burst size < 1, but a non-infinite rate: %d",
    48  			o.QPSLimit.Burst()).Err()
    49  	}
    50  
    51  	if o.MinQPS == rate.Inf {
    52  		return errors.Reason("MinQPS cannot be infinite").Err()
    53  	}
    54  
    55  	if o.MinQPS > 0 && o.MinQPS > o.QPSLimit.Limit() {
    56  		return errors.Reason(
    57  			"MinQPS: %f is greater than QPSLimit: %f",
    58  			o.MinQPS, o.QPSLimit.Limit()).Err()
    59  	}
    60  
    61  	return nil
    62  }
    63  
    64  // durationFromLimit converts a rate.Limit to a time.Duration.
    65  func durationFromLimit(limit rate.Limit) time.Duration {
    66  	switch {
    67  	case limit == rate.Inf:
    68  		return 0
    69  	case limit <= 0:
    70  		// Reset the duration to 0, instead of returning rate.InfDuration.
    71  		return 0
    72  	default:
    73  		seconds := float64(1) / float64(limit)
    74  		return time.Duration(float64(time.Second) * seconds)
    75  	}
    76  }