Skip to content

Commit

Permalink
cf: gracefully handle corrupted API cache index (#483)
Browse files Browse the repository at this point in the history
  • Loading branch information
itzg authored Oct 15, 2024
1 parent 232bed5 commit 4bcb995
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions src/main/java/me/itzg/helpers/cache/ApiCachingImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.TemporalAmount;
Expand Down Expand Up @@ -74,17 +77,50 @@ private Path resolveContentFile(String operation, String filename) {
return cacheNamespaceDir.resolve(operation).resolve(filename);
}

private CacheIndex loadCacheIndex() throws IOException {
private CacheIndex loadCacheIndex() {
final Path cacheIndexPath = cacheNamespaceDir.resolve(CACHE_INDEX_FILENAME);
if (Files.exists(cacheIndexPath)) {
log.debug("Loading cache index from {}", cacheIndexPath);
return objectMapper.readValue(cacheIndexPath.toFile(), CacheIndex.class);
try {
return objectMapper.readValue(cacheIndexPath.toFile(), CacheIndex.class);
} catch (IOException e) {
log.warn("Failed to load API cache index from {}", cacheIndexPath, e);
wipeCacheDirectory();
return new CacheIndex();
}
}
else {
return new CacheIndex();
}
}

private void wipeCacheDirectory() {
if (!Files.exists(cacheNamespaceDir)) {
log.debug("Skipping wipe of non-existent cache directory {}", cacheNamespaceDir);
return;
}

log.debug("Wiping cache directory {}", cacheNamespaceDir);
try {
Files.walkFileTree(cacheNamespaceDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.getFileName().toString().endsWith(".json")) {
try {
log.debug("Wiping cache file {}", file);
Files.delete(file);
} catch (IOException e) {
log.warn("Failed to delete cache file {}", file, e);
}
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
log.warn("Unexpected failure while wiping cache directory", e);
}
}

@Override
public <R> Mono<R> cache(String operation, Class<R> returnType, Mono<R> resolver, Object... keys) {
final String keysKey = Stream.of(keys)
Expand Down

0 comments on commit 4bcb995

Please sign in to comment.