| 1 |
--- |
| 2 |
title: "An informal introduction to async programming" |
| 3 |
output: rmarkdown::html_vignette |
| 4 |
vignette: > |
| 5 |
%\VignetteEngine{knitr::rmarkdown} |
| 6 |
%\VignetteIndexEntry{An informal introduction to async programming} |
| 7 |
%\VignetteEncoding{UTF-8} |
| 8 |
--- |
| 9 |
|
| 10 |
Hello, R and/or Shiny user! Let’s talk about async programming! |
| 11 |
|
| 12 |
**Async programming? Sounds complicated.** |
| 13 |
|
| 14 |
It is, very! You may want to grab some coffee. |
| 15 |
|
| 16 |
**Ugh. Tell me why I even need to know this?** |
| 17 |
|
| 18 |
Async programming is a major new addition to Shiny that can make certain classes |
| 19 |
of apps dramatically more responsive under load. |
| 20 |
|
| 21 |
Because R is single threaded (i.e. it can only do one thing at a time), a given |
| 22 |
Shiny app process can also only do one thing at a time: if it is fitting a |
| 23 |
linear model for one client, it can’t simultaneously serve up a CSV download for |
| 24 |
another client. |
| 25 |
|
| 26 |
For many Shiny apps, this isn’t a big problem; if no one processing step takes |
| 27 |
very long, then no client has to wait an undue amount of time before they start |
| 28 |
seeing results. But for apps that perform long-running operations — either |
| 29 |
expensive computations that take a while to complete, or waiting on slow network |
| 30 |
operations like database or web API queries — your users’ experience can suffer |
| 31 |
dramatically as traffic ramps up. Operations that normally are lightning quick, |
| 32 |
like downloading a small JavaScript file, can get stuck in traffic behind |
| 33 |
something slow. |
| 34 |
|
| 35 |
**Oh, OK—more responsiveness is always good. But you said this’ll only help for |
| 36 |
certain classes of Shiny apps?** |
| 37 |
|
| 38 |
It’s mostly helpful for apps that have a few specific operations that take a |
| 39 |
long time, rather than lots of little operations that are all a bit slow on |
| 40 |
their own and add up to one big slow mess. We’re looking for watermelons, not |
| 41 |
blueberries. |
| 42 |
|
| 43 |
**Watermelons… sure. So then, how does this all work?** |
| 44 |
|
| 45 |
It all starts with *async functions*. An async function is one that performs an |
| 46 |
operation that takes a long time, yet returns control to you immediately. |
| 47 |
Whereas a normal function like `read.csv` will not return until its work is done |
| 48 |
and it has the value you requested, an asynchronous `read.csv.async` function |
| 49 |
would kick off the CSV reading operation, but then return immediately, long |
| 50 |
before the real work has actually completed. |
| 51 |
|
| 52 |
```r |
| 53 |
library(mirai) |
| 54 |
|
| 55 |
read.csv.async <- \(file, header = TRUE, stringsAsFactors = FALSE) { |
| 56 |
mirai( |
| 57 |
read.csv(file, header = header, stringsAsFactors = stringsAsFactors), |
| 58 |
.args = environment() |
| 59 |
) |
| 60 |
} |
| 61 |
``` |
| 62 |
|
| 63 |
(Don't worry about what this definition means for now. You'll learn more about defining async functions in [Launching tasks](promises_04_mirai.html).) |
| 64 |
|
| 65 |
**So instead of “read this CSV file” it’s more like “begin reading this CSV |
| 66 |
file”?** |
| 67 |
|
| 68 |
Yes! That’s what async functions do: they start things, and give you back a |
| 69 |
special object called a *promise*. If it doesn’t return a promise, it’s not an |
| 70 |
async function. |
| 71 |
|
| 72 |
**Oh, I’ve heard of promises in R! From [the NSE |
| 73 |
chapter](http://adv-r.had.co.nz/Computing-on-the-language.html) in Hadley’s |
| 74 |
Advanced R book!** |
| 75 |
|
| 76 |
Ah... this is awkward, but no. I’m using the word “promise”, but I’m not referring |
| 77 |
to *that* kind of promise. For the purposes of async programming, try to forget |
| 78 |
that you’ve ever heard of that kind of promise, OK? |
| 79 |
|
| 80 |
I know it seems needlessly confusing, but the promises we’re talking about here |
| 81 |
are ~~shamelessly copied from~~ directly inspired by a central abstraction in modern |
| 82 |
JavaScript, and the JS folks named them “promises”. |
| 83 |
|
| 84 |
**Fine, whatever. So what are these promises?** |
| 85 |
|
| 86 |
Conceptually, they’re a stand-in for the *eventual result* of the operation. For |
| 87 |
example, in the case of our `read.csv.async` function, the |
| 88 |
promise is a stand-in for a data frame. At some point, the operation is going to |
| 89 |
finish, and a data frame is going to become available. The promise gives us a |
| 90 |
way to get at that value. |
| 91 |
|
| 92 |
**Let me guess: it’s an object that has `has_completed()` and |
| 93 |
`get_value()` methods?** |
| 94 |
|
| 95 |
Good guess, but no. Promises are *not* a way to directly inquire about the |
| 96 |
status of an operation, nor to directly retrieve the result value. That is |
| 97 |
probably the simplest and most obvious way to build an async framework, but in |
| 98 |
practice it’s very difficult to build deeply async programs with an API like |
| 99 |
that. |
| 100 |
|
| 101 |
Instead, a promise lets you *chain together operations* that should be performed |
| 102 |
whenever the operation completes. These operations might have side effects (like |
| 103 |
plotting, or writing to disk, or printing to the console) or they might |
| 104 |
transform the result values somehow. |
| 105 |
|
| 106 |
**Chain together operations? Using the `|>` operator?** |
| 107 |
|
| 108 |
A lot like that! You can’t use the `|>` operator itself as we need to wrap execution of the promise step within a function that may be called with the incoming promise resolves. So whereas |
| 109 |
you might do this to a regular data frame: |
| 110 |
|
| 111 |
```r |
| 112 |
library(dplyr) |
| 113 |
read.csv("https://rstudio.github.io/promises/data.csv") |> |
| 114 |
filter(state == "NY") |> |
| 115 |
View() |
| 116 |
``` |
| 117 |
|
| 118 |
The async version would look like: |
| 119 |
|
| 120 |
```r |
| 121 |
library(dplyr) |
| 122 |
read.csv.async("https://rstudio.github.io/promises/data.csv") |> |
| 123 |
then(\(df) df |> filter(state == "NY")) |> |
| 124 |
then(\(df) View(df)) |
| 125 |
``` |
| 126 |
|
| 127 |
The `then()` call here is the secret sauce. It creates a promise pipeline, chaining the provided callback by having it run on the result of the incoming promise value. |
| 128 |
|
| 129 |
**Why can't I just use `|>` directly?** |
| 130 |
|
| 131 |
Not all values are promises. So while the `|>` operator can be used to |
| 132 |
chain together operations on an object, it does not wrap and unwrap promise objects. |
| 133 |
Instead, the `then()` function is designed to work with promises, and it will |
| 134 |
unwrap the promise for you, passing the result value to the function you provide. |
| 135 |
|
| 136 |
`then()` *must* take a promise |
| 137 |
as input; that is, the left-hand side of the `|>` operator must be an expression that |
| 138 |
yields a promise. `then()` will _then_ pass the unwrapped, plain old, not-a-promise value |
| 139 |
to the function—this is critically important. It means we can use promise |
| 140 |
objects with non-promise-aware functions, with `then()` serving as the bridge |
| 141 |
between asynchronous and synchronous code. |
| 142 |
|
| 143 |
However, that work often can’t be done in the present, since the whole point of |
| 144 |
a promise is that it represents work that hasn’t completed yet. So `then()` does |
| 145 |
the work of extracting and piping not at the time that it’s called, but rather, |
| 146 |
sometime in the future. |
| 147 |
|
| 148 |
**You lost me.** |
| 149 |
|
| 150 |
OK, let’s slow down and take this step by step. We’ll generate a promise by |
| 151 |
calling an async function: |
| 152 |
|
| 153 |
```r |
| 154 |
df_promise <- read.csv.async("https://rstudio.github.io/promises/data.csv") |
| 155 |
``` |
| 156 |
|
| 157 |
Even if `data.csv` is many gigabytes, `read.csv.async` returns immediately with |
| 158 |
a new promise. We store it as `df_promise`. Eventually, when the CSV reading |
| 159 |
operation successfully completes, the promise will contain a data frame, but for |
| 160 |
now it’s just an empty placeholder. |
| 161 |
|
| 162 |
One thing we definitely *can’t* do is treat `df_promise` as if it’s simply a |
| 163 |
data frame: |
| 164 |
|
| 165 |
```r |
| 166 |
# Doesn't work! |
| 167 |
dplyr::filter(df_promise, state == "NY") |
| 168 |
``` |
| 169 |
|
| 170 |
Try this and you’ll get an error like `no applicable method for 'filter_' |
| 171 |
applied to an object of class "promise"`. And the native pipe won’t help you either; |
| 172 |
`df_promise |> filter(state == "NY")` will give you the same error. |
| 173 |
|
| 174 |
**Right, that makes sense. `filter` is designed to work on data frames, and |
| 175 |
`df_promise` isn’t a data frame.** |
| 176 |
|
| 177 |
Exactly. Now let’s try something that actually works: |
| 178 |
|
| 179 |
```r |
| 180 |
df_promise |> |
| 181 |
then(\(df) df |> filter(state == "NY")) |
| 182 |
``` |
| 183 |
|
| 184 |
At the moment it’s called, this code won’t appear to do much of anything, |
| 185 |
really. But whenever the `df_promise` operation actually completes successfully, |
| 186 |
then the result of that operation—the plain old data frame—will be passed to |
| 187 |
`filter(df, state = "NY")`. |
| 188 |
|
| 189 |
**OK, so that’s good. I see what you mean about `then()` letting you use |
| 190 |
non-promise functions with promises. But the whole point of using the |
| 191 |
`filter` function is to get a data frame back. If `filter` isn’t even |
| 192 |
going to be called until some random time in the future, how do we get its value |
| 193 |
back?** |
| 194 |
|
| 195 |
I’ll tell you the answer, but it’s not going to be satisfying at first. |
| 196 |
|
| 197 |
When you use a regular `|>`, the result you get back is the return value from |
| 198 |
the right-hand side: |
| 199 |
|
| 200 |
```r |
| 201 |
df_filtered <- df |> filter(state == "NY") |
| 202 |
``` |
| 203 |
|
| 204 |
When you use `then()`, the result you get back is a promise, whose *eventual* |
| 205 |
result will be the return value from the right-hand side: |
| 206 |
|
| 207 |
```r |
| 208 |
df_filtered_promise <- df_promise |> then(\(df) df |> filter(state == "NY")) |
| 209 |
``` |
| 210 |
|
| 211 |
**Wait, what? If I have a promise, I can do stuff to it using `then()`, but |
| 212 |
then I just end up with another promise? Why not just have `then()` return a |
| 213 |
regular value instead of a promise?** |
| 214 |
|
| 215 |
Remember, the whole point of a promise is that we don’t know its value yet! So |
| 216 |
to write a function that uses a promise as input and returns some non-promise |
| 217 |
value as output, you’d need to either be a time traveler or an oracle. |
| 218 |
|
| 219 |
To summarize, once you start working with a promise, any calculations and |
| 220 |
actions that are “downstream” of that promise will need to become |
| 221 |
promise-oriented. Generally, this means once you have a promise, you need to use |
| 222 |
`then()` and keep using it until your pipeline terminates. |
| 223 |
|
| 224 |
**I guess that makes sense. Still, if the only thing you can do with promises is |
| 225 |
make more promises, that limits their usefulness, doesn’t it?** |
| 226 |
|
| 227 |
It’s a different way of thinking about things, to be sure, but it turns out |
| 228 |
there’s not much limit in usefulness—especially in the context of a Shiny app. |
| 229 |
|
| 230 |
First, you can use promises with Shiny outputs. If you’re using an |
| 231 |
async-compatible version of Shiny (version >=1.1), all of the |
| 232 |
built-in `renderXXX` functions can deal with either regular values or promises. |
| 233 |
An example of the latter: |
| 234 |
|
| 235 |
```r |
| 236 |
output$table <- renderTable({ |
| 237 |
read.csv.async("https://rstudio.github.io/promises/data.csv") |> |
| 238 |
then(\(df) df |> filter(state == "NY")) |
| 239 |
}) |
| 240 |
``` |
| 241 |
|
| 242 |
When `output$table` executes the `renderTable` code block, it will notice that |
| 243 |
the result is a promise, and wait for it to complete before continuing with the |
| 244 |
table rendering. While it’s waiting, the R process can move on to do other |
| 245 |
things. |
| 246 |
|
| 247 |
Second, you can use promises with reactive expressions. Reactive expressions |
| 248 |
treat promises about the same as they treat other values, actually. But this |
| 249 |
works perfectly fine: |
| 250 |
|
| 251 |
```r |
| 252 |
# A reactive expression that returns a promise |
| 253 |
filtered_df <- reactive({ |
| 254 |
read.csv.async("https://rstudio.github.io/promises/data.csv") |> |
| 255 |
then(\(df) df |> filter(state == "NY")) |> |
| 256 |
then(\(df) df |> arrange(median_income)) |
| 257 |
}) |
| 258 |
|
| 259 |
# A reactive expression that reads the previous |
| 260 |
# (promise-returning) reactive, and returns a |
| 261 |
# new promise |
| 262 |
top_n_by_income <- reactive({ |
| 263 |
filtered_df() |> |
| 264 |
then(\(df) df |> head(input$n)) |
| 265 |
}) |
| 266 |
|
| 267 |
output$table <- renderTable({ |
| 268 |
top_n_by_income() |
| 269 |
}) |
| 270 |
``` |
| 271 |
|
| 272 |
Third, you can use promises in reactive observers. Use them to perform |
| 273 |
asynchronous tasks in response to reactivity. |
| 274 |
|
| 275 |
```r |
| 276 |
observeEvent(input$save, { |
| 277 |
filtered_df() |> |
| 278 |
then(\(df) write.csv(df, "ny_data.csv")) |
| 279 |
}) |
| 280 |
``` |
| 281 |
|
| 282 |
**Alright, I think I see what you mean. You can’t escape from promise-land, but |
| 283 |
there’s no need to, because Shiny knows what to do with them.** |
| 284 |
|
| 285 |
Yes, that’s basically right. You just need to keep track of which functions and |
| 286 |
reactive expressions return promises instead of regular values, and be sure to |
| 287 |
interact with them using `then()` or other promise-aware functions. |
| 288 |
|
| 289 |
**Wait, there are other promise-aware functions?** |
| 290 |
|
| 291 |
Yes. The `then()` method is the one you’ll most commonly use, but there is a variant |
| 292 |
`then(tee = TRUE)`, which creates a *promise tee* object (it’s analogous to the |
| 293 |
magrittr `%T>%` operator). `then(tee = TRUE)` method acts like `then()`, but |
| 294 |
instead of returning a promise for the result value, it returns the original |
| 295 |
value instead. Meaning `p |> then(tee = TRUE, \(df) cat(df, "\n"))` won’t return a promise for the |
| 296 |
return value of `cat()` (which is always `NULL`) but instead the value of `p`. |
| 297 |
This is useful for logging, or other “side effecty” operations. |
| 298 |
|
| 299 |
There’s also `catch()` and its tee version, `catch(tee = TRUE)`, which are used for error |
| 300 |
handling. I won’t confuse you with more about that now, but you can read more |
| 301 |
[here](promises_03_overview.html#error-handling). |
| 302 |
|
| 303 |
The `promises` package is where all of these operators live, and it also comes |
| 304 |
with some additional functions for working with promises. |
| 305 |
|
| 306 |
So far, the only actual async function we’ve talked about has been |
| 307 |
`read.csv.async`, which doesn’t actually exist. To learn where actual async |
| 308 |
functions come from, read this guide to the [`mirai` package](promises_04_mirai.html). |
| 309 |
|
| 310 |
There are the lower-level functions `then`, `catch`, and `finally`, which are |
| 311 |
the non-pipe, non-operator equivalents of the promise operators we’ve been |
| 312 |
discussing. See [reference](promises_03_overview.html#accessing-results-with-then). |
| 313 |
|
| 314 |
And finally, there are `promise_all`, `promise_race`, and `promise_map`, used to combine |
| 315 |
multiple promises into a single promise. Learn more about them [here](../reference/promise_all.html). |
| 316 |
|
| 317 |
**OK, looks like I have a lot of stuff to read up on. And I’ll probably have to |
| 318 |
reread this conversation a few times before it fully sinks in.** |
| 319 |
|
| 320 |
Sorry. I told you it was complicated. If you make it through the rest of the guide, you’ll be 95% of the way there. |
| 321 |
|
| 322 |
<div style="font-size: 20px; margin-top: 40px; text-align: right;"> |
| 323 |
Next: [Working with promises](promises_03_overview.html) |
| 324 |
</div> |