Debian Codegraph @

man/otel.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/otel.R
3 \name{with_otel_span}
4 \alias{with_otel_span}
5 \alias{with_otel_promise_domain}
6 \alias{local_otel_promise_domain}
7 \title{OpenTelemetry integration}
8 \usage{
9 with_otel_span(name, expr, ..., tracer, attributes = NULL)
10
11 with_otel_promise_domain(expr)
12
13 local_otel_promise_domain(envir = parent.frame())
14 }
15 \arguments{
16 \item{name}{Character string. The name of the otel span.}
17
18 \item{expr}{An expression to evaluate within the otel span context.}
19
20 \item{...}{Additional arguments passed to \code{\link[otel:start_span]{otel::start_span()}}.}
21
22 \item{tracer}{(Required) An \code{{otel}} tracer. It is required to provide your
23 own tracer from your own package. See \code{\link[otel:get_tracer]{otel::get_tracer()}} for more
24 details.}
25
26 \item{attributes}{Attributes passed through \code{\link[otel:as_attributes]{otel::as_attributes()}} (when
27 not \code{NULL})}
28
29 \item{envir}{The "local" environment in which to add the promise domain. When
30 the environment is exited, the promise domain is removed.}
31 }
32 \description{
33 \pkg{otel} provides tools for integrating with OpenTelemetry, a framework for
34 observability and tracing in distributed systems.
35
36 These methods are intended to enhance the framework to be used with the
37 \pkg{promises} package, not as a generic replacement.
38
39 Developer note - Barret 2025/09: This otel span handoff promise domain topic is
40 complex and has been discussed over many hours. Many advanced Shiny/R
41 developers are not even aware of promise domains (very reasonable!),
42 therefore this topic requires more in-depth documentation and examples.
43 }
44 \section{Functions}{
45 \itemize{
46 \item \code{with_otel_span()}: Creates an OpenTelemetry span, executes the given expression within it, and
47 ends the span.
48
49 This method \strong{requires} the use of \code{with_otel_promise_domain()}
50 to be within the execution stack.
51
52 This function is designed to handle both synchronous and asynchronous
53 (promise-based) operations. For promises, the span is automatically ended
54 when the promise resolves or rejects.
55
56 Returns the result of evaluating \code{expr}. If \code{expr} returns a promise, the
57 span will be automatically ended when the promise completes.
58
59 This function differs from synchronous otel span operations in that it
60 installs a promise domain and properly handles asynchronous operations. In
61 addition, the internal span will be ended either when the function exits (for
62 synchronous operations) or when a returned promise completes (for
63 asynchronous operations).
64
65 If OpenTelemetry is not enabled, the expression will be evaluated without any
66 tracing context.
67
68 \item \code{with_otel_promise_domain()}: Adds an idempotent handoff Active OpenTelemetry span promise domain.
69
70 Package authors are required to use this function to have otel span context
71 persist across asynchronous boundaries. This method is only needed once per
72 promise domain stack. If you are unsure, feel free to call
73 \code{with_otel_promise_domain()} as the underlying promise domain will only be
74 added if not found within the current promise domain stack. If your package
75 \strong{only} works within Shiny apps, Shiny will have already added the domain so
76 no need to add it yourself. If your package works outside of Shiny and you
77 use \code{{promises}} (i.e. \code{{chromote}}), then you'll need to use this wrapper
78 method.
79
80 This method adds a \emph{handoff} Active OpenTelemetry span promise domain to the
81 expression evaluation. This \emph{handoff} promise domain will only run once on
82 reactivation. This is critical if there are many layered
83 \code{with_otel_span()} calls, such as within Shiny reactivity. For example, if
84 we nested many \code{with_otel_span()} calls of which each call added a promise
85 domain that reactivated each otel span on restore, we'd reactivate \code{k} otel
86 span objects (\code{O(k)}) when we only need to activate the \strong{last} span
87 (\code{O(1)}).
88
89 Returns the result of evaluating \code{expr} within the otel span promise domain.
90
91 \item \code{local_otel_promise_domain()}: Local OpenTelemetry span promise domain
92
93 Adds an OpenTelemetry span promise domain to the local scope. This is useful
94 for \code{{coro}} operations where encapsulating the coro operations inside a
95 \verb{with_*()} methods is not allowed.
96
97 When not using \code{{coro}}, please prefer to use \code{with_otel_span()} or
98 \code{with_otel_promise_domain()}.
99
100 }}
101 \section{Definitions}{
102
103 \itemize{
104 \item Promise domain: An environment in which has setup/teardown methods. These
105 environments can be composed together to facilitate execution context for
106 promises. In normal R execution, this can be achieved with scope / stack.
107 But for complex situations, such as the currently open graphics device,
108 async operations require promise domains to setup/teardown these contexts
109 to function properly. Otherwise a multi-stage promise that adds to the
110 graphics device at each stage will only ever print to the most recently
111 created graphics device, not the associated graphics device. These promise
112 domains are not automatically created, they must be manually added to the
113 execution stack, for example \code{with_otel_promise_domain()} does this for
114 OpenTelemetry spans.
115 \item Promise domain restoration: When switching from one promise chain to
116 another, the execution context is torn down and then re-established. This
117 re-establishment is called "promise domain restoration". During this
118 process, the promise domains are restored in their previously established
119 combination order.
120 \item Promise chain: A set of promise objects to execute over multiple async
121 ticks.
122 \item Async tick: the number of times an event loop must run to move computation
123 forward. (Similar to a JavaScript event loop tick.)
124 \item \code{then()} promise domain capture: When \code{then()} is called, it will capture
125 the current promise domain. This promise domain is restored (only if
126 needed) when evaluating the given \code{onFulfilled} and \code{onRejected} callbacks.
127 This captured promise domain does not go into any downstream promise chain
128 objects. The only way the promise domain is captured is exactly when the
129 \code{then()} method is called.
130 }
131
132 \code{with_otel_promise_domain()} creates a promise domain that restores the
133 currently active OpenTelemetry span from when a call to \code{promises::then()} is
134 executed. Given the special circumstance where only the current otel span is
135 needed to continue recording (not a full ancestry tree of otel spans), we can
136 capture \emph{just} the current otel span and reactivate that otel span during promise
137 domain restoration.
138 }
139
140 \section{When promise domains are captured}{
141
142
143 Asynchronous operation
144 \itemize{
145 \item Creates \code{async_op} otel span
146 \item Automatically ends the otel span (\code{async_op}) when the promise (p)
147 resolves or rejects
148 }
149
150 The code below illustrates an example of when the promise domain are
151 created/captured/restored and when otel span objects are
152 created/activated/reactivated/ended.
153
154 \if{html}{\out{<div class="sourceCode r">}}\preformatted{# t0.0
155 p2 <- with_otel_promise_domain(\{
156 # t0.1
157 p <- with_otel_span("async_op", \{
158 # ... return a promise ...
159 init_async_work() |> # t0.2
160 then( # t0.3
161 some_async_work # t1.0
162 )
163 \}) # t0.4, t1.0, t2.0
164 p |>
165 then( # t0.5
166 more_async_work # t3.0
167 )
168 \}) # t0.6
169
170 p_final <-
171 p2 |> then( # t0.7
172 final_work # t4.0
173 )
174 }\if{html}{\out{</div>}}
175
176 An in-depth explanation of the execution timeline is below.
177 \itemize{
178 \item At the first initial tick, \verb{t0.*}:
179 \itemize{
180 \item \code{t0.0}: The code is wrapped in \code{with_otel_promise_domain()}
181 \item \code{t0.1}: The \code{async_op} otel span is created and activated
182 \item \code{t0.2}: Some async work is initiated
183 \item \code{t0.3}: \code{then()} is called, capturing the active \code{async_op} otel span (as it
184 is called within \code{with_otel_promise_domain()})
185 \item \code{t0.4}: The \code{with_otel_span()} call exits, but the \code{async_op} otel span is
186 not ended as the promise is still pending. The returned promise has a
187 \code{finally()} step added to it that will end the otel span \code{async_op} when \code{p}
188 is resolved.
189 \item \code{t0.5}: Another \code{then()} is called, but there is no active otel span to
190 capture
191 \item \code{t0.6}: The otel span promise domain call exits
192 \item \code{t0.7}: Another \code{then()} is called. No otel span will be captured as there is
193 no active otel span / promise domain
194 }
195 \item At the first followup tick, \code{t1.0}:
196 \itemize{
197 \item The active \code{async_op} otel span is reactivated during promise domain
198 restoration for the duration of the \code{then} callback
199 \item The \code{some_async_work} function is called
200 }
201 \item At tick, \code{t2.0}:
202 \itemize{
203 \item \code{some_async_work} has resolved
204 \item A hidden \code{finally()} step closes the otel span, \code{async_op}
205 \item \code{p} is now resolved
206 }
207 \item At tick, \code{t3.0}:
208 \itemize{
209 \item There is no active otel span at \code{t0.5}, so no otel span is reactivated during
210 promise domain restoration
211 \item The \code{more_async_work} function is executed
212 }
213 \item At tick, \code{t4.0}:
214 \itemize{
215 \item \code{more_async_work} has resolved, therefore \code{p2} is now resolved
216 \item There was no otel span promise domain at \code{t0.7}, so no attempt is made to
217 reactivate any otel span
218 \item The \code{final_work} function is executed
219 }
220 \item At tick, \code{t5.0}:
221 \itemize{
222 \item \code{p_final} has resolved
223 }
224 }
225 }
226
227 \section{Complexity}{
228
229
230 When reactivating the \code{k}th step in a promise chain, the currently active
231 otel span (during the call to \code{then()}) will be reactivated during promise domain
232 restoration (\code{O(1)}). To restore a chain of promises, the active otel span will
233 be restored at each step (\code{O(n)}) due to the \strong{\code{n}} calls to wrapping each
234 \code{onFulfilled} and \code{onRejected} callbacks inside \code{then()}.
235
236 If we did NOT have a handoff promise domain for otel span restoration, a regular
237 promise domain approach would be needed at each step to restore the active
238 otel span. Each step would call \code{with_active_span()} \code{k} times (\code{O(k)}, where as
239 handoff domain computes in \code{O(1)}). Taking a step back, to restore each otel span
240 at for every step in a promise chain would then take \code{O(n^2)} time, not
241 \code{O(n)}. The standard, naive promise domain approach does not scale for
242 multiple similar promise domain restorations.
243 }
244
245 \section{Execution model for \code{with_otel_promise_domain()}}{
246
247 \enumerate{
248 \item \code{with_otel_promise_domain(expr)} is called.
249 \itemize{
250 \item The following steps all occur within \code{expr}.
251 }
252 \item Create an otel span object using \code{otel::start_span()}.
253 \itemize{
254 \item We need the otel span to be active during the a followup async operation.
255 Therefore, \code{otel::start_local_active_span()} is not appropriate as the
256 otel span would be ended when the function exits, not when the promise chain
257 resolves.
258 }
259 \item Be sure your otel span is activated before calling \code{promises::then()}.
260 \itemize{
261 \item Activate it using \code{with_otel_span(name, expr)} (which also
262 creates/ends the otel span) or \code{otel::with_active_span(span, expr)}.
263 }
264 \item Call \code{promises::then()}
265 }
266 \itemize{
267 \item When \code{promises::then()} is called, the two methods (\code{onFulfilled} and
268 \code{onRejected}) capture the currently active spans. (Performed by the
269 initial \code{with_otel_promise_domain()})
270 }
271 \enumerate{
272 \item During reactivation of the promise chain step, the previously captured
273 otel span is reactivated via \code{with_active_span()}. (Performed by the initial
274 \code{with_otel_promise_domain()})
275 }
276 }
277
278 \section{OpenTelemetry span compatibility}{
279
280
281 For otel span objects to exist over may async ticks, the otel span must be created
282 using \code{otel::start_span()} and later ended using \code{otel::end_span()}. Ending
283 the otel span must occur \strong{after} any promise chain work has completed.
284
285 If we were to instead use \code{otel::start_local_active_span()}, the otel span would
286 be ended when the function exits, not when the promise chain completes. Even
287 though the local otel span is created, activated, and eventually ended, the otel span
288 will not exist during reactivation of the otel span promise domain.
289
290 \code{with_otel_span()} is a convenience method that creates, activates, and
291 ends the otel span only after the returned promise (if any) resolves. It also
292 properly handles both synchronous (ending the otel span within \code{on.exit()}) and
293 asynchronous operations (ending the otel span within \code{promises::finally()}).
294 }
295
296 \examples{
297 \dontrun{
298 # Common usage:
299 with_otel_promise_domain({
300 # ... deep inside some code execution ...
301
302 # Many calls to `with_otel_span()` within `with_otel_promise_domain()`
303 with_otel_span("my_operation", {
304 # ... do some work ...
305 })
306 })
307 }
308 \dontrun{
309 with_otel_promise_domain({
310 # ... deep inside some code execution ...
311
312 # Synchronous operation
313 # * Creates `my_operation` span
314 result <- with_otel_span("my_operation", {
315 # ... do some work ...
316 print(otel::get_active_span()$name) # "my_operation"
317
318 # Nest (many) more spans
319 prom_nested <- with_otel_span("my_nested_operation", {
320 # ... do some more work ...
321 promise_resolve(42) |>
322 then(\(value) {
323 print(otel::get_active_span()$name) # "my_nested_operation"
324 print(value) # 42
325 })
326 })
327
328 # Since `then()` is called during the active `my_operation` span,
329 # the `my_operation` span will be reactivated in the `then()` callback.
330 prom_nested |> then(\(value) {
331 print(otel::get_active_span()$name) # "my_operation"
332 value
333 })
334 })
335
336 # Since `then()` is called where there is no active span,
337 # there is no _active_ span in the `then()` callback.
338 result |> then(\(value) {
339 stopifnot(inherits(otel::get_active_span(), "otel_span_noop"))
340 print(value) # 42
341 })
342 })
343 }
344 }
345 \seealso{
346 \code{\link[otel:start_span]{otel::start_span()}}, \code{\link[otel:with_active_span]{otel::with_active_span()}},
347 \code{\link[otel:end_span]{otel::end_span()}}
348 }