Debian Codegraph @

inst/doc/promises_06_shiny.Rmd

raw
1 ---
2 title: "Using promises with Shiny"
3 output: rmarkdown::html_vignette
4 vignette: >
5 %\VignetteEngine{knitr::rmarkdown}
6 %\VignetteIndexEntry{Using promises with Shiny}
7 %\VignetteEncoding{UTF-8}
8 ---
9
10 ```{css echo=FALSE}
11 .alert-secondary a, .alert-secondary a:visited {
12 color: inherit;
13 text-decoration: underline;
14 }
15 ```
16
17 <div class="alert alert-secondary">
18 As of Shiny 1.8.1, there is a new feature called **Extended Tasks** that has several advantages over the approach in this article. We highly recommend that you read [the Extended Task documentation](https://shiny.posit.co/r/articles/improve/nonblocking/) first.
19 </div>
20
21 Taking advantage of async programming from Shiny is not as simple as turning on an option or flipping a switch. If you have already written a Shiny application and are looking to improve its scalability, expect the changes required for async operation to ripple through multiple layers of server code.
22
23 Async programming with Shiny boils down to following a few steps.
24
25 1. Identify slow operations (function calls or blocks of statements) in your app.
26
27 2. Convert the slow operation into a 'mirai' using `mirai()`. (If you haven't read the [article on mirai](promises_04_mirai.html), definitely do that before proceeding!)
28
29 3. Any code that relies on the result of that operation (if any), whether directly or indirectly, now must be converted to promise handlers that operate on the mirai object.
30
31 We'll get into details for all these steps, but first, an example. Consider the following synchronous server code:
32
33 ```R
34 function(input, output, session) {
35 output$plot <- renderPlot({
36 result <- expensive_operation()
37 result <- head(result, input$n)
38 plot(result)
39 })
40 }
41 ```
42
43 We'd convert it to async like this:
44
45 ```R
46 library(promises)
47 library(mirai)
48 daemons(6)
49
50 function(input, output, session) {
51 output$plot <- renderPlot({
52 mirai({ expensive_operation() }) |>
53 then(\(x) head(x, input$n)) |>
54 then(plot)
55 })
56 }
57 ```
58
59 ## Adding prerequisites
60
61 The easiest part is adding `library(promises)`, `library(mirai)`, and `daemons(6)` to the top of the app.
62
63 The `promises` library is necessary for the `then()` method. You may also want to use promise utility functions like `promise_all` and `promise_race`.
64
65 The `mirai` library is needed because the `mirai()` function call is how you will launch asynchronous tasks.
66
67 `daemons(6)` is a directive to the `mirai` package, telling it where and how tasks should actually be executed. See the [article on mirai](promises_04_mirai.html) for more details.
68
69 ## Identifying slow operations
70
71 To find areas of your code that are good candidates for the mirai/promise treatment, let's start with the obvious: identifying the code that is making your app slow. You may assume it's your plotting code that's slow, but it's actually your database queries; or vice versa. If there's one thing that veteran programmers can agree on, it's that human intuition is a surprisingly unreliable tool for spotting performance problems.
72
73 Our recommendation is that you use the [profvis](https://profvis.r-lib.org/) profiler, which we designed to work with Shiny (see Example 3 in the profvis documentation). You can use profvis to help you focus in on where the time is actually being spent in your app.
74
75 > **Note:** As of this writing, profvis doesn't work particularly well for diagnosing performance problems in parts of your code that you've already made asynchronous. In particular, we haven't done any work to help it profile code that executes in a mirai, and the mechanism we use to hide "irrelevant" parts of the stack trace doesn't work well with promises. These are ripe areas for future development.
76
77 Async programming works well when you can identify just a few "hotspots" in your app where lots of time is being spent. It works much less well if your app is too slow because of a generalized, diffuse slowness through every aspect of your app, where no one operation takes too much time but it all adds up to a lot. The more mirai you need to introduce into your app, the more fixed communication overhead you incur. So for the most bang-for-the-buck, we want to launch a small number of mirai per session but move a lot of the waited-on code into each one.
78
79 ## Converting a slow operation into a mirai
80
81 Now that we've found hotspots that we want to make asynchronous, let's talk about the actual work of converting them to mirai.
82
83 Conceptually, mirai works like this:
84
85 ```R
86 mirai({
87 # Expensive code goes here
88 }) |>
89 then(\(result) {
90 # Code to handle result of expensive code goes here
91 })
92 ```
93
94 which seems incredibly simple. What's actually happening is that the mirai runs in a totally separate child R process, and then the result is collected up and returned to the main R process:
95
96 ```R
97 # Code here runs in process A
98 mirai({
99 # Code here runs in (child) process B
100 }) |>
101 then(\(result) {
102 # Code here runs in process A
103 })
104 ```
105
106 The fact that the mirai code block executes in a separate process means we have to take special care to deal with a number of practical issues. All the objects required by the code block must be passed along as part of the `mirai()` function call; certain objects may require custom serialization to be set up, and other objects cannot be safely used across process boundaries. Again, see the [article on mirai](promises_04_mirai.html) for more details.
107
108 ### Shiny-specific caveats and limitations
109
110 In addition to the constraints that mirai faces, there is an additional one for Shiny: reactive values and reactive expressions cannot be read from within a mirai. Whenever reactive values/expressions are read, side effects are carried out under the hood so that the currently executing observer or reactive expression can be notified when the reactive value/expression becomes invalidated. If a reactive value/expression is created in one process, but read in another process, there will be no way for readers to be notified about invalidation.
111
112 This code, for example, will not work:
113
114 ```R
115 function(input, output, session) {
116 r1 <- reactive({ ... })
117
118 r2 <- reactive({
119 mirai(
120 {
121 r1() # Will error--don't do this!
122 },
123 r1 = r1
124 )
125 })
126 }
127 ```
128
129 Even though `r1()` is called from inside the `r2` reactive expression, the fact that it's also in a mirai means the call will fail. Instead, you must read any reactive values/expressions you need in advance of launching the mirai:
130
131 ```R
132 function(input, output, session) {
133 r1 <- reactive({ ... })
134
135 r2 <- reactive({
136 val <- r1()
137 mirai(
138 {
139 val # No problem!
140 },
141 val = val
142 )
143 })
144 }
145 ```
146
147 However, it's perfectly fine to read reactive values/expressions from inside a promise _handler_. Handlers run in the original process, not a child process, so reactive operations are allowed.
148
149 ```R
150 function(input, output, session) {
151 r1 <- reactive({ ... })
152
153 r2 <- reactive({
154 mirai({ ... }) |>
155 then(\(x) rbind(x, r1())) # OK!
156 })
157 }
158 ```
159
160 ## Integrating promises with Shiny
161
162 Generally, you'll be using promises with Shiny from within outputs, reactive expressions, and observers. We've tried to integrate promises into these constructs in as natural a way as possible.
163
164 ### Outputs
165
166 Most outputs (`renderXXX({ ... })`) functions expect your code block to return a value; for example, `renderText()` expects a character vector and `renderTable()` expects a data frame. All such render functions that are included within the `shiny` package can now optionally be given a promise for such a value instead.
167
168 So this:
169
170 ```R
171 output$table <- renderTable({
172 read.csv(url) |>
173 filter(date == input$date)
174 })
175 ```
176
177 could become:
178
179 ```R
180 output$table <- renderTable({
181 mirai(read.csv(url), url = url) |>
182 then(\(df) df |> filter(date == input$date))
183 })
184 ```
185
186 or, trading elegance for efficiency:
187
188 ```R
189 output$table <- renderTable({
190 input_date <- input$date
191 mirai(
192 {
193 read.csv(url) |>
194 filter(date == input_date)
195 },
196 url = url,
197 input_date = input_date
198 )
199 })
200 ```
201
202 The important thing to keep in mind is that the promise (or promise pipeline) must be the final expression in the code block. Shiny only knows about promises you actually return to it when you hand control back.
203
204 #### Render functions with side effects: `renderPrint` and `renderPlot`
205
206 The render functions `renderPrint()` and `renderPlot()` are slightly different than other render functions, in that they can be affected by side effects in the code block you provide. In `renderPrint` you can print to the console, and in `renderPlot` you can plot to the active R graphics device.
207
208 With promises, these render functions can work in a similar way, but with a caveat. As you hopefully understand by now, mirai executes its code in a separate R process, and printing/plotting in a separate process won't have any effect on the Shiny output in the original process. These examples, then, are incorrect:
209
210 ```R
211 output$summary <- renderPrint({
212 mirai(
213 {
214 read.csv(url) |>
215 summary() |>
216 print()
217 },
218 url = url
219 )
220 })
221
222 output$plot <- renderPlot({
223 mirai(
224 {
225 df <- read.csv(url)
226 ggplot(df, aes(length, width)) + geom_point()
227 },
228 url = url
229 )
230 })
231 ```
232
233 Instead, do printing and plotting after control returns back to the original process, via a promise handler:
234
235 ```R
236 output$summary <- renderPrint({
237 mirai(read.csv(url), url = url) |>
238 then(summary) |>
239 then(print)
240 })
241
242 output$plot <- renderPlot({
243 mirai(read.csv(url), url = url) |>
244 then(\(df) {
245 ggplot(df, aes(length, width)) + geom_point()
246 })
247 })
248 ```
249
250 Again, you do need to be careful to make sure that the last expression in your code block is the promise/pipeline; this is the only way the rendering logic can know whether and when your logic has completed, and if any errors occurred (so they can be displayed to the user).
251
252 ### Observers
253
254 Observers are very similar to outputs: you must make sure that the last expression in your code block is the promise/pipeline. Like outputs, observers need to know whether and when they're done running, and if any errors occured (so they can log them and terminate the user session). The way to communicate this from your async user code is by returning the promise.
255
256 Here's a synchronous example that we'll convert to async. Clicking the `refresh_data` action button causes data to be downloaded, which is then saved to disk as `cached.rds` and also used to update the reactive value `data`.
257
258 ```R
259 data <- reactiveVal(readRDS("cached.rds"))
260
261 function(input, output, session) {
262 observeEvent(input$refresh_data, {
263 df <- read.csv(url)
264 saveRDS(df, "cached.rds")
265 data(df)
266 })
267 }
268 ```
269
270 And the async version:
271
272 ```R
273 data <- reactiveVal(readRDS("cached.rds"))
274
275 function(input, output, session) {
276 observeEvent(input$refresh_data, {
277 mirai(
278 {
279 df <- read.csv(url)
280 saveRDS(df, "cached.rds")
281 df
282 },
283 url = url
284 ) |>
285 # Assign the result to the reactive value
286 then(\(df) data(df))
287 })
288 }
289 ```
290
291 Note that in this version, we cannot call `data(df)` inside the mirai, as this would cause the update to happen in the wrong process. Instead, we use the `then()` promise method to perform the assignment back in the main process once the mirai resolves.
292
293 ### Reactive expressions
294
295 Recall that reactive expressions are used to calculate values, and are cached until they are automatically invalidated by one of their dependencies. Unlike outputs and observers, reactive expressions can be used from other reactive consumers.
296
297 Asynchronous reactive expressions are similar to regular (synchronous) reactive expressions: instead of a "normal" value, they return a promise that will yield the desired value; and a normal reactive will cache a normal value, while an async reactive will cache the promise.
298
299 The upshot is that when defining an async reactive expression, your code block should return a promise or promise pipeline, following the same rules as reactive outputs. And when calling an async reactive expression, call it like a function like you would a regular reactive expression, and treat the value that's returned like any other promise.
300
301 ```R
302 function(input, output, session) {
303 data <- eventReactive(input$refresh_data, {
304 read.csv(url)
305 })
306
307 filteredData <- reactive({
308 data() |> filter(date == input$date)
309 })
310
311 output$table <- renderTable({
312 filteredData() |> head(5)
313 })
314 }
315 ```
316
317 And now in async:
318
319 ```R
320 function(input, output, session) {
321 data <- eventReactive(input$refresh_data, {
322 mirai(read.csv(url), url = url)
323 })
324
325 filteredData <- reactive({
326 data() |> then(\(df) df |> filter(date == input$date))
327 })
328
329 output$table <- renderTable({
330 filteredData() |> then(\(df) head(df, 5))
331 })
332 }
333 ```
334
335 ## The flush cycle
336
337 In the past, Shiny's reactive programming model has operated using a mostly traditional [event loop](https://en.wikipedia.org/wiki/Event_loop) model. Somewhere many levels beneath `shiny::runApp()` was a piece of code that looked a bit like this:
338
339 ```R
340 while (TRUE) {
341 # Do nothing until a browser sends some data
342 input <- receiveInputFromBrowser()
343 # Use the received data to update reactive inputs
344 session$updateInput(input)
345 # Execute all invalidated outputs/observers
346 flushReact()
347 # After ALL outputs execute, send the results back
348 flushOutputs()
349 }
350 ```
351
352 We call this Shiny's "flush cycle". There are two important properties to our flush cycle.
353
354 1. Only one of the four steps—receiving, updating, reacting, and sending—can be executing a time. (Remember, R is single threaded.) In particular, it's not possible for inputs to be updated while outputs/observers are running. This is important in order to avoid race conditions that would be all but impossible to defend against.
355 2. Many outputs may change as a result of a single input value received from the browser, but none of them are sent back to the client until all of the outputs are ready. The advantage of this is a smoother experience for the end-user in most cases. (Admittedly, there has been some controversy regarding this property of Shiny; some app authors would strongly prefer to show outputs as soon as they are ready, or at least to have manual control over this behavior.)
356
357 While adding async support to Shiny, we aimed to keep these two properties intact. Imagine now that `flushReact()`, the line that executes invalidated outputs/observers, returns a promise that combines all of the async outputs/observers (i.e. a promise that resolves only after all of the async outputs/observers have resolved). The new, async-aware event loop is conceptually more like this:
358
359 ```R
360 doEventLoop <- function() {
361 # Do nothing until a browser sends some data
362 input <- receiveInputFromBrowser()
363 # Use the received data to update reactive inputs
364 session$updateInput(input)
365 # Execute all invalidated outputs/observers
366 flushReact() |>
367 finally(\() {
368 # After ALL outputs execute, send the results back
369 flushOutputs()
370 # Continue the event loop
371 doEventLoop()
372 })
373 }
374 ```
375
376 The resulting behavior matches the synchronous version of the event loop, in that:
377
378 1. No inputs are received from the browser until all pending async outputs/observers have completed. Unlike the synchronous version, this separation is enforced at the session level: if Session A has some async observers that have not finished executing, that only prevents Session A from processing new input values, while new input values from Session B can be handled immediately because they belong to a different session. Again, the goal of keeping input updates separate from output/observer execution is to prevent race conditions, which are even more pernicious to debug and understand when async code is involved.
379 2. For a given session, no outputs are sent back to the client, until all outputs are ready. It doesn't matter whether the outputs in question are synchronous, asynchronous, or some combination; they all must complete execution before any can be sent.