github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/api/accessor/teams_cacher.go (about)

     1  package accessor
     2  
     3  import (
     4  	"time"
     5  
     6  	"code.cloudfoundry.org/lager"
     7  	"github.com/pf-qiu/concourse/v6/atc"
     8  	"github.com/pf-qiu/concourse/v6/atc/db"
     9  	"github.com/patrickmn/go-cache"
    10  )
    11  
    12  //go:generate counterfeiter . Notifications
    13  
    14  type Notifications interface {
    15  	Listen(string) (chan bool, error)
    16  	Unlisten(string, chan bool) error
    17  }
    18  
    19  type teamsCacher struct {
    20  	logger        lager.Logger
    21  	cache         *cache.Cache
    22  	notifications Notifications
    23  	teamFactory   db.TeamFactory
    24  }
    25  
    26  func NewTeamsCacher(
    27  	logger lager.Logger,
    28  	notifications Notifications,
    29  	teamFactory db.TeamFactory,
    30  	expiration time.Duration,
    31  	cleanupInterval time.Duration,
    32  ) *teamsCacher {
    33  	c := &teamsCacher{
    34  		logger:        logger,
    35  		cache:         cache.New(expiration, cleanupInterval),
    36  		notifications: notifications,
    37  		teamFactory:   teamFactory,
    38  	}
    39  
    40  	go c.waitForNotifications()
    41  
    42  	return c
    43  }
    44  
    45  func (c *teamsCacher) GetTeams() ([]db.Team, error) {
    46  	if teams, found := c.cache.Get(atc.TeamCacheName); found {
    47  		return teams.([]db.Team), nil
    48  	}
    49  
    50  	teams, err := c.teamFactory.GetTeams()
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	c.cache.Set(atc.TeamCacheName, teams, cache.DefaultExpiration)
    56  
    57  	return teams, nil
    58  }
    59  
    60  func (c *teamsCacher) waitForNotifications() {
    61  	notifier, err := c.notifications.Listen(atc.TeamCacheChannel)
    62  	if err != nil {
    63  		c.logger.Error("failed-to-listen-for-team-cache", err)
    64  	}
    65  
    66  	defer c.notifications.Unlisten(atc.TeamCacheChannel, notifier)
    67  
    68  	for {
    69  		select {
    70  		case <-notifier:
    71  			c.cache.Delete(atc.TeamCacheName)
    72  		}
    73  	}
    74  }