go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gce/api/config/v1/timeperiod.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 config
    16  
    17  import (
    18  	"go.chromium.org/luci/common/errors"
    19  	"go.chromium.org/luci/config/validation"
    20  )
    21  
    22  // Normalize ensures this time period is in seconds.
    23  // Parses and converts duration to seconds if necessary.
    24  func (t *TimePeriod) Normalize() error {
    25  	if t.GetDuration() == "" {
    26  		return nil
    27  	}
    28  	n, err := t.Time.(*TimePeriod_Duration).ToSeconds()
    29  	if err != nil {
    30  		return errors.Annotate(err, "invalid duration").Err()
    31  	}
    32  	t.Time = &TimePeriod_Seconds{
    33  		Seconds: n,
    34  	}
    35  	return nil
    36  }
    37  
    38  // ToSeconds returns this time period in seconds. Clamps to math.MaxInt64.
    39  func (t *TimePeriod) ToSeconds() (int64, error) {
    40  	if t == nil {
    41  		return 0, nil
    42  	}
    43  	switch t := t.Time.(type) {
    44  	case *TimePeriod_Duration:
    45  		return t.ToSeconds()
    46  	case *TimePeriod_Seconds:
    47  		return t.Seconds, nil
    48  	default:
    49  		return 0, errors.Reason("unexpected type %T", t).Err()
    50  	}
    51  }
    52  
    53  // Validate validates this time period.
    54  func (t *TimePeriod) Validate(c *validation.Context) {
    55  	switch {
    56  	case t.GetDuration() != "":
    57  		c.Enter("duration")
    58  		t.Time.(*TimePeriod_Duration).Validate(c)
    59  		c.Exit()
    60  	case t.GetSeconds() < 0:
    61  		c.Errorf("seconds must be non-negative")
    62  	}
    63  }