cache.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. Copyright © The ESO Authors
  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. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package scaleway provides functionality to interact with Scaleway Secrets Management service.
  14. package scaleway
  15. import (
  16. "container/list"
  17. "fmt"
  18. "sync"
  19. )
  20. // cache is for caching values of the secrets. Secret versions are immutable, thus there is no need
  21. // for time-based expiration.
  22. type cache interface {
  23. Get(secretID string, revision uint32) ([]byte, bool)
  24. Put(secretID string, revision uint32, value []byte)
  25. }
  26. type cacheEntry struct {
  27. value []byte
  28. elem *list.Element
  29. }
  30. type cacheImpl struct {
  31. mutex sync.Mutex
  32. entries map[string]cacheEntry
  33. entryKeysByLastUsage list.List
  34. maxEntryCount int
  35. }
  36. func newCache() cache {
  37. return &cacheImpl{
  38. entries: map[string]cacheEntry{},
  39. maxEntryCount: 500,
  40. }
  41. }
  42. func (c *cacheImpl) Get(secretID string, revision uint32) ([]byte, bool) {
  43. c.mutex.Lock()
  44. defer c.mutex.Unlock()
  45. key := c.key(secretID, revision)
  46. entry, ok := c.entries[key]
  47. if !ok {
  48. return nil, false
  49. }
  50. c.entryKeysByLastUsage.MoveToFront(entry.elem)
  51. return entry.value, true
  52. }
  53. func (c *cacheImpl) Put(secretID string, revision uint32, value []byte) {
  54. c.mutex.Lock()
  55. defer c.mutex.Unlock()
  56. key := c.key(secretID, revision)
  57. _, alreadyPresent := c.entries[key]
  58. if alreadyPresent {
  59. return
  60. }
  61. if len(c.entries) == c.maxEntryCount {
  62. c.evictLeastRecentlyUsed()
  63. }
  64. entry := c.entryKeysByLastUsage.PushFront(key)
  65. c.entries[key] = cacheEntry{
  66. value: value,
  67. elem: entry,
  68. }
  69. }
  70. func (c *cacheImpl) evictLeastRecentlyUsed() {
  71. elem := c.entryKeysByLastUsage.Back()
  72. delete(c.entries, elem.Value.(string))
  73. c.entryKeysByLastUsage.Remove(elem)
  74. }
  75. func (c *cacheImpl) key(secretID string, revision uint32) string {
  76. return fmt.Sprintf("%s/%d", secretID, revision)
  77. }