|
| 1 | +#' Fetch a remote COG through the on-disk cache |
| 2 | +#' |
| 3 | +#' Given a remote `href` (http/https), downloads the file once to the cd |
| 4 | +#' cache directory and returns a local path; subsequent calls read the |
| 5 | +#' local copy instead of re-pulling from the network. Freshness is |
| 6 | +#' checked with a cheap HTTP HEAD request (comparing the S3 ETag), so a |
| 7 | +#' monthly catalog republish is picked up automatically while repeat |
| 8 | +#' builds do near-zero egress. Local paths — and non-http URLs such as |
| 9 | +#' `s3://`, which GDAL reads directly — are returned unchanged. |
| 10 | +#' |
| 11 | +#' @param href Character. Path or URL to a COG. |
| 12 | +#' @param refresh Logical. If `TRUE`, force a re-download even when a |
| 13 | +#' valid cached copy exists. Default `FALSE`. |
| 14 | +#' @param cache_dir Character. Override the cache location. If `NULL`, |
| 15 | +#' uses [cd_cache_path()]. |
| 16 | +#' |
| 17 | +#' @details |
| 18 | +#' Freshness uses the ETag when the server provides one, falling back to |
| 19 | +#' the `Content-Length` size when it does not. A host that returns |
| 20 | +#' neither validator cannot be proven fresh, so the file is re-downloaded |
| 21 | +#' on each call (safe, but un-cached) — S3, the default host, always |
| 22 | +#' returns both. Revalidation can be disabled for a fully-offline fast |
| 23 | +#' path with `options(cd.cache_revalidate = FALSE)`, which serves any |
| 24 | +#' existing cached copy without an HTTP HEAD. When the HEAD fails (e.g. |
| 25 | +#' offline) but a cached copy exists, the cached copy is served with a |
| 26 | +#' message. Downloads are written to a temporary file, validated against |
| 27 | +#' the advertised `Content-Length`, then atomically renamed, so a |
| 28 | +#' truncated download is never served as complete. |
| 29 | +#' |
| 30 | +#' @return Character path to the local (cached) file, or `href` |
| 31 | +#' unchanged for local / non-http inputs. |
| 32 | +#' |
| 33 | +#' @examples |
| 34 | +#' # Local files pass through untouched: |
| 35 | +#' f <- system.file("extdata", "example_climate.tif", package = "cd") |
| 36 | +#' identical(cd_cache_fetch(f), f) |
| 37 | +#' |
| 38 | +#' @export |
| 39 | +cd_cache_fetch <- function(href, refresh = FALSE, cache_dir = NULL) { |
| 40 | + if (length(href) != 1L || is.na(href) || !cd_is_remote(href)) { |
| 41 | + return(href) |
| 42 | + } |
| 43 | + |
| 44 | + dir <- cd_cache_path(cache_dir) |
| 45 | + ext <- tools::file_ext(href) |
| 46 | + key <- rlang::hash(href) |
| 47 | + fname <- if (nzchar(ext)) paste0(key, ".", ext) else key |
| 48 | + local_path <- file.path(dir, fname) |
| 49 | + meta_path <- paste0(local_path, ".meta") |
| 50 | + |
| 51 | + have_local <- file.exists(local_path) && file.exists(meta_path) |
| 52 | + revalidate <- isTRUE(getOption("cd.cache_revalidate", default = TRUE)) |
| 53 | + |
| 54 | + # Offline fast path: trust an existing cache without a HEAD request. |
| 55 | + if (have_local && !refresh && !revalidate) { |
| 56 | + return(local_path) |
| 57 | + } |
| 58 | + |
| 59 | + head <- cd_remote_head(href) |
| 60 | + |
| 61 | + # HEAD failed (offline / server error): serve a cached copy if present. |
| 62 | + if (is.null(head)) { |
| 63 | + if (have_local && !refresh) { |
| 64 | + rlang::inform( |
| 65 | + paste0("cd_cache_fetch: could not reach '", href, |
| 66 | + "'; serving cached copy.") |
| 67 | + ) |
| 68 | + return(local_path) |
| 69 | + } |
| 70 | + stop("cd_cache_fetch: failed to reach '", href, |
| 71 | + "' and no cached copy is available.", call. = FALSE) |
| 72 | + } |
| 73 | + |
| 74 | + # Valid cache: serve local, no download. |
| 75 | + if (have_local && !refresh) { |
| 76 | + meta <- jsonlite::read_json(meta_path) |
| 77 | + if (cd_cache_valid(head, meta)) { |
| 78 | + return(local_path) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + # Download to a temp file, validate size, atomic rename, write meta. |
| 83 | + tmp <- tempfile(tmpdir = dir, fileext = if (nzchar(ext)) paste0(".", ext) else "") |
| 84 | + on.exit(if (file.exists(tmp)) unlink(tmp), add = TRUE) |
| 85 | + cd_remote_download(href, tmp) |
| 86 | + |
| 87 | + if (!is.null(head$size) && !is.na(head$size)) { |
| 88 | + got <- file.size(tmp) |
| 89 | + if (is.na(got) || got != head$size) { |
| 90 | + stop("cd_cache_fetch: incomplete download of '", href, "' (", |
| 91 | + got, " of ", head$size, " bytes).", call. = FALSE) |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + if (!file.rename(tmp, local_path)) { |
| 96 | + stop("cd_cache_fetch: failed to move the download into the cache for '", |
| 97 | + href, "'.", call. = FALSE) |
| 98 | + } |
| 99 | + jsonlite::write_json( |
| 100 | + list(url = href, etag = head$etag, size = head$size, |
| 101 | + downloaded_at = format(Sys.time(), "%Y-%m-%dT%H:%M:%S%z")), |
| 102 | + meta_path, auto_unbox = TRUE |
| 103 | + ) |
| 104 | + local_path |
| 105 | +} |
| 106 | + |
| 107 | +#' Is an href a cacheable remote (http/https) URL? |
| 108 | +#' @noRd |
| 109 | +cd_is_remote <- function(href) { |
| 110 | + grepl("^https?://", href) |
| 111 | +} |
| 112 | + |
| 113 | +#' Is a cached copy still valid against fresh HEAD metadata? |
| 114 | +#' |
| 115 | +#' Prefers the ETag; falls back to Content-Length size when the server |
| 116 | +#' (or the stored meta) carries no ETag, so ETag-less hosts still get a |
| 117 | +#' cache hit instead of re-downloading on every call. |
| 118 | +#' @noRd |
| 119 | +cd_cache_valid <- function(head, meta) { |
| 120 | + if (!is.null(head$etag) && !is.null(meta$etag)) { |
| 121 | + return(identical(head$etag, meta$etag)) |
| 122 | + } |
| 123 | + if (!is.null(head$size) && !is.na(head$size) && !is.null(meta$size)) { |
| 124 | + return(isTRUE(as.numeric(meta$size) == head$size)) |
| 125 | + } |
| 126 | + FALSE |
| 127 | +} |
| 128 | + |
| 129 | +#' HTTP HEAD a remote COG; return its ETag and size, or NULL on failure. |
| 130 | +#' @noRd |
| 131 | +cd_remote_head <- function(href) { |
| 132 | + handle <- curl::new_handle(nobody = TRUE) |
| 133 | + res <- tryCatch( |
| 134 | + curl::curl_fetch_memory(href, handle = handle), |
| 135 | + error = function(e) NULL |
| 136 | + ) |
| 137 | + if (is.null(res) || res$status_code >= 400) { |
| 138 | + return(NULL) |
| 139 | + } |
| 140 | + hdrs <- curl::parse_headers_list(res$headers) |
| 141 | + etag <- hdrs[["etag"]] |
| 142 | + cl <- hdrs[["content-length"]] |
| 143 | + list( |
| 144 | + etag = if (!is.null(etag)) gsub('"', "", etag) else NULL, |
| 145 | + size = if (!is.null(cl)) as.numeric(cl) else NA_real_ |
| 146 | + ) |
| 147 | +} |
| 148 | + |
| 149 | +#' Download a remote COG to destfile (binary). |
| 150 | +#' @noRd |
| 151 | +cd_remote_download <- function(href, destfile) { |
| 152 | + curl::curl_download(href, destfile, mode = "wb") |
| 153 | +} |
0 commit comments