InitGlobalCache initializes the global cache with the given directory.
(cacheDir string)
| 385 | |
| 386 | // InitGlobalCache initializes the global cache with the given directory. |
| 387 | func InitGlobalCache(cacheDir string) error { |
| 388 | var err error |
| 389 | |
| 390 | once.Do(func() { |
| 391 | // Store the cache directory globally for logger initialization |
| 392 | globalCacheDir = cacheDir |
| 393 | |
| 394 | // Create cache directory if it doesn't exist |
| 395 | if err = os.MkdirAll(cacheDir, 0o750); err != nil { |
| 396 | err = fmt.Errorf("failed to create cache directory: %w", err) |
| 397 | |
| 398 | return |
| 399 | } |
| 400 | |
| 401 | // Create a Badger database directory |
| 402 | badgerDir := filepath.Join(cacheDir, "badger") |
| 403 | if err = os.MkdirAll(badgerDir, 0o750); err != nil { |
| 404 | err = fmt.Errorf("failed to create badger directory: %w", err) |
| 405 | |
| 406 | return |
| 407 | } |
| 408 | |
| 409 | // Check if there's an existing process using the badger directory |
| 410 | lockFilePath := filepath.Join(badgerDir, "LOCK") |
| 411 | lockFileExists := false |
| 412 | |
| 413 | if _, statErr := os.Stat(lockFilePath); statErr == nil { |
| 414 | lockFileExists = true |
| 415 | |
| 416 | getCacheLogger().Debug("Found existing BadgerDB lock file") |
| 417 | } |
| 418 | |
| 419 | // Initialize badger cache |
| 420 | getCacheLogger().Debug("Attempting to initialize BadgerDB cache at %s", badgerDir) |
| 421 | |
| 422 | badgerCache, badgerErr := NewBadgerCache(badgerDir) |
| 423 | if badgerErr != nil { |
| 424 | // If lock file exists and we failed to initialize, it might be a lock contention |
| 425 | if lockFileExists { |
| 426 | getCacheLogger().Debug("Lock contention detected, waiting for lock release...") |
| 427 | // Wait a short time and try again once |
| 428 | time.Sleep(500 * time.Millisecond) |
| 429 | |
| 430 | badgerCache, badgerErr = NewBadgerCache(badgerDir) |
| 431 | } |
| 432 | |
| 433 | // If still failed, don't fall back to file cache, use in-memory as temporary solution |
| 434 | if badgerErr != nil { |
| 435 | getCacheLogger().Debug("Failed to initialize BadgerDB cache: %v", badgerErr) |
| 436 | getCacheLogger().Debug("Using temporary in-memory cache - no persistence will be available") |
| 437 | |
| 438 | globalCache = NewMemoryCache() |
| 439 | err = badgerErr |
| 440 | |
| 441 | return |
| 442 | } |
| 443 | } |
| 444 |