| 204 | } |
| 205 | |
| 206 | func (c *Cache) prepare(db database.Store, fileID uuid.UUID) *cacheEntry { |
| 207 | c.lock.Lock() |
| 208 | defer c.lock.Unlock() |
| 209 | |
| 210 | hitLabel := "true" |
| 211 | entry, ok := c.data[fileID] |
| 212 | if !ok { |
| 213 | hitLabel = "false" |
| 214 | |
| 215 | var purgeOnce sync.Once |
| 216 | entry = &cacheEntry{ |
| 217 | value: lazy.NewWithError(func() (CacheEntryValue, error) { |
| 218 | val, err := fetch(db, fileID) |
| 219 | if err != nil { |
| 220 | return val, err |
| 221 | } |
| 222 | |
| 223 | // Add the size of the file to the cache size metrics. |
| 224 | c.currentCacheSize.Add(float64(val.Size)) |
| 225 | c.totalCacheSize.Add(float64(val.Size)) |
| 226 | |
| 227 | return val, err |
| 228 | }), |
| 229 | |
| 230 | close: func() { |
| 231 | entry.refCount-- |
| 232 | c.currentOpenFileReferences.Dec() |
| 233 | if entry.refCount > 0 { |
| 234 | return |
| 235 | } |
| 236 | |
| 237 | entry.purge() |
| 238 | }, |
| 239 | |
| 240 | purge: func() { |
| 241 | purgeOnce.Do(func() { |
| 242 | c.purge(fileID) |
| 243 | }) |
| 244 | }, |
| 245 | } |
| 246 | c.data[fileID] = entry |
| 247 | |
| 248 | c.currentOpenFiles.Inc() |
| 249 | c.totalOpenedFiles.Inc() |
| 250 | } |
| 251 | |
| 252 | c.currentOpenFileReferences.Inc() |
| 253 | c.totalOpenFileReferences.WithLabelValues(hitLabel).Inc() |
| 254 | entry.refCount++ |
| 255 | return entry |
| 256 | } |
| 257 | |
| 258 | // purge immediately removes an entry from the cache, even if it has open |
| 259 | // references. |