Debian Codegraph @

man/bindCache.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/bind-cache.R
3 \name{bindCache}
4 \alias{bindCache}
5 \title{Add caching with reactivity to an object}
6 \usage{
7 bindCache(x, ..., cache = "app")
8 }
9 \arguments{
10 \item{x}{The object to add caching to.}
11
12 \item{...}{One or more expressions to use in the caching key.}
13
14 \item{cache}{The scope of the cache, or a cache object. This can be \code{"app"}
15 (the default), \code{"session"}, or a cache object like a
16 \code{\link[cachem:cache_disk]{cachem::cache_disk()}}. See the Cache Scoping section for more information.}
17 }
18 \description{
19 \code{bindCache()} adds caching \code{\link[=reactive]{reactive()}} expressions and \verb{render*} functions
20 (like \code{\link[=renderText]{renderText()}}, \code{\link[=renderTable]{renderTable()}}, ...).
21
22 Ordinary \code{\link[=reactive]{reactive()}} expressions automatically cache their \emph{most recent}
23 value, which helps to avoid redundant computation in downstream reactives.
24 \code{bindCache()} will cache all previous values (as long as they fit in the
25 cache) and they can be shared across user sessions. This allows
26 \code{bindCache()} to dramatically improve performance when used correctly.
27 }
28 \details{
29 \code{bindCache()} requires one or more expressions that are used to generate a
30 \strong{cache key}, which is used to determine if a computation has occurred
31 before and hence can be retrieved from the cache. If you're familiar with the
32 concept of memoizing pure functions (e.g., the \pkg{memoise} package), you
33 can think of the cache key as the input(s) to a pure function. As such, one
34 should take care to make sure the use of \code{bindCache()} is \emph{pure} in the same
35 sense, namely:
36 \enumerate{
37 \item For a given key, the return value is always the same.
38 \item Evaluation has no side-effects.
39 }
40
41 In the example here, the \code{bindCache()} key consists of \code{input$x} and
42 \code{input$y} combined, and the value is \code{input$x * input$y}. In this simple
43 example, for any given key, there is only one possible returned value.
44
45 \if{html}{\out{<div class="sourceCode">}}\preformatted{r <- reactive(\{ input$x * input$y \}) \%>\%
46 bindCache(input$x, input$y)
47 }\if{html}{\out{</div>}}
48
49 The largest performance improvements occur when the cache key is fast to
50 compute and the reactive expression is slow to compute. To see if the value
51 should be computed, a cached reactive evaluates the key, and then serializes
52 and hashes the result. If the resulting hashed key is in the cache, then the
53 cached reactive simply retrieves the previously calculated value and returns
54 it; if not, then the value is computed and the result is stored in the cache
55 before being returned.
56
57 To compute the cache key, \code{bindCache()} hashes the contents of \code{...}, so it's
58 best to avoid including large objects in a cache key since that can result in
59 slow hashing. It's also best to avoid reference objects like environments and
60 R6 objects, since the serialization of these objects may not capture relevant
61 changes.
62
63 If you want to use a large object as part of a cache key, it may make sense
64 to do some sort of reduction on the data that still captures information
65 about whether a value can be retrieved from the cache. For example, if you
66 have a large data set with timestamps, it might make sense to extract the
67 most recent timestamp and return that. Then, instead of hashing the entire
68 data object, the cached reactive only needs to hash the timestamp.
69
70 \if{html}{\out{<div class="sourceCode">}}\preformatted{r <- reactive(\{ compute(bigdata()) \} \%>\%
71 bindCache(\{ extract_most_recent_time(bigdata()) \})
72 }\if{html}{\out{</div>}}
73
74 For computations that are very slow, it often makes sense to pair
75 \code{\link[=bindCache]{bindCache()}} with \code{\link[=bindEvent]{bindEvent()}} so that no computation is performed until
76 the user explicitly requests it (for more, see the Details section of
77 \code{\link[=bindEvent]{bindEvent()}}).
78 }
79 \section{Cache keys and reactivity}{
80
81
82 Because the \strong{value} expression (from the original \code{\link[=reactive]{reactive()}}) is
83 cached, it is not necessarily re-executed when someone retrieves a value,
84 and therefore it can't be used to decide what objects to take reactive
85 dependencies on. Instead, the \strong{key} is used to figure out which objects
86 to take reactive dependencies on. In short, the key expression is reactive,
87 and value expression is no longer reactive.
88
89 Here's an example of what not to do: if the key is \code{input$x} and the value
90 expression is from \code{reactive({input$x + input$y})}, then the resulting
91 cached reactive will only take a reactive dependency on \code{input$x} -- it
92 won't recompute \code{{input$x + input$y}} when just \code{input$y} changes.
93 Moreover, the cache won't use \code{input$y} as part of the key, and so it could
94 return incorrect values in the future when it retrieves values from the
95 cache. (See the examples below for an example of this.)
96
97 A better cache key would be something like \verb{input$x, input$y}. This does
98 two things: it ensures that a reactive dependency is taken on both
99 \code{input$x} and \code{input$y}, and it also makes sure that both values are
100 represented in the cache key.
101
102 In general, \code{key} should use the same reactive inputs as \code{value}, but the
103 computation should be simpler. If there are other (non-reactive) values
104 that are consumed, such as external data sources, they should be used in
105 the \code{key} as well. Note that if the \code{key} is large, it can make sense to do
106 some sort of reduction on it so that the serialization and hashing of the
107 cache key is not too expensive.
108
109 Remember that the key is \emph{reactive}, so it is not re-executed every single
110 time that someone accesses the cached reactive. It is only re-executed if
111 it has been invalidated by one of the reactives it depends on. For
112 example, suppose we have this cached reactive:
113
114 \if{html}{\out{<div class="sourceCode">}}\preformatted{r <- reactive(\{ input$x * input$y \}) \%>\%
115 bindCache(input$x, input$y)
116 }\if{html}{\out{</div>}}
117
118 In this case, the key expression is essentially \code{reactive(list(input$x, input$y))} (there's a bit more to it, but that's a good enough
119 approximation). The first time \code{r()} is called, it executes the key, then
120 fails to find it in the cache, so it executes the value expression, \code{{ input$x + input$y }}. If \code{r()} is called again, then it does not need to
121 re-execute the key expression, because it has not been invalidated via a
122 change to \code{input$x} or \code{input$y}; it simply returns the previous value.
123 However, if \code{input$x} or \code{input$y} changes, then the reactive expression will
124 be invalidated, and the next time that someone calls \code{r()}, the key
125 expression will need to be re-executed.
126
127 Note that if the cached reactive is passed to \code{\link[=bindEvent]{bindEvent()}}, then the key
128 expression will no longer be reactive; instead, the event expression will be
129 reactive.
130 }
131
132 \section{Cache scope}{
133
134
135 By default, when \code{bindCache()} is used, it is scoped to the running
136 application. That means that it shares a cache with all user sessions
137 connected to the application (within the R process). This is done with the
138 \code{cache} parameter's default value, \code{"app"}.
139
140 With an app-level cache scope, one user can benefit from the work done for
141 another user's session. In most cases, this is the best way to get
142 performance improvements from caching. However, in some cases, this could
143 leak information between sessions. For example, if the cache key does not
144 fully encompass the inputs used by the value, then data could leak between
145 the sessions. Or if a user sees that a cached reactive returns its value
146 very quickly, they may be able to infer that someone else has already used
147 it with the same values.
148
149 It is also possible to scope the cache to the session, with
150 \code{cache="session"}. This removes the risk of information leaking between
151 sessions, but then one session cannot benefit from computations performed in
152 another session.
153
154 It is possible to pass in caching objects directly to
155 \code{bindCache()}. This can be useful if, for example, you want to use a
156 particular type of cache with specific cached reactives, or if you want to
157 use a \code{\link[cachem:cache_disk]{cachem::cache_disk()}} that is shared across multiple processes and
158 persists beyond the current R session.
159
160 To use different settings for an application-scoped cache, you can call
161 \code{\link[=shinyOptions]{shinyOptions()}} at the top of your app.R, server.R, or
162 global.R. For example, this will create a cache with 500 MB of space
163 instead of the default 200 MB:
164
165 \if{html}{\out{<div class="sourceCode">}}\preformatted{shinyOptions(cache = cachem::cache_mem(max_size = 500e6))
166 }\if{html}{\out{</div>}}
167
168 To use different settings for a session-scoped cache, you can set
169 \code{session$cache} at the top of your server function. By default, it will
170 create a 200 MB memory cache for each session, but you can replace it with
171 something different. To use the session-scoped cache, you must also call
172 \code{bindCache()} with \code{cache="session"}. This will create a 100 MB cache for
173 the session:
174
175 \if{html}{\out{<div class="sourceCode">}}\preformatted{function(input, output, session) \{
176 session$cache <- cachem::cache_mem(max_size = 100e6)
177 ...
178 \}
179 }\if{html}{\out{</div>}}
180
181 If you want to use a cache that is shared across multiple R processes, you
182 can use a \code{\link[cachem:cache_disk]{cachem::cache_disk()}}. You can create a application-level shared
183 cache by putting this at the top of your app.R, server.R, or global.R:
184
185 \if{html}{\out{<div class="sourceCode">}}\preformatted{shinyOptions(cache = cachem::cache_disk(file.path(dirname(tempdir()), "myapp-cache")))
186 }\if{html}{\out{</div>}}
187
188 This will create a subdirectory in your system temp directory named
189 \code{myapp-cache} (replace \code{myapp-cache} with a unique name of
190 your choosing). On most platforms, this directory will be removed when
191 your system reboots. This cache will persist across multiple starts and
192 stops of the R process, as long as you do not reboot.
193
194 To have the cache persist even across multiple reboots, you can create the
195 cache in a location outside of the temp directory. For example, it could
196 be a subdirectory of the application:
197
198 \if{html}{\out{<div class="sourceCode">}}\preformatted{shinyOptions(cache = cachem::cache_disk("./myapp-cache"))
199 }\if{html}{\out{</div>}}
200
201 In this case, resetting the cache will have to be done manually, by deleting
202 the directory.
203
204 You can also scope a cache to just one item, or selected items. To do that,
205 create a \code{\link[cachem:cache_mem]{cachem::cache_mem()}} or \code{\link[cachem:cache_disk]{cachem::cache_disk()}}, and pass it
206 as the \code{cache} argument of \code{bindCache()}.
207 }
208
209 \section{Computing cache keys}{
210
211
212 The actual cache key that is used internally takes value from evaluating
213 the key expression(s) (from the \code{...} arguments) and combines it with the
214 (unevaluated) value expression.
215
216 This means that if there are two cached reactives which have the same
217 result from evaluating the key, but different value expressions, then they
218 will not need to worry about collisions.
219
220 However, if two cached reactives have identical key and value expressions
221 expressions, they will share the cached values. This is useful when using
222 \code{cache="app"}: there may be multiple user sessions which create separate
223 cached reactive objects (because they are created from the same code in the
224 server function, but the server function is executed once for each user
225 session), and those cached reactive objects across sessions can share
226 values in the cache.
227 }
228
229 \section{Async with cached reactives}{
230
231
232 With a cached reactive expression, the key and/or value expression can be
233 \emph{asynchronous}. In other words, they can be promises --- not regular R
234 promises, but rather objects provided by the
235 \href{https://rstudio.github.io/promises/}{\pkg{promises}} package, which
236 are similar to promises in JavaScript. (See \code{\link[promises:promise]{promises::promise()}} for more
237 information.) You can also use \code{\link[mirai:mirai]{mirai::mirai()}} or \code{\link[future:future]{future::future()}}
238 objects to run code in a separate process or even on a remote machine.
239
240 If the value returns a promise, then anything that consumes the cached
241 reactive must expect it to return a promise.
242
243 Similarly, if the key is a promise (in other words, if it is asynchronous),
244 then the entire cached reactive must be asynchronous, since the key must be
245 computed asynchronously before it knows whether to compute the value or the
246 value is retrieved from the cache. Anything that consumes the cached
247 reactive must therefore expect it to return a promise.
248 }
249
250 \section{Developing render functions for caching}{
251
252
253 If you've implemented your own \verb{render*()} function, it may just work with
254 \code{bindCache()}, but it is possible that you will need to make some
255 modifications. These modifications involve helping \code{bindCache()} avoid
256 cache collisions, dealing with internal state that may be set by the,
257 \code{render} function, and modifying the data as it goes in and comes out of
258 the cache.
259
260 You may need to provide a \code{cacheHint} to \code{\link[=createRenderFunction]{createRenderFunction()}} (or
261 \code{htmlwidgets::shinyRenderWidget()}, if you've authored an htmlwidget) in
262 order for \code{bindCache()} to correctly compute a cache key.
263
264 The potential problem is a cache collision. Consider the following:
265
266 \if{html}{\out{<div class="sourceCode">}}\preformatted{output$x1 <- renderText(\{ input$x \}) \%>\% bindCache(input$x)
267 output$x2 <- renderText(\{ input$x * 2 \}) \%>\% bindCache(input$x)
268 }\if{html}{\out{</div>}}
269
270 Both \code{output$x1} and \code{output$x2} use \code{input$x} as part of their cache key,
271 but if it were the only thing used in the cache key, then the two outputs
272 would have a cache collision, and they would have the same output. To avoid
273 this, a \emph{cache hint} is automatically added when \code{\link[=renderText]{renderText()}} calls
274 \code{\link[=createRenderFunction]{createRenderFunction()}}. The cache hint is used as part of the actual
275 cache key, in addition to the one passed to \code{bindCache()} by the user. The
276 cache hint can be viewed by calling the internal Shiny function
277 \code{extractCacheHint()}:
278
279 \if{html}{\out{<div class="sourceCode">}}\preformatted{r <- renderText(\{ input$x \})
280 shiny:::extractCacheHint(r)
281 }\if{html}{\out{</div>}}
282
283 This returns a nested list containing an item, \verb{$origUserFunc$body}, which
284 in this case is the expression which was passed to \code{renderText()}:
285 \code{{ input$x }}. This (quoted) expression is mixed into the actual cache
286 key, and it is how \code{output$x1} does not have collisions with \code{output$x2}.
287
288 For most developers of render functions, nothing extra needs to be done;
289 the automatic inference of the cache hint is sufficient. Again, you can
290 check it by calling \code{shiny:::extractCacheHint()}, and by testing the
291 render function for cache collisions in a real application.
292
293 In some cases, however, the automatic cache hint inference is not
294 sufficient, and it is necessary to provide a cache hint. This is true
295 for \code{renderPrint()}. Unlike \code{renderText()}, it wraps the user-provided
296 expression in another function, before passing it to \code{\link[=createRenderFunction]{createRenderFunction()}}
297 (instead of \code{\link[=createRenderFunction]{createRenderFunction()}}). Because the user code is wrapped in
298 another function, \code{createRenderFunction()} is not able to automatically
299 extract the user-provided code and use it in the cache key. Instead,
300 \code{renderPrint} calls \code{createRenderFunction()}, it explicitly passes along a
301 \code{cacheHint}, which includes a label and the original user expression.
302
303 In general, if you need to provide a \code{cacheHint}, it is best practice to
304 provide a \code{label} id, the user's \code{expr}, as well as any other arguments
305 that may influence the final value.
306
307 For \pkg{htmlwidgets}, it will try to automatically infer a cache hint;
308 again, you can inspect the cache hint with \code{shiny:::extractCacheHint()} and
309 also test it in an application. If you do need to explicitly provide a
310 cache hint, pass it to \code{shinyRenderWidget}. For example:
311
312 \if{html}{\out{<div class="sourceCode">}}\preformatted{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 }\if{html}{\out{</div>}}
323
324 If your \code{render} function sets any internal state, you may find it useful
325 in your call to \code{\link[=createRenderFunction]{createRenderFunction()}} to use
326 the \code{cacheWriteHook} and/or \code{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 \code{\link[=createWebDependency]{createWebDependency()}} to make
332 JS/CSS resources available if the cached object is loaded in a different R
333 process. (See the source of \code{htmlwidgets::shinyRenderWidget} for an example
334 of this.)
335 }
336
337 \section{Uncacheable objects}{
338
339
340 Some render functions cannot be cached, typically because they have side
341 effects or modify some external state, and they must re-execute each time
342 in order to work properly.
343
344 For developers of such code, they should call \code{\link[=createRenderFunction]{createRenderFunction()}} (or
345 \code{\link[=markRenderFunction]{markRenderFunction()}}) with \code{cacheHint = FALSE}.
346 }
347
348 \section{Caching with \code{renderPlot()}}{
349
350
351 When \code{bindCache()} is used with \code{renderPlot()}, the \code{height} and \code{width}
352 passed to the original \code{renderPlot()} are ignored. They are superseded by
353 \code{sizePolicy} argument passed to `bindCache. The default is:
354
355 \if{html}{\out{<div class="sourceCode">}}\preformatted{sizePolicy = sizeGrowthRatio(width = 400, height = 400, growthRate = 1.2)
356 }\if{html}{\out{</div>}}
357
358 \code{sizePolicy} must be a function that takes a two-element numeric vector as
359 input, representing the width and height of the \verb{<img>} element in the
360 browser window, and it must return a two-element numeric vector, representing
361 the pixel dimensions of the plot to generate. The purpose is to round the
362 actual pixel dimensions from the browser to some other dimensions, so that
363 this will not generate and cache images of every possible pixel dimension.
364 See \code{\link[=sizeGrowthRatio]{sizeGrowthRatio()}} for more information on the default sizing policy.
365 }
366
367 \examples{
368 \dontrun{
369 rc <- bindCache(
370 x = reactive({
371 Sys.sleep(2) # Pretend this is expensive
372 input$x * 100
373 }),
374 input$x
375 )
376
377 # Can make it prettier with the \%>\% operator
378 library(magrittr)
379
380 rc <- reactive({
381 Sys.sleep(2)
382 input$x * 100
383 }) \%>\%
384 bindCache(input$x)
385
386 }
387
388 ## Only run app examples in interactive R sessions
389 if (interactive()) {
390
391 # Basic example
392 shinyApp(
393 ui = fluidPage(
394 sliderInput("x", "x", 1, 10, 5),
395 sliderInput("y", "y", 1, 10, 5),
396 div("x * y: "),
397 verbatimTextOutput("txt")
398 ),
399 server = function(input, output) {
400 r <- reactive({
401 # The value expression is an _expensive_ computation
402 message("Doing expensive computation...")
403 Sys.sleep(2)
404 input$x * input$y
405 }) \%>\%
406 bindCache(input$x, input$y)
407
408 output$txt <- renderText(r())
409 }
410 )
411
412
413 # Caching renderText
414 shinyApp(
415 ui = fluidPage(
416 sliderInput("x", "x", 1, 10, 5),
417 sliderInput("y", "y", 1, 10, 5),
418 div("x * y: "),
419 verbatimTextOutput("txt")
420 ),
421 server = function(input, output) {
422 output$txt <- renderText({
423 message("Doing expensive computation...")
424 Sys.sleep(2)
425 input$x * input$y
426 }) \%>\%
427 bindCache(input$x, input$y)
428 }
429 )
430
431
432 # Demo of using events and caching with an actionButton
433 shinyApp(
434 ui = fluidPage(
435 sliderInput("x", "x", 1, 10, 5),
436 sliderInput("y", "y", 1, 10, 5),
437 actionButton("go", "Go"),
438 div("x * y: "),
439 verbatimTextOutput("txt")
440 ),
441 server = function(input, output) {
442 r <- reactive({
443 message("Doing expensive computation...")
444 Sys.sleep(2)
445 input$x * input$y
446 }) \%>\%
447 bindCache(input$x, input$y) \%>\%
448 bindEvent(input$go)
449 # The cached, eventified reactive takes a reactive dependency on
450 # input$go, but doesn't use it for the cache key. It uses input$x and
451 # input$y for the cache key, but doesn't take a reactive dependency on
452 # them, because the reactive dependency is superseded by addEvent().
453
454 output$txt <- renderText(r())
455 }
456 )
457
458 }
459
460 }
461 \seealso{
462 \code{\link[=bindEvent]{bindEvent()}}, \code{\link[=renderCachedPlot]{renderCachedPlot()}} for caching plots.
463 }