github.com/abayer/test-infra@v0.0.5/mungegithub/mungers/mungerutil/time_cache.go (about)

     1  /*
     2  Copyright 2016 The Kubernetes 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 mungerutil
    18  
    19  import (
    20  	"sync"
    21  	"time"
    22  )
    23  
    24  // FirstLabelTimeGetter represents anything that can get a label's first time.
    25  // (interface is for testability / reduced import tree.)
    26  type FirstLabelTimeGetter interface {
    27  	FirstLabelTime(label string) *time.Time
    28  	Number() int
    29  }
    30  
    31  // LabelTimeCache just caches the result of a time lookup, since the first time
    32  // a label is applied never changes.
    33  type LabelTimeCache struct {
    34  	label string
    35  	cache map[int]time.Time
    36  	lock  sync.Mutex
    37  }
    38  
    39  // NewLabelTimeCache constructs a label time cache for the given label.
    40  func NewLabelTimeCache(label string) *LabelTimeCache {
    41  	return &LabelTimeCache{
    42  		label: label,
    43  		cache: map[int]time.Time{},
    44  	}
    45  }
    46  
    47  // FirstLabelTime returns a time from the cache if possible. Otherwise, it
    48  // will look up the time. If that doesn't work either, it will return
    49  // (time.Time{}, false).
    50  func (c *LabelTimeCache) FirstLabelTime(obj FirstLabelTimeGetter) (time.Time, bool) {
    51  	c.lock.Lock()
    52  	defer c.lock.Unlock()
    53  	if t, ok := c.cache[obj.Number()]; ok {
    54  		return t, true
    55  	}
    56  	t := obj.FirstLabelTime(c.label)
    57  	if t == nil {
    58  		return time.Time{}, false
    59  	}
    60  	c.cache[obj.Number()] = *t
    61  	return *t, true
    62  }