Debian Codegraph @

R/react.R

raw
1 processId <- local({
2 # pid is not sufficient to uniquely identify a process, because
3 # distributed futures span machines which could introduce pid
4 # collisions.
5 cached <- NULL
6 function() {
7 if (is.null(cached)) {
8 cached <<- rlang::hash(list(
9 Sys.info(),
10 Sys.time()
11 ))
12 }
13 # Sys.getpid() cannot be cached because forked children will
14 # then have the same processId as their parents.
15 paste(cached, Sys.getpid())
16 }
17 })
18
19 ctx_otel_info_obj <- function(
20 isRecordingOtel = FALSE,
21 otelLabel = "<unknown>",
22 otelAttrs = list()
23 ) {
24 structure(
25 list(
26 isRecordingOtel = isRecordingOtel,
27 otelLabel = otelLabel,
28 otelAttrs = otelAttrs
29 ),
30 class = "ctx_otel_info"
31 )
32 }
33
34 with_otel_span_context <- function(otel_info, expr, domain) {
35 if (!otel_is_tracing_enabled()) {
36 return(force(expr))
37 }
38
39 isRecordingOtel <- .subset2(otel_info, "isRecordingOtel")
40 otelLabel <- .subset2(otel_info, "otelLabel")
41 otelAttrs <- .subset2(otel_info, "otelAttrs")
42
43 # Always set the reactive update span as active
44 # This ensures that any spans created within the reactive context
45 # are at least children of the reactive update span
46 maybe_with_otel_span_reactive_update(domain = domain, {
47 if (isRecordingOtel) {
48 with_otel_span(
49 otelLabel,
50 {
51 # Works with both sync and async expressions
52 # Needed for both observer and reactive contexts
53 hybrid_then(
54 expr,
55 on_failure = set_otel_exception_status_and_throw,
56 # Must upgrade the error object
57 tee = FALSE
58 )
59 },
60 # expr,
61 attributes = otelAttrs
62 )
63 } else {
64 force(expr)
65 }
66 })
67
68 }
69
70
71
72
73 #' @include graph.R
74 Context <- R6Class(
75 'Context',
76 portable = FALSE,
77 class = FALSE,
78 public = list(
79 id = character(0),
80 .reactId = character(0),
81 .reactType = "other",
82 .label = character(0), # For debug purposes
83 .invalidated = FALSE,
84 .invalidateCallbacks = list(),
85 .flushCallbacks = list(),
86 .domain = NULL,
87 .pid = NULL,
88 .weak = NULL,
89
90 .otel_info = NULL,
91
92 initialize = function(
93 domain, label='', type='other', prevId='',
94 reactId = rLog$noReactId,
95 id = .getReactiveEnvironment()$nextId(), # For dummy context
96 weak = FALSE,
97 otel_info = ctx_otel_info_obj()
98 ) {
99 id <<- id
100 .label <<- label
101 .domain <<- domain
102 .pid <<- processId()
103 .reactId <<- reactId
104 .reactType <<- type
105 .weak <<- weak
106 rLog$createContext(id, label, type, prevId, domain)
107 if (!is.null(otel_info)) {
108 if (IS_SHINY_LOCAL_PKG) {
109 stopifnot(inherits(otel_info, "ctx_otel_info"))
110 }
111 .otel_info <<- otel_info
112 }
113 },
114 run = function(func) {
115 "Run the provided function under this context."
116
117 # Use `promises::` as it shows up in the stack trace
118 promises::with_promise_domain(reactivePromiseDomain(), {
119 withReactiveDomain(.domain, {
120 with_otel_span_context(.otel_info, domain = .domain, {
121 captureStackTraces({
122 env <- .getReactiveEnvironment()
123 rLog$enter(.reactId, id, .reactType, .domain)
124 on.exit(rLog$exit(.reactId, id, .reactType, .domain), add = TRUE)
125 env$runWith(self, func)
126 })
127 })
128 })
129 })
130 },
131 invalidate = function() {
132 "Invalidate this context. It will immediately call the callbacks
133 that have been registered with onInvalidate()."
134
135 if (!identical(.pid, processId())) {
136 rlang::abort("Reactive context was created in one process and invalidated from another.")
137 }
138
139 if (.invalidated)
140 return()
141 .invalidated <<- TRUE
142
143 rLog$invalidateStart(.reactId, id, .reactType, .domain)
144 on.exit(rLog$invalidateEnd(.reactId, id, .reactType, .domain), add = TRUE)
145
146 lapply(.invalidateCallbacks, function(func) {
147 func()
148 })
149 .invalidateCallbacks <<- list()
150 NULL
151 },
152 onInvalidate = function(func) {
153 "Register a function to be called when this context is invalidated.
154 If this context is already invalidated, the function is called
155 immediately."
156
157 if (!identical(.pid, processId())) {
158 rlang::abort("Reactive context was created in one process and accessed from another.")
159 }
160
161 if (.invalidated)
162 func()
163 else
164 .invalidateCallbacks <<- c(.invalidateCallbacks, func)
165 NULL
166 },
167 addPendingFlush = function(priority) {
168 "Tell the reactive environment that this context should be flushed the
169 next time flushReact() called."
170 .getReactiveEnvironment()$addPendingFlush(self, priority)
171 },
172 onFlush = function(func) {
173 "Register a function to be called when this context is flushed."
174 .flushCallbacks <<- c(.flushCallbacks, func)
175 },
176 executeFlushCallbacks = function() {
177 "For internal use only."
178
179 lapply(.flushCallbacks, function(flushCallback) {
180 flushCallback()
181 })
182 },
183 isWeak = function() {
184 .weak
185 }
186 )
187 )
188
189 ReactiveEnvironment <- R6Class(
190 'ReactiveEnvironment',
191 portable = FALSE,
192 class = FALSE,
193 public = list(
194 .currentContext = NULL,
195 .nextId = 0L,
196 .pendingFlush = 'PriorityQueue',
197 .inFlush = FALSE,
198
199 initialize = function() {
200 .pendingFlush <<- PriorityQueue$new()
201 },
202 nextId = function() {
203 .nextId <<- .nextId + 1L
204 return(as.character(.nextId))
205 },
206 currentContext = function() {
207 if (is.null(.currentContext)) {
208 if (isTRUE(getOption('shiny.suppressMissingContextError'))) {
209 return(getDummyContext())
210 } else {
211 rlang::abort(c(
212 'Operation not allowed without an active reactive context.',
213 paste0(
214 'You tried to do something that can only be done from inside a ',
215 'reactive consumer.'
216 )
217 ))
218 }
219 }
220 return(.currentContext)
221 },
222 runWith = function(ctx, contextFunc) {
223 old.ctx <- .currentContext
224 .currentContext <<- ctx
225 on.exit(.currentContext <<- old.ctx)
226 contextFunc()
227 },
228 addPendingFlush = function(ctx, priority) {
229 .pendingFlush$enqueue(ctx, priority)
230 },
231 hasPendingFlush = function() {
232 return(!.pendingFlush$isEmpty())
233 },
234 # Returns TRUE if anything was actually called
235 flush = function() {
236 # If nothing to flush, exit early
237 if (!hasPendingFlush()) return(invisible(FALSE))
238 # If already in a flush, don't start another one
239 if (.inFlush) return(invisible(FALSE))
240 .inFlush <<- TRUE
241 on.exit({
242 .inFlush <<- FALSE
243 rLog$idle(domain = NULL)
244 })
245
246 while (hasPendingFlush()) {
247 ctx <- .pendingFlush$dequeue()
248 ctx$executeFlushCallbacks()
249 }
250
251 invisible(TRUE)
252 }
253 )
254 )
255
256 .getReactiveEnvironment <- local({
257 reactiveEnvironment <- NULL
258 function() {
259 if (is.null(reactiveEnvironment))
260 reactiveEnvironment <<- ReactiveEnvironment$new()
261 return(reactiveEnvironment)
262 }
263 })
264
265 # Causes any pending invalidations to run. Returns TRUE if any invalidations
266 # were pending (i.e. if work was actually done).
267 flushReact <- function() {
268 return(.getReactiveEnvironment()$flush())
269 }
270
271 # Retrieves the current reactive context, or errors if there is no reactive
272 # context active at the moment.
273 getCurrentContext <- function() {
274 .getReactiveEnvironment()$currentContext()
275 }
276 hasCurrentContext <- function() {
277 !is.null(.getReactiveEnvironment()$.currentContext) ||
278 isTRUE(getOption("shiny.suppressMissingContextError"))
279 }
280
281 getDummyContext <- function() {
282 Context$new(
283 getDefaultReactiveDomain(), '[none]', type = 'isolate',
284 id = "Dummy", reactId = rLog$dummyReactId
285 )
286 }
287
288 wrapForContext <- function(func, ctx) {
289 force(func)
290 force(ctx) # may be NULL (in the case of maskReactiveContext())
291
292 function(...) {
293 .getReactiveEnvironment()$runWith(ctx, function() {
294 func(...)
295 })
296 }
297 }
298
299 reactivePromiseDomain <- function() {
300 new_promise_domain(
301 wrapOnFulfilled = function(onFulfilled) {
302 force(onFulfilled)
303
304 # ctx will be NULL if we're in a maskReactiveContext()
305 ctx <- if (hasCurrentContext()) getCurrentContext() else NULL
306
307 wrapForContext(onFulfilled, ctx)
308 },
309 wrapOnRejected = function(onRejected) {
310 force(onRejected)
311
312 # ctx will be NULL if we're in a maskReactiveContext()
313 ctx <- if (hasCurrentContext()) getCurrentContext() else NULL
314
315 wrapForContext(onRejected, ctx)
316 }
317 )
318 }