Debian Codegraph @

R/reactive-domains.R

raw
1 #' @include globals.R
2 NULL
3
4 #
5 # Over the last few months we've seen a number of cases where it'd be helpful
6 # for objects that are instantiated within a Shiny app to know what Shiny
7 # session they are "owned" by. I put "owned" in quotes because there isn't a
8 # built-in notion of object ownership in Shiny today, any more than there is a
9 # notion of one object owning another in R.
10 #
11 # But it's intuitive to everyone, I think, that the outputs for a session are
12 # owned by that session, and any logic that is executed as part of the output
13 # is done on behalf of that session. And it seems like in the vast majority of
14 # cases, observers that are created inside a shinyServer function (i.e. one per
15 # session) are also intuitively owned by the session that's starting up.
16 #
17 # This notion of ownership is important/helpful for a few scenarios that have
18 # come up in recent months:
19 #
20 # 1. The showcase mode that Jonathan implemented recently highlights
21 # observers/reactives as they execute. In order for sessions to only receive
22 # highlights for their own code execution, we need to know which sessions own
23 # which observers. 2. We've seen a number of apps crash out when observers
24 # outlive their sessions and then try to do things with their sessions (the
25 # most common error message was something like "Can't write to a closed
26 # websocket", but we now silently ignore writes to closed websockets). It'd be
27 # convenient for the default behavior of observers to be that they don't
28 # outlive their parent sessions. 3. The reactive log visualizer currently
29 # visualizes all reactivity in the process; it would be great if by default it
30 # only visualized the current session. 4. When an observer has an error, it
31 # would be great to be able to send the error to the session so it can do its
32 # own handling (such as sending the error info to the client so the user can be
33 # notified). 5. Shiny Server Pro wants to show the admin how much time is being
34 # spent servicing each session.
35 #
36 # So what are the rules for establishing ownership?
37 #
38 # 1. Define the "current domain" as a global variable whose value will own any
39 # newly created observer (by default). A domain is a reference class or
40 # environment that contains the functions `onEnded(callback)`, `isEnded()`, and
41 # `reactlog(logEntry)`.
42 #
43 ## ------------------------------------------------------------------------
44 createMockDomain <- function() {
45 callbacks <- Callbacks$new()
46 ended <- FALSE
47 domain <- new.env(parent = emptyenv())
48 domain$ns <- function(id) id
49 domain$token <- "mock-domain"
50 domain$onEnded <- function(callback) {
51 return(callbacks$register(callback))
52 }
53 domain$isEnded <- function() {
54 ended
55 }
56 domain$reactlog <- function(logEntry) NULL
57 domain$end <- function() {
58 if (!ended) {
59 ended <<- TRUE
60 callbacks$invoke()
61 }
62 invisible()
63 }
64 domain$incrementBusyCount <- function() NULL
65 domain$decrementBusyCount <- function() NULL
66 return(domain)
67 }
68
69 #
70 # 2. The initial value of "current domain" is null.
71 #
72 ## ------------------------------------------------------------------------
73 .globals$domain <- NULL
74
75 #
76 # 3. Objects that can be owned include observers, reactive expressions,
77 # invalidateLater instances, reactiveTimer instances. Whenever one of these is
78 # created, by default its owner will be the current domain.
79 #
80 ## ------------------------------------------------------------------------
81
82 #' @name domains
83 #' @rdname domains
84 #' @export
85 getDefaultReactiveDomain <- function() {
86 .globals$domain
87 }
88
89 #
90 # 4. While a session is being created and the shinyServer function is executed,
91 # the current domain is set to the new session. When the shinyServer function
92 # is done executing, the previous value of the current domain is restored. This
93 # is made foolproof using a `withReactiveDomain` function.
94 #
95 ## ------------------------------------------------------------------------
96
97 #' @rdname domains
98 #' @export
99 withReactiveDomain <- function(domain, expr) {
100 # Use `promises::` as it shows up in the stack trace
101 promises::with_promise_domain(
102 createVarPromiseDomain(.globals, "domain", domain),
103 expr
104 )
105 }
106
107 #
108 # 5. While an observer or reactive expression is executing, the current domain
109 # is set to the owner of the observer. When the observer completes, the
110 # previous value of the current domain is restored.
111 #
112 # 6. Note that once created, an observer/reactive expression belongs to the
113 # same domain forever, regardless of how many times it is invalidated and
114 # re-executed, and regardless of what caused the invalidation to happen.
115 #
116 # 7. When a session ends, any observers that it owns are suspended, any
117 # invalidateLater/reactiveTimers are stopped.
118 #
119 ## ------------------------------------------------------------------------
120
121 #' @rdname domains
122 #' @export
123 onReactiveDomainEnded <- function(domain, callback, failIfNull = FALSE) {
124 if (is.null(domain)) {
125 if (isTRUE(failIfNull))
126 stop("onReactiveDomainEnded called with null domain and failIfNull=TRUE")
127 else
128 return()
129 }
130 domain$onEnded(callback)
131 }
132
133 #
134 # 8. If an uncaught error occurs while executing an observer, the session gets
135 # a chance to handle it. I suppose the default behavior would be to send the
136 # message to the client if possible, and then perhaps end the session (or not,
137 # I could argue either way).
138 #
139 # The basic idea here is inspired by Node.js domains, which you can think of as
140 # a way to track execution contexts across callback- or listener-oriented
141 # asynchronous code. They use it to unify error handling code across a graph of
142 # related objects. Our domains will be to unify both lifetime and error
143 # handling across a graph of related reactive primitives.
144 #
145 # (You could imagine that as a client update is being processed, the session
146 # associated with that client would become the current domain. IIRC this is how
147 # showcase mode is implemented today. I don't think this would cover any cases
148 # not covered by rule 5 above, and the absence of rule 5 would leave cases that
149 # this rule would not cover.)
150 #
151 # Pitfalls/open issues:
152 #
153 # 1. Our current approach has the issue of observers staying alive longer than
154 # they ought to. This proposal introduces the opposite risk: that
155 # observers/invalidateLater/reactiveTimer instances, having implicitly been
156 # assigned a parent, are suspended/disposed earlier than they ought to have
157 # been. I find this especially worrisome for invalidateLater/reactiveTimer,
158 # which will often be called in a reactive expression, and thus execute under
159 # unpredictable circumstances. Perhaps those should continue to accept an
160 # explicit "session=" parameter that the user is warned about if they don't
161 # provide a value.
162 #
163 # 2. Are there situations where it is ambiguous what the right thing to do is,
164 # and we should warn/error to ask the user to provide a domain explicitly?
165 #
166 ## ------------------------------------------------------------------------
167
168 #' Reactive domains
169 #'
170 #' Reactive domains are a mechanism for establishing ownership over reactive
171 #' primitives (like reactive expressions and observers), even if the set of
172 #' reactive primitives is dynamically created. This is useful for lifetime
173 #' management (i.e. destroying observers when the Shiny session that created
174 #' them ends) and error handling.
175 #'
176 #' At any given time, there can be either a single "default" reactive domain
177 #' object, or none (i.e. the reactive domain object is `NULL`). You can
178 #' access the current default reactive domain by calling
179 #' `getDefaultReactiveDomain`.
180 #'
181 #' Unless you specify otherwise, newly created observers and reactive
182 #' expressions will be assigned to the current default domain (if any). You can
183 #' override this assignment by providing an explicit `domain` argument to
184 #' [reactive()] or [observe()].
185 #'
186 #' For advanced usage, it's possible to override the default domain using
187 #' `withReactiveDomain`. The `domain` argument will be made the
188 #' default domain while `expr` is evaluated.
189 #'
190 #' Implementers of new reactive primitives can use `onReactiveDomainEnded`
191 #' as a convenience function for registering callbacks. If the reactive domain
192 #' is `NULL` and `failIfNull` is `FALSE`, then the callback will
193 #' never be invoked.
194 #'
195 #' @name domains
196 #' @param domain A valid domain object (for example, a Shiny session), or
197 #' `NULL`
198 #' @param expr An expression to evaluate under `domain`
199 #' @param callback A callback function to be invoked
200 #' @param failIfNull If `TRUE` then an error is given if the `domain`
201 #' is `NULL`
202 NULL
203
204 #
205 # Example 1
206 # ---
207 # ```
208 # obs1 <- observe({
209 # })
210 # shinyServer(function(input, output) {
211 # obs2 <- observe({
212 # obs3 <- observe({
213 # })
214 # })
215 # })
216 # # obs1 would have no domain, obs2 and obs3 would be owned by the session
217 # ```
218 #
219 # Example 2
220 # ---
221 # ```
222 # globalValues <- reactiveValues(broadcast="")
223 # shinyServer(function(input, output) {
224 # sessionValues <- reactiveValues()
225 # output$messageOutput <- renderText({
226 # globalValues$broadcast
227 # obs1 <- observe({...})
228 # })
229 # observe({
230 # if (input$goButton == 0) return()
231 # isolate( globalValues$broadcast <- input$messageInput )
232 # })
233 # })
234 # # The observer behind messageOutput would be owned by the session,
235 # # as would all the many instances of obs1 that were created.
236 # ```
237 # ---
238 #
239 # Example 3
240 # ---
241 # ```
242 # rexpr1 <- reactive({
243 # invalidateLater(1000)
244 # obs1 <- observe({...})
245 # })
246 # observeSomething <- function() {
247 # obs2 <- observe({...})
248 # })
249 # shinyServer(function(input, output) {
250 # obs3 <- observe({
251 # observeSomething()
252 # rexpr1()
253 # })
254 # })
255 # # rexpr1, the invalidateLater call, and obs1 would all have no owner;
256 # # obs2 and obs3 would be owned by the session.
257 # ```