go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/auth/internal/proc_cache.go (about) 1 // Copyright 2017 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 internal 16 17 import ( 18 "sync" 19 ) 20 21 var ( 22 // ProcTokenCache is shared in-process cache to use if disk cache is disabled. 23 ProcTokenCache TokenCache = &MemoryTokenCache{} 24 ) 25 26 // MemoryTokenCache implements TokenCache on top of in-process memory. 27 type MemoryTokenCache struct { 28 lock sync.RWMutex 29 cache map[string]Token 30 } 31 32 // GetToken reads the token from cache. 33 func (c *MemoryTokenCache) GetToken(key *CacheKey) (*Token, error) { 34 k := key.ToMapKey() 35 c.lock.RLock() 36 tok, ok := c.cache[k] 37 c.lock.RUnlock() 38 if ok { 39 return &tok, nil 40 } 41 return nil, nil 42 } 43 44 // PutToken writes the token to cache. 45 func (c *MemoryTokenCache) PutToken(key *CacheKey, tok *Token) error { 46 k := key.ToMapKey() 47 c.lock.Lock() 48 if c.cache == nil { 49 c.cache = make(map[string]Token, 1) 50 } 51 c.cache[k] = *tok 52 c.lock.Unlock() 53 return nil 54 } 55 56 // DeleteToken removes the token from cache. 57 func (c *MemoryTokenCache) DeleteToken(key *CacheKey) error { 58 k := key.ToMapKey() 59 c.lock.Lock() 60 delete(c.cache, k) 61 c.lock.Unlock() 62 return nil 63 }