diff --git a/.claude/rules/r-package-conventions.md b/.claude/rules/r-package-conventions.md index ea173f2..cc07ba2 100644 --- a/.claude/rules/r-package-conventions.md +++ b/.claude/rules/r-package-conventions.md @@ -114,16 +114,24 @@ This is the package's most important invariant. `download_metadata()` uses `aop_fetch()` too (GitHub first, then Ipea) and caches `metadata.csv` only after `read_metadata()` validates it. `check_connection()` (curl) is used only by `aopdata_dictionary()`. -- **Mirrors:** `metadata.csv` comes from the GitHub release `v1.0.0` first and +- **Mirrors:** `metadata.csv` comes from the GitHub release `data_release` + (`R/aopdata.R`, currently `v1.0.0`) first and the Ipea server (`www.ipea.gov.br/geobr/aopdata/`) as fallback. Data files come from the Ipea URL in `metadata$download_path2` first, with the GitHub release `v1.0.0` as fallback. Keep both mirrors working; never hardcode a single server. -- **Cache:** downloads go to `tempdir()` only (session cache). Files are - written to `.part` and renamed only when complete; a cached file that - can't be read is deleted. No `resume`. - Nothing is written outside `tempdir()`. **[NEW]** a persistent cache - (`tools::R_user_dir()`) would be a user-facing change and needs a plan. +- **Cache (`R/cache.R`):** downloads go to a persistent cache, + `get_aopdata_cache_dir()` (default `tools::R_user_dir("aopdata", "cache")`; + `set_aopdata_cache_dir(path)` or `options(aopdata.cache_dir)` put it in an + `aopdata` folder inside `path`), in `aopdata_data_release_` + (`data_dir()`). Old release folders are deleted once per session + (`delete_old_releases()`, opt-out `aopdata.keep_old_cache`). Files are + written to `..part` and renamed only when complete; a cached file + that can't be read is deleted. No `resume`. The session copy of + `metadata.csv` stays in `tempdir()`; a copy in the cache is used only when + it can't be downloaded (`inform_cache()`, class `aopdata_cache`). + **Maintainer rule:** Ipea URLs are not versioned, so any change to the + hosted files requires bumping `data_release` (and the GitHub release tag). - Network code is wrapped in `# nocov start` / `# nocov end` or `# nocov`. ## A4. data.table and sf @@ -201,13 +209,17 @@ This is the package's most important invariant. `paths` and returns statuses) and expect `NULL` plus an `aopdata_network` message. Mocking `check_connection` no longer reaches `download_data()`. Fixture files use fake basenames (`aoptest_*`) so they - can't poison the shared `tempdir()` cache. Needs testthat ≥ 3.1.7. + can't poison the shared cache. Needs testthat ≥ 3.1.7. + - `setup-cache.R` points `tools::R_user_dir()` to `tempdir()` (via + `R_USER_CACHE_DIR` / `R_USER_CONFIG_DIR`); tests never touch the real + user cache or config. - Real-network tests also need `testthat::skip_if_offline()` when added. - `tests/tests_rafa/` is the maintainer's scratch; leave it alone. ## A9. NEWS.md -Version headers are `# aopdata vX.Y.Z`. Sections are bold lines, not `##`: +Version headers are `# aopdata vX.Y.Z`; unreleased changes go under +`# aopdata (development version)` until the maintainer sets the version. Sections are bold lines, not `##`: `**Major changes**`, `**Minor changes**`, `**Bug fixes**` (add `**New features**` only if needed). Bullets are plain sentences; packages as `{pkg}`, functions in backticks. @@ -243,7 +255,7 @@ Version headers are `# aopdata vX.Y.Z`. Sections are bold lines, not `##`: | Red flag | Do instead | |---|---| | `library()`/`require()` in `R/` | `pkg::fun()` | -| Writing outside `tempdir()` | Write only to `tempdir()` or user-supplied paths | +| Writing outside `tempdir()` and the cache | Write only to `tempdir()`, `get_aopdata_cache_dir()` or user-supplied paths; examples/tests never write the real cache | | `stop()` / uncaught error on a network failure | `inform_failure()` + `return(invisible(NULL))` | | Reader result used without `is.null()` check | `check_downloaded_obj()` + early return | | A single hardcoded server URL | Ipea + GitHub-release mirrors (A3) | @@ -263,7 +275,7 @@ Version headers are `# aopdata vX.Y.Z`. Sections are bold lines, not `##`: [ ] pkg::fun() everywhere (except the @importFrom set / ggplot2 in docs) [ ] reader follows the A2 skeleton; NULL propagates at every call site [ ] no error on network failure; one informative cli message; tested offline with a mock -[ ] downloads only to tempdir(); both mirrors still used +[ ] downloads only to the cache (data_dir()); both mirrors still used [ ] user-supplied objects never modified by reference [ ] cli::cli_* for new messages [ ] roxygen: templates, @family, @return, @examplesIf NOT_CRAN diff --git a/README.md b/README.md index 8584a5a..015d4ee 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,24 @@ h3_for <- read_grid(city = 'Fortaleza') ``` +### Cache + +Downloaded files are saved in a cache directory that persists across R sessions, so each file is downloaded only once. The cache is versioned by data release: files from previous releases are deleted automatically. + +``` +# where files are cached +get_aopdata_cache_dir() + +# list cached files +list_aopdata_cache() + +# cache in an 'aopdata' folder inside another directory (kept across sessions) +set_aopdata_cache_dir("path/to/dir") + +# delete the cache +delete_aopdata_cache() +``` + ### Note In all of the functions above, note that: diff --git a/r-package/DESCRIPTION b/r-package/DESCRIPTION index de29dc2..10b517c 100644 --- a/r-package/DESCRIPTION +++ b/r-package/DESCRIPTION @@ -32,6 +32,7 @@ Imports: methods, rlang (>= 1.0.0), sf (>= 0.9-3), + tools, utils Suggests: covr, diff --git a/r-package/NAMESPACE b/r-package/NAMESPACE index 3c8bfb5..9898f1a 100644 --- a/r-package/NAMESPACE +++ b/r-package/NAMESPACE @@ -1,10 +1,14 @@ # Generated by roxygen2: do not edit by hand export(aopdata_dictionary) +export(delete_aopdata_cache) +export(get_aopdata_cache_dir) +export(list_aopdata_cache) export(read_access) export(read_grid) export(read_landuse) export(read_population) +export(set_aopdata_cache_dir) importFrom(data.table, ":=", setDT diff --git a/r-package/NEWS.md b/r-package/NEWS.md index 1a8f0bc..5ebc4bb 100644 --- a/r-package/NEWS.md +++ b/r-package/NEWS.md @@ -1,3 +1,11 @@ +# aopdata (development version) + +**Major changes** + +- Downloaded files are now cached in a directory that persists across R sessions (by default given by `tools::R_user_dir()`), so each file is downloaded only once. Previously files were cached in `tempdir()` and downloaded again in every session. The cache is versioned by data release: files from previous data releases are deleted automatically the first time data is downloaded in a session (set `options(aopdata.keep_old_cache = TRUE)` to keep them). A file replaced on the server without a new data release is not downloaded again. +- New functions to manage the cache: `set_aopdata_cache_dir()` (caches files in an `aopdata` folder inside a directory of your choice, kept across sessions), `get_aopdata_cache_dir()`, `list_aopdata_cache()` and `delete_aopdata_cache()`. Set `options(aopdata.cache_dir = "")` to use another cache directory in the current session only, e.g. `options(aopdata.cache_dir = tempdir())`. +- Cached data can now be read offline: a copy of the metadata is kept in the cache and used for the rest of the session when the metadata can't be downloaded. Messages about the cache have the condition class `aopdata_cache`. + # aopdata v1.2.0 **Major changes** diff --git a/r-package/R/aopdata.R b/r-package/R/aopdata.R index 4bb767b..db32023 100644 --- a/r-package/R/aopdata.R +++ b/r-package/R/aopdata.R @@ -25,3 +25,11 @@ if(getRversion() >= "2.15.1") utils::globalVariables( c('geometry', 'i.geom', 'id_hex', 'type', '.', ':=')) + + +# tag of the data release on GitHub; it also names the cache folder, so any +# change to the hosted files requires a new tag +data_release <- "v1.0.0" + +# session state (e.g. whether old data releases were already deleted) +aopdata_env <- new.env(parent = emptyenv()) diff --git a/r-package/R/cache.R b/r-package/R/cache.R new file mode 100644 index 0000000..31ba277 --- /dev/null +++ b/r-package/R/cache.R @@ -0,0 +1,292 @@ +#' Manage the aopdata cache +#' +#' @description +#' aopdata saves the files it downloads in a cache directory, so a file is +#' downloaded only once and is read from the cache in later R sessions. +#' +#' - `set_aopdata_cache_dir()` sets a custom location for the cache: the cache +#' directory is an `aopdata` folder created inside `path` (or `path` itself, +#' if it is already a folder named `aopdata`). The choice is +#' saved and kept across R sessions. `path = NULL` goes back to the default +#' cache directory, given by [tools::R_user_dir()]. +#' - `get_aopdata_cache_dir()` returns the cache directory in use. +#' - `list_aopdata_cache()` lists the cached files. +#' - `delete_aopdata_cache()` deletes the cached files and the cache +#' directory. Files in the cache directory that were not saved by aopdata +#' are kept, and so is the directory then. +#' +#' @details +#' Files are saved in a subfolder named after the data release +#' (`aopdata_data_release_`), so a new data release never reads files +#' cached from a previous one. Files cached from previous data releases are +#' deleted the first time data is downloaded in a session. Set +#' `options(aopdata.keep_old_cache = TRUE)` to keep them, for example when two +#' versions of aopdata with different data releases share one cache. +#' +#' The cache is keyed on the data release of the installed package: a file is +#' not downloaded again while the package's data release stays the same. +#' +#' To use a cache directory only in the current session, without saving it, +#' set `options(aopdata.cache_dir = "")`, e.g. +#' `options(aopdata.cache_dir = tempdir())`. As with `set_aopdata_cache_dir()`, +#' the cache directory is an `aopdata` folder inside that path. The option +#' takes precedence over `set_aopdata_cache_dir()`. +#' +#' A copy of the metadata of the data files is kept in the cache. When the +#' metadata can't be downloaded (e.g. offline), this copy is used for the rest +#' of the session, so cached data can still be read. A message of class +#' `aopdata_cache` says so. +#' +#' @param path A string with the path of a directory in which the cache +#' directory (an `aopdata` folder) is created, or `NULL` to use the +#' default cache directory. +#' @param verbose Logical. Whether to print a message. Defaults to `TRUE`. +#' +#' @return +#' - `set_aopdata_cache_dir()`: the path of the cache directory, invisibly. +#' - `get_aopdata_cache_dir()`: the path of the cache directory. +#' - `list_aopdata_cache()`: a character vector with the paths of the cached +#' files. +#' - `delete_aopdata_cache()`: `TRUE`, invisibly. +#' +#' @name aopdata_cache +NULL + + + + +#' @rdname aopdata_cache +#' @export +#' @examplesIf interactive() +#' # use a custom cache directory, then go back to the previous setting +#' had_config <- file.exists(file.path(tools::R_user_dir("aopdata", "config"), +#' "cache_dir")) +#' old <- get_aopdata_cache_dir() +#' set_aopdata_cache_dir(tempdir()) +#' set_aopdata_cache_dir(if (had_config) old else NULL) +set_aopdata_cache_dir <- function(path, verbose = TRUE) { + + abort_if_invalid(checkmate::check_string(path, null.ok = TRUE, + min.chars = 1), "path") + abort_if_invalid(checkmate::check_flag(verbose), "verbose") + + config_file <- config_cache_file() + + # back to the default directory + if (is.null(path)) { + unlink(config_file) + cache_dir <- default_cache_dir() + } else { + cache_dir <- cache_root(path) + dir.create(cache_dir, recursive = TRUE, showWarnings = FALSE) + if (!dir.exists(cache_dir)) { + cli::cli_abort( + "Could not create the cache directory {.file {cache_dir}}.", + class = "aopdata_error") + } + dir.create(dirname(config_file), recursive = TRUE, showWarnings = FALSE) + writeLines(cache_dir, config_file) + } + + if (isTRUE(verbose)) { + cli::cli_inform( + c("i" = "aopdata files will be cached in {.file {cache_dir}}."), + class = "aopdata_cache") + } + + return(invisible(cache_dir)) +} + + + + +#' @rdname aopdata_cache +#' @export +#' @examples +#' get_aopdata_cache_dir() +get_aopdata_cache_dir <- function() { + + # session-only option first (a folder inside that path) + path <- getOption("aopdata.cache_dir") + if (is.character(path) && length(path) == 1 && !is.na(path) && nzchar(path)) { + return(cache_root(path)) + } + + # then the saved setting, then the default + config_file <- config_cache_file() + cache_dir <- if (file.exists(config_file)) { + tryCatch(readLines(config_file, n = 1, warn = FALSE), + error = function(e) NULL) + } + if (length(cache_dir) != 1 || is.na(cache_dir) || !nzchar(cache_dir)) { + return(default_cache_dir()) + } + + return(normalize_dir(cache_dir)) +} + + + + +#' @rdname aopdata_cache +#' @export +#' @examples +#' list_aopdata_cache() +list_aopdata_cache <- function() { + files <- list.files(get_aopdata_cache_dir(), recursive = TRUE, + full.names = TRUE) + files[!grepl("[.]part$", files)] +} + + + + +#' @rdname aopdata_cache +#' @export +#' @examplesIf interactive() +#' # delete a cache directory used only in this session +#' old <- options(aopdata.cache_dir = tempdir()) +#' delete_aopdata_cache() +#' options(old) +delete_aopdata_cache <- function(verbose = TRUE) { + + abort_if_invalid(checkmate::check_flag(verbose), "verbose") + + # only the folders aopdata creates, then the cache directory if nothing + # else is left in it: an existing folder named 'aopdata' may hold the + # user's own files + cache_dir <- get_aopdata_cache_dir() + unlink(release_dirs(), recursive = TRUE, force = TRUE) + if (dir.exists(cache_dir) && + length(list.files(cache_dir, all.files = TRUE, no.. = TRUE)) == 0) { + unlink(cache_dir, recursive = TRUE, force = TRUE) + } + + if (isTRUE(verbose)) { + cli::cli_inform( + c("v" = "Deleted the aopdata files cached in {.file {cache_dir}}."), + class = "aopdata_cache") + } + + return(invisible(TRUE)) +} + + + + +#' Default cache directory +#' +#' @return The path of the default cache directory. +#' @keywords internal +default_cache_dir <- function() { + normalize_dir(tools::R_user_dir("aopdata", which = "cache")) +} + + + + +#' Path of the file that stores a custom cache directory +#' +#' @return The path of the config file (it may not exist). +#' @keywords internal +config_cache_file <- function() { + file.path(tools::R_user_dir("aopdata", which = "config"), "cache_dir") +} + + + + +#' Cache directory inside a path chosen by the user +#' +#' @param path A directory path. +#' +#' @return The absolute path of the `aopdata` folder inside `path`, or of +#' `path` itself if it is already named `aopdata` (so the result of +#' [get_aopdata_cache_dir()] can be passed back). +#' @keywords internal +cache_root <- function(path) { + path <- normalize_dir(path) + if (basename(path) == "aopdata") { return(path) } + file.path(path, "aopdata") +} + + + + +#' Make a directory path absolute +#' +#' @param path A directory path. +#' +#' @return The absolute path, with forward slashes. +#' @keywords internal +normalize_dir <- function(path) { + normalizePath(path.expand(path), winslash = "/", mustWork = FALSE) +} + + + + +#' Folders of data releases in the cache +#' +#' @return The paths of the `aopdata_data_release_*` folders in the cache +#' directory. +#' @keywords internal +release_dirs <- function() { + dirs <- list.files(get_aopdata_cache_dir(), + pattern = "^aopdata_data_release_", + full.names = TRUE) + dirs[dir.exists(dirs)] +} + + + + +#' Folder of the current data release in the cache +#' +#' @description Deletes old data releases (once per session) and creates the +#' folder of the current one if needed. Never errors: the caller +#' checks that the folder exists. +#' +#' @return The path of the folder. +#' @keywords internal +data_dir <- function() { + delete_old_releases() + path <- file.path(get_aopdata_cache_dir(), + paste0("aopdata_data_release_", data_release)) + dir.create(path, recursive = TRUE, showWarnings = FALSE) + return(path) +} + + + + +#' Delete files cached from previous data releases +#' +#' @description Runs once per session. Skipped when +#' `options(aopdata.keep_old_cache = TRUE)`. +#' +#' @return The paths of the deleted folders, invisibly. +#' @keywords internal +delete_old_releases <- function() { + + if (isTRUE(aopdata_env$old_cache_checked) || + isTRUE(getOption("aopdata.keep_old_cache", FALSE))) { + return(invisible(character(0))) + } + aopdata_env$old_cache_checked <- TRUE + + dirs <- release_dirs() + old <- dirs[basename(dirs) != paste0("aopdata_data_release_", data_release)] + if (length(old) == 0) { return(invisible(character(0))) } + + unlink(old, recursive = TRUE, force = TRUE) + deleted <- old[!dir.exists(old)] + + if (length(deleted) > 0) { + releases <- sub("^aopdata_data_release_", "", basename(deleted)) + inform_cache(paste0("Deleted the files cached from previous data releases ", + "of aopdata (", paste(releases, collapse = ", "), ").")) + } + + return(invisible(deleted)) +} diff --git a/r-package/R/download_metadata.R b/r-package/R/download_metadata.R index 0e3ec2c..5bd7c3e 100644 --- a/r-package/R/download_metadata.R +++ b/r-package/R/download_metadata.R @@ -4,7 +4,9 @@ #' fails, from the Ipea server, and caches it in `tempdir()` for #' the session. A file is cached only once it has been read #' successfully; a cached file that can't be read is downloaded -#' again. +#' again. A copy is also kept in the cache directory; when the +#' metadata can't be downloaded, that copy is used for the rest +#' of the session. #' #' @return A `data.table` with the metadata, or `NULL` (with a message) if it #' could not be downloaded. @@ -21,6 +23,8 @@ download_metadata <- function(){ if (!is.null(metadata)) { return(metadata) } if (!curl::has_internet()) { + metadata <- use_cached_metadata(tempf) + if (!is.null(metadata)) { return(metadata) } inform_failure("No internet connection.") return(invisible(NULL)) } @@ -30,7 +34,8 @@ download_metadata <- function(){ on.exit(unlink(part[file.exists(part)]), add = TRUE) # try the GitHub release, then the Ipea server - urls <- c('https://github.com/ipea/aopdata/releases/download/v1.0.0/metadata.csv', + urls <- c(paste0('https://github.com/ipea/aopdata/releases/download/', + data_release, '/metadata.csv'), 'https://www.ipea.gov.br/geobr/aopdata/metadata/metadata.csv') for (u in urls) { @@ -43,10 +48,14 @@ download_metadata <- function(){ metadata <- if (identical(status, "ok")) read_metadata(part) else NULL if (!is.null(metadata)) { suppressWarnings(file.rename(part, tempf)) + save_cached_metadata(tempf) return(metadata) } } + metadata <- use_cached_metadata(tempf) + if (!is.null(metadata)) { return(metadata) } + msg <- paste("Could not download the metadata from GitHub or the Ipea server.", "Please try again later.") inform_failure(msg) @@ -56,6 +65,62 @@ download_metadata <- function(){ +#' Path of the copy of the metadata kept in the cache directory +#' +#' @return The path (the file may not exist). +#' @keywords internal +#' +cached_metadata_file <- function() { + file.path(data_dir(), "metadata_aopdata.csv") +} + + + + +#' Keep a copy of the metadata in the cache directory +#' +#' @param tempf Path of the metadata cached in this session. +#' +#' @return `NULL`, invisibly. A failure to save the copy is ignored. +#' @keywords internal +#' +save_cached_metadata <- function(tempf) { + dest <- cached_metadata_file() + part <- paste0(dest, ".", Sys.getpid(), ".part") + ok <- suppressWarnings(file.copy(tempf, part, overwrite = TRUE)) + if (isTRUE(ok)) { suppressWarnings(file.rename(part, dest)) } + unlink(part) + return(invisible(NULL)) +} + + + + +#' Use the copy of the metadata kept in the cache directory +#' +#' @description Used when the metadata can't be downloaded. The copy is also +#' saved as the metadata of this session, so later calls neither +#' try to download it nor message again. +#' +#' @param tempf Path of the metadata cached in this session. +#' +#' @return A `data.table` with the metadata, or `NULL` if there is no valid +#' copy. +#' @keywords internal +#' +use_cached_metadata <- function(tempf) { + metadata <- read_metadata(cached_metadata_file()) + if (is.null(metadata)) { return(NULL) } + + suppressWarnings(file.copy(cached_metadata_file(), tempf, overwrite = TRUE)) + inform_cache(paste("Could not download the metadata; using the copy saved", + "in the cache. Only cached data can be read.")) + return(metadata) +} + + + + #' Read and validate a metadata file #' #' @param path Path to a metadata csv file. diff --git a/r-package/R/utils.R b/r-package/R/utils.R index 8cdbb09..45e0c9e 100644 --- a/r-package/R/utils.R +++ b/r-package/R/utils.R @@ -191,12 +191,13 @@ select_metadata <- function(t=NULL, c=NULL, y=NULL, m=NULL){ -#' Download data to a temporary directory. +#' Download data to the cache directory. #' -#' @description Downloads the requested files to a temporary directory (the -#' session cache) and reads them. Each file is downloaded from -#' the Ipea server first and, if that fails, from the GitHub -#' release mirror. +#' @description Downloads the requested files to the cache folder of the +#' current data release (see [get_aopdata_cache_dir()]) and reads +#' them. Files already cached are not downloaded again. Each file +#' is downloaded from the Ipea server first and, if that fails, +#' from the GitHub release mirror. #' #' @param url A string with the url address of aop dataset #' @param progress_bar Logical. Whether to display a progress bar. @@ -215,14 +216,22 @@ download_data <- function(url, progress_bar){ ) } - # dest files in the session cache, and partial files while downloading - dest <- file.path(tempdir(), basename(url)) - part <- paste0(dest, ".part") + # cache folder of the current data release + cache_dir <- data_dir() + if (!dir.exists(cache_dir)) { + inform_failure(paste("Could not create the cache directory", cache_dir)) + return(invisible(NULL)) + } + + # dest files in the cache, and partial files of this session while + # downloading (sessions sharing the cache don't write the same file) + dest <- file.path(cache_dir, basename(url)) + part <- paste0(dest, ".", Sys.getpid(), ".part") on.exit(unlink(part[file.exists(part)]), add = TRUE) # backup links - mirror <- paste0('https://github.com/ipea/aopdata/releases/download/v1.0.0/', - basename(url)) + mirror <- paste0('https://github.com/ipea/aopdata/releases/download/', + data_release, '/', basename(url)) sources <- list(url, mirror) labels <- c("Downloading files", "Downloading files (mirror)") @@ -243,6 +252,10 @@ download_data <- function(url, progress_bar){ # move complete downloads into the cache done <- pending & status == "ok" moved <- suppressWarnings(file.rename(part[done], dest[done])) + + # another session may have saved the same file first (on Windows, the + # rename fails while that file is open) + moved <- moved | (file.exists(dest[done]) & file.size(dest[done]) > 0) status[done] <- ifelse(moved, "ok", "http_error") } @@ -382,11 +395,11 @@ aop_fetch <- function(urls, paths, progress = FALSE, -#' Load data from tempdir to global environment +#' Load data from the cache #' -#' @description Reads data from tempdir to global environment. +#' @description Reads cached data files. #' -#' @param temps The paths of one or more data files stored in tempdir, all +#' @param temps The paths of one or more cached data files, all #' `.csv` or all `.gpkg`. #' #' @return Returns either an `sf` or a `data.frame`, depending of the data set @@ -578,3 +591,17 @@ abort_if_invalid <- function(check, arg, call = rlang::caller_env()) { inform_failure <- function(msg) { cli::cli_inform(c("x" = "{msg}"), class = "aopdata_network") } + + + + +#' Inform the user about the cache +#' +#' @param msg The message text. +#' +#' @return Signals a message of class `aopdata_cache`. +#' @keywords internal +#' +inform_cache <- function(msg) { + cli::cli_inform(c("i" = "{msg}"), class = "aopdata_cache") +} diff --git a/r-package/README.md b/r-package/README.md index 1b2fe0b..43d8ee7 100644 --- a/r-package/README.md +++ b/r-package/README.md @@ -128,6 +128,24 @@ h3_for <- read_grid(city = 'Fortaleza') ``` +### Cache + +Downloaded files are saved in a cache directory that persists across R sessions, so each file is downloaded only once. The cache is versioned by data release: files from previous releases are deleted automatically. + +``` +# where files are cached +get_aopdata_cache_dir() + +# list cached files +list_aopdata_cache() + +# cache in an 'aopdata' folder inside another directory (kept across sessions) +set_aopdata_cache_dir("path/to/dir") + +# delete the cache +delete_aopdata_cache() +``` + ### Note In all of the functions above, note that: diff --git a/r-package/man/aopdata_cache.Rd b/r-package/man/aopdata_cache.Rd new file mode 100644 index 0000000..4cc46ce --- /dev/null +++ b/r-package/man/aopdata_cache.Rd @@ -0,0 +1,90 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cache.R +\name{aopdata_cache} +\alias{aopdata_cache} +\alias{set_aopdata_cache_dir} +\alias{get_aopdata_cache_dir} +\alias{list_aopdata_cache} +\alias{delete_aopdata_cache} +\title{Manage the aopdata cache} +\usage{ +set_aopdata_cache_dir(path, verbose = TRUE) + +get_aopdata_cache_dir() + +list_aopdata_cache() + +delete_aopdata_cache(verbose = TRUE) +} +\arguments{ +\item{path}{A string with the path of a directory in which the cache +directory (an \code{aopdata} folder) is created, or \code{NULL} to use the +default cache directory.} + +\item{verbose}{Logical. Whether to print a message. Defaults to \code{TRUE}.} +} +\value{ +\itemize{ +\item \code{set_aopdata_cache_dir()}: the path of the cache directory, invisibly. +\item \code{get_aopdata_cache_dir()}: the path of the cache directory. +\item \code{list_aopdata_cache()}: a character vector with the paths of the cached +files. +\item \code{delete_aopdata_cache()}: \code{TRUE}, invisibly. +} +} +\description{ +aopdata saves the files it downloads in a cache directory, so a file is +downloaded only once and is read from the cache in later R sessions. +\itemize{ +\item \code{set_aopdata_cache_dir()} sets a custom location for the cache: the cache +directory is an \code{aopdata} folder created inside \code{path} (or \code{path} itself, +if it is already a folder named \code{aopdata}). The choice is +saved and kept across R sessions. \code{path = NULL} goes back to the default +cache directory, given by \code{\link[tools:R_user_dir]{tools::R_user_dir()}}. +\item \code{get_aopdata_cache_dir()} returns the cache directory in use. +\item \code{list_aopdata_cache()} lists the cached files. +\item \code{delete_aopdata_cache()} deletes the cached files and the cache +directory. Files in the cache directory that were not saved by aopdata +are kept, and so is the directory then. +} +} +\details{ +Files are saved in a subfolder named after the data release +(\verb{aopdata_data_release_}), so a new data release never reads files +cached from a previous one. Files cached from previous data releases are +deleted the first time data is downloaded in a session. Set +\code{options(aopdata.keep_old_cache = TRUE)} to keep them, for example when two +versions of aopdata with different data releases share one cache. + +The cache is keyed on the data release of the installed package: a file is +not downloaded again while the package's data release stays the same. + +To use a cache directory only in the current session, without saving it, +set \code{options(aopdata.cache_dir = "")}, e.g. +\code{options(aopdata.cache_dir = tempdir())}. As with \code{set_aopdata_cache_dir()}, +the cache directory is an \code{aopdata} folder inside that path. The option +takes precedence over \code{set_aopdata_cache_dir()}. + +A copy of the metadata of the data files is kept in the cache. When the +metadata can't be downloaded (e.g. offline), this copy is used for the rest +of the session, so cached data can still be read. A message of class +\code{aopdata_cache} says so. +} +\examples{ +\dontshow{if (interactive()) withAutoprint(\{ # examplesIf} +# use a custom cache directory, then go back to the previous setting +had_config <- file.exists(file.path(tools::R_user_dir("aopdata", "config"), + "cache_dir")) +old <- get_aopdata_cache_dir() +set_aopdata_cache_dir(tempdir()) +set_aopdata_cache_dir(if (had_config) old else NULL) +\dontshow{\}) # examplesIf} +get_aopdata_cache_dir() +list_aopdata_cache() +\dontshow{if (interactive()) withAutoprint(\{ # examplesIf} +# delete a cache directory used only in this session +old <- options(aopdata.cache_dir = tempdir()) +delete_aopdata_cache() +options(old) +\dontshow{\}) # examplesIf} +} diff --git a/r-package/man/cache_root.Rd b/r-package/man/cache_root.Rd new file mode 100644 index 0000000..68c4935 --- /dev/null +++ b/r-package/man/cache_root.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cache.R +\name{cache_root} +\alias{cache_root} +\title{Cache directory inside a path chosen by the user} +\usage{ +cache_root(path) +} +\arguments{ +\item{path}{A directory path.} +} +\value{ +The absolute path of the \code{aopdata} folder inside \code{path}, or of +\code{path} itself if it is already named \code{aopdata} (so the result of +\code{\link[=get_aopdata_cache_dir]{get_aopdata_cache_dir()}} can be passed back). +} +\description{ +Cache directory inside a path chosen by the user +} +\keyword{internal} diff --git a/r-package/man/cached_metadata_file.Rd b/r-package/man/cached_metadata_file.Rd new file mode 100644 index 0000000..572018d --- /dev/null +++ b/r-package/man/cached_metadata_file.Rd @@ -0,0 +1,15 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/download_metadata.R +\name{cached_metadata_file} +\alias{cached_metadata_file} +\title{Path of the copy of the metadata kept in the cache directory} +\usage{ +cached_metadata_file() +} +\value{ +The path (the file may not exist). +} +\description{ +Path of the copy of the metadata kept in the cache directory +} +\keyword{internal} diff --git a/r-package/man/config_cache_file.Rd b/r-package/man/config_cache_file.Rd new file mode 100644 index 0000000..11836cc --- /dev/null +++ b/r-package/man/config_cache_file.Rd @@ -0,0 +1,15 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cache.R +\name{config_cache_file} +\alias{config_cache_file} +\title{Path of the file that stores a custom cache directory} +\usage{ +config_cache_file() +} +\value{ +The path of the config file (it may not exist). +} +\description{ +Path of the file that stores a custom cache directory +} +\keyword{internal} diff --git a/r-package/man/data_dir.Rd b/r-package/man/data_dir.Rd new file mode 100644 index 0000000..c1000e3 --- /dev/null +++ b/r-package/man/data_dir.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cache.R +\name{data_dir} +\alias{data_dir} +\title{Folder of the current data release in the cache} +\usage{ +data_dir() +} +\value{ +The path of the folder. +} +\description{ +Deletes old data releases (once per session) and creates the +folder of the current one if needed. Never errors: the caller +checks that the folder exists. +} +\keyword{internal} diff --git a/r-package/man/default_cache_dir.Rd b/r-package/man/default_cache_dir.Rd new file mode 100644 index 0000000..4ea8382 --- /dev/null +++ b/r-package/man/default_cache_dir.Rd @@ -0,0 +1,15 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cache.R +\name{default_cache_dir} +\alias{default_cache_dir} +\title{Default cache directory} +\usage{ +default_cache_dir() +} +\value{ +The path of the default cache directory. +} +\description{ +Default cache directory +} +\keyword{internal} diff --git a/r-package/man/delete_old_releases.Rd b/r-package/man/delete_old_releases.Rd new file mode 100644 index 0000000..7c85bfb --- /dev/null +++ b/r-package/man/delete_old_releases.Rd @@ -0,0 +1,16 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cache.R +\name{delete_old_releases} +\alias{delete_old_releases} +\title{Delete files cached from previous data releases} +\usage{ +delete_old_releases() +} +\value{ +The paths of the deleted folders, invisibly. +} +\description{ +Runs once per session. Skipped when +\code{options(aopdata.keep_old_cache = TRUE)}. +} +\keyword{internal} diff --git a/r-package/man/download_data.Rd b/r-package/man/download_data.Rd index c04983f..6ac94ff 100644 --- a/r-package/man/download_data.Rd +++ b/r-package/man/download_data.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/utils.R \name{download_data} \alias{download_data} -\title{Download data to a temporary directory.} +\title{Download data to the cache directory.} \usage{ download_data(url, progress_bar) } @@ -16,9 +16,10 @@ An \code{sf} or a \code{data.frame}, or \code{NULL} (with a message) if any file could not be downloaded or read. } \description{ -Downloads the requested files to a temporary directory (the -session cache) and reads them. Each file is downloaded from -the Ipea server first and, if that fails, from the GitHub -release mirror. +Downloads the requested files to the cache folder of the +current data release (see \code{\link[=get_aopdata_cache_dir]{get_aopdata_cache_dir()}}) and reads +them. Files already cached are not downloaded again. Each file +is downloaded from the Ipea server first and, if that fails, +from the GitHub release mirror. } \keyword{internal} diff --git a/r-package/man/download_metadata.Rd b/r-package/man/download_metadata.Rd index 86eb453..0546b59 100644 --- a/r-package/man/download_metadata.Rd +++ b/r-package/man/download_metadata.Rd @@ -15,7 +15,9 @@ Downloads \code{metadata.csv} from the GitHub release or, if that fails, from the Ipea server, and caches it in \code{tempdir()} for the session. A file is cached only once it has been read successfully; a cached file that can't be read is downloaded -again. +again. A copy is also kept in the cache directory; when the +metadata can't be downloaded, that copy is used for the rest +of the session. } \examples{ \dontrun{ if (interactive()) { diff --git a/r-package/man/inform_cache.Rd b/r-package/man/inform_cache.Rd new file mode 100644 index 0000000..d417f84 --- /dev/null +++ b/r-package/man/inform_cache.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/utils.R +\name{inform_cache} +\alias{inform_cache} +\title{Inform the user about the cache} +\usage{ +inform_cache(msg) +} +\arguments{ +\item{msg}{The message text.} +} +\value{ +Signals a message of class \code{aopdata_cache}. +} +\description{ +Inform the user about the cache +} +\keyword{internal} diff --git a/r-package/man/load_data.Rd b/r-package/man/load_data.Rd index 7a4644b..161c6c1 100644 --- a/r-package/man/load_data.Rd +++ b/r-package/man/load_data.Rd @@ -2,12 +2,12 @@ % Please edit documentation in R/utils.R \name{load_data} \alias{load_data} -\title{Load data from tempdir to global environment} +\title{Load data from the cache} \usage{ load_data(temps) } \arguments{ -\item{temps}{The paths of one or more data files stored in tempdir, all +\item{temps}{The paths of one or more cached data files, all \code{.csv} or all \code{.gpkg}.} } \value{ @@ -15,6 +15,6 @@ Returns either an \code{sf} or a \code{data.frame}, depending of the data set that was downloaded } \description{ -Reads data from tempdir to global environment. +Reads cached data files. } \keyword{internal} diff --git a/r-package/man/normalize_dir.Rd b/r-package/man/normalize_dir.Rd new file mode 100644 index 0000000..e1d8d52 --- /dev/null +++ b/r-package/man/normalize_dir.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cache.R +\name{normalize_dir} +\alias{normalize_dir} +\title{Make a directory path absolute} +\usage{ +normalize_dir(path) +} +\arguments{ +\item{path}{A directory path.} +} +\value{ +The absolute path, with forward slashes. +} +\description{ +Make a directory path absolute +} +\keyword{internal} diff --git a/r-package/man/release_dirs.Rd b/r-package/man/release_dirs.Rd new file mode 100644 index 0000000..2a946c1 --- /dev/null +++ b/r-package/man/release_dirs.Rd @@ -0,0 +1,16 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cache.R +\name{release_dirs} +\alias{release_dirs} +\title{Folders of data releases in the cache} +\usage{ +release_dirs() +} +\value{ +The paths of the \verb{aopdata_data_release_*} folders in the cache +directory. +} +\description{ +Folders of data releases in the cache +} +\keyword{internal} diff --git a/r-package/man/save_cached_metadata.Rd b/r-package/man/save_cached_metadata.Rd new file mode 100644 index 0000000..4411cdd --- /dev/null +++ b/r-package/man/save_cached_metadata.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/download_metadata.R +\name{save_cached_metadata} +\alias{save_cached_metadata} +\title{Keep a copy of the metadata in the cache directory} +\usage{ +save_cached_metadata(tempf) +} +\arguments{ +\item{tempf}{Path of the metadata cached in this session.} +} +\value{ +\code{NULL}, invisibly. A failure to save the copy is ignored. +} +\description{ +Keep a copy of the metadata in the cache directory +} +\keyword{internal} diff --git a/r-package/man/use_cached_metadata.Rd b/r-package/man/use_cached_metadata.Rd new file mode 100644 index 0000000..198d98c --- /dev/null +++ b/r-package/man/use_cached_metadata.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/download_metadata.R +\name{use_cached_metadata} +\alias{use_cached_metadata} +\title{Use the copy of the metadata kept in the cache directory} +\usage{ +use_cached_metadata(tempf) +} +\arguments{ +\item{tempf}{Path of the metadata cached in this session.} +} +\value{ +A \code{data.table} with the metadata, or \code{NULL} if there is no valid +copy. +} +\description{ +Used when the metadata can't be downloaded. The copy is also +saved as the metadata of this session, so later calls neither +try to download it nor message again. +} +\keyword{internal} diff --git a/r-package/tests/testthat/helper-aopdata.R b/r-package/tests/testthat/helper-aopdata.R index cb219f3..9862c71 100644 --- a/r-package/tests/testthat/helper-aopdata.R +++ b/r-package/tests/testthat/helper-aopdata.R @@ -10,3 +10,8 @@ count_network_msgs <- function(expr) { ) n } + +# forget that old data releases were already checked in this session +reset_cache_state <- function() { + aopdata_env$old_cache_checked <- NULL +} diff --git a/r-package/tests/testthat/setup-cache.R b/r-package/tests/testthat/setup-cache.R new file mode 100644 index 0000000..8da79c6 --- /dev/null +++ b/r-package/tests/testthat/setup-cache.R @@ -0,0 +1,10 @@ +# tests never touch the user's real cache or config: tools::R_user_dir() +# reads these variables, so every test file uses folders inside tempdir() +aoptest_old_env <- Sys.getenv(c("R_USER_CACHE_DIR", "R_USER_CONFIG_DIR"), unset = NA) +aoptest_old_opt <- options(aopdata.cache_dir = NULL) +Sys.setenv( + R_USER_CACHE_DIR = file.path(tempdir(), "aoptest_user_cache"), + R_USER_CONFIG_DIR = file.path(tempdir(), "aoptest_user_config") +) + +# teardown-cache.R restores them diff --git a/r-package/tests/testthat/teardown-cache.R b/r-package/tests/testthat/teardown-cache.R new file mode 100644 index 0000000..6a91d98 --- /dev/null +++ b/r-package/tests/testthat/teardown-cache.R @@ -0,0 +1,9 @@ +# restore what setup-cache.R changed +for (v in names(aoptest_old_env)) { + if (is.na(aoptest_old_env[[v]])) { + Sys.unsetenv(v) + } else { + do.call(Sys.setenv, as.list(aoptest_old_env[v])) + } +} +options(aoptest_old_opt) diff --git a/r-package/tests/testthat/test_cache.R b/r-package/tests/testthat/test_cache.R new file mode 100644 index 0000000..99cdee2 --- /dev/null +++ b/r-package/tests/testthat/test_cache.R @@ -0,0 +1,162 @@ +context("cache") + +# skip tests because they take too much time +testthat::skip_on_cran() + +# setup-cache.R points tools::R_user_dir() to folders inside tempdir() + + +### set, get and reset the cache directory ---------------- + +testthat::test_that("set_aopdata_cache_dir creates an aopdata folder inside path", { + on.exit(set_aopdata_cache_dir(NULL, verbose = FALSE), add = TRUE) + path <- file.path(tempdir(), "aoptest_custom") + on.exit(unlink(path, recursive = TRUE), add = TRUE) + + testthat::expect_message(out <- set_aopdata_cache_dir(path)) + testthat::expect_equal(out, normalize_dir(file.path(path, "aopdata"))) + testthat::expect_true(dir.exists(out)) + testthat::expect_equal(get_aopdata_cache_dir(), out) + testthat::expect_equal(readLines(config_cache_file()), out) + + # back to the default, removing the saved setting + testthat::expect_equal(set_aopdata_cache_dir(NULL, verbose = FALSE), + default_cache_dir()) + testthat::expect_false(file.exists(config_cache_file())) + testthat::expect_equal(get_aopdata_cache_dir(), default_cache_dir()) +}) + +testthat::test_that("a relative path is saved as an absolute path", { + on.exit(set_aopdata_cache_dir(NULL, verbose = FALSE), add = TRUE) + wd <- setwd(tempdir()) + on.exit(setwd(wd), add = TRUE) + on.exit(unlink(file.path(tempdir(), "aoptest_rel"), recursive = TRUE), add = TRUE) + + out <- set_aopdata_cache_dir("aoptest_rel", verbose = FALSE) + setwd(wd) + testthat::expect_equal(get_aopdata_cache_dir(), out) + testthat::expect_true(dir.exists(out)) + testthat::expect_match(out, "aoptest_rel/aopdata$") +}) + +testthat::test_that("the aopdata.cache_dir option takes precedence, for the session", { + on.exit(set_aopdata_cache_dir(NULL, verbose = FALSE), add = TRUE) + set_aopdata_cache_dir(file.path(tempdir(), "aoptest_saved"), verbose = FALSE) + on.exit(unlink(file.path(tempdir(), "aoptest_saved"), recursive = TRUE), add = TRUE) + + old <- options(aopdata.cache_dir = file.path(tempdir(), "aoptest_opt")) + on.exit(options(old), add = TRUE) + testthat::expect_equal(get_aopdata_cache_dir(), + normalize_dir(file.path(tempdir(), "aoptest_opt", "aopdata"))) + testthat::expect_match(readLines(config_cache_file()), "aoptest_saved/aopdata$") +}) + +testthat::test_that("set_aopdata_cache_dir rejects invalid input", { + testthat::expect_error(set_aopdata_cache_dir(1), class = "aopdata_error") + testthat::expect_error(set_aopdata_cache_dir(c("a", "b")), class = "aopdata_error") + testthat::expect_error(set_aopdata_cache_dir(""), class = "aopdata_error") + testthat::expect_error(set_aopdata_cache_dir(tempdir(), verbose = NA), + class = "aopdata_error") +}) + + +testthat::test_that("the cache directory can be passed back to set_aopdata_cache_dir", { + on.exit(set_aopdata_cache_dir(NULL, verbose = FALSE), add = TRUE) + on.exit(unlink(file.path(tempdir(), "aoptest_back"), recursive = TRUE), add = TRUE) + out <- set_aopdata_cache_dir(file.path(tempdir(), "aoptest_back"), verbose = FALSE) + testthat::expect_equal(set_aopdata_cache_dir(out, verbose = FALSE), out) +}) + + +### list and delete ---------------- + +testthat::test_that("delete_aopdata_cache deletes only the aopdata folder", { + path <- file.path(tempdir(), "aoptest_user_folder") + on.exit(unlink(path, recursive = TRUE), add = TRUE) + old <- options(aopdata.cache_dir = path) + on.exit(options(old), add = TRUE) + + dir.create(path, showWarnings = FALSE) + writeLines("mine", file.path(path, "user_file.txt")) + release <- file.path(get_aopdata_cache_dir(), "aopdata_data_release_v1.0.0") + dir.create(release, recursive = TRUE) + writeLines("x", file.path(release, "aoptest_a.csv")) + + testthat::expect_equal(basename(list_aopdata_cache()), "aoptest_a.csv") + + testthat::expect_message(delete_aopdata_cache()) + testthat::expect_false(dir.exists(get_aopdata_cache_dir())) + testthat::expect_true(file.exists(file.path(path, "user_file.txt"))) + testthat::expect_length(list_aopdata_cache(), 0) +}) + +testthat::test_that("delete_aopdata_cache keeps a user's own 'aopdata' folder", { + path <- file.path(tempdir(), "aoptest_own") + on.exit(unlink(path, recursive = TRUE), add = TRUE) + old <- options(aopdata.cache_dir = path) + on.exit(options(old), add = TRUE) + + # a folder named 'aopdata' that already holds the user's files + dir.create(file.path(path, "aopdata", "R"), recursive = TRUE) + writeLines("mine", file.path(path, "aopdata", "R", "code.R")) + release <- file.path(get_aopdata_cache_dir(), "aopdata_data_release_v1.0.0") + dir.create(release) + writeLines("x", file.path(release, "aoptest_a.csv")) + + delete_aopdata_cache(verbose = FALSE) + testthat::expect_false(dir.exists(release)) + testthat::expect_true(file.exists(file.path(path, "aopdata", "R", "code.R"))) +}) + + +### old data releases ---------------- + +testthat::test_that("old data releases are deleted once per session, unless kept", { + path <- file.path(tempdir(), "aoptest_releases") + on.exit(unlink(path, recursive = TRUE), add = TRUE) + old <- options(aopdata.cache_dir = path) + on.exit(options(old), add = TRUE) + reset_cache_state() + on.exit(reset_cache_state(), add = TRUE) + + make_release <- function(tag) { + d <- file.path(get_aopdata_cache_dir(), paste0("aopdata_data_release_", tag)) + dir.create(d, recursive = TRUE, showWarnings = FALSE) + writeLines("x", file.path(d, "aoptest_a.csv")) + d + } + old_release <- make_release("v0.0.1") + current <- make_release(data_release) + other <- file.path(get_aopdata_cache_dir(), "not_a_release") + dir.create(other) + + # kept with the option + keep <- options(aopdata.keep_old_cache = TRUE) + testthat::expect_length(delete_old_releases(), 0) + options(keep) + testthat::expect_true(dir.exists(old_release)) + + # deleted, with one message + testthat::expect_message(delete_old_releases(), "v0.0.1", class = "aopdata_cache") + testthat::expect_false(dir.exists(old_release)) + testthat::expect_true(dir.exists(current)) + testthat::expect_true(dir.exists(other)) + + # only once per session + make_release("v0.0.2") + testthat::expect_silent(delete_old_releases()) + testthat::expect_true(dir.exists(file.path(get_aopdata_cache_dir(), + "aopdata_data_release_v0.0.2"))) +}) + +testthat::test_that("delete_aopdata_cache keeps a user's file named 'aopdata'", { + path <- file.path(tempdir(), "aoptest_file") + on.exit(unlink(path, recursive = TRUE), add = TRUE) + dir.create(path) + writeLines("x", file.path(path, "aopdata")) + old <- options(aopdata.cache_dir = path) + on.exit(options(old), add = TRUE) + + delete_aopdata_cache(verbose = FALSE) + testthat::expect_true(file.exists(file.path(path, "aopdata"))) +}) diff --git a/r-package/tests/testthat/test_utils.R b/r-package/tests/testthat/test_utils.R index b1b9172..d94893f 100644 --- a/r-package/tests/testthat/test_utils.R +++ b/r-package/tests/testthat/test_utils.R @@ -38,7 +38,7 @@ testthat::test_that("download_data falls back to the mirror per file, keeping or } ) urls <- paste0("https://www.ipea.gov.br/x/aoptest_", c("a", "b", "c"), ".csv") - dest <- file.path(tempdir(), basename(urls)) + dest <- file.path(data_dir(), basename(urls)) on.exit(unlink(dest), add = TRUE) out <- download_data(urls, progress_bar = FALSE) @@ -58,7 +58,7 @@ testthat::test_that("download_data returns NULL and cleans up when both servers } ) url <- "https://www.ipea.gov.br/x/aoptest_bothfail.csv" - dest <- file.path(tempdir(), basename(url)) + dest <- file.path(data_dir(), basename(url)) testthat::expect_message( out <- download_data(url, progress_bar = FALSE), @@ -66,7 +66,7 @@ testthat::test_that("download_data returns NULL and cleans up when both servers ) testthat::expect_null(out) testthat::expect_false(file.exists(dest)) - testthat::expect_false(file.exists(paste0(dest, ".part"))) + testthat::expect_length(list.files(dirname(dest), "aoptest_bothfail.*part$"), 0) }) testthat::test_that("download_data reuses a complete cached file", { @@ -74,13 +74,54 @@ testthat::test_that("download_data reuses a complete cached file", { aop_fetch = function(...) stop("aop_fetch should not be called") ) url <- "https://www.ipea.gov.br/x/aoptest_cached.csv" - dest <- file.path(tempdir(), basename(url)) + dest <- file.path(data_dir(), basename(url)) write_fixture(dest) on.exit(unlink(dest), add = TRUE) testthat::expect_s3_class(download_data(url, progress_bar = FALSE), "data.frame") }) +testthat::test_that("download_data accepts a file another session saved first", { + url <- "https://www.ipea.gov.br/x/aoptest_race.csv" + dest <- file.path(data_dir(), basename(url)) + on.exit(unlink(dest), add = TRUE) + testthat::local_mocked_bindings( + # the other session's file is saved; this session's part file is gone, + # so moving it fails + aop_fetch = function(urls, paths, progress = FALSE, label = NULL) { + write_fixture(dest) + "ok" + } + ) + testthat::expect_equal(count_network_msgs(out <- download_data(url, FALSE)), 0) + testthat::expect_s3_class(out, "data.frame") + testthat::expect_length(list.files(dirname(dest), "aoptest_race.*part$"), 0) +}) + +testthat::test_that("download_data saves files in the cache folder of the release", { + testthat::local_mocked_bindings( + aop_fetch = function(urls, paths, ...) { write_fixture(paths); "ok" } + ) + url <- "https://www.ipea.gov.br/x/aoptest_release.csv" + dest <- file.path(get_aopdata_cache_dir(), + paste0("aopdata_data_release_", data_release), basename(url)) + on.exit(unlink(dest), add = TRUE) + download_data(url, progress_bar = FALSE) + testthat::expect_true(file.exists(dest)) + testthat::expect_true(dest %in% list_aopdata_cache()) +}) + +testthat::test_that("download_data fails gracefully if the cache can't be created", { + testthat::local_mocked_bindings( + data_dir = function() file.path(tempdir(), "aoptest_no_such_dir"), + aop_fetch = function(...) stop("aop_fetch should not be called") + ) + testthat::expect_equal( + count_network_msgs(out <- download_data("https://x/aoptest_a.csv", FALSE)), 1 + ) + testthat::expect_null(out) +}) + testthat::test_that("download_data stops without the mirror when interrupted", { calls <- 0 testthat::local_mocked_bindings( @@ -107,7 +148,7 @@ testthat::test_that("download_data removes a cached file that can't be read", { } ) url <- "https://www.ipea.gov.br/x/aoptest_bad.gpkg" - dest <- file.path(tempdir(), basename(url)) + dest <- file.path(data_dir(), basename(url)) on.exit(unlink(dest), add = TRUE) testthat::expect_message( @@ -178,17 +219,33 @@ testthat::test_that("aop_fetch reports an interrupted download as aborted", { ### download_metadata (offline: aop_fetch is mocked) ---------------- -# moves the session's cached metadata aside; restore() puts it back +# moves the session's metadata and its copy in the cache aside; restore() +# puts them back stash_metadata_cache <- function() { - tempf <- file.path(tempdir(), "metadata_aopdata.csv") - backup <- tempfile(fileext = ".csv") - had_cache <- file.exists(tempf) - if (had_cache) file.rename(tempf, backup) + files <- c(file.path(tempdir(), "metadata_aopdata.csv"), cached_metadata_file()) + backup <- c(tempfile(fileext = ".csv"), tempfile(fileext = ".csv")) + had <- file.exists(files) + file.rename(files[had], backup[had]) restore <- function() { - unlink(c(tempf, paste0(tempf, ".part"))) - if (had_cache) file.rename(backup, tempf) + unlink(files) + unlink(list.files(dirname(files), "^metadata_aopdata.*part$", + full.names = TRUE)) + file.rename(backup[had], files[had]) } - list(path = tempf, restore = restore) + list(path = files[1], cached = files[2], restore = restore) +} + +# number of aopdata_cache messages signalled while evaluating expr +count_cache_msgs <- function(expr) { + n <- 0 + withCallingHandlers( + expr, + aopdata_cache = function(m) { + n <<- n + 1 + invokeRestart("muffleMessage") + } + ) + n } write_metadata_fixture <- function(path) { @@ -267,6 +324,55 @@ testthat::test_that("download_metadata says when there is no internet", { testthat::expect_null(out) }) +testthat::test_that("download_metadata keeps a copy in the cache", { + cache <- stash_metadata_cache() + on.exit(cache$restore(), add = TRUE) + testthat::local_mocked_bindings( + aop_fetch = function(urls, paths, ...) { write_metadata_fixture(paths); "ok" } + ) + download_metadata() + testthat::expect_equal(read_metadata(cache$cached)$city, "nat") +}) + +testthat::test_that("download_metadata works if the copy can't be saved", { + cache <- stash_metadata_cache() + on.exit(cache$restore(), add = TRUE) + testthat::local_mocked_bindings( + aop_fetch = function(urls, paths, ...) { write_metadata_fixture(paths); "ok" }, + cached_metadata_file = function() file.path(tempdir(), "aoptest_no_dir", "m.csv") + ) + testthat::expect_equal(count_network_msgs(meta <- download_metadata()), 0) + testthat::expect_equal(meta$city, "nat") +}) + +testthat::test_that("download_metadata uses the cached copy offline, once", { + # servers_down first: the has_internet() mock lasts until the end of the test + for (offline in c("servers_down", "no_internet")) { + cache <- stash_metadata_cache() + write_metadata_fixture(cache$cached) + if (offline == "no_internet") { + testthat::local_mocked_bindings(has_internet = function() FALSE, + .package = "curl") + } + testthat::local_mocked_bindings( + aop_fetch = function(urls, paths, ...) "conn_error" + ) + n_net <- count_network_msgs( + n_cache <- count_cache_msgs(meta <- download_metadata()) + ) + testthat::expect_equal(c(n_net, n_cache), c(0, 1)) + testthat::expect_equal(meta$city, "nat") + + # later calls in the session use it silently + n_net <- count_network_msgs( + n_cache <- count_cache_msgs(meta <- download_metadata()) + ) + testthat::expect_equal(c(n_net, n_cache), c(0, 0)) + testthat::expect_equal(meta$city, "nat") + cache$restore() + } +}) + testthat::test_that("download_metadata stops without the second source when interrupted", { cache <- stash_metadata_cache() on.exit(cache$restore(), add = TRUE)