Skip to content

Commit 4bcb995

Browse files
authored
cf: gracefully handle corrupted API cache index (#483)
1 parent 232bed5 commit 4bcb995

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

src/main/java/me/itzg/helpers/cache/ApiCachingImpl.java

+38-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22

33
import com.fasterxml.jackson.databind.ObjectMapper;
44
import java.io.IOException;
5+
import java.nio.file.FileVisitResult;
56
import java.nio.file.Files;
67
import java.nio.file.Path;
8+
import java.nio.file.SimpleFileVisitor;
9+
import java.nio.file.attribute.BasicFileAttributes;
710
import java.time.Duration;
811
import java.time.Instant;
912
import java.time.temporal.TemporalAmount;
@@ -74,17 +77,50 @@ private Path resolveContentFile(String operation, String filename) {
7477
return cacheNamespaceDir.resolve(operation).resolve(filename);
7578
}
7679

77-
private CacheIndex loadCacheIndex() throws IOException {
80+
private CacheIndex loadCacheIndex() {
7881
final Path cacheIndexPath = cacheNamespaceDir.resolve(CACHE_INDEX_FILENAME);
7982
if (Files.exists(cacheIndexPath)) {
8083
log.debug("Loading cache index from {}", cacheIndexPath);
81-
return objectMapper.readValue(cacheIndexPath.toFile(), CacheIndex.class);
84+
try {
85+
return objectMapper.readValue(cacheIndexPath.toFile(), CacheIndex.class);
86+
} catch (IOException e) {
87+
log.warn("Failed to load API cache index from {}", cacheIndexPath, e);
88+
wipeCacheDirectory();
89+
return new CacheIndex();
90+
}
8291
}
8392
else {
8493
return new CacheIndex();
8594
}
8695
}
8796

97+
private void wipeCacheDirectory() {
98+
if (!Files.exists(cacheNamespaceDir)) {
99+
log.debug("Skipping wipe of non-existent cache directory {}", cacheNamespaceDir);
100+
return;
101+
}
102+
103+
log.debug("Wiping cache directory {}", cacheNamespaceDir);
104+
try {
105+
Files.walkFileTree(cacheNamespaceDir, new SimpleFileVisitor<Path>() {
106+
@Override
107+
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
108+
if (file.getFileName().toString().endsWith(".json")) {
109+
try {
110+
log.debug("Wiping cache file {}", file);
111+
Files.delete(file);
112+
} catch (IOException e) {
113+
log.warn("Failed to delete cache file {}", file, e);
114+
}
115+
}
116+
return FileVisitResult.CONTINUE;
117+
}
118+
});
119+
} catch (IOException e) {
120+
log.warn("Unexpected failure while wiping cache directory", e);
121+
}
122+
}
123+
88124
@Override
89125
public <R> Mono<R> cache(String operation, Class<R> returnType, Mono<R> resolver, Object... keys) {
90126
final String keysKey = Stream.of(keys)

0 commit comments

Comments
 (0)