Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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