File: groupcache.go

package info (click to toggle)
golang-github-canonical-candid 1.12.3-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 3,016 kB
  • sloc: python: 1,903; sh: 235; makefile: 81
file content (80 lines) | stat: -rw-r--r-- 2,021 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE.client file for details.

package candidclient

import (
	"context"
	"sort"
	"time"

	"github.com/juju/utils/v2/cache"
	"gopkg.in/errgo.v1"

	"github.com/canonical/candid/params"
)

// GroupCache holds a cache of group membership information.
type GroupCache struct {
	cache  *cache.Cache
	client *Client
}

// NewGroupCache returns a GroupCache that will cache
// group membership information.
//
// It will cache results for at most cacheTime.
//
// Note that use of this type should be avoided when possible - in
// the future it may not be possible to enumerate group membership
// for a user.
func NewGroupCache(c *Client, cacheTime time.Duration) *GroupCache {
	return &GroupCache{
		cache:  cache.New(cacheTime),
		client: c,
	}
}

// Groups returns the set of groups that the user is a member of.
func (gc *GroupCache) Groups(username string) ([]string, error) {
	groupMap, err := gc.groupMap(username)
	if err != nil {
		return nil, errgo.Mask(err)
	}
	groups := make([]string, 0, len(groupMap))
	for g := range groupMap {
		groups = append(groups, g)
	}
	sort.Strings(groups)
	return groups, nil
}

func (gc *GroupCache) groupMap(username string) (map[string]bool, error) {
	groups0, err := gc.cache.Get(username, func() (interface{}, error) {
		groups, err := gc.client.UserGroups(context.TODO(), &params.UserGroupsRequest{
			Username: params.Username(username),
		})
		if err != nil && errgo.Cause(err) != params.ErrNotFound {
			return nil, errgo.Mask(err)
		}
		groupMap := make(map[string]bool)
		for _, g := range groups {
			groupMap[g] = true
		}
		return groupMap, nil
	})
	if err != nil {
		return nil, errgo.Notef(err, "cannot fetch groups")
	}
	return groups0.(map[string]bool), nil
}

// CacheEvict evicts username from the cache.
func (c *GroupCache) CacheEvict(username string) {
	c.cache.Evict(username)
}

// CacheEvictAll evicts everything from the cache.
func (c *GroupCache) CacheEvictAll() {
	c.cache.EvictAll()
}