interface.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package cache contains an interface for a cache around a typed value, and
  4. // various cache implementations that implement that interface.
  5. package cache
  6. import "time"
  7. // Cache is the interface for the cache types in this package.
  8. //
  9. // Functions in this interface take a key parameter, but it is valid for a
  10. // cache type to hold a single value associated with a key, and simply drop the
  11. // cached value if provided with a different key.
  12. //
  13. // It is valid for Cache implementations to be concurrency-safe or not, and
  14. // each implementation should document this. If you need a concurrency-safe
  15. // cache, an existing cache can be wrapped with a lock using NewLocking(inner).
  16. //
  17. // K and V should be types that can be successfully passed to json.Marshal.
  18. type Cache[K comparable, V any] interface {
  19. // Get should return a previously-cached value or call the provided
  20. // FillFunc to obtain a new one. The provided key can be used either to
  21. // allow multiple cached values, or to drop the cache if the key
  22. // changes; either is valid.
  23. Get(K, FillFunc[V]) (V, error)
  24. // Forget should remove the given key from the cache, if it is present.
  25. // If it is not present, nothing should be done.
  26. Forget(K)
  27. // Empty should empty the cache such that the next call to Get should
  28. // call the provided FillFunc for all possible keys.
  29. Empty()
  30. }
  31. // FillFunc is the signature of a function for filling a cache. It should
  32. // return the value to be cached, the time that the cached value is valid
  33. // until, or an error.
  34. type FillFunc[T any] func() (T, time.Time, error)