Debian Codegraph @

R/promise.R

raw
1 Promise <- function() {
2 self <- new.env(parent = emptyenv())
3 private <- new.env(parent = emptyenv())
4
5 private$state <- "pending"
6 private$value <- NULL
7 private$visible <- TRUE
8 private$publicResolveRejectCalled <- FALSE
9 private$onFulfilled <- list()
10 private$onRejected <- list()
11 private$onFinally <- list()
12 private$rejectionHandled <- FALSE
13
14 private$doResolve <- function(value) {
15 val <- withVisible(value)
16 value <- val$value
17 visible <- val$visible
18
19 if (is.promising(value)) {
20 value <- as.promise(value)
21 if (identical(self, attr(value, "promise_impl", exact = TRUE))) {
22 return(private$doReject(simpleError(
23 "Chaining cycle detected for promise"
24 )))
25 }
26 # This then() call doesn't need promise domains; semantically, it doesn't
27 # really exist, as it's just a convenient way to implement the new promise
28 # inhabiting the old promise's corpse.
29 without_promise_domain({
30 value$then(
31 private$doResolve,
32 private$doReject
33 )
34 })
35 } else {
36 private$doResolveFinalValue(value, visible)
37 }
38 }
39
40 private$doReject <- function(reason) {
41 if (is.promising(reason)) {
42 reason <- as.promise(reason)
43 # This then() call doesn't need promise domains; semantically, it doesn't
44 # really exist, as it's just a convenient way to implement the new promise
45 # inhabiting the old promise's corpse.
46 without_promise_domain({
47 reason$then(
48 private$doResolve,
49 private$doReject
50 )
51 })
52 } else {
53 private$doRejectFinalReason(reason)
54 }
55 }
56
57 # These "final" versions of resolve/reject are for when we've
58 # established that the value/reason is not itself a promise.
59 private$doResolveFinalValue <- function(value, visible) {
60 private$value <- value
61 private$visible <- visible
62 private$state <- "fulfilled"
63
64 later(function() {
65 lapply(private$onFulfilled, function(f) {
66 f(private$value, private$visible)
67 })
68 private$onFulfilled <- list()
69 })
70 }
71
72 private$doRejectFinalReason <- function(reason) {
73 private$value <- reason
74 private$state <- "rejected"
75
76 later(function() {
77 lapply(private$onRejected, function(f) {
78 private$rejectionHandled <- TRUE
79 f(private$value)
80 })
81 private$onRejected <- list()
82
83 later(
84 function() {
85 if (!private$rejectionHandled) {
86 # warning() was unreliable here
87 cat(
88 file = stderr(),
89 "Unhandled promise error: ",
90 reason$message,
91 "\n",
92 sep = ""
93 )
94 }
95 }
96 )
97 })
98 }
99
100 self$status <- function() {
101 private$state
102 }
103
104 self$resolve <- function(value) {
105 # Only allow this to be called once, then no-op.
106 if (private$publicResolveRejectCalled) {
107 return(invisible())
108 }
109 private$publicResolveRejectCalled <- TRUE
110
111 tryCatch(
112 {
113 # Important: Do not trigger evaluation of value before
114 # passing to doResolve. doResolve calls withVisible() on
115 # value, so evaluating it before that point will cause
116 # the visibility to be lost.
117 private$doResolve(value)
118 },
119 error = function(err) {
120 private$doReject(err)
121 }
122 )
123
124 invisible()
125 }
126
127 self$reject <- function(reason) {
128 # Only allow this to be called once, then no-op.
129 if (private$publicResolveRejectCalled) {
130 return(invisible())
131 }
132 private$publicResolveRejectCalled <- TRUE
133
134 tryCatch(
135 {
136 force(reason)
137 if (is.character(reason)) {
138 reason <- simpleError(reason)
139 }
140 private$doReject(reason)
141 },
142 error = function(err) {
143 private$doReject(err)
144 }
145 )
146
147 invisible()
148 }
149
150 self$then <- function(
151 onFulfilled = NULL,
152 onRejected = NULL,
153 onFinally = NULL
154 ) {
155 onFulfilled <- normalizeOnFulfilled(onFulfilled)
156 onRejected <- normalizeOnRejected(onRejected)
157 if (!is.function(onFinally)) {
158 onFinally <- NULL
159 }
160
161 promise2 <- promise(function(resolve, reject) {
162 res <- promiseDomain$onThen(onFulfilled, onRejected, onFinally)
163
164 if (!is.null(res)) {
165 onFulfilled <- res$onFulfilled
166 onRejected <- res$onRejected
167 }
168
169 handleFulfill <- function(value, visible) {
170 if (is.function(onFulfilled)) {
171 resolve(onFulfilled(value, visible))
172 } else {
173 resolve(if (visible) value else invisible(value))
174 }
175 }
176
177 handleReject <- function(reason) {
178 if (is.function(onRejected)) {
179 # Yes, resolve, not reject.
180 resolve(onRejected(reason))
181 } else {
182 # Yes, reject, not resolve.
183 reject(reason)
184 }
185 }
186
187 if (private$state == "pending") {
188 private$onFulfilled <- c(
189 private$onFulfilled,
190 list(
191 handleFulfill
192 )
193 )
194 private$onRejected <- c(
195 private$onRejected,
196 list(
197 handleReject
198 )
199 )
200 } else if (private$state == "fulfilled") {
201 later(function() {
202 handleFulfill(private$value, private$visible)
203 })
204 } else if (private$state == "rejected") {
205 later(function() {
206 private$rejectionHandled <- TRUE
207 handleReject(private$value)
208 })
209 } else {
210 stop("Unexpected state ", private$state)
211 }
212 })
213
214 invisible(promise2)
215 }
216
217 self$catch <- function(onRejected) {
218 invisible(self$then(onRejected = onRejected))
219 }
220
221 self$finally <- function(onFinally) {
222 invisible(self$then(
223 onFinally = onFinally
224 ))
225 }
226
227 self$format <- function() {
228 if (private$state == "pending") {
229 "<Promise [pending]>"
230 } else {
231 classname <- class(private$value)[[1]]
232 if (length(classname) == 0) {
233 classname <- ""
234 }
235
236 sprintf("<Promise [%s: %s]>", private$state, classname)
237 }
238 }
239
240 self$.__enclos_env__ <- list(private = private)
241 class(self) <- "Promise"
242 self
243 }
244
245 normalizeOnFulfilled <- function(onFulfilled) {
246 if (!is.function(onFulfilled)) {
247 if (!is.null(onFulfilled)) {
248 warning("`onFulfilled` must be a function or `NULL`")
249 }
250 return(NULL)
251 }
252
253 args <- formals(onFulfilled)
254 arg_count <- length(args)
255
256 if (arg_count >= 2 && names(args)[[2]] == ".visible") {
257 onFulfilled
258 } else if (arg_count > 0) {
259 function(value, .visible) {
260 if (isTRUE(.visible)) {
261 onFulfilled(value)
262 } else {
263 onFulfilled(invisible(value))
264 }
265 }
266 } else {
267 function(value, .visible) {
268 onFulfilled()
269 }
270 }
271 }
272
273 normalizeOnRejected <- function(onRejected) {
274 if (!is.function(onRejected)) {
275 if (!is.null(onRejected)) {
276 warning("`onRejected` must be a function or `NULL`")
277 }
278 return(NULL)
279 }
280
281 args <- formals(onRejected)
282 arg_count <- length(args)
283
284 if (arg_count >= 1) {
285 onRejected
286 } else if (arg_count == 0) {
287 function(reason) {
288 onRejected()
289 }
290 }
291 }
292
293 #' Create a new promise object
294 #'
295 #' `promise()` creates a new promise. A promise is a placeholder object for the
296 #' eventual result (or error) of an asynchronous operation. This function is not
297 #' generally needed to carry out asynchronous programming tasks; instead, it is
298 #' intended to be used mostly by package authors who want to write asynchronous
299 #' functions that return promises.
300 #'
301 #' The `action` function should be a piece of code that returns quickly, but
302 #' initiates a potentially long-running, asynchronous task. If/when the task
303 #' successfully completes, call `resolve(value)` where `value` is the result of
304 #' the computation (like the return value). If the task fails, call
305 #' `reject(reason)`, where `reason` is either an error object, or a character
306 #' string.
307 #'
308 #' It's important that asynchronous tasks kicked off from `action` be coded very
309 #' carefully--in particular, all errors must be caught and passed to `reject()`.
310 #' Failure to do so will cause those errors to be lost, at best; and the caller
311 #' of the asynchronous task will never receive a response (the asynchronous
312 #' equivalent of a function call that never returns, i.e. hangs).
313 #'
314 #' The return value of `action` will be ignored.
315 #'
316 #' @section `action=` formulas:
317 #'
318 #' `r lifecycle::badge("superseded")`
319 #'
320 #' With `{promises}` depending on R >= 4.1, the shorthand of a formula, `~
321 #' fn(.)` for `action` is no longer recommended by the `{promises}` package or
322 #' tidyverse (for example,
323 #' [`{purrr}`](https://github.com/tidyverse/purrr/commit/670c3ed9920f15da0d4175068ecddc41f0f1f335#diff-c4dcc43795da5c7f6bf5a94d957b5507ce795fedd6d3eb092ccad03678c4f76dR15))
324 #' as we now have access to the function shorthand, `\(x) fn(x)`. Please update
325 #' your `action` code to use the new function shorthand syntax `\(resolve,
326 #' reject) resolve(arg1, arg2)` instead of `~ { resolve(arg1, arg2) }`. The
327 #' magically created `resolve`/`reject` functions can be confusing when chained
328 #' with other methods.
329 #'
330 #' @param action A function with signature `function(resolve, reject)`.
331 #'
332 #' @return A promise object (see \code{\link{then}}).
333 #'
334 #' @examples
335 #' # Create a promise that resolves to a random value after 2 secs
336 #' p1 <- promise(\(resolve, reject) {
337 #' later::later(\() resolve(runif(1)), delay = 2)
338 #' })
339 #'
340 #' p1 |> then(print)
341 #'
342 #' # Create a promise that errors immediately
343 #' p2 <- promise(\(resolve, reject) {
344 #' reject("An error has occurred")
345 #' })
346 #' then(p2,
347 #' onFulfilled = \(value) message("Success"),
348 #' onRejected = \(err) message("Failure")
349 #' )
350 #'
351 #' @export
352 promise <- function(action) {
353 if (is.function(action)) {
354 if (length(formals(action)) != 2) {
355 stop("'action' function must have two arguments")
356 }
357 } else if (inherits(action, "formula")) {
358 if (length(action) != 2) {
359 stop("'action' must be a function or one-sided formula")
360 }
361 } else {
362 stop("Invalid action argument--should be a function")
363 }
364
365 p <- Promise()
366
367 tryCatch(
368 {
369 if (is.function(action)) {
370 action(p$resolve, p$reject)
371 } else if (inherits(action, "formula")) {
372 eval(
373 action[[2]],
374 list(
375 resolve = p$resolve,
376 reject = p$reject,
377 return = function(value) {
378 warning("Can't return a value from a promise, use resolve/reject")
379 }
380 ),
381 environment(action)
382 )
383 }
384 },
385 error = function(e) {
386 if (p$status() == "pending") {
387 p$reject(e)
388 } else {
389 # Too late to do anything useful. Just notify.
390 warning(e)
391 }
392 }
393 )
394 structure(
395 list(
396 then = p$then,
397 catch = p$catch,
398 finally = p$finally
399 ),
400 class = "promise",
401 promise_impl = p
402 )
403 }
404
405 #' Create a resolved or rejected promise
406 #'
407 #' Helper functions to conveniently create a promise that is resolved to the
408 #' given value (or rejected with the given reason).
409 #'
410 #' @param value A value, or promise, that the new promise should be resolved to.
411 #' This expression will be lazily evaluated, and if evaluating the expression
412 #' raises an error, then the new promise will be rejected with that error as
413 #' the reason.
414 #' @param reason An error message string, or error object.
415 #'
416 #' @examples
417 #' promise_resolve(mtcars) |>
418 #' then(head) |>
419 #' then(print)
420 #'
421 #' promise_reject("Something went wrong") |>
422 #' catch(tee = TRUE, \(e) message(conditionMessage(e)))
423 #'
424 #' @export
425 promise_resolve <- function(value) {
426 promise(function(resolve, reject) resolve(value))
427 }
428
429 #' @rdname promise_resolve
430 #' @export
431 promise_reject <- function(reason) {
432 promise(function(resolve, reject) reject(reason))
433 }
434
435 #' Coerce to a promise
436 #'
437 #' Use `is.promise` to determine whether an R object is a promise. Use
438 #' `as.promise` (an S3 generic method) to attempt to coerce an R object to a
439 #' promise, and `is.promising` (another S3 generic method) to test whether
440 #' `as.promise` is supported. [mirai::mirai] objects have an `as.promise` method
441 #' defined in the mirai package, and this package provides one for converting
442 #' [future::Future] objects into promises.
443 #'
444 #' @param x An R object to test or coerce.
445 #'
446 #' @return `as.promise` returns a promise object, or throws an error if the
447 #' object cannot be converted.
448 #'
449 #' `is.promise` returns `TRUE` if the given value is a promise object, and
450 #' `FALSE` otherwise.
451 #'
452 #' `is.promising` returns `TRUE` if the given value is a promise object or
453 #' if it can be converted to a promise object using `as.promise`, and `FALSE`
454 #' otherwise.
455 #'
456 #' @export
457 is.promise <- function(x) {
458 inherits(x, "promise")
459 }
460
461 #' @rdname is.promise
462 #' @export
463 is.promising <- function(x) {
464 UseMethod("is.promising")
465 }
466
467 #' @export
468 is.promising.default <- function(x) {
469 FALSE
470 }
471
472 #' @export
473 is.promising.promise <- function(x) {
474 TRUE
475 }
476
477 #' @export
478 is.promising.Future <- function(x) {
479 TRUE
480 }
481
482 #' @rdname is.promise
483 #' @export
484 as.promise <- function(x) {
485 UseMethod("as.promise", x)
486 }
487
488 #' @export
489 as.promise.promise <- function(x) {
490 x
491 }
492
493 #' @export
494 as.promise.Future <- function(x) {
495 # We want to create a promise only once for each Future object, and cache it
496 # as an attribute. This spares us from having multiple polling loops waiting
497 # for the same Future.
498 #
499 ## Note: 2025-07-barret:
500 ## Active bindings will not work as `{future}` does not proactively retrieve results. A poll must be used.
501 #
502 ## Note: 2025-08-barret:
503 ## From conversation with Henrik, while it may be possible to use `immediateCondition` within future to _immediately_ send a value back from a worker to the main R session,
504 ## `future::resolved()` is still required to pull the _immediate_ value into the R session (even when the future has not fully resolved yet).
505 ## Therefore, the polling mechanism below is still required.
506 ## For comparison, mirai has a background process that waits for results and will interrupt the main R session with the value.
507
508 cached <- attr(x, "converted_promise", exact = TRUE)
509 if (!is.null(cached)) {
510 return(cached)
511 }
512
513 p <- promise(function(resolve, reject) {
514 poll_interval <- 0.1
515 check <- function() {
516 # timeout = 0 is important, the default waits for 200ms
517 is_resolved <- tryCatch(
518 {
519 future::resolved(x, timeout = 0)
520 },
521 FutureError = function(e) {
522 reject(e)
523 TRUE
524 }
525 )
526 if (is_resolved) {
527 tryCatch(
528 {
529 result <- future::value(x, signal = TRUE)
530 resolve(result)
531 },
532 FutureError = function(e) {
533 reject(e)
534 TRUE
535 },
536 error = function(e) {
537 reject(e)
538 }
539 )
540 } else {
541 later(check, poll_interval)
542 }
543 }
544 check()
545 })
546
547 # Store the new promise for next time
548 attr(x, "converted_promise") <- p
549 p
550 }
551
552 #' @export
553 as.promise.default <- function(x) {
554 # TODO: If x is an error or try-error, should this return a rejected promise?
555 stop(
556 "Don't know how to convert object of class ",
557 class(x)[[1L]],
558 " into a promise"
559 )
560 }
561
562 #' Fulfill a promise
563 #'
564 #' Use these functions to satisfy a promise with either success (\code{resolve})
565 #' or failure (\code{reject}). These functions are not exported, but rather, are
566 #' passed as arguments to the \code{action} function you pass to a [promise]
567 #' constructor.
568 #'
569 #' @param value The result from a successful calculation.
570 #' @param reason An error or string that explains why the operation failed.
571 #'
572 #' @keywords internal
573 resolve <- function(value = NULL) {
574 stop("resolve() must be called from within a promise constructor")
575 }
576
577 #' @rdname resolve
578 #' @keywords internal
579 reject <- function(reason) {
580 stop("reject() must be called from within a promise constructor")
581 }