Debian Codegraph @

R/utils.R

raw
1 # @staticimports pkg:staticimports
2 # is_installed
3
4 #' Combine multiple promise objects
5 #'
6 #' Use `promise_all` to wait for multiple promise objects to all be successfully
7 #' fulfilled. Use `promise_race` to wait for the first of multiple promise
8 #' objects to be either fulfilled or rejected.
9 #'
10 #' @param ... Promise objects. Either all arguments must be named, or all
11 #' arguments must be unnamed. If `.list` is provided, then these arguments are
12 #' ignored.
13 #' @param .list A list of promise objects--an alternative to `...`.
14 #'
15 #' @return A promise.
16 #'
17 #' For `promise_all`, if all of the promises were successful, the returned
18 #' promise will resolve to a list of the promises' values; if any promise
19 #' fails, the first error to be encountered will be used to reject the
20 #' returned promise.
21 #'
22 #' For `promise_race`, the first of the promises to either fulfill or reject
23 #' will be passed through to the returned promise.
24 #'
25 #' @examples
26 #' p1 <- promise(\(resolve, reject) later::later(\() resolve(1), delay = 1))
27 #' p2 <- promise(\(resolve, reject) later::later(\() resolve(2), delay = 2))
28 #'
29 #' # Resolves after 1 second, to the value: 1
30 #' promise_race(p1, p2) |>
31 #' then(\(x) {
32 #' cat("promise_race:\n")
33 #' str(x)
34 #' })
35 #'
36 #' # Resolves after 2 seconds, to the value: list(1, 2)
37 #' promise_all(p1, p2) |>
38 #' then(\(x) {
39 #' cat("promise_all:\n")
40 #' str(x)
41 #' })
42 #'
43 #' @export
44 promise_all <- function(..., .list = NULL) {
45 if (missing(.list)) {
46 .list <- list(...)
47 }
48
49 if (length(.list) == 0) {
50 return(promise_resolve(list()))
51 }
52
53 # Verify that .list members are either all named or all unnamed
54 listnames <- names(.list)
55 nameCount <- sum(nzchar(listnames))
56 if (nameCount != 0 && nameCount != length(.list)) {
57 stop(
58 "promise_all expects promise arguments (or list) to be either all named or all unnamed"
59 )
60 }
61
62 # done <- list()
63
64 promise(function(resolve, reject) {
65 remaining <- length(.list)
66 indices <- seq_len(remaining)
67 if (nameCount > 0) {
68 # By setting names, `results` will have the same names
69 names(indices) <- listnames
70 }
71
72 results <- lapply(indices, function(idx) {
73 # done[[idx]] <<- FALSE
74 then(
75 .list[[idx]],
76 onFulfilled = function(value) {
77 # Save the result so we can return it to the user.
78 # This weird assignment is similar to `results[[idx]] <- value`, except
79 # that it handles NULL values correctly.
80 results[idx] <<- list(value)
81
82 # Record the fact that the promise was completed.
83 # done[[idx]] <<- TRUE
84 remaining <<- remaining - 1L
85
86 # If all of the tasks are done, resolve.
87 # If (all(as.logical(done)))
88 if (remaining == 0L) {
89 resolve(results)
90 }
91 },
92 onRejected = function(reason) {
93 # TODO: Cancel promises that are still running; Use `done` list
94 reject(reason)
95 }
96 )
97
98 # Init each `results` entry as `NA` until `onFulfilled()` is called
99 NA
100 })
101
102 # Return nothing to promise
103 NULL
104 })
105 }
106
107 #' @rdname promise_all
108 #' @export
109 promise_race <- function(..., .list = NULL) {
110 if (missing(.list)) {
111 .list <- list(...)
112 }
113
114 promise(function(resolve, reject) {
115 lapply(.list, function(promise) {
116 then(promise, resolve, reject)
117 })
118 })
119 }
120
121 #' Promise-aware lapply/map
122 #'
123 #' Similar to [`base::lapply()`] or [`purrr::map`], but promise-aware: the `.f`
124 #' function is permitted to return promises, and while `lapply` returns a list,
125 #' `promise_map` returns a promise that resolves to a similar list (of resolved
126 #' values only, no promises).
127 #'
128 #' `promise_map` processes elements of `.x` serially; that is, if `.f(.x[[1]])`
129 #' returns a promise, then `.f(.x[[2]])` will not be invoked until that promise
130 #' is resolved. If any such promise rejects (errors), then the promise returned
131 #' by `promise_map` immediately rejects with that err.
132 #'
133 #' @param .x A vector (atomic or list) or an expression object (but not a
134 #' promise). Other objects (including classed objects) will be coerced by
135 #' base::as.list.
136 #' @param .f The function to be applied to each element of `.x`. The function is
137 #' permitted, but not required, to return a promise.
138 #' @param ... Optional arguments to `.f`.
139 #' @return A promise that resolves to a list (of values, not promises).
140 #'
141 #' @examples
142 #' # Waits x seconds, then returns x*10
143 #' wait_this_long <- function(x) {
144 #' promise(\(resolve, reject) {
145 #' later::later(\() resolve(x*10), delay = x)
146 #' })
147 #' }
148 #'
149 #' promise_map(
150 #' list(A=1, B=2, C=3),
151 #' wait_this_long
152 #' ) |>
153 #' then(print)
154 #'
155 #' @export
156 promise_map <- function(.x, .f, ...) {
157 .f <- match.fun(.f)
158 if (!is.vector(.x) || is.object(.x)) {
159 .x <- as.list(.x)
160 }
161 x_names <- names(.x)
162 results <- vector("list", length(.x))
163
164 do_next <- function(pos) {
165 if (pos > length(results)) {
166 return(stats::setNames(results, x_names))
167 } else {
168 # The next line may throw, that's fine, it will be caught by resolve() and
169 # reject the promise
170 this_result <- .f(.x[[pos]], ...)
171 p <- promise_resolve(this_result)
172 then(p, function(this_value) {
173 # This weird assignment is similar to `results[[pos]] <- this_value`,
174 # except that it handles `NULL` values correctly.
175 results[pos] <<- list(this_value)
176 do_next(pos + 1)
177 })
178 }
179 }
180
181 promise(function(resolve, reject) {
182 resolve(do_next(1))
183 })
184 }
185
186 #' Promise-aware version of Reduce
187 #'
188 #' Similar to [`purrr::reduce`] (left fold), but the function `.f` is permitted
189 #' to return a promise. `promise_reduce` will wait for any returned promise to
190 #' resolve before invoking `.f` with the next element; in other words, execution
191 #' is serial. `.f` can return a promise as output but should never encounter a
192 #' promise as input (unless `.x` itself is a list of promises to begin with, in
193 #' which case the second parameter would be a promise).
194 #'
195 #' @param .x A vector or list to reduce. (Not a promise.)
196 #' @param .f A function that takes two parameters. The first parameter will be
197 #' the "result" (initially `.init`, and then set to the result of the most
198 #' recent call to `func`), and the second parameter will be an element of `.x`.
199 #' @param ... Other arguments to pass to `.f`
200 #' @param .init The initial result value of the fold, passed into `.f` when it
201 #' is first executed.
202 #'
203 #' @return A promise that will resolve to the result of calling `.f` on the last
204 #' element (or `.init` if `.x` had no elements). If any invocation of `.f`
205 #' results in an error or a rejected promise, then the overall
206 #' `promise_reduce` promise will immediately reject with that error.
207 #'
208 #' @examples
209 #' # Returns a promise for the sum of e1 + e2, with a 0.5 sec delay
210 #' slowly_add <- function(e1, e2) {
211 #' promise(\(resolve, reject) {
212 #' later::later(\() resolve(e1 + e2), delay = 0.5)
213 #' })
214 #' }
215 #'
216 #' # Prints 55 after a little over 5 seconds
217 #' promise_reduce(1:10, slowly_add, .init = 0) |>
218 #' then(print)
219 #'
220 #' @export
221 promise_reduce <- function(.x, .f, ..., .init) {
222 p <- promise_resolve(.init)
223 lapply(.x, function(item) {
224 p <<- then(p, function(x) {
225 .f(x, item, ...)
226 })
227 })
228 p
229 }
230
231 # Placeholder to make R cmd check.
232 # * Need purrr for docs, but don't need purrr for functionality
233 # * Get failure if we don't include it
234 # * Get failure if we do include it, but don't use it. So using it below.
235 function() {
236 purrr::reduce
237 }
238
239 # Determine if `identical(x, FALSE)`
240 is_false <- function(x) {
241 is.logical(x) && length(x) == 1L && !is.na(x) && !x
242 }