Debian Codegraph @

R/multi_download.R

raw
1 #' Advanced download interface
2 #'
3 #' Download multiple files concurrently, with support for resuming large files.
4 #' This function is based on [multi_run()] and hence does not error in case any
5 #' of the individual requests fail; you should inspect the return value to find
6 #' out which of the downloads were completed successfully.
7 #'
8 #' Upon completion of all requests, this function returns a data frame with results.
9 #' The `success` column indicates if a request was successfully completed (regardless
10 #' of the HTTP status code). If it failed, e.g. due to a networking issue, the error
11 #' message is in the `error` column. A `success` value `NA` indicates that the request
12 #' was still in progress when the function was interrupted or reached the elapsed
13 #' `multi_timeout` and perhaps the download can be resumed if the server supports it.
14 #'
15 #' It is also important to inspect the `status_code` column to see if any of the
16 #' requests were successful but had a non-success HTTP code, and hence the downloaded
17 #' file probably contains an error page instead of the requested content.
18 #'
19 #' Note that when you set `resume = TRUE` you should expect HTTP-206 or HTTP-416
20 #' responses. The latter could indicate that the file was already complete, hence
21 #' there was no content left to resume from the server. If you try to resume a file
22 #' download but the server does not support this, success if `FALSE` and the file
23 #' will not be touched. In fact, if we request to a download to be resumed and the
24 #' server responds `HTTP 200` instead of `HTTP 206`, libcurl will error and not
25 #' download anything, because this probably means the server did not respect our
26 #' range request and is sending us the full file.
27 #'
28 #' ## About HTTP/2
29 #'
30 #' Availability of HTTP/2 can increase the performance when making many parallel
31 #' requests to a server, because HTTP/2 can multiplex many requests over a single
32 #' TCP connection. Support for HTTP/2 depends on the version of `libcurl` that
33 #' your system has, and the TLS back-end that is in use, check [curl_version].
34 #' For clients or servers without HTTP/2, curl makes at most 6 connections per
35 #' host over which it distributes the queued downloads.
36 #'
37 #' On Windows and MacOS you can switch the active TLS backend by setting an
38 #' environment variable [`CURL_SSL_BACKEND`](https://curl.se/libcurl/c/libcurl-env.html)
39 #' in your `~/.Renviron` file. On Windows you can switch between `SecureChannel`
40 #' (default) and `OpenSSL` where only the latter supports HTTP/2. On MacOS you
41 #' can use either `SecureTransport` or `LibreSSL`, the default varies by MacOS
42 #' version.
43 #'
44 #' @returns The function returns a data frame with one row for each downloaded file and
45 #' the following columns:
46 #' - `success` if the HTTP request was successfully performed, regardless of the
47 #' response status code. This is `FALSE` in case of a network error, or in case
48 #' you tried to resume from a server that did not support this. A value of `NA`
49 #' means the download was interrupted while in progress.
50 #' - `status_code` the HTTP status code from the request. A successful download is
51 #' usually `200` for full requests or `206` for resumed requests. Anything else
52 #' could indicate that the downloaded file contains an error page instead of the
53 #' requested content.
54 #' - `resumefrom` the file size before the request, in case a download was resumed.
55 #' - `url` final url (after redirects) of the request.
56 #' - `destfile` downloaded file on disk.
57 #' - `error` if `success == FALSE` this column contains an error message.
58 #' - `type` the `Content-Type` response header value.
59 #' - `modified` the `Last-Modified` response header value.
60 #' - `time` total elapsed download time for this file in seconds.
61 #' - `headers` vector with http response headers for the request.
62 #'
63 #' @export
64 #' @param urls vector with URLs to download. Alternatively it may also be a
65 #' list of [handle][new_handle] objects that have the `url` option already set.
66 #' @param destfiles vector (of equal length as `urls`) with paths of output files,
67 #' or `NULL` to use [basename] of urls.
68 #' @param resume if the file already exists, resume the download. Note that this may
69 #' change server responses, see details.
70 #' @param multi_timeout in seconds, passed to [multi_run]
71 #' @param progress print download progress information
72 #' @param multiplex passed to [new_pool]
73 #' @param ... extra handle options passed to each request [new_handle]
74 #' @examples \dontrun{
75 #' # Example: some large files
76 #' urls <- sprintf(
77 #' "https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2021-%02d.parquet", 1:12)
78 #' res <- multi_download(urls, resume = TRUE) # You can interrupt (ESC) and resume
79 #'
80 #' # Example: revdep checker
81 #' # Download all reverse dependencies for the 'curl' package from CRAN:
82 #' pkg <- 'curl'
83 #' mirror <- 'https://cloud.r-project.org'
84 #' db <- available.packages(repos = mirror)
85 #' packages <- c(pkg, tools::package_dependencies(pkg, db = db, reverse = TRUE)[[pkg]])
86 #' versions <- db[packages,'Version']
87 #' urls <- sprintf("%s/src/contrib/%s_%s.tar.gz", mirror, packages, versions)
88 #' res <- multi_download(urls)
89 #' all.equal(unname(tools::md5sum(res$destfile)), unname(db[packages, 'MD5sum']))
90 #' # And then you could use e.g.: tools:::check_packages_in_dir()
91 #'
92 #' # Example: URL checker
93 #' pkg_url_checker <- function(dir){
94 #' db <- tools:::url_db_from_package_sources(dir)
95 #' res <- multi_download(db$URL, rep('/dev/null', nrow(db)), nobody=TRUE)
96 #' db$OK <- res$status_code == 200
97 #' db
98 #' }
99 #'
100 #' # Use a local package source directory
101 #' pkg_url_checker(".")
102 #'
103 #' }
104 multi_download <- function(urls, destfiles = NULL, resume = FALSE, progress = TRUE,
105 multi_timeout = Inf, multiplex = TRUE, ...){
106 if(inherits(urls, 'curl_handle'))
107 urls <- list(urls)
108 if(!is.character(urls) && !is.list(urls))
109 stop("Argument 'urls' must be a character vector or list of handles")
110 handles <- lapply(urls, make_one_handle)
111 if(is.null(destfiles)){
112 destfiles <- vapply(handles, guess_handle_filename, character(1))
113 }
114 dupes <- setdiff(destfiles[duplicated(destfiles)], c("/dev/null", "NUL"))
115 if(length(dupes)){
116 stop("Duplicate destfiles: ", paste(dupes, collapse = ', '))
117 }
118 stopifnot(length(urls) == length(destfiles))
119 destfiles <- normalizePath(destfiles, mustWork = FALSE)
120 writers <- rep(list(NULL), length(urls))
121 errors <- rep(NA_character_, length(urls))
122 success <- rep(NA, length(urls))
123 resumefrom <- rep(0, length(urls))
124 dlspeed <- rep(0, length(urls))
125 expected <- rep(NA, length(urls))
126 pool <- new_pool(multiplex = multiplex)
127 total <- 0
128 lapply(seq_along(urls), function(i){
129 dest <- destfiles[i]
130 handle <- handles[[i]]
131 handle_setopt(handle, ..., noprogress = TRUE)
132 if(isTRUE(resume) && file.exists(dest)){
133 startsize <- file.info(dest)$size
134 handle_setopt(handle, resume_from_large = startsize)
135 total <<- total + startsize
136 resumefrom[i] <- startsize
137 }
138 writer <- file_writer(dest, append = resume)
139 multi_add(handle, pool = pool, data = function(buf, final){
140 total <<- total + length(buf)
141 writer(buf, final)
142 if(isTRUE(progress)){
143 if(is.na(expected[i])){
144 expected[i] <<- handle_clength(handle) + resumefrom[i]
145 }
146 dlspeed[i] <<- ifelse(final, 0, handle_speed(handle)[1])
147 print_progress(success, total, sum(dlspeed), sum(expected))
148 }
149 }, done = function(req){
150 expected[i] <<- handle_received(handle) + resumefrom[i]
151 success[i] <<- TRUE
152 dlspeed[i] <<- 0
153 if(expected[i] == 0 && !file.exists(dest)){
154 file.create(dest) #create empty file
155 }
156 mtime <- handle_mtime(handle)
157 if(!is.na(mtime)){
158 Sys.setFileTime(dest, handle_mtime(handle))
159 }
160 }, fail = function(err){
161 expected[i] <<- handle_received(handle) + resumefrom[i]
162 success[i] <<- FALSE
163 errors[i] <<- err
164 dlspeed[i] <<- 0
165 })
166 writers[[i]] <<- writer
167 if(isTRUE(progress) && (i %% 100 == 0)){
168 print_stream("\rPreparing request %d of %d...", i, length(urls))
169 }
170 })
171 on.exit(lapply(writers, function(writer){
172 # fallback to close writer in case the download got interrupted
173 writer(raw(0), close = TRUE)
174 }))
175 tryCatch({
176 multi_run(timeout = multi_timeout, pool = pool)
177 if(isTRUE(progress)){
178 print_progress(success, total, sum(dlspeed), sum(expected), TRUE)
179 }
180 }, interrupt = function(e){
181 message("download interrupted")
182 })
183 out <- lapply(handles, handle_data)
184 results <- data.frame(
185 success = success,
186 status_code = vapply(out, function(x){x$status_code}, numeric(1)),
187 resumefrom = resumefrom,
188 url = vapply(out, function(x){x$url}, character(1)),
189 destfile = normalizePath(destfiles, mustWork = FALSE),
190 error = errors,
191 type = vapply(out, function(x){x$type}, character(1)),
192 modified = structure(vapply(out, function(x){x$modified}, numeric(1)), class = c("POSIXct", "POSIXt")),
193 time = vapply(out, function(x){unname(x$times['total'])}, numeric(1)),
194 stringsAsFactors = FALSE
195 )
196 results$headers <- lapply(out, function(x){parse_headers(x$headers)})
197 class(results) <- c("tbl_df", "tbl", "data.frame")
198 results
199 }
200
201 make_one_handle <- function(url_or_handle){
202 if(inherits(url_or_handle, 'curl_handle')){
203 handle <- url_or_handle
204 url <- handle_data(handle)$url
205 if(is.na(url) || identical(url, ""))
206 stop("Handle passed to multi_download() but has no URL set")
207 return(handle)
208 }
209 if(is.character(url_or_handle)){
210 return(new_handle(url = url_or_handle))
211 }
212 stop("Argument urls does not contain url or curl handle")
213 }
214
215 guess_handle_filename <- function(handle){
216 url <- handle_data(handle)$url
217 destfile <- basename(curl_parse_url(url)$path)
218 if(!length(destfile) || is.na(destfile) || !nchar(destfile))
219 stop("Failed to guess filename for: ", url)
220 destfile
221 }
222
223 # Print at most 10x per second in interactive, and once per sec in batch/CI
224 print_progress <- local({
225 last <- 0
226 function(sucvec, total, speed, expected, finalize = FALSE){
227 throttle <- ifelse(interactive(), 0.1, 5)
228 now <- unclass(Sys.time())
229 if(isTRUE(finalize) || now - last > throttle){
230 last <<- now
231 done <- sum(!is.na(sucvec))
232 pending <- sum(is.na(sucvec))
233 pctstr <- if(!identical(expected, 0.0)){
234 sprintf("(%s%%)", ifelse(is.na(expected), "??", as.character(round(100 * total/expected))))
235 } else {""}
236 speedstr <- if(!finalize){
237 sprintf(" (%s/s)", format_size(speed))
238 } else {""}
239 downloaded <- format_size(total)
240 print_stream('\rDownload status: %d done; %d in progress%s. Total size: %s %s...',
241 done, pending, speedstr, downloaded, pctstr)
242 }
243 if(finalize){
244 cat(" done! \n", file = stderr())
245 flush(stderr())
246 }
247 }
248 })
249
250 print_stream <- function(...){
251 cat(sprintf(...), file = stderr())
252 }