|
|
|
|
|
|
| CACHE_DIR <- "./cache_data"
|
|
|
|
|
| if (!dir.exists(CACHE_DIR)) {
|
| dir.create(CACHE_DIR, recursive = TRUE)
|
| }
|
|
|
|
|
|
|
|
|
|
|
|
|
| generate_cache_key <- function(operation_name, ...) {
|
|
|
| args_list <- list(...)
|
|
|
|
|
|
|
| if (length(args_list) > 0) {
|
| if (!is.null(names(args_list))) {
|
| args_list <- args_list[order(names(args_list))]
|
| }
|
|
|
| args_digest <- digest::digest(lapply(args_list, deparse))
|
| key_string <- paste(operation_name, args_digest, sep = "_")
|
| } else {
|
| key_string <- operation_name
|
| }
|
|
|
|
|
| key_string <- gsub("[^a-zA-Z0-9_.-]", "_", key_string)
|
| return(paste0(key_string, ".rds"))
|
| }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| get_cached_item <- function(key, max_age_seconds = NULL) {
|
| cache_file_path <- file.path(CACHE_DIR, key)
|
| if (file.exists(cache_file_path)) {
|
| if (!is.null(max_age_seconds)) {
|
| file_info <- file.info(cache_file_path)
|
| if (difftime(Sys.time(), file_info$mtime, units = "secs") > max_age_seconds) {
|
|
|
| message(paste("Cache stale for key:", key, "- Recomputing."))
|
| return(NULL)
|
| }
|
| }
|
| message(paste("Cache hit for key:", key))
|
| return(readRDS(cache_file_path))
|
| } else {
|
| message(paste("Cache miss for key:", key))
|
| return(NULL)
|
| }
|
| }
|
|
|
|
|
|
|
|
|
|
|
| save_cached_item <- function(key, value) {
|
| if (is.null(value)) {
|
|
|
|
|
| message(paste("Skipping saving NULL value to cache for key:", key))
|
| return()
|
| }
|
| cache_file_path <- file.path(CACHE_DIR, key)
|
| tryCatch({
|
| saveRDS(value, file = cache_file_path)
|
| message(paste("Saved item to cache. Key:", key))
|
| }, error = function(e) {
|
| warning(paste("Error saving item to cache for key:", key, ":", e$message))
|
| })
|
| }
|
|
|
|
|
| clear_all_cache <- function() {
|
| files_in_cache <- list.files(CACHE_DIR, full.names = TRUE)
|
| if (length(files_in_cache) > 0) {
|
| removed_files <- file.remove(files_in_cache)
|
| message(paste("Cleared", sum(removed_files), "files from cache."))
|
| } else {
|
| message("Cache directory is already empty.")
|
| }
|
| }
|
|
|
|
|
| if (!requireNamespace("digest", quietly = TRUE)) {
|
|
|
|
|
|
|
| message("Package 'digest' is not installed. Cache key generation might not be robust. Please install it.")
|
| } |