Debian Codegraph @

R/otel.R

raw
1 # ## Use when otel v0.3.0 is released: https://github.com/r-lib/otel/commit/43e59c45a7de50cfd8af95f73d45f9899f957b44
2 # # attributes = as_attributes(attributes)
3 # attributes = if (!is.null(attributes)) {
4 # as_attributes(attributes)
5 # }
6 NULL
7
8 #' @importFrom otel
9 #' start_span
10 #' end_span
11 #' get_active_span
12 #' is_tracing_enabled
13 #' with_active_span
14 NULL
15
16 # Fixed variable named required for `otel::default_tracer_name()`
17 # which is used in `otel::get_tracer()` within `promises_otel_tracer()`
18 otel_tracer_name <- "co.posit.r-package.promises"
19
20 # Using local scope avoids an environment object lookup on each call.
21 # Inspired by httr2:::get_tracer(). Taken from Shiny
22 # Benchmark: https://github.com/rstudio/shiny/pull/4269/files#diff-0cc4a76032b57fcc125d41dfa3fb0f0c39976bb00a1d84bb56a0b77c331ce2d1R42
23 testthat__is_testing <- function() {
24 identical(Sys.getenv("TESTTHAT"), "true")
25 }
26
27 promises_otel_tracer <- local({
28 tracer <- NULL
29 function() {
30 if (!is.null(tracer)) {
31 return(tracer)
32 }
33 if (testthat__is_testing()) {
34 # Don't cache the tracer in unit tests. It interferes with tracer provider
35 # injection in otelsdk::with_otel_record().
36 return(otel::get_tracer())
37 }
38 tracer <<- otel::get_tracer()
39 tracer
40 }
41 })
42
43 #' OpenTelemetry integration
44 #'
45 #' @description
46 #' \pkg{otel} provides tools for integrating with OpenTelemetry, a framework for
47 #' observability and tracing in distributed systems.
48 #'
49 #' These methods are intended to enhance the framework to be used with the
50 #' \pkg{promises} package, not as a generic replacement.
51 #'
52 #' Developer note - Barret 2025/09: This otel span handoff promise domain topic is
53 #' complex and has been discussed over many hours. Many advanced Shiny/R
54 #' developers are not even aware of promise domains (very reasonable!),
55 #' therefore this topic requires more in-depth documentation and examples.
56 #'
57 #' @section Definitions:
58 #'
59 #' * Promise domain: An environment in which has setup/teardown methods. These
60 #' environments can be composed together to facilitate execution context for
61 #' promises. In normal R execution, this can be achieved with scope / stack.
62 #' But for complex situations, such as the currently open graphics device,
63 #' async operations require promise domains to setup/teardown these contexts
64 #' to function properly. Otherwise a multi-stage promise that adds to the
65 #' graphics device at each stage will only ever print to the most recently
66 #' created graphics device, not the associated graphics device. These promise
67 #' domains are not automatically created, they must be manually added to the
68 #' execution stack, for example `with_otel_promise_domain()` does this for
69 #' OpenTelemetry spans.
70 #' * Promise domain restoration: When switching from one promise chain to
71 #' another, the execution context is torn down and then re-established. This
72 #' re-establishment is called "promise domain restoration". During this
73 #' process, the promise domains are restored in their previously established
74 #' combination order.
75 #' * Promise chain: A set of promise objects to execute over multiple async
76 #' ticks.
77 #' * Async tick: the number of times an event loop must run to move computation
78 #' forward. (Similar to a JavaScript event loop tick.)
79 #' * `then()` promise domain capture: When `then()` is called, it will capture
80 #' the current promise domain. This promise domain is restored (only if
81 #' needed) when evaluating the given `onFulfilled` and `onRejected` callbacks.
82 #' This captured promise domain does not go into any downstream promise chain
83 #' objects. The only way the promise domain is captured is exactly when the
84 #' `then()` method is called.
85 #'
86 #' `with_otel_promise_domain()` creates a promise domain that restores the
87 #' currently active OpenTelemetry span from when a call to `promises::then()` is
88 #' executed. Given the special circumstance where only the current otel span is
89 #' needed to continue recording (not a full ancestry tree of otel spans), we can
90 #' capture _just_ the current otel span and reactivate that otel span during promise
91 #' domain restoration.
92 #'
93 #' @section When promise domains are captured:
94 #'
95 #' Asynchronous operation
96 #' * Creates `async_op` otel span
97 #' * Automatically ends the otel span (`async_op`) when the promise (p)
98 #' resolves or rejects
99 #'
100 #' The code below illustrates an example of when the promise domain are
101 #' created/captured/restored and when otel span objects are
102 #' created/activated/reactivated/ended.
103 #'
104 #' ```r
105 #' # t0.0
106 #' p2 <- with_otel_promise_domain({
107 #' # t0.1
108 #' p <- with_otel_span("async_op", {
109 #' # ... return a promise ...
110 #' init_async_work() |> # t0.2
111 #' then( # t0.3
112 #' some_async_work # t1.0
113 #' )
114 #' }) # t0.4, t1.0, t2.0
115 #' p |>
116 #' then( # t0.5
117 #' more_async_work # t3.0
118 #' )
119 #' }) # t0.6
120 #'
121 #' p_final <-
122 #' p2 |> then( # t0.7
123 #' final_work # t4.0
124 #' )
125 #' ```
126 #'
127 #' An in-depth explanation of the execution timeline is below.
128 #' * At the first initial tick, `t0.*`:
129 #' * `t0.0`: The code is wrapped in `with_otel_promise_domain()`
130 #' * `t0.1`: The `async_op` otel span is created and activated
131 #' * `t0.2`: Some async work is initiated
132 #' * `t0.3`: `then()` is called, capturing the active `async_op` otel span (as it
133 #' is called within `with_otel_promise_domain()`)
134 #' * `t0.4`: The `with_otel_span()` call exits, but the `async_op` otel span is
135 #' not ended as the promise is still pending. The returned promise has a
136 #' `finally()` step added to it that will end the otel span `async_op` when `p`
137 #' is resolved.
138 #' * `t0.5`: Another `then()` is called, but there is no active otel span to
139 #' capture
140 #' * `t0.6`: The otel span promise domain call exits
141 #' * `t0.7`: Another `then()` is called. No otel span will be captured as there is
142 #' no active otel span / promise domain
143 #' * At the first followup tick, `t1.0`:
144 #' * The active `async_op` otel span is reactivated during promise domain
145 #' restoration for the duration of the `then` callback
146 #' * The `some_async_work` function is called
147 #' * At tick, `t2.0`:
148 #' * `some_async_work` has resolved
149 #' * A hidden `finally()` step closes the otel span, `async_op`
150 #' * `p` is now resolved
151 #' * At tick, `t3.0`:
152 #' * There is no active otel span at `t0.5`, so no otel span is reactivated during
153 #' promise domain restoration
154 #' * The `more_async_work` function is executed
155 #' * At tick, `t4.0`:
156 #' * `more_async_work` has resolved, therefore `p2` is now resolved
157 #' * There was no otel span promise domain at `t0.7`, so no attempt is made to
158 #' reactivate any otel span
159 #' * The `final_work` function is executed
160 #' * At tick, `t5.0`:
161 #' * `p_final` has resolved
162
163 #'
164 #' @section Complexity:
165 #'
166 #' When reactivating the `k`th step in a promise chain, the currently active
167 #' otel span (during the call to `then()`) will be reactivated during promise domain
168 #' restoration (`O(1)`). To restore a chain of promises, the active otel span will
169 #' be restored at each step (`O(n)`) due to the **`n`** calls to wrapping each
170 #' `onFulfilled` and `onRejected` callbacks inside `then()`.
171 #'
172 #' If we did NOT have a handoff promise domain for otel span restoration, a regular
173 #' promise domain approach would be needed at each step to restore the active
174 #' otel span. Each step would call `with_active_span()` `k` times (`O(k)`, where as
175 #' handoff domain computes in `O(1)`). Taking a step back, to restore each otel span
176 #' at for every step in a promise chain would then take `O(n^2)` time, not
177 #' `O(n)`. The standard, naive promise domain approach does not scale for
178 #' multiple similar promise domain restorations.
179 #'
180 #'
181 #' @section Execution model for `with_otel_promise_domain()`:
182 #'
183 #' 1. `with_otel_promise_domain(expr)` is called.
184 #' * The following steps all occur within `expr`.
185 #' 2. Create an otel span object using `otel::start_span()`.
186 #' * We need the otel span to be active during the a followup async operation.
187 #' Therefore, `otel::start_local_active_span()` is not appropriate as the
188 #' otel span would be ended when the function exits, not when the promise chain
189 #' resolves.
190 #' 2. Be sure your otel span is activated before calling `promises::then()`.
191 #' * Activate it using `with_otel_span(name, expr)` (which also
192 #' creates/ends the otel span) or `otel::with_active_span(span, expr)`.
193 #' 3. Call `promises::then()`
194 #' * When `promises::then()` is called, the two methods (`onFulfilled` and
195 #' `onRejected`) capture the currently active spans. (Performed by the
196 #' initial `with_otel_promise_domain()`)
197 #' 4. During reactivation of the promise chain step, the previously captured
198 #' otel span is reactivated via `with_active_span()`. (Performed by the initial
199 #' `with_otel_promise_domain()`)
200 #'
201 #' @section OpenTelemetry span compatibility:
202 #'
203 #' For otel span objects to exist over may async ticks, the otel span must be created
204 #' using `otel::start_span()` and later ended using `otel::end_span()`. Ending
205 #' the otel span must occur **after** any promise chain work has completed.
206 #'
207 #' If we were to instead use `otel::start_local_active_span()`, the otel span would
208 #' be ended when the function exits, not when the promise chain completes. Even
209 #' though the local otel span is created, activated, and eventually ended, the otel span
210 #' will not exist during reactivation of the otel span promise domain.
211 #'
212 #' `with_otel_span()` is a convenience method that creates, activates, and
213 #' ends the otel span only after the returned promise (if any) resolves. It also
214 #' properly handles both synchronous (ending the otel span within `on.exit()`) and
215 #' asynchronous operations (ending the otel span within `promises::finally()`).
216 #'
217 #'
218 #'
219 #'
220 #' @describeIn otel Creates an OpenTelemetry span, executes the given expression within it, and
221 #' ends the span.
222 #'
223 #' This method **requires** the use of `with_otel_promise_domain()`
224 #' to be within the execution stack.
225 #'
226 #' This function is designed to handle both synchronous and asynchronous
227 #' (promise-based) operations. For promises, the span is automatically ended
228 #' when the promise resolves or rejects.
229 #'
230 #' Returns the result of evaluating `expr`. If `expr` returns a promise, the
231 #' span will be automatically ended when the promise completes.
232 #'
233 #' This function differs from synchronous otel span operations in that it
234 #' installs a promise domain and properly handles asynchronous operations. In
235 #' addition, the internal span will be ended either when the function exits (for
236 #' synchronous operations) or when a returned promise completes (for
237 #' asynchronous operations).
238 #'
239 #' If OpenTelemetry is not enabled, the expression will be evaluated without any
240 #' tracing context.
241 #'
242 #' @param name Character string. The name of the otel span.
243 #' @param expr An expression to evaluate within the otel span context.
244 #' @param ... Additional arguments passed to [`otel::start_span()`].
245 #' @param tracer (Required) An `{otel}` tracer. It is required to provide your
246 #' own tracer from your own package. See [`otel::get_tracer()`] for more
247 #' details.
248 #' @param attributes Attributes passed through [`otel::as_attributes()`] (when
249 #' not `NULL`)
250 #' @export
251 #' @seealso [`otel::start_span()`], [`otel::with_active_span()`],
252 #' [`otel::end_span()`]
253 #' @examples
254 #' \dontrun{
255 #' # Common usage:
256 #' with_otel_promise_domain({
257 #' # ... deep inside some code execution ...
258 #'
259 #' # Many calls to `with_otel_span()` within `with_otel_promise_domain()`
260 #' with_otel_span("my_operation", {
261 #' # ... do some work ...
262 #' })
263 #' })
264 #' }
265 #' \dontrun{
266 #' with_otel_promise_domain({
267 #' # ... deep inside some code execution ...
268 #'
269 #' # Synchronous operation
270 #' # * Creates `my_operation` span
271 #' result <- with_otel_span("my_operation", {
272 #' # ... do some work ...
273 #' print(otel::get_active_span()$name) # "my_operation"
274 #'
275 #' # Nest (many) more spans
276 #' prom_nested <- with_otel_span("my_nested_operation", {
277 #' # ... do some more work ...
278 #' promise_resolve(42) |>
279 #' then(\(value) {
280 #' print(otel::get_active_span()$name) # "my_nested_operation"
281 #' print(value) # 42
282 #' })
283 #' })
284 #'
285 #' # Since `then()` is called during the active `my_operation` span,
286 #' # the `my_operation` span will be reactivated in the `then()` callback.
287 #' prom_nested |> then(\(value) {
288 #' print(otel::get_active_span()$name) # "my_operation"
289 #' value
290 #' })
291 #' })
292 #'
293 #' # Since `then()` is called where there is no active span,
294 #' # there is no _active_ span in the `then()` callback.
295 #' result |> then(\(value) {
296 #' stopifnot(inherits(otel::get_active_span(), "otel_span_noop"))
297 #' print(value) # 42
298 #' })
299 #' })
300 #' }
301 with_otel_span <- function(
302 name,
303 expr,
304 ...,
305 tracer,
306 attributes = NULL
307 ) {
308 # If tracing is not enabled, just run the expression
309 #
310 # ```
311 # tracer <- get_tracer(); bench::mark(check = FALSE, !is_tracing_enabled(tracer), inherits(tracer, "otel_tracer_noop"), !.subset2(tracer, "is_enabled")())[,1:4]
312 # #> A tibble: 3 × 4
313 # #> expression min median `itr/sec`
314 # #> <bch:expr> <bch:tm> <bch:tm> <dbl>
315 # #> 1 "!is_tracing_enabled(tracer)" 2.79µs 3.4µs 278206.
316 # #> 2 "inherits(tracer, \"otel_tracer_noop\")" 205.01ns 287ns 3184760.
317 # #> 3 "!.subset2(tracer, \"is_enabled\")()" 82.02ns 164ns 5716255.
318 # ```
319 #
320 # Speed is important here as to not slow down non-tracing operations.
321 # Therefore, we use the fastest method and require `tracer=` to be provided.
322 # The method is safe to call as it just returns either `TRUE` or `FALSE` (if a
323 # noop tracer).
324 if (!.subset2(tracer, "is_enabled")()) {
325 return(force(expr))
326 }
327
328 span <- start_span(name, ..., tracer = tracer, attributes = attributes)
329
330 needs_cleanup <- TRUE
331 cleanup <- function() {
332 end_span(span)
333 }
334 on.exit(if (needs_cleanup) cleanup(), add = TRUE)
335
336 result <- with_active_span(span, expr)
337
338 if (is.promising(result)) {
339 needs_cleanup <- FALSE
340
341 result <- finally(result, cleanup)
342 }
343
344 result
345 }
346
347
348 #' @describeIn otel Adds an idempotent handoff Active OpenTelemetry span promise domain.
349 #'
350 #' Package authors are required to use this function to have otel span context
351 #' persist across asynchronous boundaries. This method is only needed once per
352 #' promise domain stack. If you are unsure, feel free to call
353 #' `with_otel_promise_domain()` as the underlying promise domain will only be
354 #' added if not found within the current promise domain stack. If your package
355 #' **only** works within Shiny apps, Shiny will have already added the domain so
356 #' no need to add it yourself. If your package works outside of Shiny and you
357 #' use `{promises}` (i.e. `{chromote}`), then you'll need to use this wrapper
358 #' method.
359 #'
360 #' This method adds a _handoff_ Active OpenTelemetry span promise domain to the
361 #' expression evaluation. This _handoff_ promise domain will only run once on
362 #' reactivation. This is critical if there are many layered
363 #' `with_otel_span()` calls, such as within Shiny reactivity. For example, if
364 #' we nested many `with_otel_span()` calls of which each call added a promise
365 #' domain that reactivated each otel span on restore, we'd reactivate `k` otel
366 #' span objects (`O(k)`) when we only need to activate the **last** span
367 #' (`O(1)`).
368 #'
369 #' Returns the result of evaluating `expr` within the otel span promise domain.
370 #'
371 #' @export
372 with_otel_promise_domain <- function(expr) {
373 # with_otel_promise_domain <- function(expr) {
374 # Do not add the otel span handoff promise domain twice
375 if (has_otel_promise_domain()) {
376 return(force(expr))
377 }
378 act_span_pd <- create_otel_promise_domain()
379 with_promise_domain(act_span_pd, expr)
380 }
381
382
383 #' @describeIn otel Local OpenTelemetry span promise domain
384 #'
385 #' Adds an OpenTelemetry span promise domain to the local scope. This is useful
386 #' for `{coro}` operations where encapsulating the coro operations inside a
387 #' `with_*()` methods is not allowed.
388 #'
389 #' When not using `{coro}`, please prefer to use `with_otel_span()` or
390 #' `with_otel_promise_domain()`.
391 #' @export
392 #' @param envir The "local" environment in which to add the promise domain. When
393 #' the environment is exited, the promise domain is removed.
394 local_otel_promise_domain <- function(envir = parent.frame()) {
395 # local_otel_promise_domain <- function(envir = parent.frame()) {
396 if (has_otel_promise_domain()) {
397 return(invisible())
398 }
399
400 local_promise_domain(
401 create_otel_promise_domain(),
402 envir = envir
403 )
404 }
405
406 # Modifies the current promise domain to include `domain` for the local scope.
407 local_promise_domain <- function(
408 domain,
409 envir = parent.frame(),
410 replace = FALSE
411 ) {
412 oldval <- current_promise_domain()
413 if (replace) {
414 globals$domain <- domain
415 } else {
416 globals$domain <- compose_domains(oldval, domain)
417 }
418
419 # Inspired by `withr::defer()`
420 defer(
421 {
422 globals$domain <- oldval
423 },
424 envir = envir
425 )
426
427 invisible()
428 }
429
430 # # TODO: Set attributes on the current active span
431 # # 5. Set attributes on the current active span
432 # set_otel_span_attrs(status = 200L)
433
434 # -- Helpers --------------------------------------------------------------
435
436 has_otel_promise_domain <- function(domain = current_promise_domain()) {
437 # Works for:
438 # * `list()` `compose_domains()` result
439 # * `NULL` - current_promise_domain() init value
440 # * environment objects - `new_promise_domain()` result
441 isTRUE(domain[[".otel_promise_domain"]])
442 }
443
444 #' Create a OpenTelemetry handoff promise domain
445 #'
446 #' Creates a handoff promise domain captures the currently active span. Upon
447 #' promise domain restoration, the previously captured span will be reactivated.
448 #'
449 #' @param span An OpenTelemetry span object.
450 #' @noRd
451 create_otel_promise_domain <- function() {
452 new_promise_domain(
453 .otel_promise_domain = TRUE, # set flag for later discovery
454 wrapOnFulfilled = function(onFulfilled) {
455 force(onFulfilled)
456
457 ## Motivation on why we can't use
458 ## `promises_otel_tracer()$get_active_span()` here to save 10 microseconds:
459 ## https://github.com/r-lib/otel/issues/31#issuecomment-3250669840
460 #> ❯❯ bench::mark(promises_otel_tracer()$get_active_span(), get_active_span())
461 #> # A tibble: 2 × 13
462 #> expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time
463 #> <bch:expr> <bch:> <bch:t> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list>
464 #> 1 promises_otel_tra… 4.8µs 6.52µs 144270. 0B 14.4 9999 1 69.3ms <otl_spn_> <Rprofmem> <bench_tm>
465 #> 2 get_active_span() 14.3µs 15.13µs 64876. 7.02KB 38.9 9994 6 154ms <otl_spn_> <Rprofmem> <bench_tm>
466 # ℹ 1 more variable: gc <list>
467 ## tl/dr: Speed comes at the cost of safety. Just use this for now as it is only a single cost on restore.
468
469 # Instead, use `get_active_span()` directly so that the recording status
470 # can be changed over time for testing and within the terminal. The 10
471 # microseconds is not worth the inconsistent behavior or the time to debug
472 # the inconsistent behavior.
473
474 # The `is_recording()` method is deemed safe to call as the underlying C++
475 # method just checks an internal class instance property, is
476 # non-allocating and has been declared noexcept.
477
478 span <- get_active_span()
479 if (!.subset2(span, "is_recording")()) {
480 return(onFulfilled)
481 }
482
483 function(...) {
484 with_active_span(span, {
485 onFulfilled(...)
486 })
487 }
488 },
489 wrapOnRejected = function(onRejected) {
490 force(onRejected)
491
492 span <- get_active_span()
493 if (!.subset2(span, "is_recording")()) {
494 return(onRejected)
495 }
496
497 function(...) {
498 with_active_span(span, {
499 onRejected(...)
500 })
501 }
502 }
503 )
504 }