| 1 |
#' Task or computation that proceeds in the background |
| 2 |
#' |
| 3 |
#' @description In normal Shiny reactive code, whenever an observer, calc, or |
| 4 |
#' output is busy computing, it blocks the current session from receiving any |
| 5 |
#' inputs or attempting to proceed with any other computation related to that |
| 6 |
#' session. |
| 7 |
#' |
| 8 |
#' The `ExtendedTask` class allows you to have an expensive operation that is |
| 9 |
#' started by a reactive effect, and whose (eventual) results can be accessed |
| 10 |
#' by a regular observer, calc, or output; but during the course of the |
| 11 |
#' operation, the current session is completely unblocked, allowing the user |
| 12 |
#' to continue using the rest of the app while the operation proceeds in the |
| 13 |
#' background. |
| 14 |
#' |
| 15 |
#' Note that each `ExtendedTask` object does not represent a _single |
| 16 |
#' invocation_ of its long-running function. Rather, it's an object that is |
| 17 |
#' used to invoke the function with different arguments, keeps track of |
| 18 |
#' whether an invocation is in progress, and provides ways to get at the |
| 19 |
#' current status or results of the operation. A single `ExtendedTask` object |
| 20 |
#' does not permit overlapping invocations: if the `invoke()` method is called |
| 21 |
#' before the previous `invoke()` is completed, the new invocation will not |
| 22 |
#' begin until the previous invocation has completed. |
| 23 |
#' |
| 24 |
#' @section `ExtendedTask` versus asynchronous reactives: |
| 25 |
#' |
| 26 |
#' Shiny has long supported [using |
| 27 |
#' \{promises\}](https://rstudio.github.io/promises/articles/promises_06_shiny.html) |
| 28 |
#' to write asynchronous observers, calcs, or outputs. You may be wondering |
| 29 |
#' what the differences are between those techniques and this class. |
| 30 |
#' |
| 31 |
#' Asynchronous observers, calcs, and outputs are not--and have never |
| 32 |
#' been--designed to let a user start a long-running operation, while keeping |
| 33 |
#' that very same (browser) session responsive to other interactions. Instead, |
| 34 |
#' they unblock other sessions, so you can take a long-running operation that |
| 35 |
#' would normally bring the entire R process to a halt and limit the blocking |
| 36 |
#' to just the session that started the operation. (For more details, see the |
| 37 |
#' section on ["The Flush |
| 38 |
#' Cycle"](https://rstudio.github.io/promises/articles/promises_06_shiny.html#the-flush-cycle).) |
| 39 |
#' |
| 40 |
#' `ExtendedTask`, on the other hand, invokes an asynchronous function (that |
| 41 |
#' is, a function that quickly returns a promise) and allows even that very |
| 42 |
#' session to immediately unblock and carry on with other user interactions. |
| 43 |
#' |
| 44 |
#' @section OpenTelemetry Integration: |
| 45 |
#' |
| 46 |
#' When an `ExtendedTask` is created, if OpenTelemetry tracing is enabled for |
| 47 |
#' `"reactivity"` (see [withOtelCollect()]), the `ExtendedTask` will record |
| 48 |
#' spans for each invocation of the task. The tracing level at `invoke()` time |
| 49 |
#' does not affect whether spans are recorded; only the tracing level when |
| 50 |
#' calling `ExtendedTask$new()` matters. |
| 51 |
#' |
| 52 |
#' The OTel span will be named based on the label created from the variable the |
| 53 |
#' `ExtendedTask` is assigned to. If no label can be determined, the span will |
| 54 |
#' be named `<anonymous>`. Similar to other Shiny OpenTelemetry spans, the span |
| 55 |
#' will also include source reference attributes and session ID attributes. |
| 56 |
#' |
| 57 |
#' ```r |
| 58 |
#' withOtelCollect("all", { |
| 59 |
#' my_task <- ExtendedTask$new(function(...) { ... }) |
| 60 |
#' }) |
| 61 |
#' |
| 62 |
#' # Span recorded for this invocation: ExtendedTask my_task |
| 63 |
#' my_task$invoke(...) |
| 64 |
#' ``` |
| 65 |
#' |
| 66 |
#' @examplesIf rlang::is_interactive() && rlang::is_installed("mirai") |
| 67 |
#' library(shiny) |
| 68 |
#' library(bslib) |
| 69 |
#' library(mirai) |
| 70 |
#' |
| 71 |
#' # Set background processes for running tasks |
| 72 |
#' daemons(1) |
| 73 |
#' # Reset when the app is stopped |
| 74 |
#' onStop(function() daemons(0)) |
| 75 |
#' |
| 76 |
#' ui <- page_fluid( |
| 77 |
#' titlePanel("Extended Task Demo"), |
| 78 |
#' p( |
| 79 |
#' 'Click the button below to perform a "calculation"', |
| 80 |
#' "that takes a while to perform." |
| 81 |
#' ), |
| 82 |
#' input_task_button("recalculate", "Recalculate"), |
| 83 |
#' p(textOutput("result")) |
| 84 |
#' ) |
| 85 |
#' |
| 86 |
#' server <- function(input, output) { |
| 87 |
#' rand_task <- ExtendedTask$new(function() { |
| 88 |
#' mirai( |
| 89 |
#' { |
| 90 |
#' # Slow operation goes here |
| 91 |
#' Sys.sleep(2) |
| 92 |
#' sample(1:100, 1) |
| 93 |
#' } |
| 94 |
#' ) |
| 95 |
#' }) |
| 96 |
#' |
| 97 |
#' # Make button state reflect task. |
| 98 |
#' # If using R >=4.1, you can do this instead: |
| 99 |
#' # rand_task <- ExtendedTask$new(...) |> bind_task_button("recalculate") |
| 100 |
#' bind_task_button(rand_task, "recalculate") |
| 101 |
#' |
| 102 |
#' observeEvent(input$recalculate, { |
| 103 |
#' # Invoke the extended in an observer |
| 104 |
#' rand_task$invoke() |
| 105 |
#' }) |
| 106 |
#' |
| 107 |
#' output$result <- renderText({ |
| 108 |
#' # React to updated results when the task completes |
| 109 |
#' number <- rand_task$result() |
| 110 |
#' paste0("Your number is ", number, ".") |
| 111 |
#' }) |
| 112 |
#' } |
| 113 |
#' |
| 114 |
#' shinyApp(ui, server) |
| 115 |
#' |
| 116 |
#' @export |
| 117 |
ExtendedTask <- R6Class("ExtendedTask", portable = TRUE, cloneable = FALSE, |
| 118 |
public = list( |
| 119 |
#' @description |
| 120 |
#' Creates a new `ExtendedTask` object. `ExtendedTask` should generally be |
| 121 |
#' created either at the top of a server function, or at the top of a module |
| 122 |
#' server function. |
| 123 |
#' |
| 124 |
#' @param func The long-running operation to execute. This should be an |
| 125 |
#' asynchronous function, meaning, it should use the |
| 126 |
#' [\{promises\}](https://rstudio.github.io/promises/) package, most |
| 127 |
#' likely in conjunction with the |
| 128 |
#' [\{mirai\}](https://mirai.r-lib.org) or |
| 129 |
#' [\{future\}](https://rstudio.github.io/promises/articles/promises_04_futures.html) |
| 130 |
#' package. (In short, the return value of `func` should be a |
| 131 |
#' [`mirai`][mirai::mirai()], [`Future`][future::future()], `promise`, |
| 132 |
#' or something else that [promises::as.promise()] understands.) |
| 133 |
#' |
| 134 |
#' It's also important that this logic does not read from any |
| 135 |
#' reactive inputs/sources, as inputs may change after the function is |
| 136 |
#' invoked; instead, if the function needs to access reactive inputs, it |
| 137 |
#' should take parameters and the caller of the `invoke()` method should |
| 138 |
#' read reactive inputs and pass them as arguments. |
| 139 |
initialize = function(func) { |
| 140 |
private$func <- func |
| 141 |
|
| 142 |
# Do not show these private reactive values in otel spans |
| 143 |
with_no_otel_collect({ |
| 144 |
private$rv_status <- reactiveVal("initial", label = "ExtendedTask$private$status") |
| 145 |
private$rv_value <- reactiveVal(NULL, label = "ExtendedTask$private$value") |
| 146 |
private$rv_error <- reactiveVal(NULL, label = "ExtendedTask$private$error") |
| 147 |
}) |
| 148 |
|
| 149 |
private$invocation_queue <- fastmap::fastqueue() |
| 150 |
|
| 151 |
domain <- getDefaultReactiveDomain() |
| 152 |
|
| 153 |
# Set a label for the reactive values for easier debugging |
| 154 |
# Go up an extra sys.call() to get the user's call to ExtendedTask$new() |
| 155 |
# The first sys.call() is to `initialize(...)` |
| 156 |
call_srcref <- get_call_srcref(-1) |
| 157 |
label <- rassignSrcrefToLabel( |
| 158 |
call_srcref, |
| 159 |
defaultLabel = "<anonymous>" |
| 160 |
) |
| 161 |
private$otel_span_label <- otel_span_label_extended_task(label, domain = domain) |
| 162 |
private$otel_log_label_add_to_queue <- otel_log_label_extended_task_add_to_queue(label, domain = domain) |
| 163 |
|
| 164 |
private$otel_attrs <- c( |
| 165 |
otel_srcref_attributes(call_srcref, "ExtendedTask"), |
| 166 |
otel_session_id_attrs(domain) |
| 167 |
) %||% list() |
| 168 |
|
| 169 |
# Capture this value at init-time, not run-time |
| 170 |
# This way, the span is only created if otel was enabled at time of creation... just like other spans |
| 171 |
private$is_recording_otel <- has_otel_collect("reactivity") |
| 172 |
}, |
| 173 |
#' @description |
| 174 |
#' Starts executing the long-running operation. If this `ExtendedTask` is |
| 175 |
#' already running (meaning, a previous call to `invoke()` is not yet |
| 176 |
#' complete) then enqueues this invocation until after the current |
| 177 |
#' invocation, and any already-enqueued invocation, completes. |
| 178 |
#' |
| 179 |
#' @param ... Parameters to use for this invocation of the underlying |
| 180 |
#' function. If reactive inputs are needed by the underlying function, |
| 181 |
#' they should be read by the caller of `invoke` and passed in as |
| 182 |
#' arguments. |
| 183 |
invoke = function(...) { |
| 184 |
args <- rlang::dots_list(..., .ignore_empty = "none") |
| 185 |
call <- rlang::caller_call(n = 0) |
| 186 |
|
| 187 |
if ( |
| 188 |
isolate(private$rv_status()) == "running" || |
| 189 |
private$invocation_queue$size() > 0 |
| 190 |
) { |
| 191 |
otel_log( |
| 192 |
private$otel_log_add_to_queue_label, |
| 193 |
severity = "debug", |
| 194 |
attributes = c( |
| 195 |
private$otel_attrs, |
| 196 |
list( |
| 197 |
queue_size = private$invocation_queue$size() + 1L |
| 198 |
) |
| 199 |
) |
| 200 |
) |
| 201 |
private$invocation_queue$add(list(args = args, call = call)) |
| 202 |
} else { |
| 203 |
|
| 204 |
if (private$is_recording_otel) { |
| 205 |
private$otel_span <- start_otel_span( |
| 206 |
private$otel_span_label, |
| 207 |
attributes = private$otel_attrs |
| 208 |
) |
| 209 |
otel::local_active_span(private$otel_span) |
| 210 |
} |
| 211 |
|
| 212 |
private$do_invoke(args, call = call) |
| 213 |
} |
| 214 |
invisible(NULL) |
| 215 |
}, |
| 216 |
#' @description |
| 217 |
#' This is a reactive read that invalidates the caller when the task's |
| 218 |
#' status changes. |
| 219 |
#' |
| 220 |
#' Returns one of the following values: |
| 221 |
#' |
| 222 |
#' * `"initial"`: This `ExtendedTask` has not yet been invoked |
| 223 |
#' * `"running"`: An invocation is currently running |
| 224 |
#' * `"success"`: An invocation completed successfully, and a value can be |
| 225 |
#' retrieved via the `result()` method |
| 226 |
#' * `"error"`: An invocation completed with an error, which will be |
| 227 |
#' re-thrown if you call the `result()` method |
| 228 |
status = function() { |
| 229 |
private$rv_status() |
| 230 |
}, |
| 231 |
#' @description |
| 232 |
#' Attempts to read the results of the most recent invocation. This is a |
| 233 |
#' reactive read that invalidates as the task's status changes. |
| 234 |
#' |
| 235 |
#' The actual behavior differs greatly depending on the current status of |
| 236 |
#' the task: |
| 237 |
#' |
| 238 |
#' * `"initial"`: Throws a silent error (like [`req(FALSE)`][req()]). If |
| 239 |
#' this happens during output rendering, the output will be blanked out. |
| 240 |
#' * `"running"`: Throws a special silent error that, if it happens during |
| 241 |
#' output rendering, makes the output appear "in progress" until further |
| 242 |
#' notice. |
| 243 |
#' * `"success"`: Returns the return value of the most recent invocation. |
| 244 |
#' * `"error"`: Throws whatever error was thrown by the most recent |
| 245 |
#' invocation. |
| 246 |
#' |
| 247 |
#' This method is intended to be called fairly naively by any output or |
| 248 |
#' reactive expression that cares about the output--you just have to be |
| 249 |
#' aware that if the result isn't ready for whatever reason, processing will |
| 250 |
#' stop in much the same way as `req(FALSE)` does, but when the result is |
| 251 |
#' ready you'll get invalidated, and when you run again the result should be |
| 252 |
#' there. |
| 253 |
#' |
| 254 |
#' Note that the `result()` method is generally not meant to be used with |
| 255 |
#' [observeEvent()], [eventReactive()], [bindEvent()], or [isolate()] as the |
| 256 |
#' invalidation will be ignored. |
| 257 |
result = function() { |
| 258 |
switch (private$rv_status(), |
| 259 |
running = req(FALSE, cancelOutput = "progress"), |
| 260 |
success = if (private$rv_value()$visible) { |
| 261 |
private$rv_value()$value |
| 262 |
} else { |
| 263 |
invisible(private$rv_value()$value) |
| 264 |
}, |
| 265 |
error = stop(private$rv_error()), |
| 266 |
# default case (initial, cancelled) |
| 267 |
req(FALSE) |
| 268 |
) |
| 269 |
} |
| 270 |
), |
| 271 |
private = list( |
| 272 |
func = NULL, |
| 273 |
# reactive value with "initial"|"running"|"success"|"error" |
| 274 |
rv_status = NULL, |
| 275 |
rv_value = NULL, |
| 276 |
rv_error = NULL, |
| 277 |
invocation_queue = NULL, |
| 278 |
|
| 279 |
otel_span_label = NULL, |
| 280 |
otel_log_label_add_to_queue = NULL, |
| 281 |
otel_attrs = list(), |
| 282 |
is_recording_otel = FALSE, |
| 283 |
otel_span = NULL, |
| 284 |
|
| 285 |
do_invoke = function(args, call = NULL) { |
| 286 |
private$rv_status("running") |
| 287 |
private$rv_value(NULL) |
| 288 |
private$rv_error(NULL) |
| 289 |
|
| 290 |
p <- promise_resolve( |
| 291 |
maskReactiveContext(do.call(private$func, args)) |
| 292 |
) |
| 293 |
|
| 294 |
p <- promises::then( |
| 295 |
p, |
| 296 |
onFulfilled = function(value, .visible) { |
| 297 |
if (is_otel_span(private$otel_span)) { |
| 298 |
|
| 299 |
private$otel_span$end(status_code = "ok") |
| 300 |
private$otel_span <- NULL |
| 301 |
} |
| 302 |
private$on_success(list(value = value, visible = .visible)) |
| 303 |
}, |
| 304 |
onRejected = function(error) { |
| 305 |
if (is_otel_span(private$otel_span)) { |
| 306 |
private$otel_span$end(status_code = "error") |
| 307 |
private$otel_span <- NULL |
| 308 |
} |
| 309 |
private$on_error(error, call = call) |
| 310 |
} |
| 311 |
) |
| 312 |
|
| 313 |
promises::finally(p, onFinally = function() { |
| 314 |
if (private$invocation_queue$size() > 0) { |
| 315 |
next_call <- private$invocation_queue$remove() |
| 316 |
private$do_invoke(next_call$args, next_call$call) |
| 317 |
} |
| 318 |
}) |
| 319 |
|
| 320 |
invisible(NULL) |
| 321 |
}, |
| 322 |
|
| 323 |
on_error = function(err, call = NULL) { |
| 324 |
cli::cli_warn( |
| 325 |
"ERROR: An error occurred when invoking the ExtendedTask.", |
| 326 |
parent = err, |
| 327 |
call = call |
| 328 |
) |
| 329 |
private$rv_status("error") |
| 330 |
private$rv_error(err) |
| 331 |
}, |
| 332 |
|
| 333 |
on_success = function(value) { |
| 334 |
private$rv_status("success") |
| 335 |
private$rv_value(value) |
| 336 |
} |
| 337 |
) |
| 338 |
) |