cache.go 2.1 KB

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