Debian Codegraph @

R/later.R

raw
1 # nocov start
2 # tested implicitly
3
4 .onLoad <- function(libname, pkgname) {
5 ensureInitialized()
6 .globals$next_id <- 0L
7 # Store a ref to the global loop so it doesn't get GC'd.
8 .globals$global_loop <- create_loop(parent = NULL)
9 }
10
11 # nocov end
12
13 .globals <- new.env(parent = emptyenv())
14 # A registry of weak refs to loop handle objects. Given an ID number, we can
15 # get the corresponding loop handle. We use weak refs because we don't want
16 # this registry to keep the loop objects alive.
17 .loops <- new.env(parent = emptyenv())
18
19 # Our own weakref functions are implemented (instead of using those from
20 # `rlang`) to avoid loading `rlang` automatically upon package load, as this
21 # causes additional overhead for packages which only link to `later`.
22 new_weakref <- function(loop) {
23 .Call(`_later_new_weakref`, loop)
24 }
25
26 wref_key <- function(w) {
27 .Call(`_later_wref_key`, w)
28 }
29
30 #' Private event loops
31 #'
32 #' Normally, later uses a global event loop for scheduling and running
33 #' functions. However, in some cases, it is useful to create a \emph{private}
34 #' event loop to schedule and execute tasks without disturbing the global event
35 #' loop. For example, you might have asynchronous code that queries a remote
36 #' data source, but want to wait for a full back-and-forth communication to
37 #' complete before continuing in your code -- from the caller's perspective, it
38 #' should behave like synchronous code, and not do anything with the global
39 #' event loop (which could run code unrelated to your operation). To do this,
40 #' you would run your asynchronous code using a private event loop.
41 #'
42 #' \code{create_loop} creates and returns a handle to a private event loop,
43 #' which is useful when for scheduling tasks when you do not want to interfere
44 #' with the global event loop.
45 #'
46 #' \code{destroy_loop} destroys a private event loop.
47 #'
48 #' \code{exists_loop} reports whether an event loop exists -- that is, that it
49 #' has not been destroyed.
50 #'
51 #' \code{current_loop} returns the currently-active event loop. Any calls to
52 #' \code{\link{later}()} or \code{\link{run_now}()} will use the current loop by
53 #' default.
54 #'
55 #' \code{with_loop} evaluates an expression with a given event loop as the
56 #' currently-active loop.
57 #'
58 #' \code{with_temp_loop} creates an event loop, makes it the current loop, then
59 #' evaluates the given expression. Afterwards, the new event loop is destroyed.
60 #'
61 #' \code{global_loop} returns a handle to the global event loop.
62 #'
63 #'
64 #' @param loop A handle to an event loop.
65 #' @param expr An expression to evaluate.
66 #' @param parent The parent event loop for the one being created. Whenever the
67 #' parent loop runs, this loop will also automatically run, without having to
68 #' manually call \code{\link{run_now}()} on this loop. If \code{NULL}, then
69 #' this loop will not have a parent event loop that automatically runs it; the
70 #' only way to run this loop will be by calling \code{\link{run_now}()} on this
71 #' loop.
72 #' @rdname create_loop
73 #'
74 #' @export
75 create_loop <- function(parent = current_loop()) {
76 id <- .globals$next_id
77 .globals$next_id <- id + 1L
78
79 if (is.null(parent)) {
80 parent_id <- -1L
81 } else if (inherits(parent, "event_loop")) {
82 parent_id <- parent$id
83 } else {
84 stop("`parent` must be NULL or an event_loop object.")
85 }
86 createCallbackRegistry(id, parent_id)
87
88 # Create the handle for the loop
89 loop <- new.env(parent = emptyenv())
90 class(loop) <- "event_loop"
91 loop$id <- id
92 lockBinding("id", loop)
93
94 # Add a weak reference to the loop object in our registry.
95 .loops[[as.character(id)]] <- new_weakref(loop)
96
97 if (id != 0L) {
98 # Inform the C++ layer that there are no more R references when the handle
99 # is GC'd (unless it's the global loop.) The global loop handle never gets
100 # GC'd under normal circumstances because .globals$global_loop refers to it.
101 # However, if the package is unloaded it can get GC'd, and we don't want the
102 # destroy_loop() finalizer to give an error message about not being able to
103 # destroy the global loop.
104 reg.finalizer(loop, notify_r_ref_deleted, onexit = TRUE)
105 }
106
107 loop
108 }
109
110 notify_r_ref_deleted <- function(loop) {
111 res <- notifyRRefDeleted(loop$id)
112 if (res) {
113 rm(list = as.character(loop$id), envir = .loops)
114 }
115 invisible(res)
116 }
117
118 #' @rdname create_loop
119 #' @export
120 destroy_loop <- function(loop) {
121 res <- deleteCallbackRegistry(loop$id)
122 if (res) {
123 rm(list = as.character(loop$id), envir = .loops)
124 }
125 invisible(res)
126 }
127
128 #' @rdname create_loop
129 #' @export
130 exists_loop <- function(loop) {
131 existsCallbackRegistry(loop$id)
132 }
133
134 #' @rdname create_loop
135 #' @export
136 current_loop <- function() {
137 id <- getCurrentRegistryId()
138 loop_weakref <- .loops[[as.character(id)]]
139
140 loop <- wref_key(loop_weakref)
141 if (is.null(loop)) {
142 stop("Current loop with id ", id, " not found.")
143 }
144
145 loop
146 }
147
148 #' @rdname create_loop
149 #' @export
150 with_temp_loop <- function(expr) {
151 loop <- create_loop(parent = NULL)
152 on.exit(destroy_loop(loop))
153
154 with_loop(loop, expr)
155 }
156
157 #' @rdname create_loop
158 #' @export
159 with_loop <- function(loop, expr) {
160 if (!exists_loop(loop)) {
161 stop("loop has been destroyed!")
162 }
163 old_loop <- current_loop()
164 if (!identical(loop, old_loop)) {
165 on.exit(setCurrentRegistryId(old_loop$id))
166 setCurrentRegistryId(loop$id)
167 }
168
169 force(expr)
170 }
171
172 #' @rdname create_loop
173 #' @export
174 global_loop <- function() {
175 .globals$global_loop
176 }
177
178 #' @export
179 format.event_loop <- function(x, ...) {
180 str <- paste0("<event loop> ID: ", x$id)
181 if (!exists_loop(x)) {
182 str <- paste(str, "(destroyed)")
183 }
184 str
185 }
186
187 #' @export
188 print.event_loop <- function(x, ...) {
189 cat(format(x, ...))
190 }
191
192
193 #' Executes a function later
194 #'
195 #' Schedule an R function or formula to run after a specified period of time.
196 #' Similar to JavaScript's `setTimeout` function. Like JavaScript, R is
197 #' single-threaded so there's no guarantee that the operation will run exactly
198 #' at the requested time, only that at least that much time will elapse.
199 #'
200 #' The mechanism used by this package is inspired by Simon Urbanek's
201 #' [background](https://github.com/s-u/background) package and similar code in
202 #' Rhttpd.
203 #'
204 #' @note
205 #' To avoid bugs due to reentrancy, by default, scheduled operations only run
206 #' when there is no other R code present on the execution stack; i.e., when R is
207 #' sitting at the top-level prompt. You can force past-due operations to run at
208 #' a time of your choosing by calling [run_now()].
209 #'
210 #' Error handling is not particularly well-defined and may change in the future.
211 #' options(error=browser) should work and errors in `func` should generally not
212 #' crash the R process, but not much else can be said about it at this point.
213 #' If you must have specific behavior occur in the face of errors, put error
214 #' handling logic inside of `func`.
215 #'
216 #' @param func A function or formula (see [rlang::as_function()]).
217 #' @param delay Number of seconds in the future to delay execution. There is no
218 #' guarantee that the function will be executed at the desired time, but it
219 #' should not execute earlier.
220 #' @param loop A handle to an event loop. Defaults to the currently-active loop.
221 #'
222 #' @return A function, which, if invoked, will cancel the callback. The
223 #' function will return \code{TRUE} if the callback was successfully
224 #' cancelled and \code{FALSE} if not (this occurs if the callback has
225 #' executed or has been cancelled already).
226 #'
227 #' @examples
228 #' # Example of formula style
229 #' later(~cat("Hello from the past\n"), 3)
230 #'
231 #' # Example of function style
232 #' later(function() {
233 #' print(summary(cars))
234 #' }, 2)
235 #'
236 #' @export
237 later <- function(func, delay = 0, loop = current_loop()) {
238 # `rlang::as_function` is used conditionally so that `rlang` is not loaded
239 # until used, avoiding this overhead for packages only linking to `later`
240 if (!is.function(func)) {
241 func <- rlang::as_function(func)
242 }
243 id <- execLater(func, delay, loop$id)
244
245 invisible(create_canceller(id, loop$id))
246 }
247
248 # Returns a function that will cancel a callback with the given ID. If the
249 # callback has already been executed or canceled, then the function has no
250 # effect.
251 create_canceller <- function(id, loop_id) {
252 force(id)
253 force(loop_id)
254 function() {
255 invisible(cancel(id, loop_id))
256 }
257 }
258
259 #' Executes a function when a file descriptor is ready
260 #'
261 #' Schedule an R function or formula to run after an indeterminate amount of
262 #' time when file descriptors are ready for reading or writing, subject to an
263 #' optional timeout.
264 #'
265 #' On the occasion the system-level `poll` (on Windows `WSAPoll`) returns an
266 #' error, the callback will be made on a vector of all `NA`s. This is
267 #' indistinguishable from a case where the `poll` succeeds but there are error
268 #' conditions pending against each file descriptor.
269 #'
270 #' If no file descriptors are supplied, the callback is scheduled for immediate
271 #' execution and made on the empty logical vector `logical(0)`.
272 #'
273 #' @param func A function that takes a single argument, a logical vector that
274 #' indicates which file descriptors are ready (a concatenation of `readfds`,
275 #' `writefds` and `exceptfds`). This may be all `FALSE` if the
276 #' `timeout` argument is non-`Inf`. File descriptors with error conditions
277 #' pending are represented as `NA`, as are invalid file descriptors such as
278 #' those already closed.
279 #' @param readfds Integer vector of file descriptors, or Windows SOCKETs, to
280 #' monitor for being ready to read.
281 #' @param writefds Integer vector of file descriptors, or Windows SOCKETs, to
282 #' monitor being ready to write.
283 #' @param exceptfds Integer vector of file descriptors, or Windows SOCKETs, to
284 #' monitor for error conditions pending.
285 #' @param timeout Number of seconds to wait before giving up, and calling `func`
286 #' with all `FALSE`. The default `Inf` implies waiting indefinitely.
287 #' Specifying `0` will check once without blocking, and supplying a negative
288 #' value defaults to a timeout of 1s.
289 #' @param loop A handle to an event loop. Defaults to the currently-active loop.
290 #'
291 #' @inherit later return note
292 #'
293 #' @examplesIf requireNamespace("nanonext", quietly = TRUE)
294 #' # create nanonext sockets
295 #' s1 <- nanonext::socket(listen = "inproc://nano")
296 #' s2 <- nanonext::socket(dial = "inproc://nano")
297 #' fd1 <- nanonext::opt(s1, "recv-fd")
298 #' fd2 <- nanonext::opt(s2, "recv-fd")
299 #'
300 #' # 1. timeout: prints FALSE, FALSE
301 #' later_fd(print, c(fd1, fd2), timeout = 0.1)
302 #' Sys.sleep(0.2)
303 #' run_now()
304 #'
305 #' # 2. fd1 ready: prints TRUE, FALSE
306 #' later_fd(print, c(fd1, fd2), timeout = 1)
307 #' res <- nanonext::send(s2, "msg")
308 #' Sys.sleep(0.1)
309 #' run_now()
310 #'
311 #' # 3. both ready: prints TRUE, TRUE
312 #' res <- nanonext::send(s1, "msg")
313 #' later_fd(print, c(fd1, fd2), timeout = 1)
314 #' Sys.sleep(0.1)
315 #' run_now()
316 #'
317 #' # 4. fd2 ready: prints FALSE, TRUE
318 #' res <- nanonext::recv(s1)
319 #' later_fd(print, c(fd1, fd2), timeout = 1)
320 #' Sys.sleep(0.1)
321 #' run_now()
322 #'
323 #' # 5. fds invalid: prints NA, NA
324 #' close(s2)
325 #' close(s1)
326 #' later_fd(print, c(fd1, fd2), timeout = 0)
327 #' Sys.sleep(0.1)
328 #' run_now()
329 #'
330 #' @export
331 later_fd <- function(
332 func,
333 readfds = integer(),
334 writefds = integer(),
335 exceptfds = integer(),
336 timeout = Inf,
337 loop = current_loop()
338 ) {
339 if (!is.function(func)) {
340 func <- rlang::as_function(func)
341 }
342 xptr <- execLater_fd(func, readfds, writefds, exceptfds, timeout, loop$id)
343
344 invisible(create_fd_canceller(xptr))
345 }
346
347 # Returns a function that will cancel a callback with the given external
348 # pointer. If the callback has already been executed or canceled, then the
349 # function has no effect.
350 create_fd_canceller <- function(xptr) {
351 force(xptr)
352 function() {
353 invisible(fd_cancel(xptr))
354 }
355 }
356
357 #' Execute scheduled operations
358 #'
359 #' Normally, operations scheduled with [later()] will not execute unless/until
360 #' no other R code is on the stack (i.e. at the top-level). If you need to run
361 #' blocking R code for a long time and want to allow scheduled operations to run
362 #' at well-defined points of your own operation, you can call `run_now()` at
363 #' those points and any operations that are due to run will do so.
364 #'
365 #' If one of the callbacks throws an error, the error will _not_ be caught, and
366 #' subsequent callbacks will not be executed (until `run_now()` is called again,
367 #' or control returns to the R prompt). You must use your own
368 #' [tryCatch][base::conditions] if you want to handle errors.
369 #'
370 #' @param timeoutSecs Wait (block) for up to this number of seconds waiting for
371 #' an operation to be ready to run. If `0`, then return immediately if there
372 #' are no operations that are ready to run. If `Inf` or negative, then wait as
373 #' long as it takes (if none are scheduled, then this will block forever).
374 #' @param all If `FALSE`, `run_now()` will execute at most one scheduled
375 #' operation (instead of all eligible operations). This can be useful in cases
376 #' where you want to interleave scheduled operations with your own logic.
377 #' @param loop A handle to an event loop. Defaults to the currently-active loop.
378 #'
379 #' @return A logical indicating whether any callbacks were actually run.
380 #'
381 #' @export
382 run_now <- function(timeoutSecs = 0L, all = TRUE, loop = current_loop()) {
383 invisible(execCallbacks(timeoutSecs, all, loop$id))
384 }
385
386 #' Check if later loop is empty
387 #'
388 #' Returns true if there are currently no callbacks that are scheduled to
389 #' execute in the present or future.
390 #'
391 #' @inheritParams create_loop
392 #' @keywords internal
393 #' @export
394 loop_empty <- function(loop = current_loop()) {
395 idle(loop$id)
396 }
397
398 #' Relative time to next scheduled operation
399 #'
400 #' Returns the duration between now and the earliest operation that is currently
401 #' scheduled, in seconds. If the operation is in the past, the value will be
402 #' negative. If no operation is currently scheduled, the value will be `Inf`.
403 #'
404 #' @inheritParams create_loop
405 #' @export
406 next_op_secs <- function(loop = current_loop()) {
407 nextOpSecs(loop$id)
408 }
409
410 #' Get the contents of an event loop, as a list
411 #'
412 #' This function is for debugging only.
413 #'
414 #' @keywords internal
415 list_queue <- function(loop = current_loop()) {
416 list_queue_(loop$id)
417 }