Set adds a file to the cache with appropriate expiry
(key string, file *CachedFile)
| 86 | |
| 87 | // Set adds a file to the cache with appropriate expiry |
| 88 | func (fc *FileCache) Set(key string, file *CachedFile) { |
| 89 | // First check if cache is closed |
| 90 | fc.closeMutex.RLock() |
| 91 | if fc.closed { |
| 92 | fc.closeMutex.RUnlock() |
| 93 | return |
| 94 | } |
| 95 | fc.closeMutex.RUnlock() |
| 96 | |
| 97 | // Check file size - don't cache very large files |
| 98 | totalEntrySize := len(file.Data) + len(file.GzipData) |
| 99 | if totalEntrySize > MaxFileCacheSize { |
| 100 | return |
| 101 | } |
| 102 | |
| 103 | // Write lock for cache access |
| 104 | fc.cacheMutex.Lock() |
| 105 | defer fc.cacheMutex.Unlock() |
| 106 | |
| 107 | // Set the expiry time based on file type if not already set |
| 108 | if file.ExpiresAt.IsZero() { |
| 109 | file.ExpiresAt = CalculateExpiry(file.MimeType, file.Path) |
| 110 | } |
| 111 | |
| 112 | // Calculate TTL duration from ExpiresAt |
| 113 | ttl := file.ExpiresAt.Sub(time.Now()) |
| 114 | if ttl <= 0 { |
| 115 | // Don't cache expired files |
| 116 | return |
| 117 | } |
| 118 | |
| 119 | // Add to Olric cache with expiry |
| 120 | err := fc.cache.Put(context.Background(), key, file, olric.EX(ttl)) |
| 121 | if err != nil { |
| 122 | log.Printf("[117] Error setting key %s in Olric cache: %v", key, err) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | // CalculateExpiry determines expiry time based on file type |
| 127 | func CalculateExpiry(mimeType, path string) time.Time { |