| 1 |
otel_tracer_name = 'org.yihui.knitr' |
| 2 |
|
| 3 |
# generic otel helpers: |
| 4 |
|
| 5 |
otel_cache_tracer = NULL |
| 6 |
otel_active_span = NULL |
| 7 |
|
| 8 |
local({ |
| 9 |
otel_tracer = NULL |
| 10 |
otel_is_tracing = FALSE |
| 11 |
|
| 12 |
otel_cache_tracer <<- function() { |
| 13 |
requireNamespace('otel', quietly = TRUE) || return() |
| 14 |
otel_tracer <<- otel::get_tracer(otel_tracer_name) |
| 15 |
otel_is_tracing <<- tracer_enabled(otel_tracer) |
| 16 |
} |
| 17 |
|
| 18 |
# - without specifying `scope`, the span ends when this function returns; |
| 19 |
# to make this a local span (last as long as the function it is called from), |
| 20 |
# specify `scope = environment()` |
| 21 |
# - arguments remain unevaluated on early return |
| 22 |
otel_active_span <<- function( |
| 23 |
name, |
| 24 |
label, |
| 25 |
attributes = list(), |
| 26 |
scope = environment() |
| 27 |
) { |
| 28 |
otel_is_tracing || return() |
| 29 |
otel::start_local_active_span( |
| 30 |
name = sprintf('%s %s', name, label), |
| 31 |
attributes = otel::as_attributes(attributes), |
| 32 |
tracer = otel_tracer, |
| 33 |
activation_scope = scope |
| 34 |
) |
| 35 |
} |
| 36 |
}) |
| 37 |
|
| 38 |
tracer_enabled = function(tracer) { |
| 39 |
.subset2(tracer, 'is_enabled')() |
| 40 |
} |
| 41 |
|
| 42 |
with_otel_record = function(expr) { |
| 43 |
on.exit(otel_cache_tracer()) |
| 44 |
otelsdk::with_otel_record({ |
| 45 |
otel_cache_tracer() |
| 46 |
expr |
| 47 |
}) |
| 48 |
} |
| 49 |
|
| 50 |
# knitr-specific helpers: |
| 51 |
|
| 52 |
make_chunk_attributes = function(options) { |
| 53 |
list( |
| 54 |
knitr.chunk.device = options$dev, |
| 55 |
knitr.chunk.echo = options$echo, |
| 56 |
knitr.chunk.engine = options$engine, |
| 57 |
knitr.chunk.eval = options$eval, |
| 58 |
knitr.chunk.label = options$label |
| 59 |
) |
| 60 |
} |
| 61 |
|
| 62 |
make_knitr_attributes = function() { |
| 63 |
list( |
| 64 |
knitr.format = out_format(), |
| 65 |
knitr.input = get_knitr_concord('infile'), |
| 66 |
knitr.output = get_knitr_concord('outfile') |
| 67 |
) |
| 68 |
} |
| 69 |
|
| 70 |
# safe version that always returns a string |
| 71 |
get_knitr_concord = function(name) { |
| 72 |
knit_concord$get(name) %n% '' |
| 73 |
} |