Debian Codegraph @

R/graph.R

raw
1 # domain is like session
2
3
4 # used to help define truly global react id's.
5 # should work across session and in global namespace
6 .globals$reactIdCounter <- 0L
7 nextGlobalReactId <- function() {
8 .globals$reactIdCounter <- .globals$reactIdCounter + 1L
9 reactIdStr(.globals$reactIdCounter)
10 }
11 reactIdStr <- function(num) {
12 paste0("r", num)
13 }
14
15
16 #' Reactive Log Visualizer
17 #'
18 #' Provides an interactive browser-based tool for visualizing reactive
19 #' dependencies and execution in your application.
20 #'
21 #' To use the reactive log visualizer, start with a fresh R session and
22 #' run the command `reactlog::reactlog_enable()`; then launch your
23 #' application in the usual way (e.g. using [runApp()]). At
24 #' any time you can hit Ctrl+F3 (or for Mac users, Command+F3) in your
25 #' web browser to launch the reactive log visualization.
26 #'
27 #' The reactive log visualization only includes reactive activity up
28 #' until the time the report was loaded. If you want to see more recent
29 #' activity, refresh the browser.
30 #'
31 #' Note that Shiny does not distinguish between reactive dependencies
32 #' that "belong" to one Shiny user session versus another, so the
33 #' visualization will include all reactive activity that has taken place
34 #' in the process, not just for a particular application or session.
35 #'
36 #' As an alternative to pressing Ctrl/Command+F3--for example, if you
37 #' are using reactives outside of the context of a Shiny
38 #' application--you can run the `reactlogShow` function, which will
39 #' generate the reactive log visualization as a static HTML file and
40 #' launch it in your default browser. In this case, refreshing your
41 #' browser will not load new activity into the report; you will need to
42 #' call `reactlogShow()` explicitly.
43 #'
44 #' For security and performance reasons, do not enable
45 #' `options(shiny.reactlog=TRUE)` (or `reactlog::reactlog_enable()`) in
46 #' production environments. When the option is enabled, it's possible
47 #' for any user of your app to see at least some of the source code of
48 #' your reactive expressions and observers. In addition, reactlog
49 #' should be considered a memory leak as it will constantly grow and
50 #' will never reset until the R session is restarted.
51 #'
52 #' @name reactlog
53 NULL
54
55
56 #' @describeIn reactlog Return a list of reactive information. Can be used in
57 #' conjunction with [reactlog::reactlog_show] to later display the reactlog
58 #' graph.
59 #' @export
60 reactlog <- function() {
61 rLog$asList()
62 }
63
64 #' @describeIn reactlog Display a full reactlog graph for all sessions.
65 #' @param time A boolean that specifies whether or not to display the
66 #' time that each reactive takes to calculate a result.
67 #' @export
68 reactlogShow <- function(time = TRUE) {
69 check_reactlog()
70 reactlog::reactlog_show(reactlog(), time = time)
71 }
72
73 #' @describeIn reactlog Resets the entire reactlog stack. Useful for debugging
74 #' and removing all prior reactive history.
75 #' @export
76 reactlogReset <- function() {
77 rLog$reset()
78 }
79
80 #' @describeIn reactlog Adds "mark" entry into the reactlog stack. This is
81 #' useful for programmatically adding a marked entry in the reactlog, rather
82 #' than using your keyboard's key combination.
83 #'
84 #' For example, we can _mark_ the reactlog at the beginning of an
85 #' `observeEvent`'s calculation:
86 #' ```r
87 #' observeEvent(input$my_event_trigger, {
88 #' # Add a mark in the reactlog
89 #' reactlogAddMark()
90 #' # Run your regular event reaction code here...
91 #' ....
92 #' })
93 #' ```
94 #' @param session The Shiny session to assign the mark to. Defaults to the
95 #' current session.
96 #' @export
97 reactlogAddMark <- function(session = getDefaultReactiveDomain()) {
98 rLog$userMark(session)
99 }
100
101 # called in "/reactlog" middleware
102 renderReactlog <- function(sessionToken = NULL, time = TRUE) {
103 check_reactlog()
104 reactlog::reactlog_render(
105 reactlog(),
106 session_token = sessionToken,
107 time = time
108 )
109 }
110
111 check_reactlog <- function() {
112 if (!is_installed("reactlog", reactlog_min_version)) {
113 rlang::check_installed("reactlog", reactlog_min_version)
114 }
115 }
116
117 # Should match the (suggested) version in DESCRIPTION file
118 reactlog_min_version <- "1.0.0"
119
120 RLog <- R6Class(
121 "RLog",
122 portable = FALSE,
123 private = list(
124 option = "shiny.reactlog",
125 msgOption = "shiny.reactlog.console",
126 appendEntry = function(domain, logEntry) {
127 if (self$isLogging()) {
128 sessionToken <- if (is.null(domain)) NULL else domain$token
129 logStack$push(c(logEntry, list(
130 session = sessionToken,
131 time = as.numeric(Sys.time())
132 )))
133 }
134 if (!is.null(domain)) domain$reactlog(logEntry)
135 }
136 ),
137 public = list(
138 msg = "<MessageLogger>",
139 logStack = "<Stack>",
140 noReactIdLabel = "NoCtxReactId",
141 noReactId = reactIdStr("NoCtxReactId"),
142 dummyReactIdLabel = "DummyReactId",
143 dummyReactId = reactIdStr("DummyReactId"),
144 asList = function() {
145 ret <- self$logStack$as_list()
146 attr(ret, "version") <- "1"
147 ret
148 },
149 ctxIdStr = function(ctxId) {
150 if (is.null(ctxId) || identical(ctxId, "")) {
151 return(NULL)
152 }
153 paste0("ctx", ctxId)
154 },
155 namesIdStr = function(reactId) {
156 paste0("names(", reactId, ")")
157 },
158 asListIdStr = function(reactId) {
159 paste0("reactiveValuesToList(", reactId, ")")
160 },
161 asListAllIdStr = function(reactId) {
162 paste0("reactiveValuesToList(", reactId, ", all.names = TRUE)")
163 },
164 keyIdStr = function(reactId, key) {
165 paste0(reactId, "$", key)
166 },
167 valueStr = function(value, n = 200) {
168 if (!self$isLogging()) {
169 # return a placeholder string to avoid calling str
170 return("<reactlog is turned off>")
171 }
172 output <- try(silent = TRUE, {
173 # only capture the first level of the object
174 utils::capture.output(utils::str(value, max.level = 1))
175 })
176 outputTxt <- paste0(output, collapse = "\n")
177 msg$shortenString(outputTxt, n = n)
178 },
179 initialize = function(rlogOption = "shiny.reactlog", msgOption = "shiny.reactlog.console") {
180 private$option <- rlogOption
181 private$msgOption <- msgOption
182
183 self$reset()
184 },
185 reset = function() {
186 .globals$reactIdCounter <- 0L
187
188 self$logStack <- fastmap::faststack()
189 self$msg <- MessageLogger$new(option = private$msgOption)
190
191 # setup dummy and missing react information
192 self$msg$setReact(force = TRUE, list(reactId = self$noReactId, label = self$noReactIdLabel))
193 self$msg$setReact(force = TRUE, list(reactId = self$dummyReactId, label = self$dummyReactIdLabel))
194 },
195 isLogging = function() {
196 isTRUE(getOption(private$option, FALSE))
197 },
198 define = function(reactId, value, label, type, domain) {
199 valueStr <- self$valueStr(value)
200 if (msg$hasReact(reactId)) {
201 stop("react definition for id: ", reactId, " already found!!", "Label: ", label, "Type: ", type)
202 }
203 msg$setReact(list(reactId = reactId, label = label))
204 msg$log("define:", msg$reactStr(reactId), msg$typeStr(type = type), msg$valueStr(valueStr))
205 private$appendEntry(domain, list(
206 action = "define",
207 reactId = reactId,
208 label = msg$shortenString(label),
209 type = type,
210 value = valueStr
211 ))
212 },
213 defineNames = function(reactId, value, label, domain) {
214 self$define(self$namesIdStr(reactId), value, self$namesIdStr(label), "reactiveValuesNames", domain)
215 },
216 defineAsList = function(reactId, value, label, domain) {
217 self$define(self$asListIdStr(reactId), value, self$asListIdStr(label), "reactiveValuesAsList", domain)
218 },
219 defineAsListAll = function(reactId, value, label, domain) {
220 self$define(self$asListAllIdStr(reactId), value, self$asListAllIdStr(label), "reactiveValuesAsListAll", domain)
221 },
222 defineKey = function(reactId, value, key, label, domain) {
223 self$define(self$keyIdStr(reactId, key), value, self$keyIdStr(label, key), "reactiveValuesKey", domain)
224 },
225 defineObserver = function(reactId, label, domain) {
226 self$define(reactId, value = NULL, label, "observer", domain)
227 },
228 dependsOn = function(reactId, depOnReactId, ctxId, domain) {
229 if (is.null(reactId)) {
230 return()
231 }
232 ctxId <- ctxIdStr(ctxId)
233 msg$log("dependsOn:", msg$reactStr(reactId), " on", msg$reactStr(depOnReactId), msg$ctxStr(ctxId))
234 private$appendEntry(domain, list(
235 action = "dependsOn",
236 reactId = reactId,
237 depOnReactId = depOnReactId,
238 ctxId = ctxId
239 ))
240 },
241 dependsOnKey = function(reactId, depOnReactId, key, ctxId, domain) {
242 self$dependsOn(reactId, self$keyIdStr(depOnReactId, key), ctxId, domain)
243 },
244 dependsOnRemove = function(reactId, depOnReactId, ctxId, domain) {
245 ctxId <- self$ctxIdStr(ctxId)
246 msg$log("dependsOnRemove:", msg$reactStr(reactId), " on", msg$reactStr(depOnReactId), msg$ctxStr(ctxId))
247 private$appendEntry(domain, list(
248 action = "dependsOnRemove",
249 reactId = reactId,
250 depOnReactId = depOnReactId,
251 ctxId = ctxId
252 ))
253 },
254 dependsOnKeyRemove = function(reactId, depOnReactId, key, ctxId, domain) {
255 self$dependsOnRemove(reactId, self$keyIdStr(depOnReactId, key), ctxId, domain)
256 },
257 createContext = function(ctxId, label, type, prevCtxId, domain) {
258 ctxId <- self$ctxIdStr(ctxId)
259 prevCtxId <- self$ctxIdStr(prevCtxId)
260 msg$log("createContext:", msg$ctxPrevCtxStr(preCtxIdTxt = " ", ctxId, prevCtxId, type))
261 private$appendEntry(domain, list(
262 action = "createContext",
263 ctxId = ctxId,
264 label = msg$shortenString(label),
265 type = type,
266 prevCtxId = prevCtxId,
267 srcref = as.vector(attr(label, "srcref")), srcfile = attr(label, "srcfile")
268 ))
269 },
270 enter = function(reactId, ctxId, type, domain) {
271 ctxId <- self$ctxIdStr(ctxId)
272 if (identical(type, "isolate")) {
273 msg$log("isolateEnter:", msg$reactStr(reactId), msg$ctxStr(ctxId))
274 msg$depthIncrement()
275 private$appendEntry(domain, list(
276 action = "isolateEnter",
277 reactId = reactId,
278 ctxId = ctxId
279 ))
280 } else {
281 msg$log("enter:", msg$reactStr(reactId), msg$ctxStr(ctxId, type))
282 msg$depthIncrement()
283 private$appendEntry(domain, list(
284 action = "enter",
285 reactId = reactId,
286 ctxId = ctxId,
287 type = type
288 ))
289 }
290 },
291 exit = function(reactId, ctxId, type, domain) {
292 ctxId <- self$ctxIdStr(ctxId)
293 if (identical(type, "isolate")) {
294 msg$depthDecrement()
295 msg$log("isolateExit:", msg$reactStr(reactId), msg$ctxStr(ctxId))
296 private$appendEntry(domain, list(
297 action = "isolateExit",
298 reactId = reactId,
299 ctxId = ctxId
300 ))
301 } else {
302 msg$depthDecrement()
303 msg$log("exit:", msg$reactStr(reactId), msg$ctxStr(ctxId, type))
304 private$appendEntry(domain, list(
305 action = "exit",
306 reactId = reactId,
307 ctxId = ctxId,
308 type = type
309 ))
310 }
311 },
312 valueChange = function(reactId, value, domain) {
313 valueStr <- self$valueStr(value)
314 msg$log("valueChange:", msg$reactStr(reactId), msg$valueStr(valueStr))
315 private$appendEntry(domain, list(
316 action = "valueChange",
317 reactId = reactId,
318 value = valueStr
319 ))
320 },
321 valueChangeNames = function(reactId, nameValues, domain) {
322 self$valueChange(self$namesIdStr(reactId), nameValues, domain)
323 },
324 valueChangeAsList = function(reactId, listValue, domain) {
325 self$valueChange(self$asListIdStr(reactId), listValue, domain)
326 },
327 valueChangeAsListAll = function(reactId, listValue, domain) {
328 self$valueChange(self$asListAllIdStr(reactId), listValue, domain)
329 },
330 valueChangeKey = function(reactId, key, value, domain) {
331 self$valueChange(self$keyIdStr(reactId, key), value, domain)
332 },
333 invalidateStart = function(reactId, ctxId, type, domain) {
334 ctxId <- self$ctxIdStr(ctxId)
335 if (identical(type, "isolate")) {
336 msg$log("isolateInvalidateStart:", msg$reactStr(reactId), msg$ctxStr(ctxId))
337 msg$depthIncrement()
338 private$appendEntry(domain, list(
339 action = "isolateInvalidateStart",
340 reactId = reactId,
341 ctxId = ctxId
342 ))
343 } else {
344 msg$log("invalidateStart:", msg$reactStr(reactId), msg$ctxStr(ctxId, type))
345 msg$depthIncrement()
346 private$appendEntry(domain, list(
347 action = "invalidateStart",
348 reactId = reactId,
349 ctxId = ctxId,
350 type = type
351 ))
352 }
353 },
354 invalidateEnd = function(reactId, ctxId, type, domain) {
355 ctxId <- self$ctxIdStr(ctxId)
356 if (identical(type, "isolate")) {
357 msg$depthDecrement()
358 msg$log("isolateInvalidateEnd:", msg$reactStr(reactId), msg$ctxStr(ctxId))
359 private$appendEntry(domain, list(
360 action = "isolateInvalidateEnd",
361 reactId = reactId,
362 ctxId = ctxId
363 ))
364 } else {
365 msg$depthDecrement()
366 msg$log("invalidateEnd:", msg$reactStr(reactId), msg$ctxStr(ctxId, type))
367 private$appendEntry(domain, list(
368 action = "invalidateEnd",
369 reactId = reactId,
370 ctxId = ctxId,
371 type = type
372 ))
373 }
374 },
375 invalidateLater = function(reactId, runningCtx, millis, domain) {
376 msg$log("invalidateLater: ", millis, "ms", msg$reactStr(reactId), msg$ctxStr(runningCtx))
377 private$appendEntry(domain, list(
378 action = "invalidateLater",
379 reactId = reactId,
380 ctxId = runningCtx,
381 millis = millis
382 ))
383 },
384 idle = function(domain = NULL) {
385 msg$log("idle")
386 private$appendEntry(domain, list(
387 action = "idle"
388 ))
389 },
390 asyncStart = function(domain = NULL) {
391 msg$log("asyncStart")
392 private$appendEntry(domain, list(
393 action = "asyncStart"
394 ))
395 },
396 asyncStop = function(domain = NULL) {
397 msg$log("asyncStop")
398 private$appendEntry(domain, list(
399 action = "asyncStop"
400 ))
401 },
402 freezeReactiveVal = function(reactId, domain) {
403 msg$log("freeze:", msg$reactStr(reactId))
404 private$appendEntry(domain, list(
405 action = "freeze",
406 reactId = reactId
407 ))
408 },
409 freezeReactiveKey = function(reactId, key, domain) {
410 self$freezeReactiveVal(self$keyIdStr(reactId, key), domain)
411 },
412 thawReactiveVal = function(reactId, domain) {
413 msg$log("thaw:", msg$reactStr(reactId))
414 private$appendEntry(domain, list(
415 action = "thaw",
416 reactId = reactId
417 ))
418 },
419 thawReactiveKey = function(reactId, key, domain) {
420 self$thawReactiveVal(self$keyIdStr(reactId, key), domain)
421 },
422 userMark = function(domain = NULL) {
423 msg$log("userMark")
424 private$appendEntry(domain, list(
425 action = "userMark"
426 ))
427 }
428 )
429 )
430
431 MessageLogger <- R6Class(
432 "MessageLogger",
433 portable = FALSE,
434 public = list(
435 depth = 0L,
436 reactCache = list(),
437 option = "shiny.reactlog.console",
438 initialize = function(option = "shiny.reactlog.console", depth = 0L) {
439 if (!missing(depth)) self$depth <- depth
440 if (!missing(option)) self$option <- option
441 },
442 isLogging = function() {
443 isTRUE(getOption(self$option))
444 },
445 isNotLogging = function() {
446 !isTRUE(getOption(self$option))
447 },
448 depthIncrement = function() {
449 if (self$isNotLogging()) {
450 return(NULL)
451 }
452 self$depth <- self$depth + 1L
453 },
454 depthDecrement = function() {
455 if (self$isNotLogging()) {
456 return(NULL)
457 }
458 self$depth <- self$depth - 1L
459 },
460 hasReact = function(reactId) {
461 if (self$isNotLogging()) {
462 return(FALSE)
463 }
464 !is.null(self$getReact(reactId))
465 },
466 getReact = function(reactId, force = FALSE) {
467 if (identical(force, FALSE) && self$isNotLogging()) {
468 return(NULL)
469 }
470 self$reactCache[[reactId]]
471 },
472 setReact = function(reactObj, force = FALSE) {
473 if (identical(force, FALSE) && self$isNotLogging()) {
474 return(NULL)
475 }
476 self$reactCache[[reactObj$reactId]] <- reactObj
477 },
478 shortenString = function(txt, n = 250) {
479 if (is.null(txt) || isTRUE(is.na(txt))) {
480 return("")
481 }
482 if (nchar(txt) > n) {
483 return(
484 paste0(substr(txt, 1, n - 3), "...")
485 )
486 }
487 return(txt)
488 },
489 singleLine = function(txt) {
490 gsub("([^\\])\\n", "\\1\\\\n", txt)
491 },
492 valueStr = function(valueStr) {
493 paste0(
494 " '", self$shortenString(self$singleLine(valueStr)), "'"
495 )
496 },
497 reactStr = function(reactId) {
498 if (self$isNotLogging()) {
499 return(NULL)
500 }
501 reactInfo <- self$getReact(reactId)
502 if (is.null(reactInfo)) {
503 return(" <UNKNOWN_REACTID>")
504 }
505 paste0(
506 " ", reactInfo$reactId, ":'", self$shortenString(self$singleLine(reactInfo$label)), "'"
507 )
508 },
509 typeStr = function(type = NULL) {
510 self$ctxStr(ctxId = NULL, type = type)
511 },
512 ctxStr = function(ctxId = NULL, type = NULL) {
513 if (self$isNotLogging()) {
514 return(NULL)
515 }
516 self$ctxPrevCtxStr(ctxId = ctxId, prevCtxId = NULL, type = type)
517 },
518 ctxPrevCtxStr = function(ctxId = NULL, prevCtxId = NULL, type = NULL, preCtxIdTxt = " in ") {
519 if (self$isNotLogging()) {
520 return(NULL)
521 }
522 paste0(
523 if (!is.null(ctxId)) paste0(preCtxIdTxt, ctxId),
524 if (!is.null(prevCtxId)) paste0(" from ", prevCtxId),
525 if (!is.null(type) && !identical(type, "other")) paste0(" - ", type)
526 )
527 },
528 log = function(...) {
529 if (self$isNotLogging()) {
530 return(NULL)
531 }
532 msg <- paste0(
533 paste0(rep("= ", depth), collapse = ""), "- ", paste0(..., collapse = ""),
534 collapse = ""
535 )
536 message(msg)
537 }
538 )
539 )
540
541 on_load({
542 rLog <- RLog$new("shiny.reactlog", "shiny.reactlog.console")
543 })