GetNamespacedCache returns (and initializes if needed) a cache scoped to the provided namespace. Namespaced caches live alongside the global cache but operate on their own storage so they aren't affected by global cache invalidation.
(namespace string)
| 493 | // Namespaced caches live alongside the global cache but operate on their own storage so they aren't |
| 494 | // affected by global cache invalidation. |
| 495 | func GetNamespacedCache(namespace string) Cache { |
| 496 | namespacedCacheMu.RLock() |
| 497 | if cache, ok := namespacedCaches[namespace]; ok { |
| 498 | namespacedCacheMu.RUnlock() |
| 499 | |
| 500 | return cache |
| 501 | } |
| 502 | namespacedCacheMu.RUnlock() |
| 503 | |
| 504 | namespacedCacheMu.Lock() |
| 505 | defer namespacedCacheMu.Unlock() |
| 506 | |
| 507 | // Double-check after acquiring write lock |
| 508 | if cache, ok := namespacedCaches[namespace]; ok { |
| 509 | return cache |
| 510 | } |
| 511 | |
| 512 | // If the global cache directory hasn't been set up yet, fall back to in-memory cache. |
| 513 | if globalCacheDir == "" { |
| 514 | memCache := NewMemoryCache() |
| 515 | namespacedCaches[namespace] = memCache |
| 516 | getCacheLogger().Debug("Using in-memory cache for namespace %s (global cache dir not set)", namespace) |
| 517 | |
| 518 | return memCache |
| 519 | } |
| 520 | |
| 521 | namespaceDir := filepath.Join(globalCacheDir, "plugins", namespace) |
| 522 | if err := os.MkdirAll(namespaceDir, 0o750); err != nil { |
| 523 | getCacheLogger().Debug("Failed to create namespace cache directory %s: %v", namespaceDir, err) |
| 524 | memCache := NewMemoryCache() |
| 525 | namespacedCaches[namespace] = memCache |
| 526 | getCacheLogger().Debug("Using in-memory cache for namespace %s", namespace) |
| 527 | |
| 528 | return memCache |
| 529 | } |
| 530 | |
| 531 | badgerCache, err := NewBadgerCache(namespaceDir) |
| 532 | if err != nil { |
| 533 | getCacheLogger().Debug("Failed to initialize namespaced cache %s: %v", namespace, err) |
| 534 | memCache := NewMemoryCache() |
| 535 | namespacedCaches[namespace] = memCache |
| 536 | getCacheLogger().Debug("Using in-memory cache for namespace %s", namespace) |
| 537 | |
| 538 | return memCache |
| 539 | } |
| 540 | |
| 541 | getCacheLogger().Debug("Initialized namespaced cache at %s", namespaceDir) |
| 542 | namespacedCaches[namespace] = badgerCache |
| 543 | |
| 544 | return badgerCache |
| 545 | } |