cache.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  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
  14. import (
  15. "container/list"
  16. "fmt"
  17. "sync"
  18. )
  19. // cache is for caching values of the secrets. Secret versions are immutable, thus there is no need
  20. // for time-based expiration.
  21. type cache interface {
  22. Get(secretID string, revision uint32) ([]byte, bool)
  23. Put(secretID string, revision uint32, value []byte)
  24. }
  25. type cacheEntry struct {
  26. value []byte
  27. elem *list.Element
  28. }
  29. type cacheImpl struct {
  30. mutex sync.Mutex
  31. entries map[string]cacheEntry
  32. entryKeysByLastUsage list.List
  33. maxEntryCount int
  34. }
  35. func newCache() cache {
  36. return &cacheImpl{
  37. entries: map[string]cacheEntry{},
  38. maxEntryCount: 500,
  39. }
  40. }
  41. func (c *cacheImpl) Get(secretID string, revision uint32) ([]byte, bool) {
  42. c.mutex.Lock()
  43. defer c.mutex.Unlock()
  44. key := c.key(secretID, revision)
  45. entry, ok := c.entries[key]
  46. if !ok {
  47. return nil, false
  48. }
  49. c.entryKeysByLastUsage.MoveToFront(entry.elem)
  50. return entry.value, true
  51. }
  52. func (c *cacheImpl) Put(secretID string, revision uint32, value []byte) {
  53. c.mutex.Lock()
  54. defer c.mutex.Unlock()
  55. key := c.key(secretID, revision)
  56. _, alreadyPresent := c.entries[key]
  57. if alreadyPresent {
  58. return
  59. }
  60. if len(c.entries) == c.maxEntryCount {
  61. c.evictLeastRecentlyUsed()
  62. }
  63. entry := c.entryKeysByLastUsage.PushFront(key)
  64. c.entries[key] = cacheEntry{
  65. value: value,
  66. elem: entry,
  67. }
  68. }
  69. func (c *cacheImpl) evictLeastRecentlyUsed() {
  70. elem := c.entryKeysByLastUsage.Back()
  71. delete(c.entries, elem.Value.(string))
  72. c.entryKeysByLastUsage.Remove(elem)
  73. }
  74. func (c *cacheImpl) key(secretID string, revision uint32) string {
  75. return fmt.Sprintf("%s/%d", secretID, revision)
  76. }