Debian Codegraph @

R/bind-cache.R

raw
1 utils::globalVariables(".GenericCallEnv", add = TRUE)
2
3 #' Add caching with reactivity to an object
4 #'
5 #' @description
6 #'
7 #' `bindCache()` adds caching [reactive()] expressions and `render*` functions
8 #' (like [renderText()], [renderTable()], ...).
9 #'
10 #' Ordinary [reactive()] expressions automatically cache their _most recent_
11 #' value, which helps to avoid redundant computation in downstream reactives.
12 #' `bindCache()` will cache all previous values (as long as they fit in the
13 #' cache) and they can be shared across user sessions. This allows
14 #' `bindCache()` to dramatically improve performance when used correctly.
15
16 #' @details
17 #'
18 #' `bindCache()` requires one or more expressions that are used to generate a
19 #' **cache key**, which is used to determine if a computation has occurred
20 #' before and hence can be retrieved from the cache. If you're familiar with the
21 #' concept of memoizing pure functions (e.g., the \pkg{memoise} package), you
22 #' can think of the cache key as the input(s) to a pure function. As such, one
23 #' should take care to make sure the use of `bindCache()` is _pure_ in the same
24 #' sense, namely:
25 #'
26 #' 1. For a given key, the return value is always the same.
27 #' 2. Evaluation has no side-effects.
28 #'
29 #' In the example here, the `bindCache()` key consists of `input$x` and
30 #' `input$y` combined, and the value is `input$x * input$y`. In this simple
31 #' example, for any given key, there is only one possible returned value.
32 #'
33 #' ```
34 #' r <- reactive({ input$x * input$y }) %>%
35 #' bindCache(input$x, input$y)
36 #' ```
37 #'
38
39 #' The largest performance improvements occur when the cache key is fast to
40 #' compute and the reactive expression is slow to compute. To see if the value
41 #' should be computed, a cached reactive evaluates the key, and then serializes
42 #' and hashes the result. If the resulting hashed key is in the cache, then the
43 #' cached reactive simply retrieves the previously calculated value and returns
44 #' it; if not, then the value is computed and the result is stored in the cache
45 #' before being returned.
46 #'
47 #' To compute the cache key, `bindCache()` hashes the contents of `...`, so it's
48 #' best to avoid including large objects in a cache key since that can result in
49 #' slow hashing. It's also best to avoid reference objects like environments and
50 #' R6 objects, since the serialization of these objects may not capture relevant
51 #' changes.
52 #'
53 #' If you want to use a large object as part of a cache key, it may make sense
54 #' to do some sort of reduction on the data that still captures information
55 #' about whether a value can be retrieved from the cache. For example, if you
56 #' have a large data set with timestamps, it might make sense to extract the
57 #' most recent timestamp and return that. Then, instead of hashing the entire
58 #' data object, the cached reactive only needs to hash the timestamp.
59 #'
60 #' ```
61 #' r <- reactive({ compute(bigdata()) } %>%
62 #' bindCache({ extract_most_recent_time(bigdata()) })
63 #' ```
64 #'
65 #' For computations that are very slow, it often makes sense to pair
66 #' [bindCache()] with [bindEvent()] so that no computation is performed until
67 #' the user explicitly requests it (for more, see the Details section of
68 #' [bindEvent()]).
69
70 #' @section Cache keys and reactivity:
71 #'
72 #' Because the **value** expression (from the original [reactive()]) is
73 #' cached, it is not necessarily re-executed when someone retrieves a value,
74 #' and therefore it can't be used to decide what objects to take reactive
75 #' dependencies on. Instead, the **key** is used to figure out which objects
76 #' to take reactive dependencies on. In short, the key expression is reactive,
77 #' and value expression is no longer reactive.
78 #'
79 #' Here's an example of what not to do: if the key is `input$x` and the value
80 #' expression is from `reactive({input$x + input$y})`, then the resulting
81 #' cached reactive will only take a reactive dependency on `input$x` -- it
82 #' won't recompute `{input$x + input$y}` when just `input$y` changes.
83 #' Moreover, the cache won't use `input$y` as part of the key, and so it could
84 #' return incorrect values in the future when it retrieves values from the
85 #' cache. (See the examples below for an example of this.)
86 #'
87 #' A better cache key would be something like `input$x, input$y`. This does
88 #' two things: it ensures that a reactive dependency is taken on both
89 #' `input$x` and `input$y`, and it also makes sure that both values are
90 #' represented in the cache key.
91 #'
92 #' In general, `key` should use the same reactive inputs as `value`, but the
93 #' computation should be simpler. If there are other (non-reactive) values
94 #' that are consumed, such as external data sources, they should be used in
95 #' the `key` as well. Note that if the `key` is large, it can make sense to do
96 #' some sort of reduction on it so that the serialization and hashing of the
97 #' cache key is not too expensive.
98 #'
99 #' Remember that the key is _reactive_, so it is not re-executed every single
100 #' time that someone accesses the cached reactive. It is only re-executed if
101 #' it has been invalidated by one of the reactives it depends on. For
102 #' example, suppose we have this cached reactive:
103 #'
104 #' ```
105 #' r <- reactive({ input$x * input$y }) %>%
106 #' bindCache(input$x, input$y)
107 #' ```
108 #'
109 #' In this case, the key expression is essentially `reactive(list(input$x,
110 #' input$y))` (there's a bit more to it, but that's a good enough
111 #' approximation). The first time `r()` is called, it executes the key, then
112 #' fails to find it in the cache, so it executes the value expression, `{
113 #' input$x + input$y }`. If `r()` is called again, then it does not need to
114 #' re-execute the key expression, because it has not been invalidated via a
115 #' change to `input$x` or `input$y`; it simply returns the previous value.
116 #' However, if `input$x` or `input$y` changes, then the reactive expression will
117 #' be invalidated, and the next time that someone calls `r()`, the key
118 #' expression will need to be re-executed.
119 #'
120 #' Note that if the cached reactive is passed to [bindEvent()], then the key
121 #' expression will no longer be reactive; instead, the event expression will be
122 #' reactive.
123 #'
124 #'
125 #' @section Cache scope:
126 #'
127 #' By default, when `bindCache()` is used, it is scoped to the running
128 #' application. That means that it shares a cache with all user sessions
129 #' connected to the application (within the R process). This is done with the
130 #' `cache` parameter's default value, `"app"`.
131 #'
132 #' With an app-level cache scope, one user can benefit from the work done for
133 #' another user's session. In most cases, this is the best way to get
134 #' performance improvements from caching. However, in some cases, this could
135 #' leak information between sessions. For example, if the cache key does not
136 #' fully encompass the inputs used by the value, then data could leak between
137 #' the sessions. Or if a user sees that a cached reactive returns its value
138 #' very quickly, they may be able to infer that someone else has already used
139 #' it with the same values.
140 #'
141 #' It is also possible to scope the cache to the session, with
142 #' `cache="session"`. This removes the risk of information leaking between
143 #' sessions, but then one session cannot benefit from computations performed in
144 #' another session.
145 #'
146 #' It is possible to pass in caching objects directly to
147 #' `bindCache()`. This can be useful if, for example, you want to use a
148 #' particular type of cache with specific cached reactives, or if you want to
149 #' use a [cachem::cache_disk()] that is shared across multiple processes and
150 #' persists beyond the current R session.
151 #'
152 #' To use different settings for an application-scoped cache, you can call
153 #' [shinyOptions()] at the top of your app.R, server.R, or
154 #' global.R. For example, this will create a cache with 500 MB of space
155 #' instead of the default 200 MB:
156 #'
157 #' ```
158 #' shinyOptions(cache = cachem::cache_mem(max_size = 500e6))
159 #' ```
160 #'
161 #' To use different settings for a session-scoped cache, you can set
162 #' `session$cache` at the top of your server function. By default, it will
163 #' create a 200 MB memory cache for each session, but you can replace it with
164 #' something different. To use the session-scoped cache, you must also call
165 #' `bindCache()` with `cache="session"`. This will create a 100 MB cache for
166 #' the session:
167 #'
168 #' ```
169 #' function(input, output, session) {
170 #' session$cache <- cachem::cache_mem(max_size = 100e6)
171 #' ...
172 #' }
173 #' ```
174 #'
175 #' If you want to use a cache that is shared across multiple R processes, you
176 #' can use a [cachem::cache_disk()]. You can create a application-level shared
177 #' cache by putting this at the top of your app.R, server.R, or global.R:
178 #'
179 #' ```
180 #' shinyOptions(cache = cachem::cache_disk(file.path(dirname(tempdir()), "myapp-cache")))
181 #' ```
182 #'
183 #' This will create a subdirectory in your system temp directory named
184 #' `myapp-cache` (replace `myapp-cache` with a unique name of
185 #' your choosing). On most platforms, this directory will be removed when
186 #' your system reboots. This cache will persist across multiple starts and
187 #' stops of the R process, as long as you do not reboot.
188 #'
189 #' To have the cache persist even across multiple reboots, you can create the
190 #' cache in a location outside of the temp directory. For example, it could
191 #' be a subdirectory of the application:
192 #'
193 #' ```
194 #' shinyOptions(cache = cachem::cache_disk("./myapp-cache"))
195 #' ```
196 #'
197 #' In this case, resetting the cache will have to be done manually, by deleting
198 #' the directory.
199 #'
200 #' You can also scope a cache to just one item, or selected items. To do that,
201 #' create a [cachem::cache_mem()] or [cachem::cache_disk()], and pass it
202 #' as the `cache` argument of `bindCache()`.
203 #'
204
205 #'
206 #' @section Computing cache keys:
207 #'
208 #' The actual cache key that is used internally takes value from evaluating
209 #' the key expression(s) (from the `...` arguments) and combines it with the
210 #' (unevaluated) value expression.
211 #'
212 #' This means that if there are two cached reactives which have the same
213 #' result from evaluating the key, but different value expressions, then they
214 #' will not need to worry about collisions.
215 #'
216 #' However, if two cached reactives have identical key and value expressions
217 #' expressions, they will share the cached values. This is useful when using
218 #' `cache="app"`: there may be multiple user sessions which create separate
219 #' cached reactive objects (because they are created from the same code in the
220 #' server function, but the server function is executed once for each user
221 #' session), and those cached reactive objects across sessions can share
222 #' values in the cache.
223
224
225
226 #'
227 #' @section Async with cached reactives:
228 #'
229 #' With a cached reactive expression, the key and/or value expression can be
230 #' _asynchronous_. In other words, they can be promises --- not regular R
231 #' promises, but rather objects provided by the
232 #' \href{https://rstudio.github.io/promises/}{\pkg{promises}} package, which
233 #' are similar to promises in JavaScript. (See [promises::promise()] for more
234 #' information.) You can also use [mirai::mirai()] or [future::future()]
235 #' objects to run code in a separate process or even on a remote machine.
236 #'
237 #' If the value returns a promise, then anything that consumes the cached
238 #' reactive must expect it to return a promise.
239 #'
240 #' Similarly, if the key is a promise (in other words, if it is asynchronous),
241 #' then the entire cached reactive must be asynchronous, since the key must be
242 #' computed asynchronously before it knows whether to compute the value or the
243 #' value is retrieved from the cache. Anything that consumes the cached
244 #' reactive must therefore expect it to return a promise.
245 #'
246
247 #'
248 #' @section Developing render functions for caching:
249 #'
250 #' If you've implemented your own `render*()` function, it may just work with
251 #' `bindCache()`, but it is possible that you will need to make some
252 #' modifications. These modifications involve helping `bindCache()` avoid
253 #' cache collisions, dealing with internal state that may be set by the,
254 #' `render` function, and modifying the data as it goes in and comes out of
255 #' the cache.
256 #'
257 #' You may need to provide a `cacheHint` to [createRenderFunction()] (or
258 #' `htmlwidgets::shinyRenderWidget()`, if you've authored an htmlwidget) in
259 #' order for `bindCache()` to correctly compute a cache key.
260 #'
261 #' The potential problem is a cache collision. Consider the following:
262 #'
263 #' ```
264 #' output$x1 <- renderText({ input$x }) %>% bindCache(input$x)
265 #' output$x2 <- renderText({ input$x * 2 }) %>% bindCache(input$x)
266 #' ```
267 #'
268 #' Both `output$x1` and `output$x2` use `input$x` as part of their cache key,
269 #' but if it were the only thing used in the cache key, then the two outputs
270 #' would have a cache collision, and they would have the same output. To avoid
271 #' this, a _cache hint_ is automatically added when [renderText()] calls
272 #' [createRenderFunction()]. The cache hint is used as part of the actual
273 #' cache key, in addition to the one passed to `bindCache()` by the user. The
274 #' cache hint can be viewed by calling the internal Shiny function
275 #' `extractCacheHint()`:
276 #'
277 #' ```
278 #' r <- renderText({ input$x })
279 #' shiny:::extractCacheHint(r)
280 #' ```
281 #'
282 #' This returns a nested list containing an item, `$origUserFunc$body`, which
283 #' in this case is the expression which was passed to `renderText()`:
284 #' `{ input$x }`. This (quoted) expression is mixed into the actual cache
285 #' key, and it is how `output$x1` does not have collisions with `output$x2`.
286 #'
287 #' For most developers of render functions, nothing extra needs to be done;
288 #' the automatic inference of the cache hint is sufficient. Again, you can
289 #' check it by calling `shiny:::extractCacheHint()`, and by testing the
290 #' render function for cache collisions in a real application.
291 #'
292 #' In some cases, however, the automatic cache hint inference is not
293 #' sufficient, and it is necessary to provide a cache hint. This is true
294 #' for `renderPrint()`. Unlike `renderText()`, it wraps the user-provided
295 #' expression in another function, before passing it to [createRenderFunction()]
296 #' (instead of [createRenderFunction()]). Because the user code is wrapped in
297 #' another function, `createRenderFunction()` is not able to automatically
298 #' extract the user-provided code and use it in the cache key. Instead,
299 #' `renderPrint` calls `createRenderFunction()`, it explicitly passes along a
300 #' `cacheHint`, which includes a label and the original user expression.
301 #'
302 #' In general, if you need to provide a `cacheHint`, it is best practice to
303 #' provide a `label` id, the user's `expr`, as well as any other arguments
304 #' that may influence the final value.
305 #'
306 #' For \pkg{htmlwidgets}, it will try to automatically infer a cache hint;
307 #' again, you can inspect the cache hint with `shiny:::extractCacheHint()` and
308 #' also test it in an application. If you do need to explicitly provide a
309 #' cache hint, pass it to `shinyRenderWidget`. For example:
310 #'
311 #' ```
312 #' renderMyWidget <- function(expr) {
313 #' q <- rlang::enquo0(expr)
314 #'
315 #' htmlwidgets::shinyRenderWidget(
316 #' q,
317 #' myWidgetOutput,
318 #' quoted = TRUE,
319 #' cacheHint = list(label = "myWidget", userQuo = q)
320 #' )
321 #' }
322 #' ```
323 #'
324 #' If your `render` function sets any internal state, you may find it useful
325 #' in your call to [createRenderFunction()] to use
326 #' the `cacheWriteHook` and/or `cacheReadHook` parameters. These hooks are
327 #' functions that run just before the object is stored in the cache, and just
328 #' after the object is retrieved from the cache. They can modify the data
329 #' that is stored and retrieved; this can be useful if extra information needs
330 #' to be stored in the cache. They can also be used to modify the state of the
331 #' application; for example, it can call [createWebDependency()] to make
332 #' JS/CSS resources available if the cached object is loaded in a different R
333 #' process. (See the source of `htmlwidgets::shinyRenderWidget` for an example
334 #' of this.)
335 #'
336 #' @section Uncacheable objects:
337 #'
338 #' Some render functions cannot be cached, typically because they have side
339 #' effects or modify some external state, and they must re-execute each time
340 #' in order to work properly.
341 #'
342 #' For developers of such code, they should call [createRenderFunction()] (or
343 #' [markRenderFunction()]) with `cacheHint = FALSE`.
344 #'
345 #'
346 #' @section Caching with `renderPlot()`:
347 #'
348 #' When `bindCache()` is used with `renderPlot()`, the `height` and `width`
349 #' passed to the original `renderPlot()` are ignored. They are superseded by
350 #' `sizePolicy` argument passed to `bindCache. The default is:
351 #'
352 #' ```
353 #' sizePolicy = sizeGrowthRatio(width = 400, height = 400, growthRate = 1.2)
354 #' ```
355 #'
356 #' `sizePolicy` must be a function that takes a two-element numeric vector as
357 #' input, representing the width and height of the `<img>` element in the
358 #' browser window, and it must return a two-element numeric vector, representing
359 #' the pixel dimensions of the plot to generate. The purpose is to round the
360 #' actual pixel dimensions from the browser to some other dimensions, so that
361 #' this will not generate and cache images of every possible pixel dimension.
362 #' See [sizeGrowthRatio()] for more information on the default sizing policy.
363 #'
364 #' @param x The object to add caching to.
365 #' @param ... One or more expressions to use in the caching key.
366 #' @param cache The scope of the cache, or a cache object. This can be `"app"`
367 #' (the default), `"session"`, or a cache object like a
368 #' [cachem::cache_disk()]. See the Cache Scoping section for more information.
369 #'
370 #' @seealso [bindEvent()], [renderCachedPlot()] for caching plots.
371 #'
372 #' @examples
373 #' \dontrun{
374 #' rc <- bindCache(
375 #' x = reactive({
376 #' Sys.sleep(2) # Pretend this is expensive
377 #' input$x * 100
378 #' }),
379 #' input$x
380 #' )
381 #'
382 #' # Can make it prettier with the %>% operator
383 #' library(magrittr)
384 #'
385 #' rc <- reactive({
386 #' Sys.sleep(2)
387 #' input$x * 100
388 #' }) %>%
389 #' bindCache(input$x)
390 #'
391 #' }
392 #'
393 #' ## Only run app examples in interactive R sessions
394 #' if (interactive()) {
395 #'
396 #' # Basic example
397 #' shinyApp(
398 #' ui = fluidPage(
399 #' sliderInput("x", "x", 1, 10, 5),
400 #' sliderInput("y", "y", 1, 10, 5),
401 #' div("x * y: "),
402 #' verbatimTextOutput("txt")
403 #' ),
404 #' server = function(input, output) {
405 #' r <- reactive({
406 #' # The value expression is an _expensive_ computation
407 #' message("Doing expensive computation...")
408 #' Sys.sleep(2)
409 #' input$x * input$y
410 #' }) %>%
411 #' bindCache(input$x, input$y)
412 #'
413 #' output$txt <- renderText(r())
414 #' }
415 #' )
416 #'
417 #'
418 #' # Caching renderText
419 #' shinyApp(
420 #' ui = fluidPage(
421 #' sliderInput("x", "x", 1, 10, 5),
422 #' sliderInput("y", "y", 1, 10, 5),
423 #' div("x * y: "),
424 #' verbatimTextOutput("txt")
425 #' ),
426 #' server = function(input, output) {
427 #' output$txt <- renderText({
428 #' message("Doing expensive computation...")
429 #' Sys.sleep(2)
430 #' input$x * input$y
431 #' }) %>%
432 #' bindCache(input$x, input$y)
433 #' }
434 #' )
435 #'
436 #'
437 #' # Demo of using events and caching with an actionButton
438 #' shinyApp(
439 #' ui = fluidPage(
440 #' sliderInput("x", "x", 1, 10, 5),
441 #' sliderInput("y", "y", 1, 10, 5),
442 #' actionButton("go", "Go"),
443 #' div("x * y: "),
444 #' verbatimTextOutput("txt")
445 #' ),
446 #' server = function(input, output) {
447 #' r <- reactive({
448 #' message("Doing expensive computation...")
449 #' Sys.sleep(2)
450 #' input$x * input$y
451 #' }) %>%
452 #' bindCache(input$x, input$y) %>%
453 #' bindEvent(input$go)
454 #' # The cached, eventified reactive takes a reactive dependency on
455 #' # input$go, but doesn't use it for the cache key. It uses input$x and
456 #' # input$y for the cache key, but doesn't take a reactive dependency on
457 #' # them, because the reactive dependency is superseded by addEvent().
458 #'
459 #' output$txt <- renderText(r())
460 #' }
461 #' )
462 #'
463 #' }
464 #'
465 #' @export
466 bindCache <- function(x, ..., cache = "app") {
467 force(cache)
468
469 UseMethod("bindCache")
470 }
471
472 #' @export
473 bindCache.default <- function(x, ...) {
474 stop("Don't know how to handle object with class ", paste(class(x), collapse = ", "))
475 }
476
477 #' @export
478 bindCache.reactiveExpr <- function(x, ..., cache = "app") {
479 check_dots_unnamed()
480
481 call_srcref <- get_call_srcref(-1)
482 label <- rassignSrcrefToLabel(
483 call_srcref,
484 defaultLabel = exprToLabel(substitute(x), "cachedReactive")
485 )
486
487 domain <- reactive_get_domain(x)
488
489 # Convert the ... to a function that returns their evaluated values.
490 keyFunc <- quos_to_func(enquos0(...))
491
492 valueFunc <- reactive_get_value_func(x)
493 # Hash cache hint now -- this will be added to the key later on, to reduce the
494 # chance of key collisions with other cachedReactives.
495 cacheHint <- rlang::hash(extractCacheHint(x))
496 valueFunc <- wrapFunctionLabel(valueFunc, "cachedReactiveValueFunc", ..stacktraceon = TRUE)
497
498 x_classes <- class(x)
499 x_otel_attrs <- attr(x, "observable", exact = TRUE)$.otelAttrs
500
501 # Don't hold on to the reference for x, so that it can be GC'd
502 rm(x)
503 # Hacky workaround for issue with `%>%` preventing GC:
504 # https://github.com/tidyverse/magrittr/issues/229
505 if (exists(".GenericCallEnv") && exists(".", envir = .GenericCallEnv, inherits = FALSE)) {
506 rm(list = ".", envir = .GenericCallEnv, inherits = FALSE)
507 }
508
509 with_no_otel_collect({
510 res <- reactive(label = label, domain = domain, {
511 cache <- resolve_cache_object(cache, domain)
512 hybrid_chain(
513 keyFunc(),
514 generateCacheFun(valueFunc, cache, cacheHint, cacheReadHook = identity, cacheWriteHook = identity)
515 )
516 })
517 })
518
519 class(res) <- c("reactive.cache", class(res))
520
521 local({
522 impl <- attr(res, "observable", exact = TRUE)
523 impl$.otelAttrs <- append_otel_srcref_attrs(x_otel_attrs, call_srcref, fn_name = "bindCache")
524 })
525
526 if (has_otel_collect("reactivity")) {
527 res <- enable_otel_reactive_expr(res)
528 }
529 res
530 }
531
532 #' @export
533 bindCache.shiny.render.function <- function(x, ..., cache = "app") {
534 check_dots_unnamed()
535
536 keyFunc <- quos_to_func(enquos0(...))
537
538 cacheHint <- rlang::hash(extractCacheHint(x))
539
540 cacheWriteHook <- attr(x, "cacheWriteHook", exact = TRUE) %||% identity
541 cacheReadHook <- attr(x, "cacheReadHook", exact = TRUE) %||% identity
542
543 valueFunc <- x
544
545 renderFunc <- function(...) {
546 domain <- getDefaultReactiveDomain()
547 cache <- resolve_cache_object(cache, domain)
548
549 hybrid_chain(
550 keyFunc(),
551 generateCacheFun(valueFunc, cache, cacheHint, cacheReadHook, cacheWriteHook, ...)
552 )
553 }
554
555 # Passes over the otelAttrs from valueFunc to renderFunc
556 renderFunc <- addAttributes(renderFunc, renderFunctionAttributes(valueFunc))
557 class(renderFunc) <- c("shiny.render.function.cache", class(valueFunc))
558 renderFunc
559 }
560
561 #' @export
562 bindCache.shiny.renderPlot <- function(x, ...,
563 cache = "app",
564 sizePolicy = sizeGrowthRatio(width = 400, height = 400, growthRate = 1.2))
565 {
566 check_dots_unnamed()
567
568 valueFunc <- x
569
570 # Given the actual width/height of the image element in the browser, the
571 # resize observer computes the width/height using sizePolicy() and pushes
572 # those values into `fitWidth` and `fitHeight`. It's done this way so that the
573 # `fitWidth` and `fitHeight` only change (and cause invalidations of the key
574 # expression) when the rendered image size changes, and not every time the
575 # browser's <img> tag changes size.
576 #
577 # If the key expression were invalidated every time the image element changed
578 # size, even if the resulting key was the same (because `sizePolicy()` gave
579 # the same output for a slightly different img element size), it would result
580 # in getting the (same) image from the cache and sending it to the client
581 # again. This resize observer prevents that.
582 fitDims <- reactiveVal(NULL)
583 resizeObserverCreated <- FALSE
584 outputName <- NULL
585 ensureResizeObserver <- function() {
586 if (resizeObserverCreated)
587 return()
588
589 doResizeCheck <- function() {
590 if (is.null(outputName)) {
591 outputName <<- getCurrentOutputInfo()$name
592 }
593 session <- getDefaultReactiveDomain()
594
595 width <- session$clientData[[paste0('output_', outputName, '_width')]] %||% 0
596 height <- session$clientData[[paste0('output_', outputName, '_height')]] %||% 0
597
598 rect <- sizePolicy(c(width, height))
599 fitDims(list(width = rect[1], height = rect[2]))
600 }
601
602 # Run it once immediately, then set up the observer
603 isolate(doResizeCheck())
604
605 observe({
606 doResizeCheck()
607 }, label = "plot-resize")
608 # TODO: Make sure this observer gets GC'd if output$foo is replaced.
609 # Currently, if you reassign output$foo, the observer persists until the
610 # session ends. This is generally bad programming practice and should be
611 # rare, but still, we should try to clean up properly.
612
613 resizeObserverCreated <<- TRUE
614 }
615
616 renderFunc <- function(...) {
617 hybrid_chain(
618 # Pass in fitDims so that so that the generated plot will be the
619 # dimensions specified by the sizePolicy; otherwise the plot would be the
620 # exact dimensions of the img element, which isn't what we want for cached
621 # plots.
622 valueFunc(..., get_dims = fitDims),
623 function(img) {
624 # Replace exact pixel dimensions; instead, the max-height and max-width
625 # will be set to 100% from CSS.
626 img$class <- "shiny-scalable"
627 img$width <- NULL
628 img$height <- NULL
629
630 img
631 }
632 )
633 }
634
635 renderFunc <- addAttributes(renderFunc, renderFunctionAttributes(valueFunc))
636 class(renderFunc) <- class(valueFunc)
637
638 bindCache.shiny.render.function(
639 renderFunc,
640 ...,
641 {
642 ensureResizeObserver()
643 session <- getDefaultReactiveDomain()
644 if (is.null(session) || is.null(fitDims())) {
645 req(FALSE)
646 }
647 pixelratio <- session$clientData$pixelratio %||% 1
648
649 list(fitDims(), pixelratio)
650 },
651 cache = cache
652 )
653 }
654
655 #' @export
656 bindCache.reactive.cache <- function(x, ...) {
657 stop("bindCache() has already been called on the object.")
658 }
659
660 #' @export
661 bindCache.shiny.render.function.cache <- bindCache.reactive.cache
662
663 #' @export
664 bindCache.reactive.event <- function(x, ...) {
665 stop("Can't call bindCache() after calling bindEvent() on an object. Maybe you wanted to call bindEvent() after bindCache()?")
666 }
667
668 #' @export
669 bindCache.shiny.render.function.event <- bindCache.reactive.event
670
671 #' @export
672 bindCache.Observer <- function(x, ...) {
673 stop("Can't bindCache an observer, because observers exist for the side efects, not for their return values.")
674 }
675
676 #' @export
677 bindCache.function <- function(x, ...) {
678 stop(
679 "Don't know how to add caching to a plain function. ",
680 "If this is a render* function for Shiny, it may need to be updated. ",
681 "Please see ?shiny::bindCache for more information."
682 )
683 }
684
685 # Returns a function which should be passed as a step in to hybrid_chain(). The
686 # returned function takes a cache key as input and manages storing and retrieving
687 # values from the cache, as well as executing the valueFunc if needed.
688 generateCacheFun <- function(
689 valueFunc,
690 cache,
691 cacheHint,
692 cacheReadHook,
693 cacheWriteHook,
694 ...
695 ) {
696 function(cacheKeyResult) {
697 key_str <- rlang::hash(list(cacheKeyResult, cacheHint))
698 res <- cache$get(key_str)
699
700 # Case 1: cache hit
701 if (!is.key_missing(res)) {
702 return(hybrid_chain(
703 {
704 # The first step is just to convert `res` to a promise or not, so
705 # that hybrid_chain() knows to propagate the promise-ness.
706 if (res$is_promise) promise_resolve(res)
707 else res
708 },
709 function(res) {
710 if (res$error) {
711 stop(res$value)
712 }
713
714 cacheReadHook(valueWithVisible(res))
715 }
716 ))
717 }
718
719 # Case 2: cache miss
720 #
721 # valueFunc() might return a promise, or an actual value. Normally we'd
722 # use a hybrid_chain() for this, but in this case, we need to have
723 # different behavior if it's a promise or not a promise -- the
724 # information about whether or not it's a promise needs to be stored in
725 # the cache. We need to handle both cases and record in the cache
726 # whether it's a promise or not, so that any consumer of the
727 # cachedReactive() will be given the correct kind of object (a promise
728 # vs. an actual value) in the case of a future cache hit.
729 p <- withCallingHandlers(
730 withVisible(isolate(valueFunc(...))),
731 error = function(e) {
732 cache$set(key_str, list(
733 is_promise = FALSE,
734 value = e,
735 visible = TRUE,
736 error = TRUE
737 ))
738 }
739 )
740
741 if (is.promising(p$value)) {
742 p$value <- as.promise(p$value)
743 p$value <- p$value$
744 then(function(value) {
745 res <- withVisible(value)
746 cache$set(key_str, list(
747 is_promise = TRUE,
748 value = cacheWriteHook(res$value),
749 visible = res$visible,
750 error = FALSE
751 ))
752 valueWithVisible(res)
753 })$
754 catch(function(e) {
755 cache$set(key_str, list(
756 is_promise = TRUE,
757 value = e,
758 visible = TRUE,
759 error = TRUE
760 ))
761 stop(e)
762 })
763 valueWithVisible(p)
764 } else {
765 # result is an ordinary value, not a promise.
766 cache$set(key_str, list(
767 is_promise = FALSE,
768 value = cacheWriteHook(p$value),
769 visible = p$visible,
770 error = FALSE
771 ))
772 return(valueWithVisible(p))
773 }
774 }
775 }
776
777 extractCacheHint <- function(func) {
778 cacheHint <- attr(func, "cacheHint", exact = TRUE)
779
780 if (is_false(cacheHint)) {
781 stop(
782 "Cannot call `bindCache()` on this object because it is marked as not cacheable.",
783 call. = FALSE
784 )
785 }
786
787 if (is.null(cacheHint)) {
788 warning("No cacheHint found for this object. ",
789 "Caching may not work properly.")
790 }
791
792 cacheHint
793 }