cache.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package discover
  7. import (
  8. stdsync "sync"
  9. "time"
  10. "github.com/thejerf/suture/v4"
  11. "github.com/syncthing/syncthing/lib/protocol"
  12. )
  13. // A cachedFinder is a Finder with associated cache timeouts.
  14. type cachedFinder struct {
  15. Finder
  16. cacheTime time.Duration
  17. negCacheTime time.Duration
  18. cache *cache
  19. token *suture.ServiceToken
  20. }
  21. // An error may implement cachedError, in which case it will be interrogated
  22. // to see how long we should cache the error. This overrides the default
  23. // negative cache time.
  24. type cachedError interface {
  25. CacheFor() time.Duration
  26. }
  27. // A cache can be embedded wherever useful
  28. type cache struct {
  29. entries map[protocol.DeviceID]CacheEntry
  30. mut stdsync.Mutex
  31. }
  32. func newCache() *cache {
  33. return &cache{
  34. entries: make(map[protocol.DeviceID]CacheEntry),
  35. }
  36. }
  37. func (c *cache) Set(id protocol.DeviceID, ce CacheEntry) {
  38. c.mut.Lock()
  39. c.entries[id] = ce
  40. c.mut.Unlock()
  41. }
  42. func (c *cache) Get(id protocol.DeviceID) (CacheEntry, bool) {
  43. c.mut.Lock()
  44. ce, ok := c.entries[id]
  45. c.mut.Unlock()
  46. return ce, ok
  47. }
  48. func (c *cache) Cache() map[protocol.DeviceID]CacheEntry {
  49. c.mut.Lock()
  50. m := make(map[protocol.DeviceID]CacheEntry, len(c.entries))
  51. for k, v := range c.entries {
  52. m[k] = v
  53. }
  54. c.mut.Unlock()
  55. return m
  56. }