Compare commits

...

11 Commits

Author SHA1 Message Date
Barret Schloerke
b5da7868fa v1.12.0 (#4312) 2025-12-03 15:48:49 -05:00
ismirsehregal
c8a41aa834 Update dateYMD (#4318)
Co-authored-by: Garrick Aden-Buie <garrick@adenbuie.com>
2025-12-01 10:25:28 -05:00
Copilot
390f6d3b95 chore(otel): Rename shiny.otel.bind to shiny.otel.collect (#4321)
Co-authored-by: Barret Schloerke <barret@posit.co>
2025-11-25 16:36:56 -05:00
Barret Schloerke
9a2140cd19 chore(test): Fix stacks test with R 4.5.2 (#4322) 2025-11-25 16:31:53 -05:00
Barret Schloerke
e3cf4fb089 refactor(otel): Cache tracer and logger on init and on demand (#4315)
Co-authored-by: Charlie Gao <53399081+shikokuchuo@users.noreply.github.com>
2025-11-11 08:44:57 -05:00
Barret Schloerke
472a1cdba1 refactor(otel): Refactor internal method names (#4313) 2025-11-06 11:20:37 -05:00
Barret Schloerke
b56c275364 feat(otel): Enhanced OpenTelemetry support (#4300) 2025-10-28 14:01:50 -04:00
Garrick Aden-Buie
592e825a0f feat: Replace client-side markdown rendering with server-side in showcase mode (#4306)
* feat: Replace client-side markdown rendering with server-side in showcase mode

* `devtools::document()` (GitHub Actions)

* chore: callout rendering differences may happen
2025-10-22 09:34:20 -04:00
Barret Schloerke
50a140c580 ci(test): Disable installation of Cairo for unit tests (#4301) 2025-10-15 16:24:22 -04:00
Barret Schloerke
48d255a235 feat: Add {otel} support (#4269) 2025-10-14 15:40:36 -04:00
Barret Schloerke
a01fcc5194 chore(check): Fix minor check warnings (#4299) 2025-10-10 16:30:47 -04:00
79 changed files with 5053 additions and 2073 deletions

View File

@@ -32,3 +32,4 @@
^eslint\.config\.mjs$
^_dev$
^.claude$
^README-npm\.md$

View File

@@ -6,7 +6,7 @@ on:
push:
branches: [main, rc-**]
pull_request:
branches: [main]
branches:
schedule:
- cron: "0 5 * * 1" # every monday
@@ -19,3 +19,7 @@ jobs:
uses: rstudio/shiny-workflows/.github/workflows/routine.yaml@v1
R-CMD-check:
uses: rstudio/shiny-workflows/.github/workflows/R-CMD-check.yaml@v1
with:
# On R 4.2, Cairo has difficulty installing
# Remove this line when https://github.com/s-u/Cairo/issues/52 is merged
extra-packages: Cairo=?ignore

View File

@@ -6,6 +6,7 @@
"[r]": {
"files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true,
"editor.formatOnSave": false,
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",

View File

@@ -1,7 +1,7 @@
Type: Package
Package: shiny
Title: Web Application Framework for R
Version: 1.11.1.9000
Version: 1.12.0
Authors@R: c(
person("Winston", "Chang", , "winston@posit.co", role = "aut",
comment = c(ORCID = "0000-0002-1576-2126")),
@@ -60,10 +60,6 @@ Authors@R: c(
comment = "Javascript strftime library"),
person(, "SpryMedia Limited", role = c("ctb", "cph"),
comment = "DataTables library"),
person("John", "Fraser", role = c("ctb", "cph"),
comment = "showdown.js library"),
person("John", "Gruber", role = c("ctb", "cph"),
comment = "showdown.js library"),
person("Ivan", "Sagalaev", role = c("ctb", "cph"),
comment = "highlight.js library"),
person("R Core Team", role = c("ctb", "cph"),
@@ -83,7 +79,7 @@ Imports:
bslib (>= 0.6.0),
cachem (>= 1.1.0),
cli,
commonmark (>= 1.7),
commonmark (>= 2.0.0),
fastmap (>= 1.1.1),
fontawesome (>= 0.4.0),
glue (>= 1.3.2),
@@ -94,7 +90,8 @@ Imports:
later (>= 1.0.0),
lifecycle (>= 0.2.0),
mime (>= 0.3),
promises (>= 1.3.2),
otel,
promises (>= 1.5.0),
R6 (>= 2.0),
rlang (>= 0.4.10),
sourcetools,
@@ -114,6 +111,7 @@ Suggests:
magrittr,
markdown,
mirai,
otelsdk (>= 0.2.0),
ragg,
reactlog (>= 1.0.0),
rmarkdown,
@@ -185,6 +183,14 @@ Collate:
'modal.R'
'modules.R'
'notifications.R'
'otel-attr-srcref.R'
'otel-collect.R'
'otel-enable.R'
'otel-error.R'
'otel-label.R'
'otel-reactive-update.R'
'otel-session.R'
'otel-shiny.R'
'priorityqueue.R'
'progress.R'
'react.R'

View File

@@ -387,10 +387,13 @@ importFrom(lifecycle,is_present)
importFrom(promises,"%...!%")
importFrom(promises,"%...>%")
importFrom(promises,as.promise)
importFrom(promises,hybrid_then)
importFrom(promises,is.promise)
importFrom(promises,is.promising)
importFrom(promises,promise)
importFrom(promises,new_promise_domain)
importFrom(promises,promise_reject)
importFrom(promises,promise_resolve)
importFrom(promises,with_promise_domain)
importFrom(rlang,"%||%")
importFrom(rlang,"fn_body<-")
importFrom(rlang,"fn_fmls<-")

104
NEWS.md
View File

@@ -1,18 +1,106 @@
# shiny (development version)
# shiny 1.12.0
## OpenTelemetry support
* Shiny now supports [OpenTelemetry](https://opentelemetry.io/) via
[`{otel}`](https://otel.r-lib.org/index.html). By default, if
`otel::is_tracing_enabled()` returns `TRUE`, then `{shiny}` records all
OpenTelemetry spans. See [`{otelsdk}`'s Collecting Telemetry
Data](https://otelsdk.r-lib.org/reference/collecting.html) for more details
on configuring OpenTelemetry. (#4269, #4300)
* Supported values for `options(shiny.otel.collect)` (or
`Sys.getenv("SHINY_OTEL_COLLECT")`):
* `"none"` - No Shiny OpenTelemetry tracing.
* `"session"` - Adds session start/end spans.
* `"reactive_update"` - Spans for any synchronous/asynchronous reactive
update. (Includes `"session"` features).
* `"reactivity"` - Spans for all reactive expressions. (Includes
`"reactive_update"` features).
* `"all"` [default] - All Shiny OpenTelemetry tracing. Currently equivalent
to `"reactivity"`.
* OpenTelemetry spans are recorded for:
* `session_start`: Wraps the calling of the `server()` function. Also
contains HTTP request within the attributes.
* `session_end`: Wraps the calling of the `onSessionEnded()` handlers.
* `reactive_update`: Signals the start of when Shiny knows something is to
be calculated. This span ends when there are no more reactive updates
(promises or synchronous) to be calculated.
* `reactive`, `observe`, `output`: Captures the calculation (including any
async promise chains) of a reactive expression (`reactive()`), an observer
(`observe()`), or an output render function (`render*()`).
* `reactive debounce`, `reactive throttle`: Captures the calculation
(including any async promise chains) of a `debounce()`d or `throttle()`d
reactive expression.
* `reactiveFileReader`, `reactivePoll`: Captures the calculation
(including any async promise chains) of a `reactiveFileReader()` or
`reactivePoll()`.
* `ExtendedTask`: Captures the calculation (including any async promise
chains) of an `ExtendedTask`.
* OpenTelemetry Logs are recorded for:
* `Set reactiveVal <name>` - When a `reactiveVal()` is set
* `Set reactiveValues <name>$<key>` - When a `reactiveValues()` element is
set
* Fatal or unhandled errors - When an error occurs that causes the session
to end, or when an unhandled error occurs in a reactive context. Contains
the error within the attributes. To unsanitize the error message being
collected, set `options(shiny.otel.sanitize.errors = FALSE)`.
* `Set ExtendedTask <name> <value>` - When an `ExtendedTask`'s respective
reactive value (e.g., `status`, `value`, and `error`) is set.
* `<ExtendedTask name> add to queue` - When an `ExtendedTask` is added to
the task queue.
* All OpenTelemetry logs and spans will contain a `session.id` attribute
containing the active session ID.
## New features
* The `icon` argument of `updateActionButton()`/`updateActionLink()` nows allows values other than `shiny::icon()` (e.g., `fontawesome::fa()`, `bsicons::bs_icon()`, etc). (#4249)
* `updateActionButton()` and `updateActionLink()` now accept values other than
`shiny::icon()` for the `icon` argument (e.g., `fontawesome::fa()`,
`bsicons::bs_icon()`, etc). (#4249)
## Bug fixes
## Bug fixes and minor improvements
* `updateActionButton()`/`updateActionLink()` now correctly renders HTML content passed to the `label` argument. (#4249)
* Showcase mode now uses server-side markdown rendering with the
`{commonmark}` package, providing support for GitHub Flavored Markdown
features (tables, strikethrough, autolinks, task lists). While most existing
README.md files should continue to work as expected, some minor rendering
differences may occur due to the change in markdown processor. (#4202,
#4201)
* Fixed an issue where `updateSelectizeInput(options = list(plugins="remove_button"))` could lead to multiple remove buttons. (#4275)
* `debounce()`, `reactiveFileReader()`, `reactivePoll()`, `reactiveValues()`,
and `throttle()` now attempt to retrieve the assigned name for the default
label if the srcref is available. If a value cannot easily be produced, a
default label is used instead. (#4269, #4300)
## Changes
* The default label for items described below will now attempt to retrieve the
assigned name if the srcref is available. If a value can not easily be
produced, a default label will be used instead. This should improve the
OpenTelemetry span labels and the reactlog experience. (#4269, #4300)
* `reactiveValues()`, `reactivePoll()`, `reactiveFileReader()`, `debounce()`,
`throttle()`, `observe()`
* Combinations of `bindEvent()` and `reactive()` / `observe()`
* Combination of `bindCache()` and `reactive()`
* The return value of `actionButton()`/`actionLink()` changed slightly: `label` and `icon` are wrapped in an additional HTML container element. This allows for: 1. `updateActionButton()`/`updateActionLink()` to distinguish between the `label` and `icon` when making updates and 2. spacing between `label` and `icon` to be more easily customized via CSS.
* `updateActionButton()` and `updateActionLink()` now correctly render HTML
content passed to the `label` argument. (#4249)
* `updateSelectizeInput()` no longer creates multiple remove buttons when
`options = list(plugins="remove_button")` is used. (#4275)
* `dateRangeInput()`/`updateDateRangeInput()` now correctly considers the time
zones of date-time objects (POSIXct) passed to the `start`, `end`, `min` and
`max` arguments. (thanks @ismirsehregal, #4318)
## Breaking changes
* The return value of `actionButton()` and `actionLink()` now wraps `label`
and `icon` in an additional HTML container element. This allows
`updateActionButton()` and `updateActionLink()` to distinguish between the
`label` and `icon` when making updates, and allows spacing between `label`
and `icon` to be more easily customized via CSS.
# shiny 1.11.1
@@ -684,7 +772,7 @@ This release features plot caching, an important new tool for improving performa
### Minor new features and improvements
* Upgrade FontAwesome from 4.7.0 to 5.3.1 and made `icon` tags browsable, which means they will display in a web browser or RStudio viewer by default (#2186). Note that if your application or library depends on FontAwesome directly using custom CSS, you may need to make some or all of the changes recommended in [Upgrade from Version 4](https://fontawesome.com/how-to-use/on-the-web/setup/upgrading-from-version-4). Font Awesome icons can also now be used in static R Markdown documents.
* Upgrade FontAwesome from 4.7.0 to 5.3.1 and made `icon` tags browsable, which means they will display in a web browser or RStudio viewer by default (#2186). Note that if your application or library depends on FontAwesome directly using custom CSS, you may need to make some or all of the changes recommended in [Upgrade from Version 4](https://docs.fontawesome.com/v5/web/setup/upgrade-from-v4). Font Awesome icons can also now be used in static R Markdown documents.
* Address #174: Added `datesdisabled` and `daysofweekdisabled` as new parameters to `dateInput()`. This resolves #174 and exposes the underlying arguments of [Bootstrap Datepicker](http://bootstrap-datepicker.readthedocs.io/en/latest/options.html#datesdisabled). `datesdisabled` expects a character vector with values in `yyyy/mm/dd` format and `daysofweekdisabled` expects an integer vector with day interger ids (Sunday=0, Saturday=6). The default value for both is `NULL`, which leaves all days selectable. Thanks, @nathancday! (#2147)

View File

@@ -478,7 +478,12 @@ bindCache.default <- function(x, ...) {
bindCache.reactiveExpr <- function(x, ..., cache = "app") {
check_dots_unnamed()
label <- exprToLabel(substitute(key), "cachedReactive")
call_srcref <- get_call_srcref(-1)
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = exprToLabel(substitute(x), "cachedReactive")
)
domain <- reactive_get_domain(x)
# Convert the ... to a function that returns their evaluated values.
@@ -490,24 +495,37 @@ bindCache.reactiveExpr <- function(x, ..., cache = "app") {
cacheHint <- rlang::hash(extractCacheHint(x))
valueFunc <- wrapFunctionLabel(valueFunc, "cachedReactiveValueFunc", ..stacktraceon = TRUE)
x_classes <- class(x)
x_otel_attrs <- attr(x, "observable", exact = TRUE)$.otelAttrs
# Don't hold on to the reference for x, so that it can be GC'd
rm(x)
# Hacky workaround for issue with `%>%` preventing GC:
# https://github.com/tidyverse/magrittr/issues/229
if (exists(".GenericCallEnv") && exists(".", envir = .GenericCallEnv)) {
rm(list = ".", envir = .GenericCallEnv)
if (exists(".GenericCallEnv") && exists(".", envir = .GenericCallEnv, inherits = FALSE)) {
rm(list = ".", envir = .GenericCallEnv, inherits = FALSE)
}
res <- reactive(label = label, domain = domain, {
cache <- resolve_cache_object(cache, domain)
hybrid_chain(
keyFunc(),
generateCacheFun(valueFunc, cache, cacheHint, cacheReadHook = identity, cacheWriteHook = identity)
)
with_no_otel_collect({
res <- reactive(label = label, domain = domain, {
cache <- resolve_cache_object(cache, domain)
hybrid_chain(
keyFunc(),
generateCacheFun(valueFunc, cache, cacheHint, cacheReadHook = identity, cacheWriteHook = identity)
)
})
})
class(res) <- c("reactive.cache", class(res))
local({
impl <- attr(res, "observable", exact = TRUE)
impl$.otelAttrs <- append_otel_srcref_attrs(x_otel_attrs, call_srcref)
})
if (has_otel_collect("reactivity")) {
res <- enable_otel_reactive_expr(res)
}
res
}
@@ -534,6 +552,7 @@ bindCache.shiny.render.function <- function(x, ..., cache = "app") {
)
}
# Passes over the otelAttrs from valueFunc to renderFunc
renderFunc <- addAttributes(renderFunc, renderFunctionAttributes(valueFunc))
class(renderFunc) <- c("shiny.render.function.cache", class(valueFunc))
renderFunc
@@ -585,7 +604,7 @@ bindCache.shiny.renderPlot <- function(x, ...,
observe({
doResizeCheck()
})
}, label = "plot-resize")
# TODO: Make sure this observer gets GC'd if output$foo is replaced.
# Currently, if you reassign output$foo, the observer persists until the
# session ends. This is generally bad programming practice and should be

View File

@@ -196,31 +196,58 @@ bindEvent.reactiveExpr <- function(x, ..., ignoreNULL = TRUE, ignoreInit = FALSE
valueFunc <- reactive_get_value_func(x)
valueFunc <- wrapFunctionLabel(valueFunc, "eventReactiveValueFunc", ..stacktraceon = TRUE)
label <- label %||%
sprintf('bindEvent(%s, %s)', attr(x, "observable", exact = TRUE)$.label, quos_to_label(qs))
call_srcref <- get_call_srcref(-1)
if (is.null(label)) {
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = as_default_label(sprintf(
'bindEvent(%s, %s)',
attr(x, "observable", exact = TRUE)$.label,
quos_to_label(qs)
))
)
}
x_classes <- class(x)
x_otel_attrs <- attr(x, "observable", exact = TRUE)$.otelAttrs
# Don't hold on to the reference for x, so that it can be GC'd
rm(x)
initialized <- FALSE
res <- reactive(label = label, domain = domain, ..stacktraceon = FALSE, {
hybrid_chain(
eventFunc(),
function(value) {
if (ignoreInit && !initialized) {
initialized <<- TRUE
req(FALSE)
with_no_otel_collect({
res <- reactive(label = label, domain = domain, ..stacktraceon = FALSE, {
hybrid_chain(
{
eventFunc()
},
function(value) {
if (ignoreInit && !initialized) {
initialized <<- TRUE
req(FALSE)
}
req(!ignoreNULL || !isNullEvent(value))
isolate(valueFunc())
}
req(!ignoreNULL || !isNullEvent(value))
isolate(valueFunc())
}
)
)
})
})
class(res) <- c("reactive.event", class(res))
class(res) <- c("reactive.event", x_classes)
local({
impl <- attr(res, "observable", exact = TRUE)
impl$.otelAttrs <- append_otel_srcref_attrs(x_otel_attrs, call_srcref)
})
if (has_otel_collect("reactivity")) {
res <- enable_otel_reactive_expr(res)
}
res
}
@@ -249,6 +276,7 @@ bindEvent.shiny.render.function <- function(x, ..., ignoreNULL = TRUE, ignoreIni
)
}
# Passes over the otelAttrs from valueFunc to renderFunc
renderFunc <- addAttributes(renderFunc, renderFunctionAttributes(valueFunc))
class(renderFunc) <- c("shiny.render.function.event", class(valueFunc))
renderFunc
@@ -269,7 +297,17 @@ bindEvent.Observer <- function(x, ..., ignoreNULL = TRUE, ignoreInit = FALSE,
# Note that because the observer will already have been logged by this point,
# this updated label won't show up in the reactlog.
x$.label <- label %||% sprintf('bindEvent(%s, %s)', x$.label, quos_to_label(qs))
if (is.null(label)) {
call_srcref <- get_call_srcref(-1)
x$.label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = as_default_label(
sprintf('bindEvent(%s, %s)', x$.label, quos_to_label(qs))
)
)
} else {
x$.label <- label
}
initialized <- FALSE
@@ -302,6 +340,13 @@ bindEvent.Observer <- function(x, ..., ignoreNULL = TRUE, ignoreInit = FALSE,
)
class(x) <- c("Observer.event", class(x))
call_srcref <- get_call_srcref(-1)
x$.otelAttrs <- append_otel_srcref_attrs(x$.otelAttrs, call_srcref)
if (has_otel_collect("reactivity")) {
x <- enable_otel_observe(x)
}
invisible(x)
}

View File

@@ -134,7 +134,9 @@ getCallCategories <- function(calls) {
#' @rdname stacktrace
#' @export
captureStackTraces <- function(expr) {
promises::with_promise_domain(createStackTracePromiseDomain(),
# Use `promises::` as it shows up in the stack trace
promises::with_promise_domain(
createStackTracePromiseDomain(),
expr
)
}
@@ -184,7 +186,7 @@ createStackTracePromiseDomain <- function() {
# These are actually stateless, we wouldn't have to create a new one each time
# if we didn't want to. They're pretty cheap though.
d <- promises::new_promise_domain(
d <- new_promise_domain(
wrapOnFulfilled = function(onFulfilled) {
force(onFulfilled)
# Subscription time
@@ -278,7 +280,7 @@ withLogErrors <- function(expr,
result <- captureStackTraces(expr)
# Handle expr being an async operation
if (promises::is.promise(result)) {
if (is.promise(result)) {
result <- promises::catch(result, function(cond) {
# Don't print shiny.silent.error (i.e. validation errors)
if (cnd_inherits(cond, "shiny.silent.error")) {
@@ -556,8 +558,9 @@ dropTrivialTestFrames <- function(callnames) {
"testthat::test_local"
)
firstGoodCall <- min(which(!hideable))
toRemove <- firstGoodCall - 1L
# Remove everything from inception to calling the test
# It shouldn't matter how you get there, just that you're finally testing
toRemove <- max(which(hideable))
c(
rep_len(FALSE, toRemove),

View File

@@ -116,10 +116,33 @@ ExtendedTask <- R6Class("ExtendedTask", portable = TRUE, cloneable = FALSE,
#' read reactive inputs and pass them as arguments.
initialize = function(func) {
private$func <- func
private$rv_status <- reactiveVal("initial")
private$rv_value <- reactiveVal(NULL)
private$rv_error <- reactiveVal(NULL)
# Do not show these private reactive values in otel spans
with_no_otel_collect({
private$rv_status <- reactiveVal("initial", label = "ExtendedTask$private$status")
private$rv_value <- reactiveVal(NULL, label = "ExtendedTask$private$value")
private$rv_error <- reactiveVal(NULL, label = "ExtendedTask$private$error")
})
private$invocation_queue <- fastmap::fastqueue()
domain <- getDefaultReactiveDomain()
# Set a label for the reactive values for easier debugging
# Go up an extra sys.call() to get the user's call to ExtendedTask$new()
# The first sys.call() is to `initialize(...)`
call_srcref <- get_call_srcref(-1)
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = "<anonymous>"
)
private$otel_span_label <- otel_span_label_extended_task(label, domain = domain)
private$otel_log_label_add_to_queue <- otel_log_label_extended_task_add_to_queue(label, domain = domain)
private$otel_attrs <- c(
otel_srcref_attributes(call_srcref),
otel_session_id_attrs(domain)
) %||% list()
},
#' @description
#' Starts executing the long-running operation. If this `ExtendedTask` is
@@ -139,8 +162,27 @@ ExtendedTask <- R6Class("ExtendedTask", portable = TRUE, cloneable = FALSE,
isolate(private$rv_status()) == "running" ||
private$invocation_queue$size() > 0
) {
otel_log(
private$otel_log_add_to_queue_label,
severity = "debug",
attributes = c(
private$otel_attrs,
list(
queue_size = private$invocation_queue$size() + 1L
)
)
)
private$invocation_queue$add(list(args = args, call = call))
} else {
if (has_otel_collect("reactivity")) {
private$otel_span <- start_otel_span(
private$otel_span_label,
attributes = private$otel_attrs
)
otel::local_active_span(private$otel_span)
}
private$do_invoke(args, call = call)
}
invisible(NULL)
@@ -188,7 +230,7 @@ ExtendedTask <- R6Class("ExtendedTask", portable = TRUE, cloneable = FALSE,
#' invalidation will be ignored.
result = function() {
switch (private$rv_status(),
running = req(FALSE, cancelOutput="progress"),
running = req(FALSE, cancelOutput = "progress"),
success = if (private$rv_value()$visible) {
private$rv_value()$value
} else {
@@ -208,21 +250,35 @@ ExtendedTask <- R6Class("ExtendedTask", portable = TRUE, cloneable = FALSE,
rv_error = NULL,
invocation_queue = NULL,
otel_span_label = NULL,
otel_log_label_add_to_queue = NULL,
otel_attrs = list(),
otel_span = NULL,
do_invoke = function(args, call = NULL) {
private$rv_status("running")
private$rv_value(NULL)
private$rv_error(NULL)
p <- promises::promise_resolve(
p <- promise_resolve(
maskReactiveContext(do.call(private$func, args))
)
p <- promises::then(
p,
onFulfilled = function(value, .visible) {
if (is_otel_span(private$otel_span)) {
private$otel_span$end(status_code = "ok")
private$otel_span <- NULL
}
private$on_success(list(value = value, visible = .visible))
},
onRejected = function(error) {
if (is_otel_span(private$otel_span)) {
private$otel_span$end(status_code = "error")
private$otel_span <- NULL
}
private$on_error(error, call = call)
}
)

View File

@@ -25,3 +25,7 @@ on_load_exprs <- list()
on_load <- function(expr) {
on_load_exprs[[length(on_load_exprs) + 1]] <<- substitute(expr)
}
on_load({
IS_SHINY_LOCAL_PKG <- exists(".__DEVTOOLS__")
})

View File

@@ -100,7 +100,7 @@ plotPNG <- function(func, filename=tempfile(fileext='.png'),
createGraphicsDevicePromiseDomain <- function(which = dev.cur()) {
force(which)
promises::new_promise_domain(
new_promise_domain(
wrapOnFulfilled = function(onFulfilled) {
force(onFulfilled)
function(...) {

View File

@@ -436,34 +436,36 @@ MockShinySession <- R6Class(
if (!is.function(func))
stop(paste("Unexpected", class(func), "output for", name))
obs <- observe({
# We could just stash the promise, but we get an "unhandled promise error". This bypasses
prom <- NULL
tryCatch({
v <- private$withCurrentOutput(name, func(self, name))
if (!promises::is.promise(v)){
# Make our sync value into a promise
prom <- promises::promise(function(resolve, reject){ resolve(v) })
} else {
prom <- v
}
}, error=function(e){
# Error running value()
prom <<- promises::promise(function(resolve, reject){ reject(e) })
})
private$outs[[name]]$promise <- hybrid_chain(
prom,
function(v){
list(val = v, err = NULL)
}, catch=function(e){
if (
!inherits(e, c("shiny.custom.error", "shiny.output.cancel", "shiny.output.progress", "shiny.silent.error"))
) {
self$unhandledError(e, close = FALSE)
with_no_otel_collect({
obs <- observe({
# We could just stash the promise, but we get an "unhandled promise error". This bypasses
prom <- NULL
tryCatch({
v <- private$withCurrentOutput(name, func(self, name))
if (!is.promise(v)){
# Make our sync value into a promise
prom <- promise_resolve(v)
} else {
prom <- v
}
list(val = NULL, err = e)
}, error=function(e){
# Error running value()
prom <<- promise_reject(e)
})
private$outs[[name]]$promise <- hybrid_chain(
prom,
function(v){
list(val = v, err = NULL)
}, catch=function(e){
if (
!inherits(e, c("shiny.custom.error", "shiny.output.cancel", "shiny.output.progress", "shiny.silent.error"))
) {
self$unhandledError(e, close = FALSE)
}
list(val = NULL, err = e)
})
})
})
private$outs[[name]] <- list(obs = obs, func = func, promise = NULL)
},
@@ -716,7 +718,7 @@ MockShinySession <- R6Class(
stop("Nested calls to withCurrentOutput() are not allowed.")
}
promises::with_promise_domain(
with_promise_domain(
createVarPromiseDomain(private, "currentOutputName", name),
expr
)

57
R/otel-attr-srcref.R Normal file
View File

@@ -0,0 +1,57 @@
# Very similar to srcrefFromShinyCall(),
# however, this works when the function does not have a srcref attr set
otel_srcref_attributes <- function(srcref) {
if (is.function(srcref)) {
srcref <- getSrcRefs(srcref)[[1]][[1]]
}
if (is.null(srcref)) {
return(NULL)
}
stopifnot(inherits(srcref, "srcref"))
# Semantic conventions for code: https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/
#
# Inspiration from https://github.com/r-lib/testthat/pull/2087/files#diff-92de3306849d93d6f7e76c5aaa1b0c037e2d716f72848f8a1c70536e0c8a1564R123-R124
dropNulls(list(
"code.filepath" = attr(srcref, "srcfile")$filename,
"code.lineno" = srcref[1],
"code.column" = srcref[2]
))
}
#' Get the srcref for the call at the specified stack level
#'
#' If you need to go farther back in the `sys.call()` stack, supply a larger
#' negative number to `which_offset`. The default of 0 gets the immediate
#' caller. `-1` would get the caller's caller, and so on.
#' @param which_offset The stack level to get the call from. Defaults to -1 (the
#' immediate caller).
#' @return An srcref object, or NULL if none is found.
#' @noRd
get_call_srcref <- function(which_offset = 0) {
# Go back one call to account for this function itself
call <- sys.call(which_offset - 1)
srcref <- attr(call, "srcref", exact = TRUE)
srcref
}
append_otel_srcref_attrs <- function(attrs, call_srcref) {
if (is.null(call_srcref)) {
return(attrs)
}
srcref_attrs <- otel_srcref_attributes(call_srcref)
if (is.null(srcref_attrs)) {
return(attrs)
}
attrs[names(srcref_attrs)] <- srcref_attrs
attrs
}

60
R/otel-collect.R Normal file
View File

@@ -0,0 +1,60 @@
otel_collect_choices <- c(
"none",
"session",
"reactive_update",
"reactivity",
"all"
)
# Check if the collect level is sufficient
otel_collect_is_enabled <- function(
impl_level,
# Listen to option and fall back to the env var
opt_collect_level = getOption("shiny.otel.collect", Sys.getenv("SHINY_OTEL_COLLECT", "all"))
) {
opt_collect_level <- as_otel_collect(opt_collect_level)
which(opt_collect_level == otel_collect_choices) >=
which(impl_level == otel_collect_choices)
}
# Check if tracing is enabled and if the collect level is sufficient
has_otel_collect <- function(collect) {
# Only check pkg author input iff loaded with pkgload
if (IS_SHINY_LOCAL_PKG) {
stopifnot(length(collect) == 1, any(collect == otel_collect_choices))
}
otel_is_tracing_enabled() && otel_collect_is_enabled(collect)
}
# Run expr with otel collection disabled
with_no_otel_collect <- function(expr) {
withr::with_options(
list(
shiny.otel.collect = "none"
),
expr
)
}
## -- Helpers -----------------------------------------------------
# shiny.otel.collect can be:
# "none"; To do nothing / fully opt-out
# "session" for session/start events
# "reactive_update" (includes "session" features) and reactive_update spans
# "reactivity" (includes "reactive_update" features) and spans for all reactive things
# "all" - Anything that Shiny can do. (Currently equivalent to the "reactivity" level)
as_otel_collect <- function(collect = "all") {
if (!is.character(collect)) {
stop("`collect` must be a character vector.")
}
# Match to collect enum
collect <- match.arg(collect, otel_collect_choices, several.ok = FALSE)
return(collect)
}

194
R/otel-enable.R Normal file
View File

@@ -0,0 +1,194 @@
# # Approach
# Use flags on the reactive object to indicate whether to record OpenTelemetry spans.
#
# Cadence:
# * `$.isRecordingOtel` - Whether to record OpenTelemetry spans for this reactive object
# * `$.otelLabel` - The label to use for the OpenTelemetry span
# * `$.otelAttrs` - Additional attributes to add to the OpenTelemetry span
#' Add OpenTelemetry for reactivity to an object
#'
#' @description
#'
#' `enable_otel_*()` methods add OpenTelemetry flags for [reactive()] expressions
#' and `render*` functions (like [renderText()], [renderTable()], ...).
#'
#' Wrapper to creating an active reactive OpenTelemetry span that closes when
#' the reactive expression is done computing. Typically this is when the
#' reactive expression finishes (synchronous) or when the returned promise is
#' done computing (asynchronous).
#' @section Async with OpenTelemetry:
#'
#' With a reactive expression, the key and/or value expression can be
#' _asynchronous_. In other words, they can be promises --- not regular R
#' promises, but rather objects provided by the
#' \href{https://rstudio.github.io/promises/}{\pkg{promises}} package, which
#' are similar to promises in JavaScript. (See [promises::promise()] for more
#' information.) You can also use [mirai::mirai()] or [future::future()]
#' objects to run code in a separate process or even on a remote machine.
#'
#' When reactive expressions are being calculated in parallel (by having
#' another reactive promise compute in the main process), the currently active
#' OpenTelemetry span will be dynamically swapped out according to the
#' currently active reactive expression. This means that as long as a promise
#' was `then()`ed or `catch()`ed with an active OpenTelemetry span, the span
#' will be correctly propagated to the next step (and subsequently other
#' steps) in the promise chain.
#'
#' While the common case is for a reactive expression to be created
#' synchronously, troubles arise when the reactive expression is created
#' asynchronously. The span **must** be created before the reactive expression
#' is executed, it **must** be active for the duration of the expression, and
#' it **must** not be closed until the reactive expression is done executing.
#' This is not easily achieved with a single function call, so we provide a
#' way to create a reactive expression that is bound to an OpenTelemetry
#' span.
#'
#' @section Span management and performance:
#'
#' Dev note - Barret 2025-10:
#' Typically, an OpenTelemetry span (`otel_span`) will inherit from the parent
#' span. This works well and we can think of the hierarchy as a tree. With
#' `options("shiny.otel.collect" = <value>)`, we are able to control with a sliding
#' dial how much of the tree we are interested in: "none", "session",
#' "reactive_update", "reactivity", and finally "all".
#'
#' Leveraging this hierarchy, we can avoid creating spans that are not needed.
#' The act of making a noop span takes on the order of 10microsec. Handling of
#' the opspan is also in the 10s of microsecond range. We should avoid this when
#' we **know** that we're not interested in the span. Therefore, manually
#' handling spans should be considered for Shiny.
#'
#' * Q:
#' * But what about app author who want the current span? Is there any
#' guarantee that the current span is expected `reactive()` span?
#' * A:
#' * No. The current span is whatever the current span is. If the app author
#' wants a specific span, they should create it themselves.
#' * Proof:
#' ```r
#' noop <- otel::get_active_span()
#' noop$get_context()$get_span_id()
#' #> [1] "0000000000000000"
#' ignore <- otelsdk::with_otel_record({
#' a <- otel::start_local_active_span("a")
#' a$get_context()$get_span_id() |> str()
#' otel::with_active_span(noop, {
#' otel::get_active_span()$get_context()$get_span_id() |> str()
#' })
#' })
#' #> chr "2645e95715841e75"
#' #> chr "2645e95715841e75"
#' # ## It is reasonable to expect the second id to be `0000000000000000`, but it's not.
#' ```
#' Therefore, the app author has no guarantee that the current span is the
#' span they're expecting. If the app author wants a specific span, they should
#' create it themselves and let natural inheritance take over.
#'
#' Given this, I will imagine that app authors will set
#' `options("shiny.otel.collect" = "reactive_update")` as their default behavior.
#' Enough to know things are happening, but not overwhelming from **everything**
#' that is reactive.
#'
#' To _light up_ a specific area, users can call `withr::with_options(list("shiny.otel.collect" = "all"), { ... })`.
#'
#' @param x The object to add caching to.
#' @param ... Future parameter expansion.
#' @noRd
NULL
enable_otel_reactive_val <- function(x) {
impl <- attr(x, ".impl", exact = TRUE)
# Set flag for otel logging when setting the value
impl$.isRecordingOtel <- TRUE
class(x) <- c("reactiveVal.otel", class(x))
x
}
enable_otel_reactive_values <- function(x) {
impl <- .subset2(x, "impl")
# Set flag for otel logging when setting values
impl$.isRecordingOtel <- TRUE
class(x) <- c("reactivevalues.otel", class(x))
x
}
enable_otel_reactive_expr <- function(x) {
domain <- reactive_get_domain(x)
impl <- attr(x, "observable", exact = TRUE)
impl$.isRecordingOtel <- TRUE
# Covers both reactive and reactive.event
impl$.otelLabel <- otel_span_label_reactive(x, domain = impl$.domain)
class(x) <- c("reactiveExpr.otel", class(x))
x
}
enable_otel_observe <- function(x) {
x$.isRecordingOtel <- TRUE
x$.otelLabel <- otel_span_label_observer(x, domain = x$.domain)
class(x) <- c("Observer.otel", class(x))
invisible(x)
}
enable_otel_shiny_render_function <- function(x) {
valueFunc <- force(x)
otel_span_label <- NULL
otel_span_attrs <- NULL
renderFunc <- function(...) {
# Dynamically determine the span label given the current reactive domain
if (is.null(otel_span_label)) {
domain <- getDefaultReactiveDomain()
otel_span_label <<-
otel_span_label_render_function(x, domain = domain)
otel_span_attrs <<- c(
attr(x, "otelAttrs"),
otel_session_id_attrs(domain)
)
}
with_otel_span(
otel_span_label,
{
hybrid_then(
valueFunc(...),
on_failure = set_otel_exception_status_and_throw,
# Must save the error object
tee = FALSE
)
},
attributes = otel_span_attrs
)
}
renderFunc <- addAttributes(renderFunc, renderFunctionAttributes(valueFunc))
class(renderFunc) <- c("shiny.render.function.otel", class(valueFunc))
renderFunc
}
# ## If we ever expose a S3 function, I'd like to add this method.
# bindOtel.function <- function(x, ...) {
# cli::cli_abort(paste0(
# "Don't know how to add OpenTelemetry recording to a plain function. ",
# "If this is a {.code render*()} function for Shiny, it may need to be updated. ",
# "Please see {.help shiny::bindOtel} for more information."
# ))
# }

56
R/otel-error.R Normal file
View File

@@ -0,0 +1,56 @@
has_seen_otel_exception <- function(cnd) {
!is.null(cnd$.shiny_otel_exception)
}
mark_otel_exception_as_seen <- function(cnd) {
cnd$.shiny_otel_exception <- TRUE
cnd
}
set_otel_exception_status_and_throw <- function(cnd) {
cnd <- set_otel_exception_status(cnd)
# Rethrow the (possibly updated) error
signalCondition(cnd)
}
set_otel_exception_status <- function(cnd) {
if (inherits(cnd, "shiny.custom.error")) {
# No-op
} else if (inherits(cnd, "shiny.output.cancel")) {
# No-op
} else if (inherits(cnd, "shiny.output.progress")) {
# No-op
} else if (cnd_inherits(cnd, "shiny.silent.error")) {
# No-op
} else {
# Only when an unknown error occurs do we set the span status to error
span <- otel::get_active_span()
# Only record the exception once at the original point of failure,
# not every reactive expression that it passes through
if (!has_seen_otel_exception(cnd)) {
span$record_exception(
# Record a sanitized error if sanitization is enabled
get_otel_error_obj(cnd)
)
cnd <- mark_otel_exception_as_seen(cnd)
}
# Record the error status on the span for any context touching this error
span$set_status("error")
}
cnd
}
get_otel_error_obj <- function(e) {
# Do not expose errors to otel if sanitization is enabled
if (getOption("shiny.otel.sanitize.errors", TRUE)) {
sanitized_error()
} else {
e
}
}

198
R/otel-label.R Normal file
View File

@@ -0,0 +1,198 @@
# observe mymod:<anonymous>
# observe <anonymous>
# observe mylabel
# -- Reactives --------------------------------------------------------------
#' OpenTelemetry Label Generation Functions
#'
#' Functions for generating formatted labels for OpenTelemetry tracing spans
#' in Shiny applications. These functions handle module namespacing and
#' cache/event modifiers for different Shiny reactive constructs.
#'
#' @param x The object to generate a label for (reactive, observer, etc.)
#' @param label Character string label for reactive values
#' @param key Character string key for reactiveValues operations
#' @param ... Additional arguments (unused)
#' @param domain Shiny domain object containing namespace information
#'
#' @return Character string formatted for OpenTelemetry span labels
#' @name otel_label
#' @noRd
NULL
otel_span_label_reactive <- function(x, ..., domain) {
fn_name <- otel_label_with_modifiers(
x,
"reactive",
cache_class = "reactive.cache",
event_class = "reactive.event"
)
label <- attr(x, "observable", exact = TRUE)[[".label"]]
otel_span_label <- otel_label_upgrade(label, domain = domain)
sprintf("%s %s", fn_name, otel_span_label)
}
otel_span_label_render_function <- function(x, ..., domain) {
fn_name <- otel_label_with_modifiers(
x,
"output",
cache_class = "shiny.render.function.cache",
event_class = "shiny.render.function.event"
)
label <- getCurrentOutputInfo(session = domain)$name %||% "<unknown>"
otel_span_label <- otel_label_upgrade(label, domain = domain)
sprintf("%s %s", fn_name, otel_span_label)
}
otel_span_label_observer <- function(x, ..., domain) {
fn_name <- otel_label_with_modifiers(
x,
"observe",
cache_class = NULL, # Do not match a cache class here
event_class = "Observer.event"
)
otel_span_label <- otel_label_upgrade(x$.label, domain = domain)
sprintf("%s %s", fn_name, otel_span_label)
}
# -- Set reactive value(s) ----------------------------------------------------
otel_log_label_set_reactive_val <- function(label, ..., domain) {
sprintf(
"Set reactiveVal %s",
otel_label_upgrade(label, domain = domain)
)
}
otel_log_label_set_reactive_values <- function(label, key, ..., domain) {
sprintf(
"Set reactiveValues %s$%s",
otel_label_upgrade(label, domain = domain),
key
)
}
# -- ExtendedTask -------------------------------------------------------------
otel_span_label_extended_task <- function(label, suffix = NULL, ..., domain) {
sprintf(
"ExtendedTask %s",
otel_label_upgrade(label, domain = domain)
)
}
otel_log_label_extended_task_add_to_queue <- function(label, ..., domain) {
sprintf(
"ExtendedTask %s add to queue",
otel_label_upgrade(label, domain = domain)
)
}
# -- Debounce / Throttle -------------------------------------------------------
otel_label_debounce <- function(label, ..., domain) {
sprintf(
"debounce %s",
otel_label_upgrade(label, domain = domain)
)
}
otel_label_throttle <- function(label, ..., domain) {
sprintf(
"throttle %s",
otel_label_upgrade(label, domain = domain)
)
}
# ---- Reactive Poll / File Reader -----------------------------------------------
otel_label_reactive_poll <- function(label, ..., domain) {
sprintf(
"reactivePoll %s",
otel_label_upgrade(label, domain = domain)
)
}
otel_label_reactive_file_reader <- function(label, ..., domain) {
sprintf(
"reactiveFileReader %s",
otel_label_upgrade(label, domain = domain)
)
}
# -- Helpers --------------------------------------------------------------
#' Modify function name based on object class modifiers
#'
#' @param x Object to check class of
#' @param fn_name Base function name
#' @param cache_class Optional class name that indicates cache operation
#' @param event_class Optional class name that indicates event operation
#'
#' @return Modified function name with "cache" or "event" suffix if applicable
#' @noRd
otel_label_with_modifiers <- function(
x,
fn_name,
cache_class = NULL,
event_class = NULL
) {
for (x_class in rev(class(x))) {
if (!is.null(cache_class) && x_class == cache_class) {
fn_name <- sprintf("%s cache", fn_name)
} else if (!is.null(event_class) && x_class == event_class) {
fn_name <- sprintf("%s event", fn_name)
}
}
fn_name
}
#' Upgrade and format OpenTelemetry labels with module namespacing
#'
#' Processes labels for OpenTelemetry tracing, replacing default verbose labels
#' with cleaner alternatives and prepending module namespaces when available.
#'
#' @param label Character string label to upgrade
#' @param ... Additional arguments (unused)
#' @param domain Shiny domain object containing namespace information
#'
#' @return Modified label string with module prefix if applicable
#' @noRd
#'
#' @details
#' Module prefix examples:
#' - "" -> ""
#' - "my-nested-mod-" -> "my-nested-mod"
otel_label_upgrade <- function(label, ..., domain) {
# By default, `observe()` sets the label to `observe(CODE)`
# This label is too big and inconsistent.
# Replace it with `<anonymous>`
# (Similar with `eventReactive()` and `observeEvent()`)
if (is_default_label(label) && grepl("(", label, fixed = TRUE)) {
label <- "<anonymous>"
# label <- sprintf("<anonymous> - %s", label)
}
if (is.null(domain)) {
return(label)
}
namespace <- domain$ns("")
if (!nzchar(namespace)) {
return(label)
}
# Remove trailing module separator
mod_ns <- sub(sprintf("%s$", ns.sep), "", namespace)
# Prepend the module name to the label
# Ex: `"mymod:x"`
sprintf("%s:%s", mod_ns, label)
}

114
R/otel-reactive-update.R Normal file
View File

@@ -0,0 +1,114 @@
# * `session$userData[["_otel_span_reactive_update"]]` - The active reactive update span (or `NULL`)
#' Start a `reactive_update` OpenTelemetry span and store it
#'
#' Used when a reactive expression is updated
#' Will only start the span iff the otel tracing is enabled
#' @param ... Ignored
#' @param domain The reactive domain to associate with the span
#' @return Invisibly returns.
#' @seealso `otel_span_reactive_update_teardown()`
#' @noRd
otel_span_reactive_update_init <- function(..., domain) {
if (!has_otel_collect("reactive_update")) return()
# Ensure cleanup is registered only once per session
if (is.null(domain$userData[["_otel_has_reactive_cleanup"]])) {
domain$userData[["_otel_has_reactive_cleanup"]] <- TRUE
# Clean up any dangling reactive spans on an unplanned exit
domain$onSessionEnded(function() {
otel_span_reactive_update_teardown(domain = domain)
})
}
# Safety check
if (is_otel_span(domain$userData[["_otel_span_reactive_update"]])) {
stop("Reactive update span already exists")
}
domain$userData[["_otel_span_reactive_update"]] <-
start_otel_span(
"reactive_update",
...,
attributes = otel_session_id_attrs(domain)
)
invisible()
}
#' End a `reactive_update` OpenTelemetry span and remove it from the session
#' @param ... Ignored
#' @param domain The reactive domain to associate with the span
#' @return Invisibly returns.
#' @seealso `otel_span_reactive_update_init()`
#' @noRd
otel_span_reactive_update_teardown <- function(..., domain) {
ospan <- domain$userData[["_otel_span_reactive_update"]]
if (is_otel_span(ospan)) {
otel::end_span(ospan)
domain$userData[["_otel_span_reactive_update"]] <- NULL
}
invisible()
}
#' Run expr within a `reactive_update` OpenTelemetry span
#'
#' Used to wrap the execution of a reactive expression. Will only
#' require/activate the span iff the otel tracing is enabled
#' @param expr The expression to executed within the span
#' @param ... Ignored
#' @param domain The reactive domain to associate with the span
#' @noRd
with_otel_span_reactive_update <- function(expr, ..., domain) {
ospan <- domain$userData[["_otel_span_reactive_update"]]
if (!is_otel_span(ospan)) {
return(force(expr))
}
# Given the reactive update span is started before and ended when exec count
# is 0, we only need to wrap the expr in the span context
otel::with_active_span(ospan, {force(expr)})
}
#' Run expr within `reactive_update` otel span if not already active
#'
#' If the reactive update otel span is not already active, run the expression
#' within the reactive update otel span context. This ensures that nested calls
#' to reactive expressions do not attempt to re-enter the same span.
#'
#' This method is used within Context `run()` and running an Output's observer
#' implementation
#' @param expr The expression to executed within the span
#' @param ... Ignored
#' @param domain The reactive domain to associate with the span
#' @noRd
maybe_with_otel_span_reactive_update <- function(expr, ..., domain) {
if (is.null(domain$userData[["_otel_reactive_update_is_active"]])) {
domain$userData[["_otel_reactive_update_is_active"]] <- TRUE
# When the expression is done promising, clear the active flag
hybrid_then(
{
with_otel_span_reactive_update(domain = domain, expr)
},
on_success = function(value) {
domain$userData[["_otel_reactive_update_is_active"]] <- NULL
},
on_failure = function(e) {
domain$userData[["_otel_reactive_update_is_active"]] <- NULL
},
# Return the value before the callbacks
tee = TRUE
)
} else {
expr
}
}

96
R/otel-session.R Normal file
View File

@@ -0,0 +1,96 @@
# Semantic conventions for session: https://opentelemetry.io/docs/specs/semconv/general/session/
#' Create and use session span and events
#'
#' If otel is disabled, the session span and events will not be created,
#' however the expression will still be evaluated.
#'
#' Span: `session_start`, `session_end`
#' @param expr Expression to evaluate within the session span
#' @param ... Ignored
#' @param domain The reactive domain
#' @noRd
otel_span_session_start <- function(expr, ..., domain) {
if (!has_otel_collect("session")) {
return(force(expr))
}
# Wrap the server initialization
with_otel_span(
"session_start",
expr,
attributes = otel::as_attributes(c(
otel_session_id_attrs(domain),
otel_session_attrs(domain)
))
)
}
otel_span_session_end <- function(expr, ..., domain) {
if (!has_otel_collect("session")) {
return(force(expr))
}
id_attrs <- otel_session_id_attrs(domain)
with_otel_span(
"session_end",
expr,
attributes = id_attrs
)
}
# -- Helpers -------------------------------
# Occurs when the websocket connection is established
otel_session_attrs <- function(domain) {
# TODO: Future: Posit Connect integration
# > we are still trying to identify all of the information we want to track/expose
#
# * `POSIT_PRODUCT` (Fallback to RSTUDIO_PRODUCT) for host environment
# * `CONNECT_SERVER` envvar to get the `session.address`.
# * `CONNECT_CONTENT_GUID` for the consistent app distinguisher
# * Maybe `CONNECT_CONTENT_JOB_KEY`?
# * Maybe `user.id` to be their user name: https://opentelemetry.io/docs/specs/semconv/registry/attributes/user/
attrs <- list(
server.path =
sub(
"/websocket/$", "/",
domain[["request"]][["PATH_INFO"]] %||% ""
),
server.address = domain[["request"]][["HTTP_HOST"]] %||% "",
server.origin = domain[["request"]][["HTTP_ORIGIN"]] %||% "",
## Currently, Shiny does not expose QUERY_STRING when connecting the websocket
# so we do not provide it here.
# QUERY_STRING = domain[["request"]][["QUERY_STRING"]] %||% "",
server.port = domain[["request"]][["SERVER_PORT"]] %||% NA_integer_
)
# Safely convert SERVER_PORT to integer
# If conversion fails, leave as-is (string or empty)
# This avoids warnings/errors if SERVER_PORT is not a valid integer
server_port <- suppressWarnings(as.integer(attrs$server.port))
if (!is.na(server_port)) {
attrs$server.port <- server_port
}
attrs
}
otel_session_id_attrs <- function(domain) {
token <- domain$token
if (is.null(token)) {
return(list())
}
list(
# Convention for client-side with session.start and session.end events
# https://opentelemetry.io/docs/specs/semconv/general/session/
#
# Since we are the server, we'll add them as an attribute to _every_ span
# within the session as we don't know exactly when they will be called.
# Given it's only a single attribute, the cost should be minimal, but it ties every reactive calculation together.
session.id = token
)
}

127
R/otel-shiny.R Normal file
View File

@@ -0,0 +1,127 @@
# Used by otel to identify the tracer and logger for this package
# https://github.com/r-lib/otel/blob/afc31bc1f4bd177870d44b051ada1d9e4e685346/R/tracer-name.R#L33-L49
# DO NOT CHANGE THIS VALUE without understanding the implications for existing telemetry data!
otel_tracer_name <- "co.posit.r-package.shiny"
init_otel <- function() {
.globals$otel_tracer <- otel::get_tracer()
.globals$otel_is_tracing_enabled <- otel::is_tracing_enabled(.globals$otel_tracer)
.globals$otel_logger <- otel::get_logger()
# .globals$otel_is_logging_enabled <- otel::is_logging_enabled()
}
on_load({init_otel()})
#' Run expr within a Shiny OpenTelemetry recording context
#'
#' Reset the OpenTelemetry tracer and logger for Shiny.
#' Used for testing purposes only.
#' @param expr Expression to evaluate within the recording context
#' @return The result of evaluating `otelsdk::with_otel_record(expr)` with freshly enabled Shiny otel tracer and logger
#' @noRd
with_shiny_otel_record <- function(expr) {
# Only use within internal testthat tests
stopifnot(testthat__is_testing())
withr::defer({ init_otel() })
otelsdk::with_otel_record({
init_otel()
force(expr)
})
}
#' Check if OpenTelemetry tracing is enabled
#'
#' @param tracer The OpenTelemetry tracer to check (default: Shiny otel tracer)
#' @return `TRUE` if tracing is enabled, `FALSE` otherwise
#' @noRd
otel_is_tracing_enabled <- function() {
.globals[["otel_is_tracing_enabled"]]
}
#' Shiny OpenTelemetry logger
#'
#' Used for logging OpenTelemetry events via `otel_log()`
#' @return An OpenTelemetry logger
#' @noRd
shiny_otel_logger <- function() {
.globals[["otel_logger"]]
}
#' Shiny OpenTelemetry tracer
#'
#' Used for creating OpenTelemetry spans via `with_otel_span()` and
#' `start_otel_span()`
#'
#' Inspired by httr2:::get_tracer().
#' @return An OpenTelemetry tracer
#' @noRd
shiny_otel_tracer <- function() {
.globals[["otel_tracer"]]
}
#' Create and use a Shiny OpenTelemetry span
#'
#' If otel is disabled, the span will not be created,
#' however the expression will still be evaluated.
#' @param name Span name
#' @param expr Expression to evaluate within the span
#' @param ... Ignored
#' @param attributes Optional span attributes
#' @return The result of evaluating `expr`
#' @noRd
with_otel_span <- function(name, expr, ..., attributes = NULL) {
promises::with_otel_span(name, expr, ..., attributes = attributes, tracer = shiny_otel_tracer())
}
#' Start a Shiny OpenTelemetry span
#'
#' @param name Span name
#' @param ... Additional arguments passed to `otel::start_span()`
#' @return An OpenTelemetry span
#' @noRd
start_otel_span <- function(name, ...) {
otel::start_span(name, ..., tracer = shiny_otel_tracer())
}
# # TODO: Set attributes on the current active span
# # 5. Set attributes on the current active span
# set_otel_span_attrs(status = 200L)
# -- Helpers --------------------------------------------------------------
is_otel_span <- function(x) {
inherits(x, "otel_span")
}
testthat__is_testing <- function() {
# testthat::is_testing()
identical(Sys.getenv("TESTTHAT"), "true")
}
#' Log a message using the Shiny OpenTelemetry logger
#'
#' @param msg The log message
#' @param ... Additional attributes to add to the log record
#' @param severity The log severity level (default: "info")
#' @param logger The OpenTelemetry logger to use (default: Shiny otel logger)
#' @return Invisibly returns.
#' @noRd
otel_log <- function(
msg,
...,
severity = "info",
logger = shiny_otel_logger()
) {
otel::log(msg, ..., severity = severity, logger = logger)
}

View File

@@ -16,6 +16,60 @@ processId <- local({
}
})
ctx_otel_info_obj <- function(
isRecordingOtel = FALSE,
otelLabel = "<unknown>",
otelAttrs = list()
) {
structure(
list(
isRecordingOtel = isRecordingOtel,
otelLabel = otelLabel,
otelAttrs = otelAttrs
),
class = "ctx_otel_info"
)
}
with_otel_span_context <- function(otel_info, expr, domain) {
if (!otel_is_tracing_enabled()) {
return(force(expr))
}
isRecordingOtel <- .subset2(otel_info, "isRecordingOtel")
otelLabel <- .subset2(otel_info, "otelLabel")
otelAttrs <- .subset2(otel_info, "otelAttrs")
# Always set the reactive update span as active
# This ensures that any spans created within the reactive context
# are at least children of the reactive update span
maybe_with_otel_span_reactive_update(domain = domain, {
if (isRecordingOtel) {
with_otel_span(
otelLabel,
{
# Works with both sync and async expressions
# Needed for both observer and reactive contexts
hybrid_then(
expr,
on_failure = set_otel_exception_status_and_throw,
# Must upgrade the error object
tee = FALSE
)
},
# expr,
attributes = otelAttrs
)
} else {
force(expr)
}
})
}
#' @include graph.R
Context <- R6Class(
'Context',
@@ -33,11 +87,14 @@ Context <- R6Class(
.pid = NULL,
.weak = NULL,
.otel_info = NULL,
initialize = function(
domain, label='', type='other', prevId='',
reactId = rLog$noReactId,
id = .getReactiveEnvironment()$nextId(), # For dummy context
weak = FALSE
weak = FALSE,
otel_info = ctx_otel_info_obj()
) {
id <<- id
.label <<- label
@@ -47,17 +104,26 @@ Context <- R6Class(
.reactType <<- type
.weak <<- weak
rLog$createContext(id, label, type, prevId, domain)
if (!is.null(otel_info)) {
if (IS_SHINY_LOCAL_PKG) {
stopifnot(inherits(otel_info, "ctx_otel_info"))
}
.otel_info <<- otel_info
}
},
run = function(func) {
"Run the provided function under this context."
# Use `promises::` as it shows up in the stack trace
promises::with_promise_domain(reactivePromiseDomain(), {
withReactiveDomain(.domain, {
captureStackTraces({
env <- .getReactiveEnvironment()
rLog$enter(.reactId, id, .reactType, .domain)
on.exit(rLog$exit(.reactId, id, .reactType, .domain), add = TRUE)
env$runWith(self, func)
with_otel_span_context(.otel_info, domain = .domain, {
captureStackTraces({
env <- .getReactiveEnvironment()
rLog$enter(.reactId, id, .reactType, .domain)
on.exit(rLog$exit(.reactId, id, .reactType, .domain), add = TRUE)
env$runWith(self, func)
})
})
})
})
@@ -231,7 +297,7 @@ wrapForContext <- function(func, ctx) {
}
reactivePromiseDomain <- function() {
promises::new_promise_domain(
new_promise_domain(
wrapOnFulfilled = function(onFulfilled) {
force(onFulfilled)

View File

@@ -45,6 +45,8 @@ createMockDomain <- function() {
callbacks <- Callbacks$new()
ended <- FALSE
domain <- new.env(parent = emptyenv())
domain$ns <- function(id) id
domain$token <- "mock-domain"
domain$onEnded <- function(callback) {
return(callbacks$register(callback))
}
@@ -95,7 +97,11 @@ getDefaultReactiveDomain <- function() {
#' @rdname domains
#' @export
withReactiveDomain <- function(domain, expr) {
promises::with_promise_domain(createVarPromiseDomain(.globals, "domain", domain), expr)
# Use `promises::` as it shows up in the stack trace
promises::with_promise_domain(
createVarPromiseDomain(.globals, "domain", domain),
expr
)
}
#

View File

@@ -79,19 +79,26 @@ ReactiveVal <- R6Class(
dependents = NULL
),
public = list(
.isRecordingOtel = FALSE, # Needs to be set by Shiny
.otelLabel = NULL, # Needs to be set by Shiny
.otelAttrs = NULL, # Needs to be set by Shiny
initialize = function(value, label = NULL) {
reactId <- nextGlobalReactId()
private$reactId <- reactId
private$value <- value
private$label <- label
private$dependents <- Dependents$new(reactId = private$reactId)
rLog$define(private$reactId, value, private$label, type = "reactiveVal", getDefaultReactiveDomain())
domain <- getDefaultReactiveDomain()
rLog$define(private$reactId, value, private$label, type = "reactiveVal", domain)
.otelLabel <<- otel_log_label_set_reactive_val(private$label, domain = domain)
},
get = function() {
private$dependents$register()
if (private$frozen)
reactiveStop()
reactiveStop()
private$value
},
@@ -99,7 +106,16 @@ ReactiveVal <- R6Class(
if (identical(private$value, value)) {
return(invisible(FALSE))
}
rLog$valueChange(private$reactId, value, getDefaultReactiveDomain())
domain <- getDefaultReactiveDomain()
if ((!is.null(domain)) && .isRecordingOtel) {
otel_log(
.otelLabel,
severity = "info",
attributes = c(private$.otelAttrs, otel_session_id_attrs(domain))
)
}
rLog$valueChange(private$reactId, value, domain)
private$value <- value
private$dependents$invalidate()
invisible(TRUE)
@@ -205,13 +221,20 @@ ReactiveVal <- R6Class(
#'
#' @export
reactiveVal <- function(value = NULL, label = NULL) {
call_srcref <- get_call_srcref()
if (missing(label)) {
call <- sys.call()
label <- rvalSrcrefToLabel(attr(call, "srcref", exact = TRUE))
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = paste0("reactiveVal", createUniqueId(4))
)
}
rv <- ReactiveVal$new(value, label)
structure(
if (!is.null(call_srcref)) {
rv$.otelAttrs <- otel_srcref_attributes(call_srcref)
}
ret <- structure(
function(x) {
if (missing(x)) {
rv$get()
@@ -224,6 +247,12 @@ reactiveVal <- function(value = NULL, label = NULL) {
label = label,
.impl = rv
)
if (has_otel_collect("reactivity")) {
ret <- enable_otel_reactive_val(ret)
}
ret
}
#' @rdname freezeReactiveValue
@@ -262,8 +291,11 @@ format.reactiveVal <- function(x, ...) {
# assigned to (e.g. for `a <- reactiveVal()`, the result should be "a"). This
# is a fragile, error-prone operation, so we default to a random label if
# necessary.
rvalSrcrefToLabel <- function(srcref,
defaultLabel = paste0("reactiveVal", createUniqueId(4))) {
rassignSrcrefToLabel <- function(
srcref,
defaultLabel,
fnName = "([a-zA-Z0-9_.]+)"
) {
if (is.null(srcref))
return(defaultLabel)
@@ -287,7 +319,11 @@ rvalSrcrefToLabel <- function(srcref,
firstLine <- substring(lines[srcref[1]], srcref[2] - 1)
m <- regexec("\\s*([^[:space:]]+)\\s*(<-|=)\\s*reactiveVal\\b", firstLine)
m <- regexec(
# Require the first assignment within the line
paste0("^\\s*([^[:space:]]+)\\s*(<<-|<-|=)\\s*", fnName, "\\b"),
firstLine
)
if (m[[1]][1] == -1) {
return(defaultLabel)
}
@@ -330,6 +366,9 @@ ReactiveValues <- R6Class(
# object, but it does not preserve order.
.nameOrder = character(0),
.isRecordingOtel = FALSE, # Needs to be set by Shiny
.otelAttrs = NULL, # Needs to be set by Shiny
initialize = function(
dedupe = TRUE,
@@ -406,6 +445,21 @@ ReactiveValues <- R6Class(
return(invisible())
}
if ((!is.null(domain)) && .isRecordingOtel) {
if (
# Any reactiveValues (other than input or clientData) are fair game
!(.label == "input" || .label == "clientData") ||
# Do not include updates to input or clientData unless _some_ reactivity has occured
!is.null(domain$userData[["_otel_has_reactive_cleanup"]])
) {
otel_log(
otel_log_label_set_reactive_values(.label, key, domain = domain),
severity = "info",
attributes = c(.otelAttrs, otel_session_id_attrs(domain))
)
}
}
# If it's new, append key to the name order
if (!key_exists) {
.nameOrder[length(.nameOrder) + 1] <<- key
@@ -579,10 +633,28 @@ reactiveValues <- function(...) {
if ((length(args) > 0) && (is.null(names(args)) || any(names(args) == "")))
rlang::abort("All arguments passed to reactiveValues() must be named.")
values <- .createReactiveValues(ReactiveValues$new())
values <- .createReactiveValues(ReactiveValues$new(), withOtel = FALSE)
# Use .subset2() instead of [[, to avoid method dispatch
.subset2(values, 'impl')$mset(args)
impl <- .subset2(values, 'impl')
call_srcref <- get_call_srcref()
if (!is.null(call_srcref)) {
impl$.label <- rassignSrcrefToLabel(
call_srcref,
# Pass through the random default label created in ReactiveValues$new()
defaultLabel = impl$.label
)
impl$.otelAttrs <- otel_srcref_attributes(call_srcref)
}
impl$mset(args)
# Add otel collection after `$mset()` so that we don't log the initial values
# Add otel collection after `.label` so that any logging uses the correct label
values <- maybeAddReactiveValuesOtel(values)
values
}
@@ -597,10 +669,11 @@ checkName <- function(x) {
# @param values A ReactiveValues object
# @param readonly Should this object be read-only?
# @param ns A namespace function (either `identity` or `NS(namespace)`)
# @param withOtel Should otel collection be attempted?
.createReactiveValues <- function(values = NULL, readonly = FALSE,
ns = identity) {
ns = identity, withOtel = TRUE) {
structure(
ret <- structure(
list(
impl = values,
readonly = readonly,
@@ -608,6 +681,20 @@ checkName <- function(x) {
),
class='reactivevalues'
)
if (withOtel) {
ret <- maybeAddReactiveValuesOtel(ret)
}
ret
}
maybeAddReactiveValuesOtel <- function(x) {
if (!has_otel_collect("reactivity")) {
return(x)
}
enable_otel_reactive_values(x)
}
#' @export
@@ -831,6 +918,10 @@ Observable <- R6Class(
.mostRecentCtxId = character(0),
.ctx = 'Context',
.isRecordingOtel = FALSE, # Needs to be set by Shiny
.otelLabel = NULL, # Needs to be set by Shiny
.otelAttrs = NULL, # Needs to be set by Shiny
initialize = function(func, label = deparse(substitute(func)),
domain = getDefaultReactiveDomain(),
..stacktraceon = TRUE) {
@@ -885,9 +976,19 @@ Observable <- R6Class(
simpleExprToFunction(fn_body(.origFunc), "reactive")
},
.updateValue = function() {
ctx <- Context$new(.domain, .label, type = 'observable',
prevId = .mostRecentCtxId, reactId = .reactId,
weak = TRUE)
ctx <- Context$new(
.domain,
.label,
type = 'observable',
prevId = .mostRecentCtxId,
reactId = .reactId,
weak = TRUE,
otel_info = ctx_otel_info_obj(
isRecordingOtel = .isRecordingOtel,
otelLabel = .otelLabel,
otelAttrs = c(.otelAttrs, otel_session_id_attrs(.domain))
)
)
.mostRecentCtxId <<- ctx$id
# A Dependency object will have a weak reference to the context, which
@@ -920,6 +1021,15 @@ Observable <- R6Class(
},
error = function(cond) {
if (.isRecordingOtel) {
# `cond` is too early in the stack to be updated by `ctx`'s
# `with_otel_span_context()` where it calls
# `set_otel_exception_status_and_throw()` on eval error.
# So we mark it as seen here.
# When the error is re-thrown later, it won't be a _new_ error
cond <- mark_otel_exception_as_seen(cond)
}
# If an error occurs, we want to propagate the error, but we also
# want to save a copy of it, so future callers of this reactive will
# get the same error (i.e. the error is cached).
@@ -1017,12 +1127,24 @@ reactive <- function(
label <- exprToLabel(userExpr, "reactive", label)
o <- Observable$new(func, label, domain, ..stacktraceon = ..stacktraceon)
structure(
call_srcref <- get_call_srcref()
if (!is.null(call_srcref)) {
o$.otelAttrs <- otel_srcref_attributes(call_srcref)
}
ret <- structure(
o$getValue,
observable = o,
cacheHint = list(userExpr = zap_srcref(userExpr)),
class = c("reactiveExpr", "reactive", "function")
)
if (has_otel_collect("reactivity")) {
ret <- enable_otel_reactive_expr(ret)
}
ret
}
# Given the srcref to a reactive expression, attempts to figure out what the
@@ -1030,7 +1152,7 @@ reactive <- function(
# scans the line of code that started the reactive block and looks for something
# that looks like assignment. If we fail, fall back to a default value (likely
# the block of code in the body of the reactive).
rexprSrcrefToLabel <- function(srcref, defaultLabel) {
rexprSrcrefToLabel <- function(srcref, defaultLabel, fnName) {
if (is.null(srcref))
return(defaultLabel)
@@ -1053,7 +1175,8 @@ rexprSrcrefToLabel <- function(srcref, defaultLabel) {
firstLine <- substring(lines[srcref[1]], 1, srcref[2] - 1)
m <- regexec("(.*)(<-|=)\\s*reactive\\s*\\($", firstLine)
# Require the assignment to be parsed from the start
m <- regexec(paste0("^(.*)(<<-|<-|=)\\s*", fnName, "\\s*\\($"), firstLine)
if (m[[1]][1] == -1) {
return(defaultLabel)
}
@@ -1127,6 +1250,10 @@ Observer <- R6Class(
.prevId = character(0),
.ctx = NULL,
.isRecordingOtel = FALSE, # Needs to be set by Shiny
.otelLabel = NULL, # Needs to be set by Shiny
.otelAttrs = NULL, # Needs to be set by Shiny
initialize = function(observerFunc, label, suspended = FALSE, priority = 0,
domain = getDefaultReactiveDomain(),
autoDestroy = TRUE, ..stacktraceon = TRUE) {
@@ -1161,7 +1288,18 @@ Observer <- R6Class(
.createContext()$invalidate()
},
.createContext = function() {
ctx <- Context$new(.domain, .label, type='observer', prevId=.prevId, reactId = .reactId)
ctx <- Context$new(
.domain,
.label,
type = 'observer',
prevId = .prevId,
reactId = .reactId,
otel_info = ctx_otel_info_obj(
isRecordingOtel = .isRecordingOtel,
otelLabel = .otelLabel,
otelAttrs = c(.otelAttrs, otel_session_id_attrs(.domain))
)
)
.prevId <<- ctx$id
if (!is.null(.ctx)) {
@@ -1430,7 +1568,14 @@ observe <- function(
check_dots_empty()
func <- installExprFunction(x, "func", env, quoted)
label <- funcToLabel(func, "observe", label)
call_srcref <- get_call_srcref()
if (is.null(label)) {
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = funcToLabel(func, "observe", label)
)
}
o <- Observer$new(
func,
@@ -1441,6 +1586,14 @@ observe <- function(
autoDestroy = autoDestroy,
..stacktraceon = ..stacktraceon
)
if (!is.null(call_srcref)) {
o$.otelAttrs <- otel_srcref_attributes(call_srcref)
}
if (has_otel_collect("reactivity")) {
o <- enable_otel_observe(o)
}
invisible(o)
}
@@ -1828,34 +1981,64 @@ coerceToFunc <- function(x) {
#' }
#' @export
reactivePoll <- function(intervalMillis, session, checkFunc, valueFunc) {
reactive_poll_impl(
fnName = "reactivePoll",
intervalMillis = intervalMillis,
session = session,
checkFunc = checkFunc,
valueFunc = valueFunc
)
}
reactive_poll_impl <- function(
fnName,
intervalMillis,
session,
checkFunc,
valueFunc
) {
intervalMillis <- coerceToFunc(intervalMillis)
rv <- reactiveValues(cookie = isolate(checkFunc()))
fnName <- match.arg(fnName, c("reactivePoll", "reactiveFileReader"), several.ok = FALSE)
call_srcref <- get_call_srcref(-1)
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = "<anonymous>",
fnName = fnName
)
re_finalized <- FALSE
env <- environment()
o <- observe({
# When no one holds a reference to the reactive returned from
# reactivePoll, destroy and remove the observer so that it doesn't keep
# firing and hold onto resources.
if (re_finalized) {
o$destroy()
rm(o, envir = env)
return()
}
with_no_otel_collect({
cookie <- reactiveVal(
isolate(checkFunc()),
label = sprintf("%s %s cookie", fnName, label)
)
rv$cookie <- checkFunc()
invalidateLater(intervalMillis(), session)
o <- observe({
# When no one holds a reference to the reactive returned from
# reactivePoll, destroy and remove the observer so that it doesn't keep
# firing and hold onto resources.
if (re_finalized) {
o$destroy()
rm(o, envir = env)
return()
}
cookie(checkFunc())
invalidateLater(intervalMillis(), session)
}, label = sprintf("%s %s cleanup", fnName, label))
})
# TODO: what to use for a label?
re <- reactive({
rv$cookie
re <- reactive(label = sprintf("%s %s", fnName, label), {
# Take a dependency on the cookie, so that when it changes, this
# reactive expression is invalidated.
cookie()
valueFunc()
}, label = NULL)
})
reg.finalizer(attr(re, "observable"), function(e) {
re_finalized <<- TRUE
@@ -1865,6 +2048,16 @@ reactivePoll <- function(intervalMillis, session, checkFunc, valueFunc) {
# reference to `re` and thus prevent it from getting GC'd.
on.exit(rm(re))
local({
impl <- attr(re, "observable", exact = TRUE)
impl$.otelLabel <-
if (fnName == "reactivePoll")
otel_label_reactive_poll(label, domain = impl$.domain)
else if (fnName == "reactiveFileReader")
otel_label_reactive_file_reader(label, domain = impl$.domain)
impl$.otelAttrs <- append_otel_srcref_attrs(impl$.otelAttrs, call_srcref)
})
return(re)
}
@@ -1928,14 +2121,16 @@ reactiveFileReader <- function(intervalMillis, session, filePath, readFunc, ...)
filePath <- coerceToFunc(filePath)
extraArgs <- list2(...)
reactivePoll(
intervalMillis, session,
function() {
reactive_poll_impl(
fnName = "reactiveFileReader",
intervalMillis = intervalMillis,
session = session,
checkFunc = function() {
path <- filePath()
info <- file.info(path)
return(paste(path, info$mtime, info$size))
},
function() {
valueFunc = function() {
do.call(readFunc, c(filePath(), extraArgs))
}
)
@@ -2017,6 +2212,8 @@ isolate <- function(expr) {
} else {
reactId <- rLog$noReactId
}
# Do not track otel spans for `isolate()`
ctx <- Context$new(getDefaultReactiveDomain(), '[isolate]', type='isolate', reactId = reactId)
on.exit(ctx$invalidate())
# Matching ..stacktraceon../..stacktraceoff.. pair
@@ -2295,26 +2492,41 @@ observeEvent <- function(eventExpr, handlerExpr,
eventQ <- exprToQuo(eventExpr, event.env, event.quoted)
handlerQ <- exprToQuo(handlerExpr, handler.env, handler.quoted)
label <- quoToLabel(eventQ, "observeEvent", label)
call_srcref <- get_call_srcref()
if (is.null(label)) {
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = quoToLabel(eventQ, "observeEvent", label)
)
}
handler <- inject(observe(
!!handlerQ,
label = label,
suspended = suspended,
priority = priority,
domain = domain,
autoDestroy = TRUE,
..stacktraceon = TRUE
))
with_no_otel_collect({
handler <- inject(observe(
!!handlerQ,
label = label,
suspended = suspended,
priority = priority,
domain = domain,
autoDestroy = TRUE,
..stacktraceon = TRUE
))
o <- inject(bindEvent(
ignoreNULL = ignoreNULL,
ignoreInit = ignoreInit,
once = once,
label = label,
!!eventQ,
x = handler
))
o <- inject(bindEvent(
ignoreNULL = ignoreNULL,
ignoreInit = ignoreInit,
once = once,
label = label,
!!eventQ,
x = handler
))
})
if (!is.null(call_srcref)) {
o$.otelAttrs <- otel_srcref_attributes(call_srcref)
}
if (has_otel_collect("reactivity")) {
o <- enable_otel_observe(o)
}
invisible(o)
}
@@ -2333,15 +2545,40 @@ eventReactive <- function(eventExpr, valueExpr,
eventQ <- exprToQuo(eventExpr, event.env, event.quoted)
valueQ <- exprToQuo(valueExpr, value.env, value.quoted)
label <- quoToLabel(eventQ, "eventReactive", label)
func <- installExprFunction(eventExpr, "func", event.env, event.quoted, wrappedWithLabel = FALSE)
# Attach a label and a reference to the original user source for debugging
userEventExpr <- fn_body(func)
invisible(inject(bindEvent(
ignoreNULL = ignoreNULL,
ignoreInit = ignoreInit,
label = label,
!!eventQ,
x = reactive(!!valueQ, domain = domain, label = label)
)))
call_srcref <- get_call_srcref()
if (is.null(label)) {
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = exprToLabel(userEventExpr, "eventReactive", label)
)
}
with_no_otel_collect({
value_r <- inject(reactive(!!valueQ, domain = domain, label = label))
r <- inject(bindEvent(
ignoreNULL = ignoreNULL,
ignoreInit = ignoreInit,
label = label,
!!eventQ,
x = value_r
))
})
if (!is.null(call_srcref)) {
impl <- attr(r, "observable", exact = TRUE)
impl$.otelAttrs <- otel_srcref_attributes(call_srcref)
}
if (has_otel_collect("reactivity")) {
r <- enable_otel_reactive_expr(r)
}
return(r)
}
isNullEvent <- function(value) {
@@ -2456,71 +2693,103 @@ isNullEvent <- function(value) {
#'
#' @export
debounce <- function(r, millis, priority = 100, domain = getDefaultReactiveDomain()) {
# TODO: make a nice label for the observer(s)
# Do not bind OpenTelemetry spans for debounce reactivity internals,
# except for the eventReactive that is returned.
force(r)
force(millis)
call_srcref <- get_call_srcref()
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = "<anonymous>"
)
if (!is.function(millis)) {
origMillis <- millis
millis <- function() origMillis
}
v <- reactiveValues(
trigger = NULL,
when = NULL # the deadline for the timer to fire; NULL if not scheduled
)
with_no_otel_collect({
trigger <- reactiveVal(NULL, label = sprintf("debounce %s trigger", label))
# the deadline for the timer to fire; NULL if not scheduled
when <- reactiveVal(NULL, label = sprintf("debounce %s when", label))
# Responsible for tracking when r() changes.
firstRun <- TRUE
observe({
if (firstRun) {
# During the first run we don't want to set v$when, as this will kick off
# the timer. We only want to do that when we see r() change.
firstRun <<- FALSE
# Responsible for tracking when r() changes.
firstRun <- TRUE
observe(
label = sprintf("debounce %s tracker", label),
domain = domain,
priority = priority,
{
if (firstRun) {
# During the first run we don't want to set `when`, as this will kick
# off the timer. We only want to do that when we see `r()` change.
firstRun <<- FALSE
# Ensure r() is called only after setting firstRun to FALSE since r()
# may throw an error
try(r(), silent = TRUE)
return()
}
# This ensures r() is still tracked after firstRun
try(r(), silent = TRUE)
# Ensure r() is called only after setting firstRun to FALSE since r()
# may throw an error
try(r(), silent = TRUE)
return()
}
# This ensures r() is still tracked after firstRun
try(r(), silent = TRUE)
# The value (or possibly millis) changed. Start or reset the timer.
v$when <- getDomainTimeMs(domain) + millis()
}, label = "debounce tracker", domain = domain, priority = priority)
# The value (or possibly millis) changed. Start or reset the timer.
when(
getDomainTimeMs(domain) + millis()
)
}
)
# This observer is the timer. It rests until v$when elapses, then touches
# v$trigger.
observe({
if (is.null(v$when))
return()
# This observer is the timer. It rests until `when` elapses, then touches
# `trigger`.
observe(
label = sprintf("debounce %s timer", label),
domain = domain,
priority = priority,
{
if (is.null(when()))
return()
now <- getDomainTimeMs(domain)
if (now >= v$when) {
# Mod by 999999999 to get predictable overflow behavior
v$trigger <- isolate(v$trigger %||% 0) %% 999999999 + 1
v$when <- NULL
} else {
invalidateLater(v$when - now)
}
}, label = "debounce timer", domain = domain, priority = priority)
now <- getDomainTimeMs(domain)
if (now >= when()) {
# Mod by 999999999 to get predictable overflow behavior
trigger(
isolate(trigger() %||% 0) %% 999999999 + 1
)
when(NULL)
} else {
invalidateLater(when() - now)
}
}
)
})
# This is the actual reactive that is returned to the user. It returns the
# value of r(), but only invalidates/updates when v$trigger is touched.
er <- eventReactive(v$trigger, {
r()
}, label = "debounce result", ignoreNULL = FALSE, domain = domain)
# value of r(), but only invalidates/updates when `trigger` is touched.
er <- eventReactive(
{trigger()}, {r()},
label = sprintf("debounce %s result", label), ignoreNULL = FALSE, domain = domain
)
# Force the value of er to be immediately cached upon creation. It's very hard
# to explain why this observer is needed, but if you want to understand, try
# commenting it out and studying the unit test failure that results.
primer <- observe({
primer$destroy()
try(er(), silent = TRUE)
}, label = "debounce primer", domain = domain, priority = priority)
# Update the otel label
local({
er_impl <- attr(er, "observable", exact = TRUE)
er_impl$.otelLabel <- otel_label_debounce(label, domain = domain)
er_impl$.otelAttrs <- append_otel_srcref_attrs(er_impl$.otelAttrs, call_srcref)
})
with_no_otel_collect({
# Force the value of er to be immediately cached upon creation. It's very hard
# to explain why this observer is needed, but if you want to understand, try
# commenting it out and studying the unit test failure that results.
primer <- observe({
primer$destroy()
try(er(), silent = TRUE)
}, label = sprintf("debounce %s primer", label), domain = domain, priority = priority)
})
er
}
@@ -2528,69 +2797,88 @@ debounce <- function(r, millis, priority = 100, domain = getDefaultReactiveDomai
#' @rdname debounce
#' @export
throttle <- function(r, millis, priority = 100, domain = getDefaultReactiveDomain()) {
# TODO: make a nice label for the observer(s)
# Do not bind OpenTelemetry spans for throttle reactivity internals,
# except for the eventReactive that is returned.
force(r)
force(millis)
call_srcref <- get_call_srcref()
label <- rassignSrcrefToLabel(
call_srcref,
defaultLabel = "<anonymous>"
)
if (!is.function(millis)) {
origMillis <- millis
millis <- function() origMillis
}
v <- reactiveValues(
trigger = 0,
lastTriggeredAt = NULL, # Last time we fired; NULL if never
pending = FALSE # If TRUE, trigger again when timer elapses
)
with_no_otel_collect({
trigger <- reactiveVal(0, label = sprintf("throttle %s trigger", label))
# Last time we fired; NULL if never
lastTriggeredAt <- reactiveVal(NULL, label = sprintf("throttle %s last triggered at", label))
# If TRUE, trigger again when timer elapses
pending <- reactiveVal(FALSE, label = sprintf("throttle %s pending", label))
})
blackoutMillisLeft <- function() {
if (is.null(v$lastTriggeredAt)) {
if (is.null(lastTriggeredAt())) {
0
} else {
max(0, v$lastTriggeredAt + millis() - getDomainTimeMs(domain))
max(0, lastTriggeredAt() + millis() - getDomainTimeMs(domain))
}
}
trigger <- function() {
v$lastTriggeredAt <- getDomainTimeMs(domain)
update_trigger <- function() {
lastTriggeredAt(getDomainTimeMs(domain))
# Mod by 999999999 to get predictable overflow behavior
v$trigger <- isolate(v$trigger) %% 999999999 + 1
v$pending <- FALSE
trigger(isolate(trigger()) %% 999999999 + 1)
pending(FALSE)
}
# Responsible for tracking when f() changes.
observeEvent(try(r(), silent = TRUE), {
if (v$pending) {
# In a blackout period and someone already scheduled; do nothing
} else if (blackoutMillisLeft() > 0) {
# In a blackout period but this is the first change in that period; set
# v$pending so that a trigger will be scheduled at the end of the period
v$pending <- TRUE
} else {
# Not in a blackout period. Trigger, which will start a new blackout
# period.
trigger()
}
}, label = "throttle tracker", ignoreNULL = FALSE, priority = priority, domain = domain)
with_no_otel_collect({
# Responsible for tracking when f() changes.
observeEvent(try(r(), silent = TRUE), {
if (pending()) {
# In a blackout period and someone already scheduled; do nothing
} else if (blackoutMillisLeft() > 0) {
# In a blackout period but this is the first change in that period; set
# pending so that a trigger will be scheduled at the end of the period
pending(TRUE)
} else {
# Not in a blackout period. Trigger, which will start a new blackout
# period.
update_trigger()
}
}, label = sprintf("throttle %s tracker", label), ignoreNULL = FALSE, priority = priority, domain = domain)
observe({
if (!v$pending) {
return()
}
observe({
if (!pending()) {
return()
}
timeout <- blackoutMillisLeft()
if (timeout > 0) {
invalidateLater(timeout)
} else {
trigger()
}
}, priority = priority, domain = domain)
timeout <- blackoutMillisLeft()
if (timeout > 0) {
invalidateLater(timeout)
} else {
update_trigger()
}
}, label = sprintf("throttle %s trigger", label), priority = priority, domain = domain)
})
# This is the actual reactive that is returned to the user. It returns the
# value of r(), but only invalidates/updates when v$trigger is touched.
eventReactive(v$trigger, {
# value of r(), but only invalidates/updates when trigger is touched.
er <- eventReactive({trigger()}, {
r()
}, label = "throttle result", ignoreNULL = FALSE, domain = domain)
}, label = sprintf("throttle %s result", label), ignoreNULL = FALSE, domain = domain)
# Update the otel label
local({
er_impl <- attr(er, "observable", exact = TRUE)
er_impl$.otelLabel <- otel_label_throttle(label, domain = domain)
er_impl$.otelAttrs <- append_otel_srcref_attrs(er_impl$.otelAttrs, call_srcref)
})
er
}

View File

@@ -253,7 +253,7 @@ drawPlot <- function(name, session, func, width, height, alt, pixelratio, res, .
hybrid_chain(
hybrid_chain(
promises::with_promise_domain(domain, {
with_promise_domain(domain, {
hybrid_chain(
func(),
function(value) {

View File

@@ -84,13 +84,22 @@
#' runApp(app)
#' }
#' @export
runApp <- function(appDir=getwd(),
port=getOption('shiny.port'),
launch.browser = getOption('shiny.launch.browser', interactive()),
host=getOption('shiny.host', '127.0.0.1'),
workerId="", quiet=FALSE,
display.mode=c("auto", "normal", "showcase"),
test.mode=getOption('shiny.testmode', FALSE)) {
runApp <- function(
appDir=getwd(),
port=getOption('shiny.port'),
launch.browser = getOption('shiny.launch.browser', interactive()),
host=getOption('shiny.host', '127.0.0.1'),
workerId="", quiet=FALSE,
display.mode=c("auto", "normal", "showcase"),
test.mode=getOption('shiny.testmode', FALSE)
) {
# * Wrap **all** execution of the app inside the otel promise domain
# * While this could be done at a lower level, it allows for _anything_ within
# shiny's control to allow for the opportunity to have otel active spans be
# reactivated upon promise domain restoration
promises::local_otel_promise_domain()
on.exit({
handlerManager$clear()
}, add = TRUE)

View File

@@ -274,15 +274,20 @@ createAppHandlers <- function(httpHandlers, serverFuncSource) {
args <- argsForServerFunc(serverFunc, shinysession)
withReactiveDomain(shinysession, {
do.call(
# No corresponding ..stacktraceoff; the server func is pure
# user code
wrapFunctionLabel(appvars$server, "server",
..stacktraceon = TRUE
),
args
)
otel_span_session_start(domain = shinysession, {
do.call(
# No corresponding ..stacktraceoff; the server func is pure
# user code
wrapFunctionLabel(appvars$server, "server",
..stacktraceon = TRUE
),
args
)
})
})
})
},
update = {

View File

@@ -70,7 +70,7 @@ getShinyOption <- function(name, default = NULL) {
#'
#' You can customize the file patterns Shiny will monitor by setting the
#' shiny.autoreload.pattern option. For example, to monitor only `ui.R`:
#' `options(shiny.autoreload.pattern = glob2rx("ui.R"))`.
#' `options(shiny.autoreload.pattern = glob2rx("ui.R"))`.
#'
#' As mentioned above, Shiny no longer polls watched files for changes.
#' Instead, using \pkg{watcher}, Shiny is notified of file changes as they
@@ -160,6 +160,21 @@ getShinyOption <- function(name, default = NULL) {
# ' side devmode features. Currently the primary feature is the client-side
# ' error console.}
### end shiny.client_devmode
#' \item{shiny.otel.collect (defaults to `Sys.getenv("SHINY_OTEL_COLLECT", "all")`)}{Determines how Shiny will
#' interact with OpenTelemetry.
#'
#' Supported values:
#' * `"none"` - No Shiny OpenTelemetry tracing.
#' * `"session"` - Adds session start/end spans.
#' * `"reactive_update"` - Spans for any synchronous/asynchronous reactive update. (Includes `"session"` features).
#' * `"reactivity"` - Spans for all reactive expressions. (Includes `"reactive_update"` features).
#' * `"all"` - All Shiny OpenTelemetry tracing. Currently equivalent to `"reactivity"`.
#'
#' This option is useful for debugging and profiling while in production. This
#' option will only be useful if the `otelsdk` package is installed and
#' `otel::is_tracing_enabled()` returns `TRUE`. Please have any OpenTelemetry
#' environment variables set before starting your Shiny app.}
#' \item{shiny.otel.sanitize.errors (defaults to `TRUE`)}{If `TRUE`, fatal and unhandled errors will be sanitized before being sent to the OpenTelemetry backend. The default value of `TRUE` is set to avoid potentially sending sensitive information to the OpenTelemetry backend. If you want the full error message and stack trace to be sent to the OpenTelemetry backend, set this option to `FALSE` or use `safeError(e)`.}
#' }
#'
#'

View File

@@ -4,11 +4,12 @@
#' @importFrom lifecycle deprecated is_present
#' @importFrom grDevices dev.set dev.cur
#' @importFrom fastmap fastmap
#' @importFrom promises %...!%
#' @importFrom promises %...>%
#' @importFrom promises
#' promise promise_resolve promise_reject is.promising
#' as.promise
#' %...!% %...>%
#' as.promise is.promising is.promise
#' promise_resolve promise_reject
#' hybrid_then
#' with_promise_domain new_promise_domain
#' @importFrom rlang
#' quo enquo enquo0 as_function get_expr get_env new_function enquos
#' eval_tidy expr pairlist2 new_quosure enexpr as_quosure is_quosure inject

View File

@@ -428,7 +428,7 @@ ShinySession <- R6Class(
stop("Nested calls to withCurrentOutput() are not allowed.")
}
promises::with_promise_domain(
with_promise_domain(
createVarPromiseDomain(private, "currentOutputName", name),
expr
)
@@ -1056,6 +1056,19 @@ ShinySession <- R6Class(
class(e) <- c("shiny.error.fatal", class(e))
}
# For fatal errors, always log.
# For non-fatal errors, only log if we haven't seen this error before.
if (close || !has_seen_otel_exception(e)) {
otel_log(
if (close) "Fatal error" else "Unhandled error",
severity = if (close) "fatal" else "error",
attributes = otel::as_attributes(list(
session.id = self$token,
error = get_otel_error_obj(e)
))
)
}
private$unhandledErrorCallbacks$invoke(e, onError = printError)
.globals$onUnhandledErrorCallbacks$invoke(e, onError = printError)
@@ -1073,7 +1086,9 @@ ShinySession <- R6Class(
}
# ..stacktraceon matches with the top-level ..stacktraceoff..
withReactiveDomain(self, {
private$closedCallbacks$invoke(onError = printError, ..stacktraceon = TRUE)
otel_span_session_end(domain = self, {
private$closedCallbacks$invoke(onError = printError, ..stacktraceon = TRUE)
})
})
},
isClosed = function() {
@@ -1142,7 +1157,8 @@ ShinySession <- R6Class(
attr(label, "srcref") <- srcref
attr(label, "srcfile") <- srcfile
obs <- observe(..stacktraceon = FALSE, {
# Do not bind this `observe()` call
obs <- with_no_otel_collect(observe(..stacktraceon = FALSE, {
private$sendMessage(recalculating = list(
name = name, status = 'recalculating'
@@ -1154,7 +1170,9 @@ ShinySession <- R6Class(
hybrid_chain(
{
private$withCurrentOutput(name, {
shinyCallingHandlers(func())
maybe_with_otel_span_reactive_update({
shinyCallingHandlers(func())
}, domain = self)
})
},
catch = function(cond) {
@@ -1179,9 +1197,7 @@ ShinySession <- R6Class(
} else {
if (isTRUE(getOption("show.error.messages"))) printError(cond)
if (getOption("shiny.sanitize.errors", FALSE)) {
cond <- simpleError(paste("An error has occurred. Check your",
"logs or contact the app author for",
"clarification."))
cond <- sanitized_error()
}
self$unhandledError(cond, close = FALSE)
invisible(structure(list(), class = "try-error", condition = cond))
@@ -1245,7 +1261,7 @@ ShinySession <- R6Class(
private$invalidatedOutputValues$set(name, value)
}
)
}, suspended=private$shouldSuspend(name), label=label)
}, suspended=private$shouldSuspend(name), label=label))
# If any output attributes were added to the render function attach
# them to observer.
@@ -2023,7 +2039,7 @@ ShinySession <- R6Class(
ext <- paste(".", ext, sep = "")
tmpdata <- tempfile(fileext = ext)
return(Context$new(getDefaultReactiveDomain(), '[download]')$run(function() {
promises::with_promise_domain(reactivePromiseDomain(), {
with_promise_domain(reactivePromiseDomain(), {
captureStackTraces({
self$incrementBusyCount()
hybrid_chain(
@@ -2195,6 +2211,8 @@ ShinySession <- R6Class(
if (private$busyCount == 0L) {
rLog$asyncStart(domain = self)
private$sendMessage(busy = "busy")
otel_span_reactive_update_init(domain = self)
}
private$busyCount <- private$busyCount + 1L
},
@@ -2216,6 +2234,8 @@ ShinySession <- R6Class(
private$startCycle()
}
})
otel_span_reactive_update_teardown(domain = self)
}
}
)
@@ -2723,3 +2743,10 @@ validate_session_object <- function(session, label = as.character(sys.call(sys.p
)
}
}
sanitized_error <- function() {
simpleError(paste("An error has occurred. Check your",
"logs or contact the app author for",
"clarification."))
}

View File

@@ -134,7 +134,12 @@ markRenderFunction <- function(
else renderFunc(...)
}
structure(
otelAttrs <-
otel_srcref_attributes(
attr(renderFunc, "wrappedFunc", exact = TRUE)
)
ret <- structure(
wrappedRenderFunc,
class = c("shiny.render.function", "function"),
outputFunc = uiFunc,
@@ -142,8 +147,15 @@ markRenderFunction <- function(
hasExecuted = hasExecuted,
cacheHint = cacheHint,
cacheWriteHook = cacheWriteHook,
cacheReadHook = cacheReadHook
cacheReadHook = cacheReadHook,
otelAttrs = otelAttrs
)
if (has_otel_collect("reactivity")) {
ret <- enable_otel_shiny_render_function(ret)
}
ret
}
#' @export
@@ -271,9 +283,7 @@ createRenderFunction <- function(
# Hoist func's wrappedFunc attribute into renderFunc, so that when we pass
# renderFunc on to markRenderFunction, it is able to find the original user
# function.
if (identical(cacheHint, "auto")) {
attr(renderFunc, "wrappedFunc") <- attr(func, "wrappedFunc", exact = TRUE)
}
attr(renderFunc, "wrappedFunc") <- attr(func, "wrappedFunc", exact = TRUE)
markRenderFunction(outputFunc, renderFunc, outputArgs, cacheHint,
cacheWriteHook, cacheReadHook)
@@ -321,7 +331,7 @@ as.tags.shiny.render.function <- function(x, ..., inline = FALSE) {
# Get relevant attributes from a render function object.
renderFunctionAttributes <- function(x) {
attrs <- c("outputFunc", "outputArgs", "hasExecuted", "cacheHint")
attrs <- c("outputFunc", "outputArgs", "hasExecuted", "cacheHint", "otelAttrs")
names(attrs) <- attrs
lapply(attrs, function(name) attr(x, name, exact = TRUE))
}
@@ -383,7 +393,7 @@ markOutputAttrs <- function(renderFunc, snapshotExclude = NULL,
#' The corresponding HTML output tag should be `div` or `img` and have
#' the CSS class name `shiny-image-output`.
#'
#' @seealso
#' @seealso
#' * For more details on how the images are generated, and how to control
#' the output, see [plotPNG()].
#' * Use [outputOptions()] to set general output options for an image output.
@@ -616,7 +626,7 @@ renderPrint <- function(expr, env = parent.frame(), quoted = FALSE,
domain <- createRenderPrintPromiseDomain(width)
hybrid_chain(
{
promises::with_promise_domain(domain, func())
with_promise_domain(domain, func())
},
function(value) {
res <- withVisible(value)
@@ -645,7 +655,7 @@ renderPrint <- function(expr, env = parent.frame(), quoted = FALSE,
createRenderPrintPromiseDomain <- function(width) {
f <- file()
promises::new_promise_domain(
new_promise_domain(
wrapOnFulfilled = function(onFulfilled) {
force(onFulfilled)
function(...) {
@@ -815,9 +825,9 @@ renderUI <- function(expr, env = parent.frame(), quoted = FALSE,
#'
#' @seealso
#' * The download handler, like other outputs, is suspended (disabled) by
#' default for download buttons and links that are hidden. Use
#' [outputOptions()] to control this behavior, e.g. to set
#' `suspendWhenHidden = FALSE` if the download is initiated by
#' default for download buttons and links that are hidden. Use
#' [outputOptions()] to control this behavior, e.g. to set
#' `suspendWhenHidden = FALSE` if the download is initiated by
#' programmatically clicking on the download button using JavaScript.
#' @export
downloadHandler <- function(filename, content, contentType=NULL, outputArgs=list()) {

View File

@@ -33,13 +33,6 @@ showcaseHead <- function() {
deps <- list(
jqueryuiDependency(),
htmlDependency(
"showdown",
"0.3.1",
src = "www/shared/showdown/compressed",
package="shiny",
script = "showdown.js"
),
htmlDependency(
"highlight.js",
"6.2",
@@ -61,10 +54,11 @@ showcaseHead <- function() {
mdfile <- file.path.ci(getwd(), 'Readme.md')
html <- tagList(
if (file.exists(mdfile))
tags$script(type="text/markdown", id="showcase-markdown-content",
paste(readUTF8(mdfile), collapse="\n"))
else ""
if (file.exists(mdfile)) {
md_content <- paste(readUTF8(mdfile), collapse="\n")
md_html <- commonmark::markdown_html(md_content, extensions = TRUE)
tags$template(id="showcase-markdown-content", HTML(md_html))
} else ""
)
return(attachDependencies(html, deps))

View File

@@ -208,8 +208,10 @@ exprToLabel <- function(expr, function_name, label = NULL) {
if (is.null(label)) {
label <- rexprSrcrefToLabel(
srcref[[1]],
simpleExprToFunction(expr, function_name)
simpleExprToFunction(expr, function_name),
function_name
)
label <- as_default_label(label)
}
if (length(srcref) >= 2) attr(label, "srcref") <- srcref[[2]]
attr(label, "srcfile") <- srcFileOfRef(srcref[[1]])
@@ -229,10 +231,12 @@ funcToLabelBody <- function(func) {
funcToLabel <- function(func, functionLabel, label = NULL) {
if (!is.null(label)) return(label)
sprintf(
'%s(%s)',
functionLabel,
funcToLabelBody(func)
as_default_label(
sprintf(
'%s(%s)',
functionLabel,
funcToLabelBody(func)
)
)
}
quoToLabelBody <- function(q) {
@@ -241,9 +245,19 @@ quoToLabelBody <- function(q) {
quoToLabel <- function(q, functionLabel, label = NULL) {
if (!is.null(label)) return(label)
sprintf(
'%s(%s)',
functionLabel,
quoToLabelBody(q)
as_default_label(
sprintf(
'%s(%s)',
functionLabel,
quoToLabelBody(q)
)
)
}
as_default_label <- function(x) {
class(x) <- c("default_label", class(x))
x
}
is_default_label <- function(x) {
inherits(x, "default_label")
}

View File

@@ -797,8 +797,8 @@ cachedFuncWithFile <- function(dir, file, func, case.sensitive = FALSE) {
last_autoreload <- 0
function(...) {
fname <- if (case.sensitive) {
file.path(dir, file)
fname <- if (case.sensitive) {
file.path(dir, file)
} else {
file.path.ci(dir, file)
}
@@ -1433,7 +1433,11 @@ URLencode <- function(value, reserved = FALSE) {
dateYMD <- function(date = NULL, argName = "value") {
if (!length(date)) return(NULL)
tryCatch({
res <- format(as.Date(date), "%Y-%m-%d")
if (inherits(date, "POSIXt")) {
res <- format(date, "%Y-%m-%d")
} else {
res <- format(as.Date(date), "%Y-%m-%d")
}
if (any(is.na(res))) stop()
date <- res
},
@@ -1525,7 +1529,7 @@ promise_chain <- function(promise, ..., catch = NULL, finally = NULL,
}
if (!is.null(domain)) {
promises::with_promise_domain(domain, do(), replace = replace)
with_promise_domain(domain, do(), replace = replace)
} else {
do()
}
@@ -1542,7 +1546,7 @@ hybrid_chain <- function(expr, ..., catch = NULL, finally = NULL,
{
captureStackTraces({
result <- withVisible(force(expr))
if (promises::is.promising(result$value)) {
if (is.promising(result$value)) {
# Purposefully NOT including domain (nor replace), as we're already in
# the domain at this point
p <- promise_chain(valueWithVisible(result), ..., catch = catch, finally = finally)
@@ -1576,7 +1580,7 @@ hybrid_chain <- function(expr, ..., catch = NULL, finally = NULL,
}
if (!is.null(domain)) {
promises::with_promise_domain(domain, do(), replace = replace)
with_promise_domain(domain, do(), replace = replace)
} else {
do()
}
@@ -1594,7 +1598,7 @@ createVarPromiseDomain <- function(env, name, value) {
force(name)
force(value)
promises::new_promise_domain(
new_promise_domain(
wrapOnFulfilled = function(onFulfilled) {
function(...) {
orig <- env[[name]]

View File

@@ -1,40 +1,121 @@
## Comments
#### 2025-12-01
Hi CRAN,
We made changes to underlying structures that packages are not suppose to test. PRs were provided for each failing package.
Maintainer change: From Winston Chang to Carson Sievert.
Please let me know if you need any further information.
Thank you,
Carson
## `R CMD check` results:
The maintainer change is correctly detected. The URL check sometimes flags a 429
error from Wikipedia, which is a temporary issue since the URL is valid when
visited manually.
```
* checking CRAN incoming feasibility ... [19s] NOTE
Maintainer: 'Carson Sievert <barret@posit.co>'
New maintainer:
Carson Sievert <barret@posit.co>
Old maintainer(s):
Winston Chang <winston@posit.co>
Found the following (possibly) invalid URLs:
URL: https://en.wikipedia.org/wiki/Reactive_programming
From: README.md
Status: 429
Message: Too Many Requests
```
## Reverse dependency fixes
The revdep checks below are failing due to changes made in https://github.com/rstudio/shiny/pull/4249 .
Unresolved PRs submitted in 2025/06:
* omicsTools - https://github.com/cheemalab/omicsTools/pull/1
* shinyGovstyle - https://github.com/dfe-analytical-services/shinyGovstyle/pull/155
* ShinyLink - https://github.com/cdc-addm/ShinyLink/pull/3
* shinySbm - https://github.com/Jo-Theo/shinySbm/pull/2
Unresolved PR submitted in 2025/10/29:
* biodosetools - PR made 2025/10/29 - https://github.com/biodosetools-team/biodosetools/pull/64
* inshiny - PR made 2025/10/29 - https://github.com/nicholasdavies/inshiny/pull/1
## Reverse dependency false positives
* SouthParkRshiny - New NOTE about installed package size. This is unrelated to any new changes in Shiny.
> ```
> * checking installed package size ... NOTE
> installed size is 8.6Mb
> sub-directories of 1Mb or more:
> data 8.0Mb
> ```
## revdepcheck results
We checked 1278 reverse dependencies (1277 from CRAN + 1 from Bioconductor), comparing R CMD check results across CRAN and dev versions of shiny.
We checked 1395 reverse dependencies (1388 from CRAN + 7 from Bioconductor), comparing R CMD check results across CRAN and dev versions of this package.
* We saw 2 new problems (NOTEs only)
* We failed to check 19 packages due to installation issues
* We saw 7 new problems
* We failed to check 21 packages
Issues with CRAN packages are summarised below.
### New problems
(This reports the first line of each new failure)
R CMD check displayed NOTEs for two packages, unrelated to changes in shiny.
* biodosetools
checking tests ... ERROR
* HH
checking installed package size ... NOTE
* inshiny
checking examples ... ERROR
checking tests ... ERROR
checking re-building of vignette outputs ... ERROR
* PopED
* omicsTools
checking tests ... ERROR
* shinyGovstyle
checking tests ... ERROR
* ShinyLink
checking tests ... ERROR
* shinySbm
checking tests ... ERROR
* SouthParkRshiny
checking installed package size ... NOTE
### Failed to check
* animalEKF
* AovBay
* Certara.VPCResults
* chipPCR
* boinet
* ctsem
* dartR.sim
* diveR
* gap
* jsmodule
* FAfA
* fio
* FossilSimShiny
* GDINA
* ggsem
* grandR
* hbsaems
* lavaan.shiny
* lcsm
* linkspotter
* loon.shiny
* robmedExtra
* MOsemiind
* MVN
* RCTrep
* rstanarm
* SensMap
* Seurat
* shinyTempSignal
* Signac
* statsr
* semdrw
* sphereML
* SurprisalAnalysis
* TestAnaAPP
* tidyvpc

View File

@@ -1,2 +1,2 @@
/*! shiny 1.11.1.9000 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
/*! shiny 1.12.0 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
:where([data-shiny-busy-spinners] .recalculating){position:relative}[data-shiny-busy-spinners] .recalculating{min-height:var(--shiny-spinner-size, 32px)}[data-shiny-busy-spinners] .recalculating:after{position:absolute;content:"";--_shiny-spinner-url: var(--shiny-spinner-url, url(spinners/ring.svg));--_shiny-spinner-color: var(--shiny-spinner-color, var(--bs-primary, #007bc2));--_shiny-spinner-size: var(--shiny-spinner-size, 32px);--_shiny-spinner-delay: var(--shiny-spinner-delay, 1s);background:var(--_shiny-spinner-color);width:var(--_shiny-spinner-size);height:var(--_shiny-spinner-size);inset:calc(50% - var(--_shiny-spinner-size) / 2);mask-image:var(--_shiny-spinner-url);-webkit-mask-image:var(--_shiny-spinner-url);opacity:0;animation-delay:var(--_shiny-spinner-delay);animation-name:fade-in;animation-duration:.25s;animation-fill-mode:forwards}[data-shiny-busy-spinners] .recalculating:has(>*),[data-shiny-busy-spinners] .recalculating:empty{opacity:1}[data-shiny-busy-spinners] .recalculating>*:not(.recalculating){opacity:var(--_shiny-fade-opacity);transition:opacity .25s ease var(--shiny-spinner-delay, 1s)}[data-shiny-busy-spinners] .recalculating.html-widget-output{visibility:inherit!important}[data-shiny-busy-spinners] .recalculating.html-widget-output>*{visibility:hidden}[data-shiny-busy-spinners] .recalculating.html-widget-output :after{visibility:visible}[data-shiny-busy-spinners] .recalculating.shiny-html-output:not(.shiny-table-output):after{display:none}[data-shiny-busy-spinners][data-shiny-busy-pulse].shiny-busy:after{--_shiny-pulse-background: var( --shiny-pulse-background, linear-gradient( 120deg, transparent, var(--bs-indigo, #4b00c1), var(--bs-purple, #74149c), var(--bs-pink, #bf007f), transparent ) );--_shiny-pulse-height: var(--shiny-pulse-height, 3px);--_shiny-pulse-speed: var(--shiny-pulse-speed, 1.2s);position:fixed;top:0;left:0;height:var(--_shiny-pulse-height);background:var(--_shiny-pulse-background);z-index:9999;animation-name:busy-page-pulse;animation-duration:var(--_shiny-pulse-speed);animation-direction:alternate;animation-iteration-count:infinite;animation-timing-function:ease-in-out;content:""}[data-shiny-busy-spinners][data-shiny-busy-pulse].shiny-busy:has(.recalculating:not(.shiny-html-output)):after{display:none}[data-shiny-busy-spinners][data-shiny-busy-pulse].shiny-busy:has(.recalculating.shiny-table-output):after{display:none}[data-shiny-busy-spinners][data-shiny-busy-pulse].shiny-busy:has(#shiny-disconnected-overlay):after{display:none}[data-shiny-busy-pulse]:not([data-shiny-busy-spinners]).shiny-busy:after{--_shiny-pulse-background: var( --shiny-pulse-background, linear-gradient( 120deg, transparent, var(--bs-indigo, #4b00c1), var(--bs-purple, #74149c), var(--bs-pink, #bf007f), transparent ) );--_shiny-pulse-height: var(--shiny-pulse-height, 3px);--_shiny-pulse-speed: var(--shiny-pulse-speed, 1.2s);position:fixed;top:0;left:0;height:var(--_shiny-pulse-height);background:var(--_shiny-pulse-background);z-index:9999;animation-name:busy-page-pulse;animation-duration:var(--_shiny-pulse-speed);animation-direction:alternate;animation-iteration-count:infinite;animation-timing-function:ease-in-out;content:""}[data-shiny-busy-pulse]:not([data-shiny-busy-spinners]).shiny-busy:has(#shiny-disconnected-overlay):after{display:none}@keyframes fade-in{0%{opacity:0}to{opacity:1}}@keyframes busy-page-pulse{0%{left:-14%;right:97%}45%{left:0%;right:14%}55%{left:14%;right:0%}to{left:97%;right:-14%}}.shiny-spinner-output-container{--shiny-spinner-size: 0px}

View File

@@ -1,3 +1,3 @@
/*! shiny 1.11.1.9000 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
/*! shiny 1.12.0 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
"use strict";(()=>{document.documentElement.classList.add("autoreload-enabled");var c=window.location.protocol==="https:"?"wss:":"ws:",s=window.location.pathname.replace(/\/?$/,"/")+"autoreload/",i=`${c}//${window.location.host}${s}`,l=document.currentScript?.dataset?.wsUrl||i;async function u(o){let e=new WebSocket(o),n=!1;return new Promise((a,r)=>{e.onopen=()=>{n=!0},e.onerror=t=>{r(t)},e.onclose=()=>{n?a(!1):r(new Error("WebSocket connection failed"))},e.onmessage=function(t){t.data==="autoreload"&&a(!0)}})}async function d(o){return new Promise(e=>setTimeout(e,o))}async function w(){for(;;){try{if(await u(l)){window.location.reload();return}}catch{console.debug("Giving up on autoreload");return}await d(1e3)}}w().catch(o=>{console.error(o)});})();
//# sourceMappingURL=shiny-autoreload.js.map

View File

@@ -1,2 +1,2 @@
/*! shiny 1.11.1.9000 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
/*! shiny 1.12.0 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
#showcase-well{border-radius:0}.shiny-code{background-color:#fff;margin-bottom:0}.shiny-code code{font-family:Menlo,Consolas,Courier New,monospace}.shiny-code-container{margin-top:20px;clear:both}.shiny-code-container h3{display:inline;margin-right:15px}.showcase-header{font-size:16px;font-weight:400}.showcase-code-link{text-align:right;padding:15px}#showcase-app-container{vertical-align:top}#showcase-code-tabs{margin-right:15px}#showcase-code-tabs pre{border:none;line-height:1em}#showcase-code-tabs .nav,#showcase-code-tabs ul{margin-bottom:0}#showcase-code-tabs .tab-content{border-style:solid;border-color:#e5e5e5;border-width:0px 1px 1px 1px;overflow:auto;border-bottom-right-radius:4px;border-bottom-left-radius:4px}#showcase-app-code{width:100%}#showcase-code-position-toggle{float:right}#showcase-sxs-code{padding-top:20px;vertical-align:top}.showcase-code-license{display:block;text-align:right}#showcase-code-content pre{background-color:#fff}

View File

@@ -1,3 +1,3 @@
/*! shiny 1.11.1.9000 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
"use strict";(()=>{var m=400;function c(e,l){let t=0;if(e.nodeType===3){let n=e.nodeValue?.replace(/\n/g,"").length??0;if(n>=l)return{element:e,offset:l};t+=n}else if(e.nodeType===1&&e.firstChild){let n=c(e.firstChild,l);if(n.element!==null)return n;t+=n.offset}return e.nextSibling?c(e.nextSibling,l-t):{element:null,offset:t}}function r(e,l,t){let n=0;for(let s=0;s<e.childNodes.length;s++){let i=e.childNodes[s];if(i.nodeType===3){let o=/\n/g,d;for(;(d=o.exec(i.nodeValue))!==null;)if(n++,n===l)return c(i,d.index+t+1)}else if(i.nodeType===1){let o=r(i,l-n,t);if(o.element!==null)return o;n+=o.offset}}return{element:null,offset:n}}function p(e,l){if(!document.createRange)return;let t=document.getElementById("srcref_"+e);if(!t){t=document.createElement("span"),t.id="srcref_"+e;let n=e,s=document.getElementById(l.replace(/\./g,"_")+"_code");if(!s)return;let i=r(s,n[0],n[4]),o=r(s,n[2],n[5]);if(i.element===null||o.element===null)return;let d=document.createRange();i.element.parentNode?.nodeName==="SPAN"&&i.element!==o.element?d.setStartBefore(i.element.parentNode):d.setStart(i.element,i.offset),o.element.parentNode?.nodeName==="SPAN"&&i.element!==o.element?d.setEndAfter(o.element.parentNode):d.setEnd(o.element,o.offset),d.surroundContents(t)}$(t).stop(!0,!0).effect("highlight",null,1600)}window.Shiny&&window.Shiny.addCustomMessageHandler("showcase-src",function(e){e.srcref&&e.srcfile&&p(e.srcref,e.srcfile)});var a=!1,u=function(e,l){let t=l?m:1,n=e?document.getElementById("showcase-sxs-code"):document.getElementById("showcase-code-inline"),s=e?document.getElementById("showcase-code-inline"):document.getElementById("showcase-sxs-code");if(document.getElementById("showcase-app-metadata")===null){let o=$("#showcase-well");e?o.fadeOut(t):o.fadeIn(t)}if(n===null||s===null){console.warn("Could not find the host elements for the code tabs. This is likely a bug in the showcase app.");return}$(n).hide(),$(s).fadeOut(t,function(){let o=document.getElementById("showcase-code-tabs");if(o===null){console.warn("Could not find the code tabs element. This is likely a bug in the showcase app.");return}if(s.removeChild(o),n.appendChild(o),e?w():document.getElementById("showcase-code-content")?.removeAttribute("style"),$(n).fadeIn(t),!e&&(document.getElementById("showcase-app-container")?.removeAttribute("style"),l)){let f=$(n).offset()?.top;f!==void 0&&$(document.body).animate({scrollTop:f})}let d=document.getElementById("readme-md");d!==null&&(d.parentElement?.removeChild(d),e?(s.appendChild(d),$(s).fadeIn(t)):document.getElementById("showcase-app-metadata")?.appendChild(d)),document.getElementById("showcase-code-position-toggle").innerHTML=e?'<i class="fa fa-level-down"></i> show below':'<i class="fa fa-level-up"></i> show with app'}),e&&$(document.body).animate({scrollTop:0},t),a=e,h(e&&l),$(window).trigger("resize")};function h(e){let t=960,n=1,s=document.getElementById("showcase-app-code").offsetWidth;s/2>960?t=s/2:s*.66>960?t=960:(t=s*.66,n=t/960),$("#showcase-app-container").animate({width:t+"px",zoom:n*100+"%"},e?m:0)}var g=function(){u(!a,!0)},y=function(){document.body.offsetWidth>1350&&u(!0,!1)};function w(){document.getElementById("showcase-code-content").style.height=$(window).height()+"px"}function E(){let e=document.getElementById("showcase-markdown-content");if(e!==null){let l=e.innerText||e.innerHTML,t=window.Showdown.converter;document.getElementById("readme-md").innerHTML=new t().makeHtml(l)}}$(window).resize(function(){a&&(h(!1),w())});window.toggleCodePosition=g;$(window).on("load",y);$(window).on("load",E);window.hljs&&window.hljs.initHighlightingOnLoad();})();
/*! shiny 1.12.0 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
"use strict";(()=>{var m=400;function c(e,s){let t=0;if(e.nodeType===3){let n=e.nodeValue?.replace(/\n/g,"").length??0;if(n>=s)return{element:e,offset:s};t+=n}else if(e.nodeType===1&&e.firstChild){let n=c(e.firstChild,s);if(n.element!==null)return n;t+=n.offset}return e.nextSibling?c(e.nextSibling,s-t):{element:null,offset:t}}function a(e,s,t){let n=0;for(let l=0;l<e.childNodes.length;l++){let i=e.childNodes[l];if(i.nodeType===3){let o=/\n/g,d;for(;(d=o.exec(i.nodeValue))!==null;)if(n++,n===s)return c(i,d.index+t+1)}else if(i.nodeType===1){let o=a(i,s-n,t);if(o.element!==null)return o;n+=o.offset}}return{element:null,offset:n}}function g(e,s){if(!document.createRange)return;let t=document.getElementById("srcref_"+e);if(!t){t=document.createElement("span"),t.id="srcref_"+e;let n=e,l=document.getElementById(s.replace(/\./g,"_")+"_code");if(!l)return;let i=a(l,n[0],n[4]),o=a(l,n[2],n[5]);if(i.element===null||o.element===null)return;let d=document.createRange();i.element.parentNode?.nodeName==="SPAN"&&i.element!==o.element?d.setStartBefore(i.element.parentNode):d.setStart(i.element,i.offset),o.element.parentNode?.nodeName==="SPAN"&&i.element!==o.element?d.setEndAfter(o.element.parentNode):d.setEnd(o.element,o.offset),d.surroundContents(t)}$(t).stop(!0,!0).effect("highlight",null,1600)}window.Shiny&&window.Shiny.addCustomMessageHandler("showcase-src",function(e){e.srcref&&e.srcfile&&g(e.srcref,e.srcfile)});var r=!1,u=function(e,s){let t=s?m:1,n=e?document.getElementById("showcase-sxs-code"):document.getElementById("showcase-code-inline"),l=e?document.getElementById("showcase-code-inline"):document.getElementById("showcase-sxs-code");if(document.getElementById("showcase-app-metadata")===null){let o=$("#showcase-well");e?o.fadeOut(t):o.fadeIn(t)}if(n===null||l===null){console.warn("Could not find the host elements for the code tabs. This is likely a bug in the showcase app.");return}$(n).hide(),$(l).fadeOut(t,function(){let o=document.getElementById("showcase-code-tabs");if(o===null){console.warn("Could not find the code tabs element. This is likely a bug in the showcase app.");return}if(l.removeChild(o),n.appendChild(o),e?p():document.getElementById("showcase-code-content")?.removeAttribute("style"),$(n).fadeIn(t),!e&&(document.getElementById("showcase-app-container")?.removeAttribute("style"),s)){let f=$(n).offset()?.top;f!==void 0&&$(document.body).animate({scrollTop:f})}let d=document.getElementById("readme-md");d!==null&&(d.parentElement?.removeChild(d),e?(l.appendChild(d),$(l).fadeIn(t)):document.getElementById("showcase-app-metadata")?.appendChild(d)),document.getElementById("showcase-code-position-toggle").innerHTML=e?'<i class="fa fa-level-down"></i> show below':'<i class="fa fa-level-up"></i> show with app'}),e&&$(document.body).animate({scrollTop:0},t),r=e,h(e&&s),$(window).trigger("resize")};function h(e){let t=960,n=1,l=document.getElementById("showcase-app-code").offsetWidth;l/2>960?t=l/2:l*.66>960?t=960:(t=l*.66,n=t/960),$("#showcase-app-container").animate({width:t+"px",zoom:n*100+"%"},e?m:0)}var w=function(){u(!r,!0)},y=function(){document.body.offsetWidth>1350&&u(!0,!1)};function p(){document.getElementById("showcase-code-content").style.height=$(window).height()+"px"}function E(){let e=document.getElementById("showcase-markdown-content");if(e!==null){let s=document.getElementById("readme-md");if(s!==null){let t=e.content.cloneNode(!0);s.appendChild(t)}}}$(window).resize(function(){r&&(h(!1),p())});window.toggleCodePosition=w;$(window).on("load",y);$(window).on("load",E);window.hljs&&window.hljs.initHighlightingOnLoad();})();
//# sourceMappingURL=shiny-showcase.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,3 +1,3 @@
/*! shiny 1.11.1.9000 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
/*! shiny 1.12.0 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
"use strict";(()=>{var t=eval;window.addEventListener("message",function(a){let e=a.data;e.code&&t(e.code)});})();
//# sourceMappingURL=shiny-testmode.js.map

View File

@@ -1,4 +1,4 @@
/*! shiny 1.11.1.9000 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
/*! shiny 1.12.0 | (c) 2012-2025 Posit Software, PBC. | License: GPL-3 | file LICENSE */
"use strict";
(() => {
var __create = Object.create;
@@ -7206,7 +7206,7 @@ ${duplicateIdMsg}`;
// srcts/src/shiny/index.ts
var ShinyClass = class {
constructor() {
this.version = "1.11.1.9000";
this.version = "1.12.0";
const { inputBindings, fileInputBinding: fileInputBinding2 } = initInputBindings();
const { outputBindings } = initOutputBindings();
setFileInputBinding(fileInputBinding2);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,34 +0,0 @@
Copyright (c) 2007, John Fraser
<http://www.attacklab.net/>
All rights reserved.
Original Markdown copyright (c) 2004, John Gruber
<http://daringfireball.net/>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name "Markdown" nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as
is" and any express or implied warranties, including, but not limited
to, the implied warranties of merchantability and fitness for a
particular purpose are disclaimed. In no event shall the copyright owner
or contributors be liable for any direct, indirect, incidental, special,
exemplary, or consequential damages (including, but not limited to,
procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including
negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.

File diff suppressed because it is too large Load Diff

View File

@@ -59,8 +59,6 @@ Other contributors:
\item Denis Ineshin (ion.rangeSlider library) [contributor, copyright holder]
\item Sami Samhuri (Javascript strftime library) [contributor, copyright holder]
\item SpryMedia Limited (DataTables library) [contributor, copyright holder]
\item John Fraser (showdown.js library) [contributor, copyright holder]
\item John Gruber (showdown.js library) [contributor, copyright holder]
\item Ivan Sagalaev (highlight.js library) [contributor, copyright holder]
\item R Core Team (tar implementation from R) [contributor, copyright holder]
}

View File

@@ -130,6 +130,23 @@ ragg package. See \code{\link[=plotPNG]{plotPNG()}} for more information.}
Cairo package. See \code{\link[=plotPNG]{plotPNG()}} for more information.}
\item{shiny.devmode (defaults to \code{NULL})}{Option to enable Shiny Developer Mode. When set,
different default \code{getOption(key)} values will be returned. See \code{\link[=devmode]{devmode()}} for more details.}
\item{shiny.otel.collect (defaults to \code{Sys.getenv("SHINY_OTEL_COLLECT", "all")})}{Determines how Shiny will
interact with OpenTelemetry.
Supported values:
\itemize{
\item \code{"none"} - No Shiny OpenTelemetry tracing.
\item \code{"session"} - Adds session start/end spans.
\item \code{"reactive_update"} - Spans for any synchronous/asynchronous reactive update. (Includes \code{"session"} features).
\item \code{"reactivity"} - Spans for all reactive expressions. (Includes \code{"reactive_update"} features).
\item \code{"all"} - All Shiny OpenTelemetry tracing. Currently equivalent to \code{"reactivity"}.
}
This option is useful for debugging and profiling while in production. This
option will only be useful if the \code{otelsdk} package is installed and
\code{otel::is_tracing_enabled()} returns \code{TRUE}. Please have any OpenTelemetry
environment variables set before starting your Shiny app.}
\item{shiny.otel.sanitize.errors (defaults to \code{TRUE})}{If \code{TRUE}, fatal and unhandled errors will be sanitized before being sent to the OpenTelemetry backend. The default value of \code{TRUE} is set to avoid potentially sending sensitive information to the OpenTelemetry backend. If you want the full error message and stack trace to be sent to the OpenTelemetry backend, set this option to \code{FALSE} or use \code{safeError(e)}.}
}
}

16
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@types/rstudio-shiny",
"version": "1.11.1-alpha.9000",
"name": "@posit/shiny",
"version": "1.11.1-alpha.9001",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@types/rstudio-shiny",
"version": "1.11.1-alpha.9000",
"name": "@posit/shiny",
"version": "1.11.1-alpha.9001",
"license": "GPL-3.0-only",
"dependencies": {
"@types/bootstrap": "5.2.x",
@@ -23,7 +23,6 @@
"@types/jqueryui": "1.12.24",
"@types/lodash": "4.x",
"@types/node": "18.x",
"@types/showdown": "1.x",
"@typescript-eslint/eslint-plugin": "8.x",
"@typescript-eslint/parser": "8.x",
"autoprefixer": "10.x",
@@ -2421,13 +2420,6 @@
"integrity": "sha512-ABnSEXM1MyO9ZZXl2yXLqzHcENuGh6kyXisnq87OQCubbJrMaargMYV/NPVmJA3lJGnDM6hzc1ce7yQM/RwI5g==",
"license": "MIT"
},
"node_modules/@types/showdown": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/@types/showdown/-/showdown-1.9.4.tgz",
"integrity": "sha512-50ehC3IAijfkvoNqmQ+VL73S7orOxmAK8ljQAFBv8o7G66lAZyxQj1L3BAv2dD86myLXI+sgKP1kcxAaxW356w==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/sizzle": {
"version": "2.3.9",
"resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.9.tgz",

View File

@@ -5,7 +5,7 @@
"url": "git+https://github.com/rstudio/shiny.git"
},
"name": "@posit/shiny",
"version": "1.11.1-alpha.9000",
"version": "1.12.0",
"license": "GPL-3.0-only",
"main": "",
"browser": "",
@@ -33,7 +33,6 @@
"@types/jqueryui": "1.12.24",
"@types/lodash": "4.x",
"@types/node": "18.x",
"@types/showdown": "1.x",
"@typescript-eslint/eslint-plugin": "8.x",
"@typescript-eslint/parser": "8.x",
"autoprefixer": "10.x",
@@ -70,7 +69,7 @@
"coverage_detailed": "npx --yes type-check --detail",
"coverage": "type-coverage -p tsconfig.json --at-least 90",
"circular": "npx --yes dpdm --transform ./srcts/src/index.ts",
"prepack": "cp README.md README-orig.md && cp npm-README.md README.md",
"prepack": "cp README.md README-orig.md && cp README-npm.md README.md",
"postpack": "test -f README-orig.md && cp README-orig.md README.md && rm README-orig.md"
},
"prettier": {

View File

@@ -1,29 +1,47 @@
# Revdeps
## Failed to check (12)
## Failed to check (28)
|package |version |error |warning |note |
|:--------------------|:-------|:-----|:-------|:----|
|ADAMgui |? | | | |
|boinet |1.5.0 |1 | | |
|ctsem |3.10.4 |1 | |1 |
|EMMAgeo |? | | | |
|FactEff |? | | | |
|FAfA |? | | | |
|fio |0.1.6 |1 | | |
|FossilSimShiny |? | | | |
|GDINA |? | | | |
|ggsem |? | | | |
|grandR |? | | | |
|GSVA |? | | | |
|lavaan.shiny |1.2 |1 | | |
|hbsaems |0.1.1 |1 | | |
|lavaan.shiny |? | | | |
|lcsm |? | | | |
|linkspotter |1.3.0 |1 | | |
|loon.shiny |? | | | |
|MOsemiind |0.1.0 |1 | | |
|MVN |6.2 |1 | | |
|Prostar |? | | | |
|rstanarm |2.32.1 |1 | | |
|sphereML |0.1.1 |1 | | |
|RCTrep |1.2.0 |1 | | |
|recmap |? | | | |
|rstanarm |2.32.2 |1 | | |
|semdrw |? | | | |
|sphereML |? | | | |
|StatTeacherAssistant |? | | | |
|TestAnaAPP |1.1.2 |1 | | |
|SurprisalAnalysis |? | | | |
|TestAnaAPP |? | | | |
## New problems (5)
## New problems (7)
|package |version |error |warning |note |
|:-------------|:-------|:------|:-------|:------|
|[omicsTools](problems.md#omicstools)|1.0.5 |__+1__ | | |
|[PopED](problems.md#poped)|0.7.0 | | |__+1__ |
|[shinyGovstyle](problems.md#shinygovstyle)|0.1.0 |__+1__ | | |
|[ShinyLink](problems.md#shinylink)|0.2.2 |__+1__ | | |
|[shinySbm](problems.md#shinysbm)|0.1.5 |__+1__ | |1 |
|package |version |error |warning |note |
|:---------------|:-------|:------|:-------|:--------|
|[biodosetools](problems.md#biodosetools)|3.7.1 |__+1__ | | |
|[inshiny](problems.md#inshiny)|0.1.0 |__+3__ | | |
|[omicsTools](problems.md#omicstools)|1.0.5 |__+1__ | | |
|[shinyGovstyle](problems.md#shinygovstyle)|0.1.0 |__+1__ | | |
|[ShinyLink](problems.md#shinylink)|0.2.2 |__+1__ | | |
|[shinySbm](problems.md#shinysbm)|0.1.5 |__+1__ | |1 |
|[SouthParkRshiny](problems.md#southparkrshiny)|1.0.0 | | |1 __+1__ |

View File

@@ -1,20 +1,25 @@
## revdepcheck results
We checked 1349 reverse dependencies (1345 from CRAN + 4 from Bioconductor), comparing R CMD check results across CRAN and dev versions of this package.
We checked 1395 reverse dependencies (1388 from CRAN + 7 from Bioconductor), comparing R CMD check results across CRAN and dev versions of this package.
* We saw 5 new problems
* We failed to check 8 packages
* We saw 7 new problems
* We failed to check 21 packages
Issues with CRAN packages are summarised below.
### New problems
(This reports the first line of each new failure)
* omicsTools
* biodosetools
checking tests ... ERROR
* PopED
checking installed package size ... NOTE
* inshiny
checking examples ... ERROR
checking tests ... ERROR
checking re-building of vignette outputs ... ERROR
* omicsTools
checking tests ... ERROR
* shinyGovstyle
checking tests ... ERROR
@@ -25,13 +30,29 @@ Issues with CRAN packages are summarised below.
* shinySbm
checking tests ... ERROR
* SouthParkRshiny
checking installed package size ... NOTE
### Failed to check
* FAfA (NA)
* fio (NA)
* GDINA (NA)
* lavaan.shiny (NA)
* loon.shiny (NA)
* rstanarm (NA)
* sphereML (NA)
* TestAnaAPP (NA)
* boinet (NA)
* ctsem (NA)
* FAfA (NA)
* fio (NA)
* FossilSimShiny (NA)
* GDINA (NA)
* ggsem (NA)
* grandR (NA)
* hbsaems (NA)
* lavaan.shiny (NA)
* lcsm (NA)
* linkspotter (NA)
* loon.shiny (NA)
* MOsemiind (NA)
* MVN (NA)
* RCTrep (NA)
* rstanarm (NA)
* semdrw (NA)
* sphereML (NA)
* SurprisalAnalysis (NA)
* TestAnaAPP (NA)

View File

@@ -1,3 +1,135 @@
# biodosetools
<details>
* Version: 3.7.1
* GitHub: https://github.com/biodosetools-team/biodosetools
* Source code: https://github.com/cran/biodosetools
* Date/Publication: 2025-10-22 08:10:02 UTC
* Number of recursive dependencies: 132
Run `revdepcheck::cloud_details(, "biodosetools")` for more info
</details>
## Newly broken
* checking tests ... ERROR
```
Running testthat.R
Running the tests in tests/testthat.R failed.
Complete output:
> library(testthat)
> library(biodosetools)
Loading required package: shiny
Loading required package: golem
>
> test_check("biodosetools")
! Problem with `glm()` -> constraint ML optimization will be used instead
...
- "<button id=\"go_filter\" type=\"button\" class=\"btn btn-default action-button\" style=\"display: none;\">"
- " <span class=\"action-label\">go</span>"
- "</button>"
+ "<button id=\"go_filter\" type=\"button\" class=\"btn btn-default action-button\" style=\"display: none;\">go</button>"
[ FAIL 2 | WARN 1 | SKIP 1 | PASS 455 ]
Error:
! Test failures.
Execution halted
```
# inshiny
<details>
* Version: 0.1.0
* GitHub: https://github.com/nicholasdavies/inshiny
* Source code: https://github.com/cran/inshiny
* Date/Publication: 2025-09-09 14:00:13 UTC
* Number of recursive dependencies: 53
Run `revdepcheck::cloud_details(, "inshiny")` for more info
</details>
## Newly broken
* checking examples ... ERROR
```
Running examples in inshiny-Ex.R failed
The error most likely occurred in:
> ### Name: inline_button
> ### Title: Inline action button
> ### Aliases: inline_button
>
> ### ** Examples
>
> ui <- bslib::page_fixed(
...
+ label = shiny::span(style = "font-style:italic", "button"),
+ icon = shiny::icon("play"),
+ meaning = "Update button", accent = "success"),
+ "."
+ )
+ )
Error in check_tags(widget, shiny::tags$button(), "shiny::actionButton()") :
Unexpected tag structure from shiny::actionButton(). Please contact the package maintainer.
Calls: <Anonymous> ... div -> dots_list -> inline -> inline_button -> check_tags
Execution halted
```
* checking tests ... ERROR
```
Running testthat.R
Running the tests in tests/testthat.R failed.
Complete output:
> # This file is part of the standard setup for testthat.
> # It is recommended that you do not modify it.
> #
> # Where should you do additional test configuration?
> # Learn more about the roles of various files in:
> # * https://r-pkgs.org/testing-design.html#sec-tests-files-overview
> # * https://testthat.r-lib.org/articles/special-files.html
...
1. ├─inshiny:::cc(...)
2. │ └─base::cat(as.character(x)) at ./helper.R:2:5
3. └─inshiny::inline_button(...)
4. └─inshiny:::check_tags(widget, shiny::tags$button(), "shiny::actionButton()")
[ FAIL 2 | WARN 0 | SKIP 9 | PASS 24 ]
Error:
! Test failures.
Execution halted
```
* checking re-building of vignette outputs ... ERROR
```
Error(s) in re-building vignettes:
--- re-building inshiny.Rmd using rmarkdown
Quitting from inshiny.Rmd:64-86 [unnamed-chunk-3]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<error/rlang_error>
Error in `check_tags()`:
! Unexpected tag structure from shiny::actionButton(). Please contact the package maintainer.
---
Backtrace:
...
Error: processing vignette 'inshiny.Rmd' failed with diagnostics:
Unexpected tag structure from shiny::actionButton(). Please contact the package maintainer.
--- failed re-building inshiny.Rmd
SUMMARY: processing the following file failed:
inshiny.Rmd
Error: Vignette re-building failed.
Execution halted
```
# omicsTools
<details>
@@ -6,7 +138,7 @@
* GitHub: https://github.com/YaoxiangLi/omicsTools
* Source code: https://github.com/cran/omicsTools
* Date/Publication: 2023-07-03 16:20:02 UTC
* Number of recursive dependencies: 87
* Number of recursive dependencies: 88
Run `revdepcheck::cloud_details(, "omicsTools")` for more info
@@ -27,43 +159,18 @@ Run `revdepcheck::cloud_details(, "omicsTools")` for more info
> # Learn more about the roles of various files in:
> # * https://r-pkgs.org/tests.html
...
lines(actual) vs lines(expected)
- "<button id=\"go_filter\" type=\"button\" class=\"btn btn-default action-button\" style=\"display: none;\">"
- " <span class=\"action-label\">go</span>"
- "</button>"
+ "<button id=\"go_filter\" type=\"button\" class=\"btn btn-default action-button\" style=\"display: none;\">go</button>"
[ FAIL 2 | WARN 0 | SKIP 1 | PASS 94 ]
Error: Test failures
Error:
! Test failures.
Execution halted
```
# PopED
<details>
* Version: 0.7.0
* GitHub: https://github.com/andrewhooker/PopED
* Source code: https://github.com/cran/PopED
* Date/Publication: 2024-10-07 19:30:02 UTC
* Number of recursive dependencies: 139
Run `revdepcheck::cloud_details(, "PopED")` for more info
</details>
## Newly broken
* checking installed package size ... NOTE
```
installed size is 5.5Mb
sub-directories of 1Mb or more:
R 1.5Mb
doc 1.4Mb
test 1.1Mb
```
# shinyGovstyle
<details>
@@ -72,7 +179,7 @@ Run `revdepcheck::cloud_details(, "PopED")` for more info
* GitHub: https://github.com/moj-analytical-services/shinyGovstyle
* Source code: https://github.com/cran/shinyGovstyle
* Date/Publication: 2024-09-12 14:40:02 UTC
* Number of recursive dependencies: 48
* Number of recursive dependencies: 49
Run `revdepcheck::cloud_details(, "shinyGovstyle")` for more info
@@ -89,15 +196,19 @@ Run `revdepcheck::cloud_details(, "shinyGovstyle")` for more info
> library(shinyGovstyle)
>
> test_check("shinyGovstyle")
Saving _problems/test-backlink_Input-7.R
[ FAIL 1 | WARN 0 | SKIP 0 | PASS 125 ]
...
══ Failed tests ════════════════════════════════════════════════════════════════
── Failure ('test-backlink_Input.R:4:3'): backlink works ───────────────────────
backlink_check$children[[1]][[2]] not identical to "Back".
Expected `backlink_check$children[[1]][[2]]` to be identical to "Back".
Differences:
target is NULL, current is character
[ FAIL 1 | WARN 0 | SKIP 0 | PASS 125 ]
Error: Test failures
Error:
! Test failures.
Execution halted
```
@@ -109,7 +220,7 @@ Run `revdepcheck::cloud_details(, "shinyGovstyle")` for more info
* GitHub: NA
* Source code: https://github.com/cran/ShinyLink
* Date/Publication: 2023-01-18 11:40:05 UTC
* Number of recursive dependencies: 129
* Number of recursive dependencies: 128
Run `revdepcheck::cloud_details(, "ShinyLink")` for more info
@@ -130,15 +241,15 @@ Run `revdepcheck::cloud_details(, "ShinyLink")` for more info
> # Learn more about the roles of various files in:
> # * https://r-pkgs.org/tests.html
...
lines(actual) vs lines(expected)
- "<button id=\"go_filter\" type=\"button\" class=\"btn btn-default action-button\" style=\"display: none;\">"
- " <span class=\"action-label\">go</span>"
- "</button>"
+ "<button id=\"go_filter\" type=\"button\" class=\"btn btn-default action-button\" style=\"display: none;\">go</button>"
[ FAIL 2 | WARN 0 | SKIP 1 | PASS 145 ]
Error: Test failures
Error:
! Test failures.
Execution halted
```
@@ -171,15 +282,15 @@ Run `revdepcheck::cloud_details(, "shinySbm")` for more info
> # Learn more about the roles of various files in:
> # * https://r-pkgs.org/tests.html
...
lines(actual) vs lines(expected)
- "<button id=\"go_filter\" type=\"button\" class=\"btn btn-default action-button\" style=\"display: none;\">"
- " <span class=\"action-label\">go</span>"
- "</button>"
+ "<button id=\"go_filter\" type=\"button\" class=\"btn btn-default action-button\" style=\"display: none;\">go</button>"
[ FAIL 2 | WARN 0 | SKIP 1 | PASS 141 ]
Error: Test failures
Error:
! Test failures.
Execution halted
```
@@ -210,3 +321,33 @@ Run `revdepcheck::cloud_details(, "shinySbm")` for more info
checkRd: (-1) visSbm.default.Rd:51: Lost braces in \itemize; meant \describe ?
```
# SouthParkRshiny
<details>
* Version: 1.0.0
* GitHub: https://github.com/Amalan-ConStat/SouthParkRshiny
* Source code: https://github.com/cran/SouthParkRshiny
* Date/Publication: 2024-03-09 11:10:08 UTC
* Number of recursive dependencies: 112
Run `revdepcheck::cloud_details(, "SouthParkRshiny")` for more info
</details>
## Newly broken
* checking installed package size ... NOTE
```
installed size is 8.6Mb
sub-directories of 1Mb or more:
data 8.0Mb
```
## In both
* checking data for non-ASCII characters ... NOTE
```
Note: found 1562 marked UTF-8 strings
```

View File

@@ -299,20 +299,18 @@ function setCodeHeightFromDocHeight() {
$(window).height() + "px";
}
// if there's a block of markdown content, render it to HTML
function renderMarkdown() {
const mdContent = document.getElementById("showcase-markdown-content");
// Move server-rendered markdown from template into the readme container
function insertMarkdownContent() {
const template = document.getElementById(
"showcase-markdown-content",
) as HTMLTemplateElement | null;
if (mdContent !== null) {
// IE8 puts the content of <script> tags into innerHTML but
// not innerText
const content = mdContent.innerText || mdContent.innerHTML;
const showdownConverter = (window as any).Showdown
.converter as showdown.ConverterStatic;
document.getElementById("readme-md")!.innerHTML =
new showdownConverter().makeHtml(content);
if (template !== null) {
const readmeContainer = document.getElementById("readme-md");
if (readmeContainer !== null) {
const content = template.content.cloneNode(true);
readmeContainer.appendChild(content);
}
}
}
@@ -331,7 +329,7 @@ declare global {
window.toggleCodePosition = toggleCodePosition;
$(window).on("load", setInitialCodePosition);
$(window).on("load", renderMarkdown);
$(window).on("load", insertMarkdownContent);
if (window.hljs) window.hljs.initHighlightingOnLoad();

View File

@@ -0,0 +1,6 @@
# reactiveValues() has useful print method
<ReactiveValues>
Values: x, y, z
Readonly: FALSE

View File

@@ -144,10 +144,10 @@
: doTryCatch
: tryCatchOne
: tryCatchList
: doTryCatch
: tryCatchOne
: tryCatchList
: tryCatch
: doWithOneRestart
: withOneRestart
: withRestarts
: test_code
: test_that
: eval [test-stacks-deep.R#XXX]
@@ -156,10 +156,10 @@
: doTryCatch
: tryCatchOne
: tryCatchList
: doTryCatch
: tryCatchOne
: tryCatchList
: tryCatch
: doWithOneRestart
: withOneRestart
: withRestarts
: test_code
: source_file
: FUN
@@ -212,10 +212,10 @@
: doTryCatch
: tryCatchOne
: tryCatchList
: doTryCatch
: tryCatchOne
: tryCatchList
: tryCatch
: doWithOneRestart
: withOneRestart
: withRestarts
: test_code
: test_that
: eval [test-stacks-deep.R#XXX]
@@ -224,10 +224,10 @@
: doTryCatch
: tryCatchOne
: tryCatchList
: doTryCatch
: tryCatchOne
: tryCatchList
: tryCatch
: doWithOneRestart
: withOneRestart
: withRestarts
: test_code
: source_file
: FUN
@@ -281,10 +281,10 @@
: doTryCatch
: tryCatchOne
: tryCatchList
: doTryCatch
: tryCatchOne
: tryCatchList
: tryCatch
: doWithOneRestart
: withOneRestart
: withRestarts
: test_code
: test_that
: eval [test-stacks-deep.R#XXX]
@@ -293,10 +293,10 @@
: doTryCatch
: tryCatchOne
: tryCatchList
: doTryCatch
: tryCatchOne
: tryCatchList
: tryCatch
: doWithOneRestart
: withOneRestart
: withRestarts
: test_code
: source_file
: FUN
@@ -335,10 +335,10 @@
: doTryCatch
: tryCatchOne
: tryCatchList
: doTryCatch
: tryCatchOne
: tryCatchList
: tryCatch
: doWithOneRestart
: withOneRestart
: withRestarts
: test_code
: test_that
: eval [test-stacks-deep.R#XXX]
@@ -347,10 +347,10 @@
: doTryCatch
: tryCatchOne
: tryCatchList
: doTryCatch
: tryCatchOne
: tryCatchList
: tryCatch
: doWithOneRestart
: withOneRestart
: withRestarts
: test_code
: source_file
: FUN

View File

@@ -3,16 +3,32 @@
Code
df
Output
num call loc
1 64 A [test-stacks.R#3]
2 63 B [test-stacks.R#7]
3 62 <reactive:C> [test-stacks.R#11]
4 42 C
5 41 renderTable [test-stacks.R#18]
6 40 func
7 39 force
8 38 withVisible
9 37 withCallingHandlers
num call loc
1 68 A [test-stacks.R#3]
2 67 B [test-stacks.R#7]
3 66 <reactive:C> [test-stacks.R#11]
4 44 C
5 43 renderTable [test-stacks.R#18]
6 42 func
7 41 force
8 40 withVisible
9 39 withCallingHandlers
10 38 domain$wrapSync
11 37 promises::with_promise_domain
12 36 captureStackTraces
13 32 tryCatch
14 31 do
15 30 hybrid_chain
16 29 renderFunc
17 28 renderTable({ C() }, server = FALSE)
18 10 isolate
19 9 withCallingHandlers [test-stacks.R#16]
20 8 domain$wrapSync
21 7 promises::with_promise_domain
22 6 captureStackTraces
23 2 tryCatch
24 1 try
25 0 causeError [test-stacks.R#14]
---
@@ -20,71 +36,76 @@
df
Output
num call loc
1 67 h
2 66 .handleSimpleError
3 65 stop
4 64 A [test-stacks.R#3]
5 63 B [test-stacks.R#7]
6 62 <reactive:C> [test-stacks.R#11]
7 61 ..stacktraceon..
8 60 .func
9 59 withVisible
10 58 withCallingHandlers
11 57 contextFunc
12 56 env$runWith
13 55 withCallingHandlers
14 54 domain$wrapSync
15 53 promises::with_promise_domain
16 52 captureStackTraces
17 51 force
18 50 domain$wrapSync
19 49 promises::with_promise_domain
20 48 withReactiveDomain
21 47 domain$wrapSync
22 46 promises::with_promise_domain
23 45 ctx$run
24 44 self$.updateValue
25 43 ..stacktraceoff..
26 42 C
27 41 renderTable [test-stacks.R#18]
28 40 func
29 39 force
30 38 withVisible
31 37 withCallingHandlers
32 36 domain$wrapSync
33 35 promises::with_promise_domain
34 34 captureStackTraces
35 33 doTryCatch
36 32 tryCatchOne
37 31 tryCatchList
38 30 tryCatch
39 29 do
40 28 hybrid_chain
41 27 renderFunc
42 26 renderTable({ C() }, server = FALSE)
43 25 ..stacktraceon.. [test-stacks.R#17]
44 24 contextFunc
45 23 env$runWith
46 22 withCallingHandlers
47 21 domain$wrapSync
48 20 promises::with_promise_domain
49 19 captureStackTraces
50 18 force
51 17 domain$wrapSync
52 16 promises::with_promise_domain
53 15 withReactiveDomain
54 14 domain$wrapSync
55 13 promises::with_promise_domain
56 12 ctx$run
57 11 ..stacktraceoff..
58 10 isolate
59 9 withCallingHandlers [test-stacks.R#16]
60 8 domain$wrapSync
61 7 promises::with_promise_domain
62 6 captureStackTraces
63 5 doTryCatch [test-stacks.R#15]
64 4 tryCatchOne
65 3 tryCatchList
66 2 tryCatch
67 1 try
1 71 h
2 70 .handleSimpleError
3 69 stop
4 68 A [test-stacks.R#3]
5 67 B [test-stacks.R#7]
6 66 <reactive:C> [test-stacks.R#11]
7 65 ..stacktraceon..
8 64 .func
9 63 withVisible
10 62 withCallingHandlers
11 61 contextFunc
12 60 env$runWith
13 59 withCallingHandlers
14 58 domain$wrapSync
15 57 promises::with_promise_domain
16 56 captureStackTraces
17 55 force
18 54 with_otel_span_context
19 53 force
20 52 domain$wrapSync
21 51 promises::with_promise_domain
22 50 withReactiveDomain
23 49 domain$wrapSync
24 48 promises::with_promise_domain
25 47 ctx$run
26 46 self$.updateValue
27 45 ..stacktraceoff..
28 44 C
29 43 renderTable [test-stacks.R#18]
30 42 func
31 41 force
32 40 withVisible
33 39 withCallingHandlers
34 38 domain$wrapSync
35 37 promises::with_promise_domain
36 36 captureStackTraces
37 35 doTryCatch
38 34 tryCatchOne
39 33 tryCatchList
40 32 tryCatch
41 31 do
42 30 hybrid_chain
43 29 renderFunc
44 28 renderTable({ C() }, server = FALSE)
45 27 ..stacktraceon.. [test-stacks.R#17]
46 26 contextFunc
47 25 env$runWith
48 24 withCallingHandlers
49 23 domain$wrapSync
50 22 promises::with_promise_domain
51 21 captureStackTraces
52 20 force
53 19 with_otel_span_context
54 18 force
55 17 domain$wrapSync
56 16 promises::with_promise_domain
57 15 withReactiveDomain
58 14 domain$wrapSync
59 13 promises::with_promise_domain
60 12 ctx$run
61 11 ..stacktraceoff..
62 10 isolate
63 9 withCallingHandlers [test-stacks.R#16]
64 8 domain$wrapSync
65 7 promises::with_promise_domain
66 6 captureStackTraces
67 5 doTryCatch [test-stacks.R#15]
68 4 tryCatchOne
69 3 tryCatchList
70 2 tryCatch
71 1 try
72 0 causeError [test-stacks.R#14]

View File

@@ -0,0 +1,322 @@
# devtools::load_all(); dev_otel_kitchen()
dev_otel_kitchen <- function() {
library(mirai)
mirai::daemons(2)
# Inspiration from
# * https://github.com/r-lib/otel/commit/a2ef493ae4b97701e4e178ac527f313580539080
# * https://github.com/r-lib/otel/commit/09c0eb6c80d5b907976de8fbaf89798cb11f8e6e#diff-169b8f234d0b208affb106fce375f86fefe2f16dba4ad66495a1dc06c8a4cd7b
otel_logger <- otel::get_logger("my-app-logger")
otel_tracer_name <- "my-app"
log_and_msg <- function(..., .envir = parent.frame()) {
msg <- paste(...)
message(" -- ", msg)
otel_log(msg, logger = otel_logger)
}
my_global_reactive <- reactiveVal(0)
app <- shinyApp(
ui = fluidPage(
sliderInput("mymod-x", "x", 1, 10, 5),
sliderInput("mymod-y", "y", 1, 10, 5),
div("x * y: "),
verbatimTextOutput("mymod-txt1"),
verbatimTextOutput("mymod-txt2"),
verbatimTextOutput("mymod-txt3"),
verbatimTextOutput("task_result")
),
server = function(input, output, session) {
log_and_msg("Start new Shiny session")
b <- reactiveVal(1)
observe(b(42))
shutdown <- function() {
later::later(
function() {
message("\n\nClosing session for minimal logfire graphs")
# session$close()
# httpuv::stopAllServers()
stopApp()
mirai::daemons(0)
},
delay = 100 / 1000
)
}
later::later(
function() {
if (!session$closed) {
log_and_msg("Invoking shutdown after 5s")
shutdown()
}
},
delay = 5
)
xMod <- function(id) {
moduleServer(id, function(input, output, session) {
xVal <- reactiveVal(NULL)
yVal <- reactiveVal(NULL)
rv <- reactiveValues(x = NULL, y = NULL)
log_and_msg("Shiny module")
x_raw <- reactive({
isolate({
my_global_reactive(my_global_reactive() + 1)
})
x_val <- xVal()
req(x_val)
log_and_msg(sprintf("X Val: %s", x_val))
x_val
})
x <- debounce(x_raw, 100)
y_raw <- reactive({
y_val <- input$y
log_and_msg(sprintf("Y Val: %s", y_val))
# Sys.sleep(0.5)
y_val
}) |> bindCache(input$y) |> bindEvent(input$y)
y <- throttle(y_raw, 100)
calc <- reactive(label = "barret_calc", {
log_and_msg("Doing expensive computation...")
x() * y()
})
observe({
log_and_msg("x: ", x())
})
output$txt1 <- renderText({
calc()
}) |>
bindCache(x(), y())
output$txt2 <- renderText({
calc()
}) |>
bindEvent(list(x(), y()))
output$txt3 <- renderText({
calc()
}) |>
bindCache(x(), y()) |>
bindEvent(list(x(), y()))
rand_task <- ExtendedTask$new(function() {
mirai::mirai(
{
# Slow operation goes here
Sys.sleep(100 / 1000)
sample(1:100, 1)
}
)
})
observeEvent(input$x, {
# Invoke the extended in an observer
rand_task$invoke()
}, label = "invoke_rand_task")
output$task_result <- renderText({
# React to updated results when the task completes
number <- rand_task$result()
paste0("Your number is ", number, ".")
})
mydesc <- reactiveFileReader(
1000,
session,
filePath = system.file("DESCRIPTION", package = "shiny"),
readFunc = read.dcf
)
observe({
mydesc()
})
myfile <- reactivePoll(
1000,
session,
checkFunc = function() {
Sys.time()
},
# This function returns the content of log_file
valueFunc = function() {
read.dcf(system.file("DESCRIPTION", package = "shiny"))
}
)
observe({
myfile()
})
x_prom <- reactive({
# t0
x_span_id <- force(otel::get_active_span_context()$get_span_id())
# message("x_prom span id: ", x_span_id)
x_val <- x()
log_and_msg("x_prom init")
p <- promises::promise(function(resolve, reject) {
log_and_msg("x_prom 0")
resolve(x_val)
})
p <- promises::then(p, function(x_val) {
log_and_msg("x_prom 1")
log_and_msg("Launching mirai")
x_val
# mirai::mirai_map(seq_len(x_val), function(i) {
# otel::start_local_active_span("slow compute")
# Sys.sleep(i / 10 / 1000)
# i
# }) |>
# promises::then(function(vals) {
# max(unlist(vals))
# })
# mirai::mirai(
# {
# otel::start_local_active_span("slow compute")
# # val
# # Sys.sleep(0.2)
# val
# },
# val = x_val
# )
})
p <- promises::then(p, function(x_val) {
log_and_msg("x_prom 2")
x_val
})
p <- promises::then(p, function(x_val) {
log_and_msg("x_prom 3")
x_val
})
})
y_prom <- reactive({
y_span_id <- force(otel::get_active_span_context()$get_span_id())
# message("y_prom span id: ", y_span_id)
y_val <- y()
log_and_msg("y_prom init")
yp <- promises::promise(function(resolve, reject) {
log_and_msg("y_prom 0")
resolve(y_val)
})
log_and_msg("make y_prom 1")
yp <- promises::then(yp, function(y_val) {
log_and_msg("y_prom 1")
y_val
})
log_and_msg("make y_prom 2")
yp <- promises::then(yp, function(y_val) {
log_and_msg("y_prom 2")
y_val + calc()
})
log_and_msg("make y_prom 3")
yp <- promises::then(yp, function(y_val) {
log_and_msg("y_prom 3")
y_val
})
log_and_msg(
"done y_prom - ",
getCurrentContext()$id,
" - ",
getCurrentContext()$.label
)
yp
})
observe(label = "proms_observer", {
p <- promises::promise_all(
x_prom(),
y_prom()
)
p <- promises::then(p, function(vals) {
log_and_msg("Vals[1]: ", vals[[1]])
log_and_msg("Vals[2]: ", vals[[2]])
# cat(force)
# Shut down the app so the telemetry can be seen easily
if (vals[[1]] < 6) {
updateSliderInput(
"x",
value = vals[[1]] + 1,
session = session
)
} else {
shutdown()
}
})
log_and_msg(
"done proms_observer - ",
getCurrentContext()$id,
" - ",
getCurrentContext()$.label
)
p
})
# |>
# bindOtel()
# Set the value late in the reactive calc
observeEvent(
{
input$x
},
{
rv$x <- input$x
},
label = "singleObserveEvent"
)
tmp_val <- reactiveVal(NULL)
# TODO: Not recording updates within the span!!
x_calc <- eventReactive(
{
isolate(tmp_val(1))
rv$x
},
{
tmp_val(2)
rv$x
}
)
y_calc <- eventReactive(
{
isolate(tmp_val(3))
input$y * 2
},
{
# x_calc()
tmp_val(4)
input$y * 2 / 2
}
)
# observeEvent(label = "set_y", {
# rv$y <- input$y
# })
observe(label = "set xVal", {
x_calc()
xVal(rv$x)
})
observe(label = "set yVal", {
yVal(y_calc())
})
})
}
xMod("mymod")
}
)
app
}

View File

@@ -930,7 +930,7 @@ test_that("bindCache reactive visibility - async", {
k <- reactiveVal(0)
res <- NULL
r <- reactive({
promise(function(resolve, reject) {
promises::promise(function(resolve, reject) {
if (k() == 0) resolve(invisible(k()))
else resolve(k())
})
@@ -943,21 +943,25 @@ test_that("bindCache reactive visibility - async", {
})
})
flushReact()
for (i in 1:3) later::run_now()
flush_and_run_later <- function(k) {
flushReact()
for (i in 1:k) later::run_now()
}
flush_and_run_later(4)
expect_identical(res, list(value = 0, visible = FALSE))
k(1)
flushReact()
for (i in 1:3) later::run_now()
flush_and_run_later(4)
expect_identical(res, list(value = 1, visible = TRUE))
# Now fetch from cache
k(0)
flushReact()
for (i in 1:3) later::run_now()
flush_and_run_later(4)
expect_identical(res, list(value = 0, visible = FALSE))
k(1)
flushReact()
for (i in 1:3) later::run_now()
flush_and_run_later(4)
expect_identical(res, list(value = 1, visible = TRUE))
})
@@ -1136,6 +1140,8 @@ test_that("Custom render functions that call installExprFunction", {
test_that("cacheWriteHook and cacheReadHook for render functions", {
testthat::skip_if(shiny_otel_tracer()$is_enabled(), "Skipping stack trace tests when OpenTelemetry is already enabled")
write_hook_n <- 0
read_hook_n <- 0

View File

@@ -0,0 +1,649 @@
# Do not move or rearrange this code - it defines helper functions used in multiple tests below
get_reactive_objects <- function() {
# Must use variables, otherwise the source reference is collapsed to a single line
r <- reactive({ 42 })
rv <- reactiveVal("test")
rvs <- reactiveValues(a = 1)
o <- observe({ 43 })
rt <- renderText({ "text" })
oe <- observeEvent({"key"}, { 45 })
er <- eventReactive({"key"}, { 46 })
# Values below this line are to test file location, not file line
r1a <- reactive({ 1 }) |> bindCache({"key"})
r2a <- reactive({ 2 }) |> bindEvent({"key"})
r3a <- reactive({ 3 }) |> bindCache({"key1"}) |> bindEvent({"key2"})
r1b <- bindCache(reactive({ 1 }), {"key"})
r2b <- bindEvent(reactive({ 2 }), {"key"})
r3b <- bindEvent(bindCache(reactive({ 3 }), {"key1"}), {"key2"})
rt1a <- renderText({"text"}) |> bindCache({"key"})
rt2a <- renderText({"text"}) |> bindEvent({"key"})
rt3a <- renderText({"text"}) |> bindCache({"key1"}) |> bindEvent({"key2"})
rt1b <- bindCache(renderText({"text"}), {"key"})
rt2b <- bindEvent(renderText({"text"}), {"key"})
rt3b <- bindEvent(bindCache(renderText({"text"}), {"key1"}), {"key2"})
o2a <- observe({ 44 }) |> bindEvent({"key"})
o2b <- bindEvent(observe({ 47 }), {"key"})
# Debounce and throttle
r_debounce <- reactive({ 48 }) |> debounce(1000)
r_throttle <- reactive({ 49 }) |> throttle(1000)
# ExtendedTask
ext_task <- ExtendedTask$new(function() { promises::promise_resolve(50) })
# Reactive with explicit label
r_labeled <- reactive({ 51 }, label = "my_reactive")
o_labeled <- observe({ 52 }, label = "my_observer")
# Poll and File
r_poll <- reactivePoll(1000, NULL, checkFunc = function() { TRUE}, valueFunc = function() { 53 })
r_file <- reactiveFileReader(1000, NULL, filePath = "path/to/file")
list(
reactive = r,
reactiveVal = rv,
reactiveValues = rvs,
observe = o,
renderText = rt,
observeEvent = oe,
eventReactive = er,
reactiveCacheA = r1a,
reactiveEventA = r2a,
reactiveCacheEventA = r3a,
reactiveCacheB = r1b,
reactiveEventB = r2b,
reactiveCacheEventB = r3b,
renderCacheA = rt1a,
renderEventA = rt2a,
renderCacheEventA = rt3a,
renderCacheB = rt1b,
renderEventB = rt2b,
renderCacheEventB = rt3b,
observeEventA = o2a,
observeEventB = o2b,
debounce = r_debounce,
throttle = r_throttle,
extendedTask = ext_task,
reactiveLabeled = r_labeled,
observeLabeled = o_labeled,
reactivePoll = r_poll,
reactiveFileReader = r_file
)
}
# Helper function to create a mock srcref
create_mock_srcref <- function(
lines = c(10, 15),
columns = c(5, 20),
filename = "test_file.R"
) {
srcfile <- list(filename = filename)
srcref <- structure(
c(lines[1], columns[1], lines[2], columns[2], columns[1], columns[2]),
class = "srcref"
)
attr(srcref, "srcfile") <- srcfile
srcref
}
test_that("otel_srcref_attributes extracts attributes from srcref object", {
srcref <- create_mock_srcref(
lines = c(15, 18),
columns = c(8, 25),
filename = "/path/to/myfile.R"
)
attrs <- otel_srcref_attributes(srcref)
expect_equal(attrs[["code.filepath"]], "/path/to/myfile.R")
expect_equal(attrs[["code.lineno"]], 15)
expect_equal(attrs[["code.column"]], 8)
})
test_that("otel_srcref_attributes handles NULL srcref", {
attrs <- otel_srcref_attributes(NULL)
expect_null(attrs)
})
test_that("otel_srcref_attributes extracts from function with srcref", {
mock_func <- function() { "test" }
srcref <- create_mock_srcref(
lines = c(42, 45),
columns = c(12, 30),
filename = "function_file.R"
)
with_mocked_bindings(
getSrcRefs = function(func) {
expect_identical(func, mock_func)
list(list(srcref))
},
{
attrs <- otel_srcref_attributes(mock_func)
expect_equal(attrs[["code.filepath"]], "function_file.R")
expect_equal(attrs[["code.lineno"]], 42)
expect_equal(attrs[["code.column"]], 12)
}
)
})
test_that("otel_srcref_attributes handles function without srcref", {
mock_func <- function() { "test" }
with_mocked_bindings(
getSrcRefs = function(func) {
list(list(NULL))
},
{
attrs <- otel_srcref_attributes(mock_func)
expect_null(attrs)
}
)
})
test_that("otel_srcref_attributes handles function with empty getSrcRefs", {
mock_func <- function() { "test" }
with_mocked_bindings(
getSrcRefs = function(func) {
list() # Empty list
},
{
expect_error(
otel_srcref_attributes(mock_func),
"subscript out of bounds|attempt to select less than one element"
)
}
)
})
test_that("otel_srcref_attributes validates srcref class", {
invalid_srcref <- structure(
c(10, 5, 15, 20, 5, 20),
class = "not_srcref"
)
expect_error(
otel_srcref_attributes(invalid_srcref),
"inherits\\(srcref, \"srcref\"\\) is not TRUE"
)
})
test_that("otel_srcref_attributes drops NULL values", {
# Create srcref with missing filename
srcref <- structure(
c(10, 5, 15, 20, 5, 20),
class = "srcref"
)
attr(srcref, "srcfile") <- list(filename = NULL)
attrs <- otel_srcref_attributes(srcref)
# Should only contain lineno and column, not filepath
expect_equal(length(attrs), 2)
expect_equal(attrs[["code.lineno"]], 10)
expect_equal(attrs[["code.column"]], 5)
expect_false("code.filepath" %in% names(attrs))
})
test_that("otel_srcref_attributes handles missing srcfile", {
srcref <- structure(
c(10, 5, 15, 20, 5, 20),
class = "srcref"
)
# No srcfile attribute
attrs <- otel_srcref_attributes(srcref)
# Should only contain lineno and column
expect_equal(length(attrs), 2)
expect_equal(attrs[["code.lineno"]], 10)
expect_equal(attrs[["code.column"]], 5)
expect_false("code.filepath" %in% names(attrs))
})
# Integration tests with reactive functions
test_that("reactive() captures otel attributes from source reference", {
# This test verifies that reactive() functions get otel attributes set
# We'll need to mock the internals since we can't easily control srcref in tests
x <- get_reactive_objects()$reactive
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 4)
expect_equal(attrs[["code.column"]], 3)
})
test_that("reactiveVal() captures otel attributes from source reference", {
x <- get_reactive_objects()$reactiveVal
# Test the attribute extraction that would be used in reactiveVal
attrs <- attr(x, ".impl")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 5)
expect_equal(attrs[["code.column"]], 3)
})
test_that("reactiveValues() captures otel attributes from source reference", {
x <- get_reactive_objects()$reactiveValues
attrs <- .subset2(x, "impl")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 6)
expect_equal(attrs[["code.column"]], 3)
})
test_that("observe() captures otel attributes from source reference", {
x <- get_reactive_objects()$observe
attrs <- x$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 7)
expect_equal(attrs[["code.column"]], 3)
})
test_that("otel attributes integration with render functions", {
x <- get_reactive_objects()$renderText
attrs <- attr(x, "otelAttrs")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 8)
expect_equal(attrs[["code.column"]], 20)
})
test_that("observeEvent() captures otel attributes from source reference", {
x <- get_reactive_objects()$observeEvent
attrs <- x$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 9)
expect_equal(attrs[["code.column"]], 3)
})
test_that("otel attributes follow OpenTelemetry semantic conventions", {
# Test that the attribute names follow the official OpenTelemetry conventions
# https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/
srcref <- create_mock_srcref(
lines = c(1, 1),
columns = c(1, 10),
filename = "convention_test.R"
)
attrs <- otel_srcref_attributes(srcref)
# Check that attribute names follow the convention
expect_true("code.filepath" %in% names(attrs))
expect_true("code.lineno" %in% names(attrs))
expect_true("code.column" %in% names(attrs))
# Check that values are of correct types
expect_true(is.character(attrs[["code.filepath"]]))
expect_true(is.numeric(attrs[["code.lineno"]]))
expect_true(is.numeric(attrs[["code.column"]]))
})
test_that("dropNulls helper works correctly in otel_srcref_attributes", {
# Test with all values present
srcref <- create_mock_srcref(
lines = c(5, 8),
columns = c(3, 15),
filename = "complete_test.R"
)
attrs <- otel_srcref_attributes(srcref)
expect_equal(length(attrs), 3)
# Test with missing filename (NULL)
srcref_no_file <- structure(
c(5, 3, 8, 15, 3, 15),
class = "srcref"
)
attr(srcref_no_file, "srcfile") <- list(filename = NULL)
attrs_no_file <- otel_srcref_attributes(srcref_no_file)
expect_equal(length(attrs_no_file), 2)
expect_false("code.filepath" %in% names(attrs_no_file))
})
test_that("otel attributes are used in reactive context execution", {
# Test that otel attributes are properly passed through to spans
mock_attrs <- list(
"code.filepath" = "context_test.R",
"code.lineno" = 42L,
"code.column" = 8L
)
# Test the context info structure used in react.R
otel_info <- ctx_otel_info_obj(
isRecordingOtel = TRUE,
otelLabel = "test_reactive",
otelAttrs = mock_attrs
)
expect_true(otel_info$isRecordingOtel)
expect_equal(otel_info$otelLabel, "test_reactive")
expect_equal(otel_info$otelAttrs, mock_attrs)
expect_equal(class(otel_info), "ctx_otel_info")
})
test_that("otel attributes are combined with session attributes", {
# Test that otel srcref attributes are properly combined with session attributes
# as happens in the reactive system
srcref_attrs <- list(
"code.filepath" = "session_test.R",
"code.lineno" = 15L,
"code.column" = 5L
)
session_attrs <- list(
"session.id" = "test-session-123"
)
# Simulate the combination as done in reactives.R
combined_attrs <- c(srcref_attrs, session_attrs)
expect_equal(length(combined_attrs), 4)
expect_equal(combined_attrs[["code.filepath"]], "session_test.R")
expect_equal(combined_attrs[["code.lineno"]], 15L)
expect_equal(combined_attrs[["session.id"]], "test-session-123")
})
test_that("eventReactive() captures otel attributes from source reference", {
x <- get_reactive_objects()$eventReactive
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 10)
expect_equal(attrs[["code.column"]], 3)
})
test_that("renderText() with bindCache() captures otel attributes", {
x <- get_reactive_objects()$renderCacheA
attrs <- attr(x, "otelAttrs")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that("renderText() with bindEvent() captures otel attributes", {
x <- get_reactive_objects()$renderEventA
attrs <- attr(x, "otelAttrs")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that(
"renderText() with bindCache() |> bindEvent() captures otel attributes",
{
x <- get_reactive_objects()$renderCacheEventA
attrs <- attr(x, "otelAttrs")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
}
)
test_that("bindCache() wrapping renderText() captures otel attributes", {
x <- get_reactive_objects()$renderCacheB
attrs <- attr(x, "otelAttrs")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that("bindEvent() wrapping renderText() captures otel attributes", {
x <- get_reactive_objects()$renderEventB
attrs <- attr(x, "otelAttrs")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that(
"bindEvent() wrapping bindCache(renderText()) captures otel attributes",
{
x <- get_reactive_objects()$renderCacheEventB
attrs <- attr(x, "otelAttrs")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
}
)
test_that("observe() with bindEvent() captures otel attributes", {
x <- get_reactive_objects()$observeEventA
attrs <- x$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that("bindEvent() wrapping observe() captures otel attributes", {
x <- get_reactive_objects()$observeEventB
attrs <- x$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that("reactive() with bindCache() captures otel attributes", {
x <- get_reactive_objects()$reactiveCacheA
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that("reactive() with bindEvent() captures otel attributes", {
x <- get_reactive_objects()$reactiveEventA
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that(
"reactive() with bindCache() |> bindEvent() captures otel attributes",
{
x <- get_reactive_objects()$reactiveCacheEventA
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
}
)
test_that("bindCache() wrapping reactive() captures otel attributes", {
x <- get_reactive_objects()$reactiveCacheB
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that("bindEvent() wrapping reactive() captures otel attributes", {
x <- get_reactive_objects()$reactiveEventB
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that(
"bindEvent() wrapping bindCache(reactive()) captures otel attributes",
{
x <- get_reactive_objects()$reactiveCacheEventB
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
}
)
# Tests for debounce/throttle
test_that("debounce() creates new reactive with otel attributes", {
x <- get_reactive_objects()$debounce
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
test_that("throttle() creates new reactive with otel attributes", {
x <- get_reactive_objects()$throttle
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
# Tests for ExtendedTask
test_that("ExtendedTask is created and is an R6 object", {
x <- get_reactive_objects()$extendedTask
expect_s3_class(x, "ExtendedTask")
expect_s3_class(x, "R6")
attrs <- .subset2(x, ".__enclos_env__")$private$otel_attrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
# Tests for reactivePoll
test_that("reactivePoll() captures otel attributes from source reference", {
x <- get_reactive_objects()$reactivePoll
impl <- attr(x, "observable", exact = TRUE)
attrs <- impl$.otelAttrs
otelLabel <- impl$.otelLabel
expect_equal(as.character(otelLabel), "reactivePoll r_poll")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
# Tests for reactiveFileReader
test_that("reactiveFileReader() captures otel attributes from source reference", {
x <- get_reactive_objects()$reactiveFileReader
impl <- attr(x, "observable", exact = TRUE)
attrs <- impl$.otelAttrs
otelLabel <- impl$.otelLabel
expect_equal(as.character(otelLabel), "reactiveFileReader r_file")
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_gt(attrs[["code.lineno"]], 12)
})
# Tests for explicit labels
test_that("reactive() with explicit label still captures otel attributes", {
x <- get_reactive_objects()$reactiveLabeled
attrs <- attr(x, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 38)
expect_equal(attrs[["code.column"]], 3)
# Verify label is preserved
label <- attr(x, "observable")$.label
expect_equal(as.character(label), "my_reactive")
})
test_that("observe() with explicit label still captures otel attributes", {
x <- get_reactive_objects()$observeLabeled
attrs <- x$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_equal(attrs[["code.lineno"]], 39)
expect_equal(attrs[["code.column"]], 3)
# Verify label is preserved
expect_equal(x$.label, "my_observer")
})
# Edge case tests
test_that("reactive created inside function captures function srcref", {
create_reactive <- function() {
reactive({ 100 })
}
r <- create_reactive()
attrs <- attr(r, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
# Line number should point to where reactive() is called inside the function
expect_true(is.numeric(attrs[["code.lineno"]]))
expect_true(is.numeric(attrs[["code.column"]]))
})
test_that("observe created inside function captures function srcref", {
create_observer <- function() {
observe({ 101 })
}
o <- create_observer()
attrs <- o$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_true(is.numeric(attrs[["code.lineno"]]))
expect_true(is.numeric(attrs[["code.column"]]))
})
test_that("reactive returned from function preserves srcref", {
make_counter <- function(initial = 0) {
reactive({ initial + 1 })
}
counter <- make_counter(42)
attrs <- attr(counter, "observable")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_true(is.numeric(attrs[["code.lineno"]]))
})
test_that("reactiveVal created in function captures srcref", {
create_val <- function() {
reactiveVal("initial")
}
rv <- create_val()
attrs <- attr(rv, ".impl")$.otelAttrs
expect_equal(attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_true(is.numeric(attrs[["code.lineno"]]))
})
test_that("nested reactive expressions preserve individual srcrefs", {
outer_reactive <- reactive({
inner_reactive <- reactive({ 200 })
inner_reactive
})
outer_attrs <- attr(outer_reactive, "observable")$.otelAttrs
expect_equal(outer_attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_true(is.numeric(outer_attrs[["code.lineno"]]))
# Get the inner reactive by executing outer
withReactiveDomain(MockShinySession$new(), {
inner_reactive <- isolate(outer_reactive())
inner_attrs <- attr(inner_reactive, "observable")$.otelAttrs
expect_equal(inner_attrs[["code.filepath"]], "test-otel-attr-srcref.R")
expect_true(is.numeric(inner_attrs[["code.lineno"]]))
# Inner should have different line number than outer
expect_false(inner_attrs[["code.lineno"]] == outer_attrs[["code.lineno"]])
})
})

View File

@@ -0,0 +1,142 @@
test_that("otel_collect_is_enabled works with valid collect levels", {
# Test with default "all" option
expect_true(otel_collect_is_enabled("none"))
expect_true(otel_collect_is_enabled("session"))
expect_true(otel_collect_is_enabled("reactive_update"))
expect_true(otel_collect_is_enabled("reactivity"))
expect_true(otel_collect_is_enabled("all"))
})
test_that("otel_collect_is_enabled respects hierarchy with 'none' option", {
# With "none" option, nothing should be enabled
expect_false(otel_collect_is_enabled("session", "none"))
expect_false(otel_collect_is_enabled("reactive_update", "none"))
expect_false(otel_collect_is_enabled("reactivity", "none"))
expect_false(otel_collect_is_enabled("all", "none"))
expect_true(otel_collect_is_enabled("none", "none"))
})
test_that("otel_collect_is_enabled respects hierarchy with 'session' option", {
# With "session" option, only "none" and "session" should be enabled
expect_true(otel_collect_is_enabled("none", "session"))
expect_true(otel_collect_is_enabled("session", "session"))
expect_false(otel_collect_is_enabled("reactive_update", "session"))
expect_false(otel_collect_is_enabled("reactivity", "session"))
expect_false(otel_collect_is_enabled("all", "session"))
})
test_that("otel_collect_is_enabled respects hierarchy with 'reactive_update' option", {
# With "reactive_update" option, "none", "session", and "reactive_update" should be enabled
expect_true(otel_collect_is_enabled("none", "reactive_update"))
expect_true(otel_collect_is_enabled("session", "reactive_update"))
expect_true(otel_collect_is_enabled("reactive_update", "reactive_update"))
expect_false(otel_collect_is_enabled("reactivity", "reactive_update"))
expect_false(otel_collect_is_enabled("all", "reactive_update"))
})
test_that("otel_collect_is_enabled respects hierarchy with 'reactivity' option", {
# With "reactivity" option, all except "all" should be enabled
expect_true(otel_collect_is_enabled("none", "reactivity"))
expect_true(otel_collect_is_enabled("session", "reactivity"))
expect_true(otel_collect_is_enabled("reactive_update", "reactivity"))
expect_true(otel_collect_is_enabled("reactivity", "reactivity"))
expect_false(otel_collect_is_enabled("all", "reactivity"))
})
test_that("otel_collect_is_enabled respects hierarchy with 'all' option", {
# With "all" option (default), everything should be enabled
expect_true(otel_collect_is_enabled("none", "all"))
expect_true(otel_collect_is_enabled("session", "all"))
expect_true(otel_collect_is_enabled("reactive_update", "all"))
expect_true(otel_collect_is_enabled("reactivity", "all"))
expect_true(otel_collect_is_enabled("all", "all"))
})
test_that("otel_collect_is_enabled uses shiny.otel.collect option", {
# Test that option is respected
withr::with_options(
list(shiny.otel.collect = "session"),
{
expect_true(otel_collect_is_enabled("none"))
expect_true(otel_collect_is_enabled("session"))
expect_false(otel_collect_is_enabled("reactive_update"))
}
)
withr::with_options(
list(shiny.otel.collect = "reactivity"),
{
expect_true(otel_collect_is_enabled("reactive_update"))
expect_true(otel_collect_is_enabled("reactivity"))
expect_false(otel_collect_is_enabled("all"))
}
)
})
test_that("otel_collect_is_enabled falls back to SHINY_OTEL_COLLECT env var", {
# Remove option to test env var fallback
withr::local_options(list(shiny.otel.collect = NULL))
# Test env var is respected
withr::local_envvar(list(SHINY_OTEL_COLLECT = "session"))
expect_true(otel_collect_is_enabled("none"))
expect_true(otel_collect_is_enabled("session"))
expect_false(otel_collect_is_enabled("reactive_update"))
withr::local_envvar(list(SHINY_OTEL_COLLECT = "none"))
expect_true(otel_collect_is_enabled("none"))
expect_false(otel_collect_is_enabled("session"))
})
test_that("otel_collect_is_enabled option takes precedence over env var", {
# Set conflicting option and env var
withr::local_options(shiny.otel.collect = "session")
withr::local_envvar(SHINY_OTEL_COLLECT = "all")
# Option should take precedence
expect_true(otel_collect_is_enabled("session"))
expect_false(otel_collect_is_enabled("reactive_update"))
})
test_that("otel_collect_is_enabled defaults to 'all' when no option or env var", {
# Remove both option and env var
withr::local_options(list(shiny.otel.collect = NULL))
withr::local_envvar(list(SHINY_OTEL_COLLECT = NA))
# Should default to "all"
expect_true(otel_collect_is_enabled("all"))
expect_true(otel_collect_is_enabled("reactivity"))
expect_true(otel_collect_is_enabled("none"))
})
# Tests for as_otel_collect()
test_that("as_otel_collect validates and returns valid collect levels", {
expect_equal(as_otel_collect("none"), "none")
expect_equal(as_otel_collect("session"), "session")
expect_equal(as_otel_collect("reactive_update"), "reactive_update")
expect_equal(as_otel_collect("reactivity"), "reactivity")
expect_equal(as_otel_collect("all"), "all")
})
test_that("as_otel_collect uses default value", {
expect_equal(as_otel_collect(), "all")
})
test_that("as_otel_collect errors on invalid input types", {
expect_error(as_otel_collect(123), "`collect` must be a character vector.")
expect_error(as_otel_collect(NULL), "`collect` must be a character vector.")
expect_error(as_otel_collect(TRUE), "`collect` must be a character vector.")
expect_error(as_otel_collect(list("all")), "`collect` must be a character vector.")
})
test_that("as_otel_collect errors on invalid collect levels", {
expect_error(as_otel_collect("invalid"), "'arg' should be one of")
expect_error(as_otel_collect("unknown"), "'arg' should be one of")
expect_error(as_otel_collect(""), "'arg' should be one of")
})
test_that("as_otel_collect errors on multiple values", {
# match.arg with several.ok = FALSE should error on multiple values
expect_error(as_otel_collect(c("all", "none")), "'arg' must be of length 1")
expect_error(as_otel_collect(c("session", "reactivity")), "'arg' must be of length 1")
})

View File

@@ -0,0 +1,231 @@
skip_on_cran()
skip_if_not_installed("otelsdk")
create_mock_session <- function() {
session <- MockShinySession$new()
session$token <- "test-session-token"
session
}
expect_session_warning <- function(session, warning) {
testthat::expect_warning(
capture.output(
type = "message",
{
session$flushReact()
}
),
warning
)
}
exception_trace_events <- function(traces) {
unlist(lapply(traces, function(trace) {
if (is.null(trace$events)) return(list())
events <- Filter(function(event) {
!is.null(event$attributes) &&
!is.null(event$attributes[["exception.message"]])
}, trace$events)
events
}), recursive = FALSE)
}
test_server_with_otel_error <- function(session, server, expr, sanitize = FALSE, args = list()) {
stopifnot(inherits(session, "MockShinySession"))
stopifnot(is.function(server))
traces <- with_shiny_otel_record({ 42 })$traces
expect_length(traces, 0)
withr::with_options(
list(
shiny.otel.collect = "all",
shiny.otel.sanitize.errors = sanitize
),
{
info <- with_shiny_otel_record({
# rlang quosure magic to capture and pass through `expr`
testServer(server, {{ expr }}, args = args, session = session)
})
}
)
info$traces
}
test_that("mark_otel_exception_as_seen() returns modified condition", {
cnd <- simpleError("test error")
result <- mark_otel_exception_as_seen(cnd)
expect_true(inherits(result, "error"))
expect_true(inherits(result, "condition"))
expect_equal(conditionMessage(result), "test error")
expect_true(isTRUE(result$.shiny_otel_exception))
})
test_that("mark_otel_exception_as_seen() marks error as seen", {
cnd <- simpleError("test error")
expect_false(has_seen_otel_exception(cnd))
cnd <- mark_otel_exception_as_seen(cnd)
expect_true(has_seen_otel_exception(cnd))
})
test_that("set_otel_exception_status() records sanitized errors by default", {
server <- function(input, output, session) {
r1 <- reactive(label = "r1", {
stop("test error in r1")
})
r2 <- reactive(label = "r2", {
r1()
})
observe(label = "obs", {
r2()
})
}
session <- create_mock_session()
traces <- test_server_with_otel_error(
sanitize = NULL,
session,
server,
{
# Expect an error to be thrown as warning
expect_session_warning(session, "test error in r1")
}
)
# IDK why, I don't have time to debug
skip_if(length(traces) > 3, "Too many traces collected; otelsdk traces are polluted. Run in single test file only: testthat::test_file(testthat::test_path('test-otel-error.R'))`")
# Find traces with exception events (should only be one)
exception_events <- exception_trace_events(traces)
# Exception should be recorded only once at the original point of failure
expect_equal(length(exception_events), 1)
expect_match(
exception_events[[1]]$attributes[["exception.message"]],
"Check your logs or contact the app author for clarification."
)
})
test_that("set_otel_exception_status() records exception only once in reactive context", {
server <- function(input, output, session) {
r1 <- reactive(label = "r1", {
stop("test error in r1")
})
r2 <- reactive(label = "r2", {
r1()
})
observe(label = "obs", {
r2()
})
}
session <- create_mock_session()
traces <- test_server_with_otel_error(session, server, {
# Expect an error to be thrown as warning
expect_session_warning(session, "test error in r1")
})
# Find traces with error status
for (trace in traces) {
expect_equal(trace$status, "error")
}
# Find traces with exception events (should only be one)
exception_events <- exception_trace_events(traces)
# Exception should be recorded only once at the original point of failure
expect_equal(length(exception_events), 1)
expect_match(
exception_events[[1]]$attributes[["exception.message"]],
"test error in r1"
)
})
test_that("set_otel_exception_status() records exception for multiple independent errors", {
server <- function(input, output, session) {
r1 <- reactive(label = "r1", {
stop("error in r1")
})
r2 <- reactive(label = "r2", {
stop("error in r2")
})
observe(label = "obs1", {
r1()
})
observe(label = "obs2", {
r2()
})
}
session <- create_mock_session()
traces <- test_server_with_otel_error(session, server, {
# Both observers should error
expect_session_warning(session, "error in r1")
})
# Find traces with exception events
exception_events <- exception_trace_events(traces)
# Each unique error should be recorded once
expect_gte(length(exception_events), 1)
})
test_that("set_otel_exception_status() does not record shiny.custom.error", {
server <- function(input, output, session) {
r <- reactive(label = "r", {
cnd <- simpleError("custom error")
class(cnd) <- c("shiny.custom.error", class(cnd))
stop(cnd)
})
observe(label = "obs", {
r()
})
}
session <- create_mock_session()
traces <- test_server_with_otel_error(session, server, {
expect_session_warning(session, "custom error")
})
# Find traces with error status (should be none for custom errors)
for (trace in traces) {
expect_true(trace$status != "error")
}
})
test_that("set_otel_exception_status() does not record shiny.silent.error", {
server <- function(input, output, session) {
r <- reactive(label = "r", {
cnd <- simpleError("silent error")
class(cnd) <- c("shiny.silent.error", class(cnd))
stop(cnd)
})
observe(label = "obs", {
r()
})
}
session <- create_mock_session()
traces <- test_server_with_otel_error(session, server, {
expect_no_error(session$flushReact())
})
# Find traces with error status (should be none for silent errors)
for (trace in traces) {
expect_true(trace$status != "error")
}
})

View File

@@ -0,0 +1,288 @@
# Tests for label methods used in otel-collect.R
test_that("otel_span_label_reactive generates correct labels", {
# Create mock reactive with observable attribute
x_reactive <- reactive({ 42 })
# Create mock observable with label
x_observe <- observe({ 42 })
# Test without domain
result <- otel_span_label_reactive(x_reactive, domain = MockShinySession$new())
expect_equal(result, "reactive mock-session:x_reactive")
# Test with cache class
x_reactive_cache <- bindCache(x_reactive, {"cacheKey"})
result <- otel_span_label_reactive(x_reactive_cache, domain = NULL)
expect_equal(result, "reactive cache x_reactive_cache")
x_reactive_cache <- x_reactive |> bindCache({"cacheKey"})
result <- otel_span_label_reactive(x_reactive_cache, domain = NULL)
expect_equal(result, "reactive cache x_reactive_cache")
x_reactive_cache <- reactive({42}) |> bindCache({"cacheKey"})
result <- otel_span_label_reactive(x_reactive_cache, domain = NULL)
expect_equal(result, "reactive cache x_reactive_cache")
# Test with event class
x_reactive_event <- bindEvent(x_reactive, {"eventKey"})
result <- otel_span_label_reactive(x_reactive_event, domain = NULL)
expect_equal(result, "reactive event x_reactive_event")
x_reactive_event <- x_reactive |> bindEvent({"eventKey"})
result <- otel_span_label_reactive(x_reactive_event, domain = NULL)
expect_equal(result, "reactive event x_reactive_event")
result <- otel_span_label_reactive(x_reactive |> bindEvent({"eventKey"}), domain = NULL)
expect_equal(result, "reactive event <anonymous>")
x_reactive_event <- reactive({42}) |> bindEvent({"eventKey"})
result <- otel_span_label_reactive(x_reactive_event, domain = NULL)
expect_equal(result, "reactive event x_reactive_event")
# x_reactive_both <- bindCache(bindEvent(x_reactive, {"eventKey"}), {"cacheKey"})
# result <- otel_span_label_reactive(x_reactive_both, domain = NULL)
# expect_equal(result, "reactive event cache x_reactive_both")
x_reactive_both2 <- bindEvent(bindCache(x_reactive, {"cacheKey"}), {"eventKey"})
result <- otel_span_label_reactive(x_reactive_both2, domain = NULL)
expect_equal(result, "reactive cache event x_reactive_both2")
})
test_that("reactive bindCache labels are created", {
x_reactive <- reactive({ 42 })
x_reactive_cache <- bindCache(x_reactive, {"cacheKey"})
expect_equal(
as.character(attr(x_reactive_cache, "observable")$.label),
"x_reactive_cache"
)
f_cache <- function() {
bindCache(x_reactive, {"cacheKey"})
}
x_reactive_cache <- f_cache()
expect_equal(
as.character(attr(x_reactive_cache, "observable")$.label),
"cachedReactive(x_reactive)"
)
expect_equal(
otel_span_label_reactive(x_reactive_cache, domain = NULL),
"reactive cache <anonymous>"
)
})
test_that("ExtendedTask otel labels are created", {
ex_task <- ExtendedTask$new(function() { promises::then(promises::promise_resolve(42), force) })
info <- with_shiny_otel_record({
ex_task$invoke()
while(!later::loop_empty()) {
later::run_now()
}
})
trace <- info$traces[[1]]
expect_equal(
trace$name,
"ExtendedTask ex_task"
)
withReactiveDomain(MockShinySession$new(), {
ex2_task <- ExtendedTask$new(function() { promises::then(promises::promise_resolve(42), force) })
info <- with_shiny_otel_record({
ex2_task$invoke()
while(!later::loop_empty()) {
later::run_now()
}
})
})
trace <- info$traces[[1]]
expect_equal(
trace$name,
"ExtendedTask mock-session:ex2_task"
)
})
test_that("otel_span_label_reactive with pre-defined label", {
x_reactive <- reactive({ 42 }, label = "counter")
result <- otel_span_label_reactive(x_reactive, domain = MockShinySession$new())
expect_equal(result, "reactive mock-session:counter")
result <- otel_span_label_reactive(x_reactive, domain = NULL)
expect_equal(result, "reactive counter")
})
test_that("observer labels are preserved", {
x_observe <- observe({ 42 }, label = "my_observer")
expect_equal(x_observe$.label, "my_observer")
expect_equal(otel_span_label_observer(x_observe, domain = NULL), "observe my_observer")
x_observe <- observe({ 42 })
expect_equal(x_observe$.label, "x_observe")
expect_equal(otel_span_label_observer(x_observe, domain = NULL), "observe x_observe")
f <- function() {
observe({ 42 })
}
x_observe <- f()
expect_equal(x_observe$.label, as_default_label("observe({\n 42\n})"))
expect_equal(otel_span_label_observer(x_observe, domain = NULL), "observe <anonymous>")
})
test_that("otel_span_label_observer generates correct labels", {
x_observe <- observe({ 42 }, label = "test_observer" )
result <- otel_span_label_observer(x_observe, domain = MockShinySession$new())
expect_equal(result, "observe mock-session:test_observer")
result <- otel_span_label_observer(x_observe, domain = NULL)
expect_equal(result, "observe test_observer")
x_observe_event <- bindEvent(x_observe, {"eventKey"})
result <- otel_span_label_observer(x_observe_event, domain = NULL)
expect_equal(result, "observe event x_observe_event")
x_observe_event <- observe({ 42 }, label = "test_observer" ) |> bindEvent({"eventKey"})
result <- otel_span_label_observer(x_observe_event, domain = NULL)
expect_equal(result, "observe event x_observe_event")
result <- otel_span_label_observer(observe({ 42 }, label = "test_observer" ) |> bindEvent({"eventKey"}), domain = NULL)
expect_equal(result, "observe event <anonymous>")
x_observe <- observe({ 42 }, label = "test_observer" )
x_observe_event <- x_observe |> bindEvent({"eventKey"})
result <- otel_span_label_observer(x_observe_event, domain = NULL)
expect_equal(result, "observe event x_observe_event")
})
test_that("throttle otel span label is correct", {
x_reactive <- reactive({ 42 })
x_throttled1 <- throttle(x_reactive, 1000)
x_throttled2 <- x_reactive |> throttle(1000)
x_throttled3 <- reactive({ 42 }) |> throttle(1000)
expect_equal(
as.character(attr(x_throttled1, "observable")$.label),
"throttle x_throttled1 result"
)
expect_equal(
as.character(attr(x_throttled2, "observable")$.label),
"throttle x_throttled2 result"
)
expect_equal(
as.character(attr(x_throttled3, "observable")$.label),
"throttle x_throttled3 result"
)
expect_equal(attr(x_throttled1, "observable")$.otelLabel, "throttle x_throttled1")
expect_equal(attr(x_throttled2, "observable")$.otelLabel, "throttle x_throttled2")
expect_equal(attr(x_throttled3, "observable")$.otelLabel, "throttle x_throttled3")
})
test_that("debounce otel span label is correct", {
x_reactive <- reactive({ 42 })
x_debounced1 <- debounce(x_reactive, 1000)
x_debounced2 <- x_reactive |> debounce(1000)
x_debounced3 <- reactive({ 42 }) |> debounce(1000)
expect_equal(
as.character(attr(x_debounced1, "observable")$.label),
"debounce x_debounced1 result"
)
expect_equal(
as.character(attr(x_debounced2, "observable")$.label),
"debounce x_debounced2 result"
)
expect_equal(
as.character(attr(x_debounced3, "observable")$.label),
"debounce x_debounced3 result"
)
expect_equal(attr(x_debounced1, "observable")$.otelLabel, "debounce x_debounced1")
expect_equal(attr(x_debounced2, "observable")$.otelLabel, "debounce x_debounced2")
expect_equal(attr(x_debounced3, "observable")$.otelLabel, "debounce x_debounced3")
})
test_that("otel_span_label_observer handles module namespacing", {
x_observe <- observe({ 42 }, label = "clicks" )
result <- otel_span_label_observer(x_observe, domain = MockShinySession$new())
expect_equal(result, "observe mock-session:clicks")
})
test_that("otel_span_label_render_function generates correct labels", {
x_render <- renderText({ "Hello" })
mock_domain <- MockShinySession$new()
testthat::local_mocked_bindings(
getCurrentOutputInfo = function(session) {
list(name = "plot1")
}
)
result <- otel_span_label_render_function(x_render, domain = NULL)
expect_equal(result, "output plot1")
result <- otel_span_label_render_function(x_render, domain = mock_domain)
expect_equal(result, "output mock-session:plot1")
x_render_event <- bindEvent(x_render, {"eventKey"})
result <- otel_span_label_render_function(x_render_event, domain = mock_domain)
expect_equal(result, "output event mock-session:plot1")
x_render_cache <- bindCache(x_render, {"cacheKey"})
result <- otel_span_label_render_function(x_render_cache, domain = mock_domain)
expect_equal(result, "output cache mock-session:plot1")
x_render_both <- bindEvent(bindCache(x_render, {"cacheKey"}), {"eventKey"})
result <- otel_span_label_render_function(x_render_both, domain = mock_domain)
expect_equal(result, "output cache event mock-session:plot1")
})
test_that("otel_span_label_render_function handles cache and event classes", {
testthat::local_mocked_bindings(
getCurrentOutputInfo = function(session) {
list(name = "table1")
}
)
x_render <- renderText({ "Hello" })
x_render_event <- bindEvent(x_render, {"eventKey"})
x_render_cache <- bindCache(x_render, {"cacheKey"})
x_render_both <- bindEvent(bindCache(x_render, {"cacheKey"}), {"eventKey"})
mock_domain <- MockShinySession$new()
result <- otel_span_label_render_function(x_render, domain = NULL)
expect_equal(result, "output table1")
result <- otel_span_label_render_function(x_render, domain = mock_domain)
expect_equal(result, "output mock-session:table1")
result <- otel_span_label_render_function(x_render_event, domain = mock_domain)
expect_equal(result, "output event mock-session:table1")
result <- otel_span_label_render_function(x_render_cache, domain = mock_domain)
expect_equal(result, "output cache mock-session:table1")
result <- otel_span_label_render_function(x_render_both, domain = mock_domain)
expect_equal(result, "output cache event mock-session:table1")
})
test_that("otel_label_upgrade handles anonymous labels", {
# Test default labels with parentheses get converted to <anonymous>
result <- otel_label_upgrade(as_default_label("observe({})"), domain = NULL)
expect_equal(result, "<anonymous>")
result <- otel_label_upgrade(as_default_label("eventReactive(input$btn, {})"), domain = NULL)
expect_equal(result, "<anonymous>")
# Test regular labels are kept as-is
result <- otel_label_upgrade(as_default_label("my_observer"), domain = NULL)
expect_equal(as.character(result), "my_observer")
result <- otel_label_upgrade("my_observer", domain = NULL)
expect_equal(result, "my_observer")
})

View File

@@ -0,0 +1,256 @@
skip_on_cran()
skip_if_not_installed("otelsdk")
expect_code_attrs <- function(trace) {
testthat::expect_true(!is.null(trace))
testthat::expect_true(is.list(trace$attributes))
testthat::expect_true(is.character(trace$attributes[["code.filepath"]]))
testthat::expect_equal(trace$attributes[["code.filepath"]], "test-otel-mock.R")
testthat::expect_true(is.numeric(trace$attributes[["code.lineno"]]))
testthat::expect_true(is.numeric(trace$attributes[["code.column"]]))
invisible(trace)
}
MOCK_SESSION_TOKEN <- "test-session-token"
expect_session_id <- function(trace) {
testthat::expect_true(!is.null(trace))
testthat::expect_true(is.list(trace$attributes))
testthat::expect_true(is.character(trace$attributes[["session.id"]]))
testthat::expect_equal(trace$attributes[["session.id"]], MOCK_SESSION_TOKEN)
invisible(trace)
}
expect_trace <- function(traces, name, pos = 1) {
# Filter to traces with the given name
trace_set <- traces[which(names(traces) == name)]
testthat::expect_gte(length(trace_set), pos)
# Get the trace at the given position
trace <- trace_set[[pos]]
testthat::expect_true(is.list(trace))
expect_code_attrs(trace)
expect_session_id(trace)
trace
}
create_mock_session <- function() {
session <- MockShinySession$new()
session$token <- MOCK_SESSION_TOKEN
session
}
test_server_with_otel <- function(session, server, expr, bind = "all", args = list()) {
stopifnot(inherits(session, "MockShinySession"))
stopifnot(is.function(server))
withr::with_options(list(shiny.otel.collect = bind), {
info <- with_shiny_otel_record({
# rlang quosure magic to capture and pass through `expr`
testServer(server, {{ expr }}, args = args, session = session)
})
})
info$traces
}
for (bind in c("all", "reactivity")) {
test_that(paste0("bind='", bind, "' handles observers"), {
server <- function(input, output, session) {
observe({
42
})
my_observe <- observe({
43
})
observe({
44
}, label = "labeled observer")
}
session <- create_mock_session()
traces <- test_server_with_otel(session, server, bind = bind, {
# probably not needed to do anything here
session$flushReact()
})
expect_trace(traces, "observe mock-session:<anonymous>")
expect_trace(traces, "observe mock-session:my_observe")
expect_trace(traces, "observe mock-session:labeled observer")
})
test_that(paste0("bind='", bind, "' handles reactiveVal / reactiveValues"), {
server <- function(input, output, session) {
rv <- reactiveVal(0)
rv2 <- (function() {reactiveVal(0)})() # test anonymous reactiveVal
rv3 <- reactiveVal(0, "labeled_rv")
observe({
isolate({
rv(rv() + 1)
rv2(rv2() + 1)
rv3(rv3() + 1)
})
})
}
session <- create_mock_session()
traces <- test_server_with_otel(session, server, bind = bind, {
session$flushReact()
expect_equal(rv(), 1)
})
expect_trace(traces, "observe mock-session:<anonymous>")
# TODO-future: Add tests to see the `Set reactiveVal mock-session:rv` logs
# Requires: https://github.com/r-lib/otelsdk/issues/21
})
test_that(paste0("bind='", bind, "' handles reactive"), {
server <- function(input, output, session) {
r <- reactive({ 42 })
r2 <- (function() {reactive({ r() })})() # test anonymous reactive
r3 <- reactive({ r2() }, label = "labeled_rv")
observe(label = "obs_r3", {
r3()
})
}
session <- create_mock_session()
traces <- test_server_with_otel(session, server, bind = bind, {
session$flushReact()
session$flushReact()
session$flushReact()
expect_equal(r(), 42)
expect_equal(r2(), 42)
expect_equal(r3(), 42)
})
observe_trace <- expect_trace(traces, "observe mock-session:obs_r3")
r_trace <- expect_trace(traces, "reactive mock-session:r")
r2_trace <- expect_trace(traces, "reactive mock-session:<anonymous>")
r3_trace <- expect_trace(traces, "reactive mock-session:labeled_rv")
expect_equal(r_trace$parent, r2_trace$span_id)
expect_equal(r2_trace$parent, r3_trace$span_id)
expect_equal(r3_trace$parent, observe_trace$span_id)
})
test_that(paste0("bind='", bind, "' outputs are supported"), {
server <- function(input, output, session) {
output$txt <- renderText({
"Hello, world!"
})
}
session <- create_mock_session()
traces <- test_server_with_otel(session, server, bind = bind, {
session$flushReact()
session$flushReact()
session$flushReact()
expect_equal(output$txt, "Hello, world!")
})
expect_trace(traces, "output mock-session:txt")
})
test_that(paste0("bind='", bind, "' extended tasks are supported"), {
server <- function(input, output, session) {
rand_task <- ExtendedTask$new(function() {
promise_resolve(42) |> promises::then(function(value) {
value
})
})
observe(label = "invoke task", {
rand_task$invoke()
})
output$result <- renderText({
# React to updated results when the task completes
number <- rand_task$result()
paste0("Your number is ", number, ".")
})
}
session <- create_mock_session()
traces <- test_server_with_otel(session, server, bind = bind, {
session$flushReact()
while(!later::loop_empty()) {
later::run_now()
session$flushReact()
}
session$flushReact()
})
invoke_obs <- expect_trace(traces, "observe mock-session:invoke task")
render1_trace <- expect_trace(traces, "output mock-session:result")
ex_task_trace <- expect_trace(traces, "ExtendedTask mock-session:rand_task")
render2_trace <- expect_trace(traces, "output mock-session:result", pos = 2)
expect_equal(invoke_obs$span_id, ex_task_trace$parent)
})
}
test_that("bind = 'reactivity' traces reactive components", {
server <- function(input, output, session) {
r <- reactive({ 42 })
observe(label = "test_obs", {
r()
})
output$txt <- renderText({
"Hello"
})
}
session <- create_mock_session()
traces <- test_server_with_otel(session, server, bind = "reactivity", {
session$flushReact()
expect_equal(r(), 42)
})
# Should trace reactive components (equivalent to "all")
expect_trace(traces, "observe mock-session:test_obs")
expect_trace(traces, "reactive mock-session:r")
expect_trace(traces, "output mock-session:txt")
})
for (bind in c("reactive_update", "session", "none")) {
test_that(paste0("bind = '", bind, "' traces reactive components"), {
server <- function(input, output, session) {
r <- reactive({ 42 })
observe(label = "test_obs", {
r()
})
output$txt <- renderText({
"Hello"
})
}
session <- create_mock_session()
traces <- test_server_with_otel(session, server, bind = bind, {
session$flushReact()
expect_equal(r(), 42)
})
trace_names <- names(traces)
expect_false(any(grepl("observe", trace_names)))
expect_false(any(grepl("reactive", trace_names)))
expect_false(any(grepl("output", trace_names)))
})
}

View File

@@ -0,0 +1,229 @@
# Tests for otel-reactive-update.R functions
# Helper function to create a mock otel span
create_mock_otel_span <- function(name, attributes = NULL, ended = FALSE) {
structure(
list(name = name, attributes = attributes, ended = ended),
class = c("mock_otel_span", "otel_span")
)
}
test_that("otel_span_reactive_update_init returns early when otel not enabled", {
domain <- MockShinySession$new()
# Convince has_otel_collect to return FALSE
withr::local_options(list(shiny.otel.collect = "none"))
# Should return early without creating span
result <- otel_span_reactive_update_init(domain = domain)
expect_null(result)
expect_null(domain$userData[["_otel_span_reactive_update"]])
})
test_that("otel_span_reactive_update_init sets up session cleanup on first call", {
callback_added <- FALSE
TestMockShinySession <- R6::R6Class(
"TestMockShinySession",
inherit = MockShinySession,
portable = FALSE,
lock_objects = FALSE,
public = list(
# Mock onSessionEnded to track if callback is added
onSessionEnded = function(callback) {
callback_added <<- TRUE
expect_true(is.function(callback))
}
)
)
domain <- TestMockShinySession$new()
withr::local_options(list(shiny.otel.collect = "reactive_update"))
local_mocked_bindings(
has_otel_collect = function(level) level == "reactive_update",
start_otel_span = function(name, ..., attributes = NULL) create_mock_otel_span(name, attributes = attributes),
otel_session_id_attrs = function(domain) list(session_id = "mock-session-id")
)
otel_span_reactive_update_init(domain = domain)
expect_true(callback_added)
expect_true(domain$userData[["_otel_has_reactive_cleanup"]])
expect_equal(
domain$userData[["_otel_span_reactive_update"]],
create_mock_otel_span("reactive_update", attributes = list(session_id = "mock-session-id"))
)
})
test_that("otel_span_reactive_update_init errors when span already exists", {
domain <- MockShinySession$new()
domain$token <- "mock-session-token"
# Set up existing span
existing_otel_span <- create_mock_otel_span("reactive_update", attributes = list(session.id = "mock-session-token"))
domain$userData[["_otel_span_reactive_update"]] <- existing_otel_span
local_mocked_bindings(
has_otel_collect = function(level) level == "reactive_update"
)
expect_error(
otel_span_reactive_update_init(domain = domain),
"Reactive update span already exists"
)
})
test_that("otel_span_reactive_update_init doesn't setup cleanup twice", {
TestMockShinySession <- R6::R6Class(
"TestMockShinySession",
inherit = MockShinySession,
portable = FALSE,
lock_objects = FALSE,
public = list(
# Mock onSessionEnded to track how many times callback is added
callback_count = 0,
onSessionEnded = function(callback) {
self$callback_count <- self$callback_count + 1
expect_true(is.function(callback))
}
)
)
domain <- TestMockShinySession$new()
# Set cleanup flag manually
domain$userData[["_otel_has_reactive_cleanup"]] <- TRUE
local_mocked_bindings(
has_otel_collect = function(level) level == "reactive_update",
start_otel_span = function(...) create_mock_otel_span("reactive_update")
)
otel_span_reactive_update_init(domain = domain)
# Should not have called onSessionEnded since cleanup was already set
expect_equal(domain$callback_count, 0)
})
test_that("otel_span_reactive_update_teardown ends span when it exists", {
domain <- MockShinySession$new()
mock_otel_span <- create_mock_otel_span("reactive_update")
domain$userData[["_otel_span_reactive_update"]] <- mock_otel_span
span_ended <- FALSE
local_mocked_bindings(
end_span = function(span) {
span_ended <<- TRUE
expect_equal(span, mock_otel_span)
},
.package = "otel"
)
otel_span_reactive_update_teardown(domain = domain)
expect_true(span_ended)
expect_null(domain$userData[["_otel_span_reactive_update"]])
})
test_that("otel_span_reactive_update_teardown handles missing span gracefully", {
domain <- MockShinySession$new()
# No span exists
expect_null(domain$userData[["_otel_span_reactive_update"]])
# Should not error
expect_no_error(otel_span_reactive_update_teardown(domain = domain))
})
test_that("with_otel_span_reactive_update executes expr without span", {
domain <- MockShinySession$new()
# No span exists
test_value <- "initial"
local_mocked_bindings(
is_otel_span = function(x) FALSE
)
result <- with_otel_span_reactive_update({
test_value <- "modified"
"result_value"
}, domain = domain)
expect_equal(result, "result_value")
expect_equal(test_value, "modified")
})
test_that("with_otel_span_reactive_update executes expr with active span", {
domain <- MockShinySession$new()
mock_otel_span <- create_mock_otel_span("reactive_update")
domain$userData[["_otel_span_reactive_update"]] <- mock_otel_span
span_was_active <- FALSE
test_value <- "initial"
local_mocked_bindings(
with_active_span = function(span, expr) {
span_was_active <<- TRUE
expect_equal(span, mock_otel_span)
force(expr)
},
.package = "otel"
)
result <- with_otel_span_reactive_update({
test_value <- "modified"
"result_value"
}, domain = domain)
expect_true(span_was_active)
expect_equal(result, "result_value")
expect_equal(test_value, "modified")
})
test_that("session cleanup callback works correctly", {
TestMockShinySession <- R6::R6Class(
"TestMockShinySession",
inherit = MockShinySession,
portable = FALSE,
lock_objects = FALSE,
public = list(
# Mock onSessionEnded to capture the callback
onSessionEnded = function(callback) {
self$cleanup_callback <<- callback
},
cleanup_callback = NULL
)
)
domain <- TestMockShinySession$new()
mock_otel_span <- create_mock_otel_span("reactive_update")
with_mocked_bindings(
has_otel_collect = function(level) level == "reactive_update",
start_otel_span = function(...) mock_otel_span,
otel_session_id_attrs = function(domain) list(session_id = "test"),
{
otel_span_reactive_update_init(domain = domain)
}
)
# Verify cleanup callback was registered
expect_true(is.function(domain$cleanup_callback))
# Set up span and test cleanup
domain$userData[["_otel_span_reactive_update"]] <- mock_otel_span
domain$userData[["_otel_has_reactive_cleanup"]] <- TRUE
span_ended <- FALSE
with_mocked_bindings(
otel_span_reactive_update_teardown = function(domain = NULL) {
span_ended <<- TRUE
},
{
# Execute the cleanup callback
domain$cleanup_callback()
expect_true(span_ended)
}
)
})

View File

@@ -0,0 +1,288 @@
# Tests for otel-session.R functions
# Helper function to create a mock domain with request info
create_mock_session_domain <- function(
token = "test-session-123",
request = list(),
session_ended_callbacks = list()
) {
TestMockShinySession <- R6::R6Class(
"TestMockShinySession",
inherit = MockShinySession,
portable = FALSE,
lock_objects = FALSE,
public = list(
# Mock onSessionEnded to capture the callback
onSessionEnded = function(callback) {
expect_true(is.function(callback))
self$cleanup_callbacks <- c(self$cleanup_callbacks, list(callback))
},
cleanup_callbacks = NULL,
request_val = NULL
),
active = list(
request = function(value) {
if (!missing(value)) {
self$request_val <- value
} else {
self$request_val
}
}
)
)
domain <- TestMockShinySession$new()
domain$request <- request
domain$token <- token
domain
}
test_that("otel_span_session_start returns early when otel not enabled", {
domain <- create_mock_session_domain()
test_value <- "initial"
# Mock has_otel_collect to return FALSE
withr::local_options(list(shiny.otel.collect = "none"))
result <- otel_span_session_start({
test_value <- "modified"
"result_value"
}, domain = domain)
expect_equal(result, "result_value")
expect_equal(test_value, "modified")
# Should not have registered any callbacks
expect_length(domain$cleanup_callbacks, 0)
})
test_that("otel_span_session_start sets up session end callback", {
domain <- create_mock_session_domain(
token = "session-456",
request = list(PATH_INFO = "/app", HTTP_HOST = "localhost")
)
test_value <- "initial"
# Mock dependencies
withr::local_options(list(shiny.otel.collect = "session"))
local_mocked_bindings(
as_attributes = function(x) x,
.package = "otel"
)
with_mocked_bindings(
has_otel_collect = function(level) level == "session",
otel_session_id_attrs = function(domain) list(session.id = domain$token),
otel_session_attrs = function(domain) list(PATH_INFO = "/app"),
with_otel_span = function(name, expr, attributes = NULL) {
expect_equal(name, "session_start")
expect_true("session.id" %in% names(attributes))
expect_equal(attributes[["session.id"]], "session-456")
force(expr)
},
{
expect_length(domain$cleanup_callbacks, 0)
result <- otel_span_session_start({
test_value <- "modified"
"result_value"
}, domain = domain)
expect_equal(result, "result_value")
expect_equal(test_value, "modified")
expect_length(domain$cleanup_callbacks, 0)
}
)
})
test_that("otel_span_session_end returns early when otel not enabled", {
domain <- create_mock_session_domain()
test_value <- "initial"
# Mock has_otel_collect to return FALSE
withr::local_options(list(shiny.otel.collect = "none"))
result <- otel_span_session_end({
test_value <- "modified"
"result_value"
}, domain = domain)
expect_equal(result, "result_value")
expect_equal(test_value, "modified")
})
test_that("otel_span_session_end creates span when enabled", {
domain <- create_mock_session_domain(token = "session-end-test")
span_created <- FALSE
test_value <- "initial"
# Mock dependencies
withr::local_options(list(shiny.otel.collect = "session"))
with_mocked_bindings(
has_otel_collect = function(level) level == "session",
otel_session_id_attrs = function(domain) list(session.id = domain$token),
with_otel_span = function(name, expr, attributes = NULL) {
span_created <<- TRUE
expect_equal(name, "session_end")
expect_equal(attributes[["session.id"]], "session-end-test")
force(expr)
},
{
result <- otel_span_session_end({
test_value <- "modified"
"result_value"
}, domain = domain)
expect_equal(result, "result_value")
expect_equal(test_value, "modified")
expect_true(span_created)
}
)
})
test_that("otel_session_attrs extracts request attributes correctly", {
# Test with full request info
domain <- create_mock_session_domain(
request = list(
PATH_INFO = "/myapp/page",
HTTP_HOST = "example.com",
HTTP_ORIGIN = "https://example.com",
SERVER_PORT = "8080"
)
)
attrs <- otel_session_attrs(domain)
expect_equal(attrs$server.path, "/myapp/page")
expect_equal(attrs$server.address, "example.com")
expect_equal(attrs$server.origin, "https://example.com")
expect_equal(attrs$server.port, 8080L) # Should be converted to integer
})
test_that("otel_session_attrs handles websocket PATH_INFO", {
domain <- create_mock_session_domain(
request = list(
PATH_INFO = "/myapp/websocket/",
HTTP_HOST = "localhost"
)
)
attrs <- otel_session_attrs(domain)
# Should strip websocket suffix
expect_equal(attrs$server.path, "/myapp/")
})
test_that("otel_session_attrs handles missing request fields", {
# Test with minimal request info
domain <- create_mock_session_domain(
request = list(
HTTP_HOST = "localhost"
)
)
attrs <- otel_session_attrs(domain)
expect_equal(attrs$server.path, "")
expect_equal(attrs$server.address, "localhost")
expect_equal(attrs$server.origin, "")
expect_equal(attrs$server.port, NA_integer_)
})
test_that("otel_session_attrs handles empty request", {
domain <- create_mock_session_domain(request = list())
attrs <- otel_session_attrs(domain)
expect_equal(attrs$server.path, "")
expect_equal(attrs$server.address, "")
expect_equal(attrs$server.origin, "")
expect_equal(attrs$server.port, NA_integer_)
})
test_that("otel_session_attrs handles invalid SERVER_PORT gracefully", {
domain <- create_mock_session_domain(
request = list(SERVER_PORT = "invalid")
)
# Should not error even with invalid port
attrs <- otel_session_attrs(domain)
# Should remain as string if conversion fails
expect_equal(attrs$server.port, "invalid")
})
test_that("otel_session_id_attrs returns correct session ID", {
domain <- create_mock_session_domain(token = "unique-session-token")
attrs <- otel_session_id_attrs(domain)
expect_equal(attrs$session.id, "unique-session-token")
expect_length(attrs, 1)
})
test_that("otel_session_id_attrs handles missing token", {
domain <- create_mock_session_domain(token = NULL)
attrs <- otel_session_id_attrs(domain)
expect_null(attrs$session.id)
})
test_that("integration test - session start with full request", {
domain <- create_mock_session_domain(
token = "integration-test-session",
request = list(
PATH_INFO = "/dashboard/",
HTTP_HOST = "shiny.example.com",
HTTP_ORIGIN = "https://shiny.example.com",
SERVER_PORT = "3838"
)
)
session_callback <- NULL
span_attributes <- NULL
# Mock dependencies
withr::local_options(list(shiny.otel.collect = "session"))
local_mocked_bindings(
as_attributes = function(x) x,
.package = "otel"
)
with_mocked_bindings(
has_otel_collect = function(level) level == "session",
otel_session_id_attrs = otel_session_id_attrs, # Use real function
otel_session_attrs = otel_session_attrs, # Use real function
with_otel_span = function(name, expr, attributes = NULL) {
span_attributes <<- attributes
force(expr)
},
otel_log = function(...) {}, # Mock log function
{
expect_length(domain$cleanup_callbacks, 0)
result <- otel_span_session_start({
"test_result"
}, domain = domain)
expect_equal(result, "test_result")
# Check span attributes include both session ID and request info
expect_equal(span_attributes[["session.id"]], "integration-test-session")
expect_equal(span_attributes[["server.path"]], "/dashboard/")
expect_equal(span_attributes[["server.address"]], "shiny.example.com")
expect_equal(span_attributes[["server.port"]], 3838L)
}
)
})

View File

@@ -0,0 +1,175 @@
# Tests for otel-shiny.R functions
# Helper function to create a mock otel span
create_mock_otel_span <- function(name = "test_span") {
structure(
list(
name = name,
activate = function(...) NULL,
end = function(...) NULL
),
class = "otel_span"
)
}
# Helper function to create a mock tracer
create_mock_tracer <- function() {
structure(
list(
name = "mock_tracer",
is_enabled = function() TRUE,
start_span = function(name, ...) create_mock_otel_span(name)
),
class = "otel_tracer"
)
}
# Helper function to create a mock logger
create_mock_logger <- function() {
structure(
list(name = "mock_logger"),
class = "otel_logger"
)
}
test_that("otel_tracer_name constant is correct", {
expect_equal(otel_tracer_name, "co.posit.r-package.shiny")
})
test_that("start_otel_span calls otel::start_span with correct parameters", {
mock_tracer <- create_mock_tracer()
mock_span <- create_mock_otel_span()
start_span_called <- FALSE
local_mocked_bindings(
start_span = function(name, ..., tracer = NULL) {
start_span_called <<- TRUE
expect_equal(name, "test_span")
expect_equal(tracer, mock_tracer)
mock_span
},
.package = "otel"
)
local_mocked_bindings(
shiny_otel_tracer = function() mock_tracer,
)
result <- start_otel_span("test_span", extra_param = "value")
expect_true(start_span_called)
expect_equal(result, mock_span)
})
test_that("is_otel_span correctly identifies otel spans", {
# Test with otel_span object
otel_span <- create_mock_otel_span()
expect_true(is_otel_span(otel_span))
# Test with non-otel objects
expect_false(is_otel_span("string"))
expect_false(is_otel_span(123))
expect_false(is_otel_span(list()))
expect_false(is_otel_span(NULL))
# Test with object that has different class
other_obj <- structure(list(), class = "other_class")
expect_false(is_otel_span(other_obj))
})
test_that("testthat__is_testing detects testing environment", {
# Test when TESTTHAT env var is set to "true"
withr::with_envvar(list(TESTTHAT = "true"), {
expect_true(testthat__is_testing())
})
# Test when TESTTHAT env var is not set
withr::with_envvar(list(TESTTHAT = NA), {
expect_false(testthat__is_testing())
})
# Test when TESTTHAT env var is set to other values
withr::with_envvar(list(TESTTHAT = "false"), {
expect_false(testthat__is_testing())
})
withr::with_envvar(list(TESTTHAT = ""), {
expect_false(testthat__is_testing())
})
})
test_that("otel_log calls otel::log with correct parameters", {
mock_logger <- create_mock_logger()
log_called <- FALSE
local_mocked_bindings(
log = function(msg, ..., severity = NULL, logger = NULL) {
log_called <<- TRUE
expect_equal(msg, "test message")
expect_equal(severity, "warn")
expect_equal(logger, mock_logger)
},
.package = "otel"
)
local_mocked_bindings(
shiny_otel_logger = function() mock_logger,
)
otel_log("test message", severity = "warn")
expect_true(log_called)
})
test_that("otel_log uses default severity and logger", {
mock_logger <- create_mock_logger()
log_called <- FALSE
local_mocked_bindings(
log = function(msg, ..., severity = NULL, logger = NULL) {
log_called <<- TRUE
expect_equal(msg, "default test")
expect_equal(severity, "info") # Default severity
expect_equal(logger, mock_logger) # Default logger
},
.package = "otel"
)
local_mocked_bindings(
shiny_otel_logger = function() mock_logger,
)
otel_log("default test")
expect_true(log_called)
})
test_that("integration test - start_otel_span with custom parameters", {
mock_tracer <- create_mock_tracer()
mock_span <- create_mock_otel_span()
start_span_params <- list()
local_mocked_bindings(
start_span = function(name, ..., tracer = NULL) {
start_span_params <<- list(
name = name,
tracer = tracer,
extra_args = list(...)
)
mock_span
},
.package = "otel"
)
local_mocked_bindings(
shiny_otel_tracer = function() mock_tracer,
)
result <- start_otel_span(
"custom_span",
attributes = list(key = "value"),
parent = "parent_span"
)
expect_equal(result, mock_span)
expect_equal(start_span_params$name, "custom_span")
expect_equal(start_span_params$tracer, mock_tracer)
expect_equal(start_span_params$extra_args$attributes, list(key = "value"))
expect_equal(start_span_params$extra_args$parent, "parent_span")
})

View File

@@ -348,12 +348,20 @@ test_that("ggplot coordmap with various scales and coords", {
sortList(list(left=10, right=20, bottom=0, top=5))
)
coord_transform_universal <- function(...) {
if (packageVersion("ggplot2") >= "4.0.0") {
coord_transform(...)
} else {
coord_trans(...)
}
}
# Log scales and log coord transformations
dat <- data.frame(xvar = c(10^-1, 10^3), yvar = c(2^-2, 2^4))
p <- ggplot(dat, aes(xvar, yvar)) + geom_point() +
scale_x_log10(expand = c(0 ,0)) +
scale_y_continuous(expand = c(0, 0)) +
coord_trans(y = "log2")
coord_transform_universal(y = "log2")
png(tmpfile)
m <- getGgplotCoordmap(print(p), 500, 400, 72)
dev.off()

View File

@@ -1,6 +1,6 @@
with_several_promise_domains <- function(expr) {
withReactiveDomain(MockShinySession$new(), {
promises::with_promise_domain(reactivePromiseDomain(), {
with_promise_domain(reactivePromiseDomain(), {
captureStackTraces({
expr
})

View File

@@ -144,7 +144,7 @@ test_that("reactiveValues keys are sorted", {
})
test_that("reactiveValues() has useful print method", {
verify_output(test_path("print-reactiveValues.txt"), {
expect_snapshot_output({
x <- reactiveValues(x = 1, y = 2, z = 3)
x
})
@@ -1656,4 +1656,3 @@ test_that("Contexts can be masked off via promise domains", {
later::run_now(all=FALSE)
}
})

View File

@@ -8,7 +8,9 @@ formatError <- function(err, full = FALSE, offset = TRUE, cleanPaths = TRUE) {
suppressWarnings(
suppressMessages(
withCallingHandlers(
printError(err, full = full, offset = offset),
{
printError(err, full = full, offset = offset)
},
warning = function(cnd) {
cat(conditionMessage(cnd), "\n", sep = "", file = stderr())
},
@@ -89,6 +91,10 @@ describe("deep stack trace filtering", {
})
test_that("deep stack capturing", {
# base::tryCatch internals changed in 4.5.2
skip_unless_r(">= 4.5.2")
skip_if_not_installed("testthat", "3.3.0")
`%...>%` <- promises::`%...>%`
`%...!%` <- promises::`%...!%`
finally <- promises::finally

View File

@@ -26,8 +26,8 @@ causeError <- function(full) {
suppressMessages(df <- extractStackTrace(conditionStackTrace(cond), full = full))
df$loc <- cleanLocs(df$loc)
# Compensate for this test being called from different call sites;
# whack the
df <- head(df, -sys.nframe())
# whack the top n frames off using the `num` frame column
df <- df[df$num >= sys.nframe(), ]
df$num <- df$num - sys.nframe()
df
}
@@ -84,12 +84,18 @@ extractStackTrace <- function(calls,
score[callnames == "..stacktraceon.."] <- 1
toShow <- (1 + cumsum(score)) > 0 & !(callnames %in% c("..stacktraceon..", "..stacktraceoff..", "..stacktracefloor.."))
# doTryCatch, tryCatchOne, and tryCatchList are not informative--they're
# just internals for tryCatch
toShow <- toShow & !(callnames %in% c("doTryCatch", "tryCatchOne", "tryCatchList"))
toShow <-
toShow &
# doTryCatch, tryCatchOne, and tryCatchList are not informative--they're
# just internals for tryCatch
!(callnames %in% c("doTryCatch", "tryCatchOne", "tryCatchList")) &
# doWithOneRestart and withOneRestart are not informative--they're
# just internals for withRestarts
!(callnames %in% c("withOneRestart", "doWithOneRestart"))
}
calls <- calls[toShow]
calls <- rev(calls) # Show in traceback() order
index <- rev(which(toShow))
width <- floor(log10(max(index))) + 1
@@ -118,6 +124,12 @@ dumpTests <- function(df) {
}
test_that("integration tests", {
if (shiny_otel_tracer()$is_enabled()) {
announce_snapshot_file(name = "stacks.md")
skip("Skipping stack trace tests when OpenTelemetry is already enabled")
}
# The expected call stack can be changed by other packages (namely, promises).
# If promises changes its internals, it can break this test on CRAN. Because
# CRAN package releases are generally not synchronized (that is, promises and

View File

@@ -1,6 +1,3 @@
library(shiny)
library(testthat)
test_that("testServer works with dir app", {
# app.R
testServer(test_path("..", "test-modules", "06_tabsets"), {

View File

@@ -1,6 +1,3 @@
library(shiny)
library(testthat)
test_that("Nested modules", {
child <- function(id) {
moduleServer(id, function(input, output, session) {

View File

@@ -1,6 +1,3 @@
library(shiny)
library(testthat)
test_that("Variables outside of the module are inaccessible", {
module <- local({
outside <- 123

View File

@@ -1,7 +1,5 @@
library(shiny)
library(testthat)
skip_if_not_installed("future")
library(future, warn.conflicts = FALSE)
library(promises)
test_that("handles observers", {
server <- function(input, output, session) {
@@ -746,7 +744,7 @@ test_that("promise chains evaluate in correct order", {
server <- function(input, output, session) {
r1 <- reactive({
promise(function(resolve, reject) {
promises::promise(function(resolve, reject) {
pushMessage("promise 1")
resolve(input$go)
})$then(function(value) {
@@ -755,7 +753,7 @@ test_that("promise chains evaluate in correct order", {
})
})
r2 <- reactive({
promise(function(resolve, reject) {
promises::promise(function(resolve, reject) {
pushMessage("promise 2")
resolve(input$go)
})$then(function(value) {

View File

@@ -239,6 +239,10 @@ test_that("dateYMD works", {
dateYMD(c("2020/01/14", "2019/11/05")),
c("2020-01-14", "2019-11-05")
)
expect_identical(
dateYMD(as.POSIXct("2025-11-09 00:01:59", tz = "Asia/Tokyo")),
"2025-11-09"
)
expect_warning(val <- dateYMD(""))
expect_identical(val, "")