Debian Codegraph @

R/domains.R

raw
1 tryCatch <- function(expr, ..., finally) {
2 base::tryCatch(
3 withCallingHandlers(
4 expr,
5 error = function(e) {
6 promiseDomain$onError(e)
7 }
8 ),
9 ...,
10 finally = finally
11 )
12 }
13
14 spliceOnFinally <- function(onFinally) {
15 list(
16 onFulfilled = finallyToFulfilled(onFinally),
17 onRejected = finallyToRejected(onFinally)
18 )
19 }
20
21 finallyToFulfilled <- function(onFinally) {
22 force(onFinally)
23 function(value, .visible) {
24 onFinally()
25 if (.visible) value else invisible(value)
26 }
27 }
28
29 finallyToRejected <- function(onFinally) {
30 force(onFinally)
31 function(reason) {
32 onFinally()
33 stop(reason)
34 }
35 }
36
37 promiseDomain <- list(
38 onThen = function(onFulfilled, onRejected, onFinally) {
39 force(onFulfilled)
40 force(onRejected)
41 force(onFinally)
42
43 # Verify that if onFinally is non-NULL, onFulfilled and onRejected are NULL
44 if (
45 !is.null(onFinally) && (!is.null(onFulfilled) || !is.null(onRejected))
46 ) {
47 stop(
48 "A single `then` call cannot combine `onFinally` with `onFulfilled`/`onRejected`"
49 )
50 }
51
52 domain <- current_promise_domain()
53
54 shouldWrapFinally <- !is.null(onFinally) &&
55 !is.null(domain) &&
56 !is.null(domain$wrapOnFinally)
57
58 newOnFinally <- if (shouldWrapFinally) {
59 domain$wrapOnFinally(onFinally)
60 } else {
61 onFinally
62 }
63
64 if (!is.null(newOnFinally)) {
65 spliced <- spliceOnFinally(newOnFinally)
66 onFulfilled <- spliced$onFulfilled
67 onRejected <- spliced$onRejected
68 }
69
70 shouldWrapFulfilled <- !is.null(onFulfilled) &&
71 !is.null(domain) &&
72 !shouldWrapFinally
73 shouldWrapRejected <- !is.null(onRejected) &&
74 !is.null(domain) &&
75 !shouldWrapFinally
76
77 results <- list(
78 onFulfilled = if (shouldWrapFulfilled) {
79 domain$wrapOnFulfilled(onFulfilled)
80 } else {
81 onFulfilled
82 },
83 onRejected = if (shouldWrapRejected) {
84 domain$wrapOnRejected(onRejected)
85 } else {
86 onRejected
87 }
88 )
89 results <- results[!vapply(results, is.null, logical(1))]
90 # If there's a domain, ensure that before any callback is invoked, we
91 # reenter the domain. This is important for this kind of code:
92 #
93 # with_promise_domain(domain, {
94 # async_sleep(0.1) |>
95 # then(\(x) {async_sleep(0.1)}) |>
96 # then(\(x) {
97 # # Without re-entry, this would be outside the domain!
98 # })
99 # })
100 #
101 # It's important to reenter even if domain is NULL. In that case, we need to
102 # ensure that the current domain is set to NULL while the callback executes.
103 results <- lapply(results, wrap_callback_reenter, domain = domain)
104 results
105 },
106 onError = function(error) {
107 domain <- current_promise_domain()
108 if (is.null(domain)) {
109 return()
110 }
111 domain$onError(error)
112 }
113 )
114
115 wrap_callback_reenter <- function(callback, domain) {
116 force(callback)
117 force(domain)
118
119 wrapper <- function(...) {
120 # replace = TRUE because we don't care what the current domain is; we're
121 # (temporarily) putting the world back to the way it was when the callback
122 # was bound to a promise.
123 reenter_promise_domain(domain, callback(...), replace = TRUE)
124 }
125
126 # There are parts of this package that will inspect formals() to see if
127 # there's a `.visible` parameter in the callback. So it's important to have
128 # the returned wrapper have the same formals as the original callback.
129 wrap_with_signature(wrapper, formals(callback))
130 }
131
132 wrap_with_signature <- function(func, formal_args) {
133 # func must have a `...` signature
134 stopifnot("..." %in% names(formals(func)))
135
136 args <- names(formal_args)
137 recall <- rlang::call2(
138 func,
139 !!!rlang::set_names(lapply(args, as.symbol), args)
140 )
141
142 rlang::new_function(formal_args, recall)
143 }
144
145 globals <- new.env(parent = emptyenv())
146
147 current_promise_domain <- function() {
148 globals$domain
149 }
150
151 #' Promise domains
152 #'
153 #' Promise domains are used to temporarily set up custom environments that
154 #' intercept and influence the registration of callbacks. Create new promise
155 #' domain objects using `new_promise_domain`, and temporarily activate a promise
156 #' domain object (for the duration of evaluating a given expression) using
157 #' `with_promise_domain`.
158 #'
159 #' While `with_promise_domain` is on the call stack, any calls to
160 #' [`promises::then()`] (or higher level functions or operators, like
161 #' [`promises::catch()`]) will belong to the promise domain. In addition, when a
162 #' `then` callback that belongs to a promise domain is invoked, then any new
163 #' calls to `then` will also belong to that promise domain. In other words, a
164 #' promise domain "infects" not only the immediate calls to `then`, but also to
165 #' "nested" calls to `then`.
166 #'
167 #' For more background, read the
168 #' [original design doc](https://gist.github.com/jcheng5/b1c87bb416f6153643cd0470ac756231).
169 #'
170 #' For examples, see the source code of the Shiny package, which uses promise
171 #' domains extensively to manage graphics devices and reactivity.
172 #'
173 #' @param domain A promise domain object to install while `expr` is evaluated.
174 #' @param expr Any R expression, to be evaluated under the influence of
175 #' `domain`.
176 #' @param replace If `FALSE`, then the effect of the `domain` will be added
177 #' to the effect of any currently active promise domain(s). If `TRUE`, then
178 #' the current promise domain(s) will be ignored for the duration of the
179 #' `with_promise_domain` call.
180 #'
181 #' @export
182 with_promise_domain <- function(domain, expr, replace = FALSE) {
183 oldval <- current_promise_domain()
184 if (replace) {
185 globals$domain <- domain
186 } else {
187 globals$domain <- compose_domains(oldval, domain)
188 }
189 on.exit(globals$domain <- oldval)
190
191 if (!is.null(domain)) domain$wrapSync(expr) else force(expr)
192 }
193
194 # Like with_promise_domain, but doesn't include the wrapSync call.
195 reenter_promise_domain <- function(domain, expr, replace) {
196 oldval <- current_promise_domain()
197 if (replace) {
198 globals$domain <- domain
199 } else {
200 globals$domain <- compose_domains(oldval, domain)
201 }
202 on.exit(globals$domain <- oldval)
203
204 force(expr)
205 }
206
207 #' @param wrapOnFulfilled A function that takes a single argument: a function
208 #' that was passed as an `onFulfilled` argument to [`promises::then()`]. The
209 #' `wrapOnFulfilled` function should return a function that is suitable for
210 #' `onFulfilled` duty.
211 #' @param wrapOnRejected A function that takes a single argument: a function
212 #' that was passed as an `onRejected` argument to [`promises::then()`]. The
213 #' `wrapOnRejected` function should return a function that is suitable for
214 #' `onRejected` duty.
215 #' @param wrapSync A function that takes a single argument: a (lazily evaluated)
216 #' expression that the function should [force()]. This expression represents
217 #' the `expr` argument passed to [`promises::with_promise_domain()`];
218 #' `wrapSync` allows the domain to manipulate the environment before/after
219 #' `expr` is evaluated.
220 #' @param onError A function that takes a single argument: an error. `onError`
221 #' will be called whenever an exception occurs in a domain (that isn't caught
222 #' by a `tryCatch`). Providing an `onError` callback doesn't cause errors to
223 #' be caught, necessarily; instead, `onError` callbacks behave like calling
224 #' handlers.
225 #' @param ... Arbitrary named values that will become elements of the promise
226 #' domain object, and can be accessed as items in an environment (i.e. using
227 #' `[[` or `$`).
228 #' @param wrapOnFinally A function that takes a single argument: a function
229 #' that was passed as an `onFinally` argument to [`promises::then()`]. The
230 #' `wrapOnFinally` function should return a function that is suitable for
231 #' `onFinally` duty. If `wrapOnFinally` is `NULL` (the default), then the
232 #' domain will use both `wrapOnFulfilled` and `wrapOnRejected` to wrap the
233 #' `onFinally`. If it's important to distinguish between normal
234 #' fulfillment/rejection handlers and finally handlers, then be sure to
235 #' provide `wrapOnFinally`, even if it's just [base::identity()].
236 #' @rdname with_promise_domain
237 #' @export
238 new_promise_domain <- function(
239 wrapOnFulfilled = identity,
240 wrapOnRejected = identity,
241 wrapSync = force,
242 onError = force,
243 ...,
244 wrapOnFinally = NULL
245 ) {
246 list2env(
247 list(
248 wrapOnFulfilled = wrapOnFulfilled,
249 wrapOnRejected = wrapOnRejected,
250 wrapOnFinally = wrapOnFinally,
251 wrapSync = wrapSync,
252 onError = onError,
253 ...
254 ),
255 parent = emptyenv()
256 )
257 }
258
259
260 compose_domains <- function(base, new) {
261 if (is.null(base)) {
262 return(new)
263 }
264
265 list(
266 # The `...` of `new_promise_domain` are not automatically composed here.
267 # For now, pass through the otel span promise domain flag
268 .otel_promise_domain = has_otel_promise_domain(base) ||
269 has_otel_promise_domain(new),
270 wrapOnFulfilled = function(onFulfilled) {
271 # Wrap new domain first (innermost), then base domain (outermost)
272 # This ensures that the new domain wraps most closely to the callback
273 new_wrapped <- new$wrapOnFulfilled(onFulfilled)
274 base$wrapOnFulfilled(new_wrapped)
275 },
276 wrapOnRejected = function(onRejected) {
277 # Wrap new domain first (innermost), then base domain (outermost)
278 # This ensures that the new domain wraps most closely to the callback
279 new_wrapped <- new$wrapOnRejected(onRejected)
280 base$wrapOnRejected(new_wrapped)
281 },
282 # Only include the new wrapSync, assuming that we've already applied the
283 # base domain's wrapSync. This assumption won't hold if we either export
284 # compose_domains in the future, or if we use it in cases where the base
285 # domain isn't currently active.
286 wrapSync = new$wrapSync,
287 onError = function(e) {
288 base$onError(e)
289 new$onError(e)
290 }
291 )
292 }
293
294 without_promise_domain <- function(expr) {
295 with_promise_domain(NULL, expr, replace = TRUE)
296 }