Debian Codegraph @

R/multi.R

raw
1 #' Async Concurrent Requests
2 #'
3 #' AJAX style concurrent requests, possibly using HTTP/2 multiplexing.
4 #' Results are only available via callback functions. Advanced use only!
5 #' For downloading many files in parallel use [multi_download] instead.
6 #'
7 #' Requests are created in the usual way using a curl [handle] and added
8 #' to the scheduler with [multi_add]. This function returns immediately
9 #' and does not perform the request yet. The user needs to call [multi_run]
10 #' which performs all scheduled requests concurrently. It returns when all
11 #' requests have completed, or case of a `timeout` or `SIGINT` (e.g.
12 #' if the user presses `ESC` or `CTRL+C` in the console). In case of
13 #' the latter, simply call [multi_run] again to resume pending requests.
14 #'
15 #' When the request succeeded, the `done` callback gets triggered with
16 #' the response data. The structure if this data is identical to [curl_fetch_memory].
17 #' When the request fails, the `fail` callback is triggered with an error
18 #' message. Note that failure here means something went wrong in performing the
19 #' request such as a connection failure, it does not check the http status code.
20 #' Just like [curl_fetch_memory], the user has to implement application logic.
21 #'
22 #' Raising an error within a callback function stops execution of that function
23 #' but does not affect other requests.
24 #'
25 #' A single handle cannot be used for multiple simultaneous requests. However
26 #' it is possible to add new requests to a pool while it is running, so you
27 #' can re-use a handle within the callback of a request from that same handle.
28 #' It is up to the user to make sure the same handle is not used in concurrent
29 #' requests.
30 #'
31 #' The [multi_cancel] function can be used to cancel a pending request.
32 #' It has no effect if the request was already completed or canceled.
33 #'
34 #' The [multi_fdset] function returns the file descriptors curl is
35 #' polling currently, and also a timeout parameter, the number of
36 #' milliseconds an application should wait (at most) before proceeding. It
37 #' is equivalent to the `curl_multi_fdset` and
38 #' `curl_multi_timeout` calls. It is handy for applications that is
39 #' expecting input (or writing output) through both curl, and other file
40 #' descriptors.
41 #'
42 #' @name multi
43 #' @rdname multi
44 #' @seealso Advanced download interface: [multi_download]
45 #' @useDynLib curl R_multi_add
46 #' @param handle a curl [handle] with preconfigured `url` option.
47 #' @param done callback function for completed request. Single argument with
48 #' response data in same structure as [curl_fetch_memory].
49 #' @param fail callback function called on failed request. Argument contains
50 #' error message.
51 #' @param data (advanced) callback function, file path, or connection object for writing
52 #' incoming data. This callback should only be used for *streaming* applications,
53 #' where small pieces of incoming data get written before the request has completed. The
54 #' signature for the callback function is `write(data, final = FALSE)`. If set
55 #' to `NULL` the entire response gets buffered internally and returned by in
56 #' the `done` callback (which is usually what you want).
57 #' @param pool a multi handle created by [new_pool]. Default uses a global pool.
58 #' @export
59 #' @examples
60 #' results <- list()
61 #' success <- function(x){
62 #' results <<- append(results, list(x))
63 #' }
64 #' failure <- function(str){
65 #' cat(paste("Failed request:", str), file = stderr())
66 #' }
67 #' # This handle will take longest (3sec)
68 #' h1 <- new_handle(url = "https://hb.cran.dev/delay/3")
69 #' multi_add(h1, done = success, fail = failure)
70 #'
71 #' # This handle writes data to a file
72 #' con <- file("output.txt")
73 #' h2 <- new_handle(url = "https://hb.cran.dev/post", postfields = "bla bla")
74 #' multi_add(h2, done = success, fail = failure, data = con)
75 #'
76 #' # This handle raises an error
77 #' h3 <- new_handle(url = "https://urldoesnotexist.xyz")
78 #' multi_add(h3, done = success, fail = failure)
79 #'
80 #' # Actually perform the requests
81 #' multi_run(timeout = 2)
82 #' multi_run()
83 #'
84 #' # Check the file
85 #' readLines("output.txt")
86 #' unlink("output.txt")
87 multi_add <- function(handle, done = NULL, fail = NULL, data = NULL, pool = NULL){
88 if(is.null(pool))
89 pool <- multi_default()
90 if(inherits(data, "connection")){
91 con <- data
92 if(isOpen(con) && identical(summary(con)$text, "text")){
93 data <- function(x, finalize = FALSE){
94 cat(rawToChar(x), file = con)
95 flush(con)
96 }
97 } else {
98 was_open <- isOpen(con)
99 data <- function(x, finalize = FALSE){
100 if(!isOpen(con))
101 open(con, 'wb')
102 writeBin(x, con = con)
103 if(isTRUE(finalize && !was_open)){
104 close(con)
105 } else {
106 flush(con)
107 }
108 }
109 }
110 } else if(is_string(data)){
111 data <- file_writer(path = data)
112 }
113 stopifnot(inherits(handle, "curl_handle"))
114 stopifnot(inherits(pool, "curl_multi"))
115 stopifnot(is.null(done) || is.function(done))
116 stopifnot(is.null(fail) || is.function(fail))
117 stopifnot(is.null(data) || is.function(data))
118 .Call(R_multi_add, handle, done, fail, data, pool)
119 }
120
121 #' @param timeout max time in seconds to wait for results. Use `0` to poll for results without
122 #' waiting at all.
123 #' @param poll If `TRUE` then return immediately after any of the requests has completed.
124 #' May also be an integer in which case it returns after n requests have completed.
125 #' @export
126 #' @useDynLib curl R_multi_run
127 #' @rdname multi
128 multi_run <- function(timeout = Inf, poll = FALSE, pool = NULL){
129 if(is.null(pool))
130 pool <- multi_default()
131 stopifnot(is.numeric(timeout))
132 stopifnot(inherits(pool, "curl_multi"))
133 .Call(R_multi_run, pool, timeout, as.integer(poll))
134 }
135
136 #' @param total_con max total concurrent connections.
137 #' @param host_con max concurrent connections per host.
138 #' @param max_streams max HTTP/2 concurrent multiplex streams per connection.
139 #' @param multiplex use HTTP/2 multiplexing if supported by host and client.
140 #' @export
141 #' @useDynLib curl R_multi_setopt
142 #' @rdname multi
143 multi_set <- function(total_con = 50, host_con = 6, max_streams = 10, multiplex = TRUE, pool = NULL){
144 if(is.null(pool))
145 pool <- multi_default()
146 stopifnot(inherits(pool, "curl_multi"))
147 stopifnot(is.numeric(total_con))
148 stopifnot(is.numeric(host_con))
149 stopifnot(is.numeric(max_streams))
150 stopifnot(is.logical(multiplex))
151 .Call(R_multi_setopt, pool, total_con, host_con, max_streams, multiplex)
152 }
153
154 #' @export
155 #' @useDynLib curl R_multi_list
156 #' @rdname multi
157 multi_list <- function(pool = NULL){
158 if(is.null(pool))
159 pool <- multi_default()
160 stopifnot(inherits(pool, "curl_multi"))
161 as.list(.Call(R_multi_list, pool))
162 }
163
164 #' @export
165 #' @useDynLib curl R_multi_cancel
166 #' @rdname multi
167 multi_cancel <- function(handle){
168 stopifnot(inherits(handle, "curl_handle"))
169 .Call(R_multi_cancel, handle)
170 }
171
172 #' @export
173 #' @useDynLib curl R_multi_new
174 #' @rdname multi
175 new_pool <- function(total_con = 100, host_con = 6, max_streams = 10, multiplex = TRUE){
176 pool <- .Call(R_multi_new)
177 multi_set(pool = pool, total_con = total_con, host_con = host_con, max_streams = max_streams, multiplex = multiplex)
178 }
179
180 multi_default <- local({
181 global_multi_handle <- NULL
182 function(){
183 if(is.null(global_multi_handle)){
184 global_multi_handle <<- new_pool()
185 }
186 stopifnot(inherits(global_multi_handle, "curl_multi"))
187 return(global_multi_handle)
188 }
189 })
190
191 #' @export
192 print.curl_multi <- function(x, ...){
193 len <- length(multi_list(x))
194 cat(sprintf("<curl multi-pool> (%d pending requests)\n", len))
195 }
196
197 #' @export
198 #' @useDynLib curl R_multi_fdset
199 #' @rdname multi
200
201 multi_fdset <- function(pool = NULL){
202 if(is.null(pool))
203 pool <- multi_default()
204 # line below duplicates checks made by C code, but may need to be reinstated if that ever changes
205 # stopifnot(inherits(pool, c("curl_multi", "curl")))
206 .Call(R_multi_fdset, pool)
207 }