go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cv/internal/configs/validation/rules.go (about)

     1  // Copyright 2018 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 validation
    16  
    17  import (
    18  	"context"
    19  	"regexp"
    20  	"time"
    21  
    22  	"go.chromium.org/luci/common/data/caching/lru"
    23  	"go.chromium.org/luci/config/validation"
    24  )
    25  
    26  // Config validation rules go here.
    27  
    28  func init() {
    29  	addRules(&validation.Rules)
    30  }
    31  
    32  // TODO(crbug.com/1252545): Use a dev-specific configuration for a dev instance
    33  // of the service after CQD is deleted.
    34  func addRules(r *validation.RuleSet) {
    35  	r.Add("regex:projects/[^/]+", "commit-queue.cfg", validateProject)
    36  	r.Add("services/${appid}", "listener-settings.cfg", validateListenerSettings)
    37  }
    38  
    39  // regexpCompileCached is the caching version of regexp.Compile.
    40  //
    41  // Most config files use the same regexp many times.
    42  func regexpCompileCached(pattern string) (*regexp.Regexp, error) {
    43  	cached, err := regexpCache.GetOrCreate(context.Background(), pattern, func() (regexpCacheValue, time.Duration, error) {
    44  		r, err := regexp.Compile(pattern)
    45  		return regexpCacheValue{r, err}, 0, nil
    46  	})
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  	return cached.r, cached.err
    51  }
    52  
    53  var regexpCache = lru.New[string, regexpCacheValue](1024)
    54  
    55  type regexpCacheValue struct {
    56  	r   *regexp.Regexp
    57  	err error
    58  }
    59  
    60  func enter(vctx *validation.Context, kind string, i int, name string) {
    61  	if name == "" {
    62  		vctx.Enter(kind+" #%d", i+1)
    63  	} else {
    64  		vctx.Enter(kind+" #%d %q", i+1, name)
    65  	}
    66  }