-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmod.rs
More file actions
7419 lines (6713 loc) · 271 KB
/
Copy pathmod.rs
File metadata and controls
7419 lines (6713 loc) · 271 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Motia LLC and/or licensed to Motia LLC under one or more
// contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.
// This software is patent protected. We welcome discussions - reach out at team@iii.dev
// See LICENSE and PATENTS files for details.
pub mod configuration;
pub mod logs_layer;
pub mod metrics;
pub mod otel;
pub(crate) mod otlp_exporter;
mod sampler;
pub mod config;
use std::{
collections::{HashMap, HashSet},
pin::Pin,
sync::Arc,
time::SystemTime,
};
use async_trait::async_trait;
use colored::Colorize;
use function_macros::{function, service};
use futures::Future;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::RwLock as TokioRwLock;
use crate::{
engine::{Engine, EngineTrait, Handler, RegisterFunctionRequest},
function::FunctionResult,
protocol::ErrorBody,
trigger::{Trigger, TriggerRegistrator, TriggerType},
workers::traits::Worker,
};
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct TracesListInput {
/// Filter by specific trace ID
trace_id: Option<String>,
/// Pagination offset (default: 0)
offset: Option<usize>,
/// Pagination limit (default: 100)
limit: Option<usize>,
/// Filter by service name (case-insensitive substring match)
service_name: Option<String>,
/// Filter by span name (case-insensitive substring match)
name: Option<String>,
/// Filter by status (case-insensitive substring match)
status: Option<String>,
/// Minimum span duration in milliseconds (sub-ms precision)
min_duration_ms: Option<f64>,
/// Maximum span duration in milliseconds (sub-ms precision)
max_duration_ms: Option<f64>,
/// Start time in unix timestamp milliseconds (include spans overlapping after this)
start_time: Option<u64>,
/// End time in unix timestamp milliseconds (include spans overlapping before this)
end_time: Option<u64>,
/// Sort field: "start_time" | "duration" (alias "duration_ms") |
/// "service_name" | "name" (default: "start_time"). Unknown values fall
/// back to "start_time".
sort_by: Option<String>,
/// Sort order: "asc" | "desc" (default: "asc")
sort_order: Option<String>,
/// Filter by span attributes (array of [key, value] pairs, AND logic, exact match)
attributes: Option<Vec<Vec<String>>>,
/// Include internal engine traces (engine.* functions). Defaults to false.
#[serde(default)]
include_internal: Option<bool>,
/// Search across all spans in each trace, not just root spans.
/// When true and a `name` filter is set, traces are matched if ANY span
/// in the trace matches the name filter. Defaults to false.
#[serde(default)]
search_all_spans: Option<bool>,
}
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct TracesClearInput {}
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct TracesTreeInput {
/// Trace ID to build the tree for
trace_id: String,
}
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct TracesGroupByInput {
/// Span attribute key to group by. Spans without this attribute are skipped.
attribute: String,
/// Earliest end_time (ms since epoch) to include.
#[serde(default)]
since_ms: Option<u64>,
/// Max groups returned after sorting by `first_seen_ms` descending. Default 100.
#[serde(default)]
limit: Option<u32>,
/// Include engine-internal spans. Defaults to false, matching `traces::list`.
#[serde(default)]
include_internal: Option<bool>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct TraceGroup {
pub value: String,
pub trace_ids: Vec<String>,
pub span_count: u32,
pub first_seen_ms: u64,
pub last_seen_ms: u64,
pub duration_ms: u32,
pub error_count: u32,
}
#[derive(Serialize)]
pub struct SpanTreeNode {
#[serde(flatten)]
pub span: otel::StoredSpan,
pub children: Vec<SpanTreeNode>,
}
// =========================================================================
// Response types for the engine::traces / metrics / logs / alerts / sampling
// / health query functions. Typed so engine::functions::info surfaces a
// response_schema (the macro emits no schema for `Option<Value>`). Heavy or
// dynamic leaves (spans, logs, raw metric points) stay `serde_json::Value`:
// their leaf types don't derive JsonSchema, and `to_value(Vec<Leaf>)` equals
// `to_value(Vec<Value>)`, so serialization is byte-identical while the
// envelope schema (the top-level contract an agent needs) is still exposed.
// Field declaration order matches the prior `json!` literals.
// =========================================================================
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct TracesListResult {
/// Stored spans (each a serialized span record).
pub spans: Vec<Value>,
/// Total matching spans before pagination.
pub total: usize,
pub offset: usize,
pub limit: usize,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct TracesTreeResult {
/// Root span-tree nodes (each a serialized, flattened span with nested children).
pub roots: Vec<Value>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct TracesGroupByResult {
pub groups: Vec<TraceGroup>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct OkResult {
pub success: bool,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct LogsClearResult {
pub success: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct LogsListResult {
/// Stored OTEL log records (serialized).
pub logs: Vec<Value>,
/// Total matching logs before pagination.
pub total: usize,
/// Echo of the applied filters (present only when storage exists).
#[serde(skip_serializing_if = "Option::is_none")]
pub query: Option<LogsListQuery>,
pub timestamp: i64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct LogsListQuery {
pub trace_id: Option<String>,
pub span_id: Option<String>,
pub severity_min: Option<i32>,
pub severity_text: Option<String>,
pub start_time: Option<u64>,
pub end_time: Option<u64>,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct MetricsListResult {
pub engine_metrics: EngineMetricsView,
/// Stored SDK metric points (serialized).
pub sdk_metrics: Vec<Value>,
pub timestamp: i64,
/// Time-bucketed aggregates (present only when an aggregate_interval was requested and produced data).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub aggregated_metrics: Vec<Value>,
/// Echo of the applied query filters (present only when a filter was supplied).
#[serde(skip_serializing_if = "Option::is_none")]
pub query: Option<MetricsListQuery>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct EngineMetricsView {
pub invocations: InvocationsView,
pub workers: WorkersView,
pub performance: PerformanceView,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct InvocationsView {
pub total: u64,
pub success: u64,
pub error: u64,
pub deferred: u64,
/// Per-function invocation counts.
pub by_function: HashMap<String, u64>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct WorkersView {
pub spawns: u64,
pub deaths: u64,
pub active: u64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct PerformanceView {
pub avg_duration_ms: f64,
pub p50_duration_ms: f64,
pub p95_duration_ms: f64,
pub p99_duration_ms: f64,
pub min_duration_ms: f64,
pub max_duration_ms: f64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct MetricsListQuery {
pub start_time: Option<u64>,
pub end_time: Option<u64>,
pub aggregate_interval: Option<u64>,
pub metric_name: Option<String>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SamplingRulesResult {
pub traces: SamplingTracesView,
pub logs: SamplingLogsView,
pub timestamp: i64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SamplingTracesView {
pub default_ratio: f64,
pub rules: Vec<SamplingRuleView>,
pub parent_based: bool,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SamplingRuleView {
// No skip_serializing_if: the prior json! always emitted these (null when unset).
pub operation: Option<String>,
pub service: Option<String>,
pub rate: f64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SamplingLogsView {
pub sampling_ratio: f64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct HealthCheckResult {
pub status: String,
pub components: HealthComponentsView,
pub timestamp: i64,
pub version: String,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct HealthComponentsView {
/// Each component is `{ status: "healthy"|"disabled", details: <object|null> }`.
pub otel: Value,
pub metrics: Value,
pub logs: Value,
pub spans: Value,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AlertsListResult {
/// Current evaluated alert states (serialized).
pub alerts: Vec<Value>,
/// Configured alert rules (present when the alert manager is initialized).
#[serde(skip_serializing_if = "Option::is_none")]
pub rules: Option<Vec<config::AlertRule>>,
pub firing_count: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
pub timestamp: i64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct AlertsEvaluateResult {
pub evaluated: bool,
/// Alerts triggered by this evaluation pass (present when the manager is initialized).
#[serde(skip_serializing_if = "Option::is_none")]
pub triggered_alerts: Option<Vec<Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
pub timestamp: i64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct RollupsListResult {
/// Pre-aggregated metric rollups (serialized).
pub rollups: Vec<Value>,
/// Pre-aggregated histogram rollups (serialized).
pub histogram_rollups: Vec<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub level: Option<usize>,
/// "on_the_fly" when computed live because no rollup storage exists.
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub query: Option<RollupsListQuery>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
pub timestamp: i64,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct RollupsListQuery {
pub start_time: Option<u64>,
pub end_time: Option<u64>,
pub metric_name: Option<String>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct BaggageGetResult {
pub value: Option<String>,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct BaggageSetResult {
pub success: bool,
pub note: String,
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct BaggageGetAllResult {
pub baggage: HashMap<String, String>,
}
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct MetricsListInput {
/// Start time in Unix timestamp milliseconds
pub start_time: Option<u64>,
/// End time in Unix timestamp milliseconds
pub end_time: Option<u64>,
/// Filter by metric name
pub metric_name: Option<String>,
/// Aggregate interval in seconds
pub aggregate_interval: Option<u64>,
}
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct LogsListInput {
/// Start time in Unix timestamp milliseconds
pub start_time: Option<u64>,
/// End time in Unix timestamp milliseconds
pub end_time: Option<u64>,
/// Filter by trace ID
pub trace_id: Option<String>,
/// Filter by span ID
pub span_id: Option<String>,
/// Minimum severity number (1-24, higher = more severe)
pub severity_min: Option<i32>,
/// Filter by severity text (e.g., "ERROR", "WARN", "INFO")
pub severity_text: Option<String>,
/// Pagination offset (default: 0)
pub offset: Option<usize>,
/// Maximum number of logs to return
pub limit: Option<usize>,
}
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct LogsClearInput {}
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct HealthCheckInput {}
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct AlertsListInput {}
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct AlertsEvaluateInput {}
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct RollupsListInput {
/// Start time in Unix timestamp milliseconds
pub start_time: Option<u64>,
/// End time in Unix timestamp milliseconds
pub end_time: Option<u64>,
/// Rollup level index (0 = 1 min, 1 = 5 min, 2 = 1 hour)
pub level: Option<usize>,
/// Filter by metric name
pub metric_name: Option<String>,
}
// =============================================================================
// Resource Attributes Helper
// =============================================================================
/// Extract resource attributes from OTEL config for log entries.
///
/// Returns a HashMap containing:
/// - `service.name` - The service name from OTEL config
/// - `service.namespace` - The service namespace (if configured)
/// - `service.version` - The service version (if configured)
/// - `deployment.environment` - From DEPLOYMENT_ENVIRONMENT env var (if set)
fn get_resource_attributes() -> HashMap<String, String> {
otel::get_otel_config()
.map(|cfg| {
let mut map = HashMap::new();
if let Some(name) = &cfg.service_name {
map.insert("service.name".to_string(), name.clone());
}
if let Some(ns) = &cfg.service_namespace {
map.insert("service.namespace".to_string(), ns.clone());
}
if let Some(ver) = &cfg.service_version {
map.insert("service.version".to_string(), ver.clone());
}
// Add deployment environment if set
if let Ok(env) = std::env::var("DEPLOYMENT_ENVIRONMENT") {
map.insert("deployment.environment".to_string(), env);
}
map
})
.unwrap_or_default()
}
/// Parses an environment variable into type `T`, logging a warning if the value is present but
/// not valid. Returns `None` when the variable is unset or cannot be parsed.
fn parse_env_var<T: std::str::FromStr>(name: &str) -> Option<T> {
let val = std::env::var(name).ok()?;
match val.parse() {
Ok(v) => Some(v),
Err(_) => {
tracing::warn!("Invalid value '{}' for {}, ignoring", val, name);
None
}
}
}
fn memory_exporter_not_enabled_error<T>() -> FunctionResult<T, ErrorBody> {
FunctionResult::Failure(ErrorBody {
code: "memory_exporter_not_enabled".to_string(),
message: "In-memory span storage is not available. Set exporter: memory or both in config."
.to_string(),
stacktrace: None,
})
}
fn healthy_component(details: Value) -> Value {
serde_json::json!({
"status": "healthy",
"details": details,
})
}
fn disabled_component() -> Value {
serde_json::json!({
"status": "disabled",
"details": null,
})
}
fn should_trigger_for_level(trigger_level: &str, log_level: &str) -> bool {
trigger_level == "all" || trigger_level == log_level
}
/// Whether a span matches a `trace` trigger's optional filters. An absent
/// filter matches anything; present filters are ANDed and compared
/// case-insensitively. Mirrors `should_trigger_for_level` for the log trigger.
fn should_trigger_for_span(
config_service: Option<&str>,
config_status: Option<&str>,
span: &otel::StoredSpan,
) -> bool {
if let Some(service) = config_service
&& !span.service_name.eq_ignore_ascii_case(service)
{
return false;
}
if let Some(status) = config_status
&& !span.status.eq_ignore_ascii_case(status)
{
return false;
}
true
}
/// The `function_id` attribute a span was produced under, if any.
fn span_function_id(span: &otel::StoredSpan) -> Option<&str> {
span.attributes
.iter()
.find(|(k, _)| k == "function_id")
.map(|(_, v)| v.as_str())
}
/// Engine-internal / plumbing spans, excluded from the `trace` trigger the
/// same way `traces::list` hides them by default (`iii.function.kind=internal`
/// or an `engine::` function id). Keeps the trigger focused on real work and
/// is the first half of breaking the trigger's feedback loop.
fn is_internal_span(span: &otel::StoredSpan) -> bool {
span.attributes.iter().any(|(k, v)| {
(k == "iii.function.kind" && v == "internal")
|| (k == "function_id" && v.starts_with("engine::"))
})
}
// =============================================================================
// OpenTelemetry Module
// =============================================================================
/// Trigger type ID for log events from the observability module
pub const LOG_TRIGGER_TYPE: &str = "log";
/// Log triggers for OTEL module
pub struct OtelLogTriggers {
pub triggers: Arc<TokioRwLock<HashSet<Trigger>>>,
}
impl Default for OtelLogTriggers {
fn default() -> Self {
Self::new()
}
}
impl OtelLogTriggers {
pub fn new() -> Self {
Self {
triggers: Arc::new(TokioRwLock::new(HashSet::new())),
}
}
}
/// Trigger type ID for span/trace events from the observability module
pub const TRACE_TRIGGER_TYPE: &str = "trace";
/// Trailing-edge coalesce window for the `trace` trigger fan-out. Spans arrive
/// batched and at high volume; collapsing a burst into one tick keeps the
/// fan-out (and the spans its own delivery produces) to a trickle.
const TRACE_COALESCE_MS: u64 = 300;
/// Live span streams the observability worker pushes onto each coalesce tick,
/// consumed by the console Traces view (and any iii client) as a real-time
/// append feed instead of refetching `engine::traces::*`. Ephemeral
/// `stream::send`: the in-memory store stays the source of truth and is
/// re-read once on (re)connect, so a dropped frame self-heals.
const TRACE_ROWS_STREAM: &str = "iii:devtools:trace-rows";
const TRACE_SPANS_STREAM: &str = "iii:devtools:trace-spans";
/// The single group every list subscriber joins — the list is a global
/// firehose, not per-trace. Detail subscribers join the `trace_id` group.
const TRACE_ROWS_GROUP: &str = "all";
/// Trace (span) triggers for the OTEL module
pub struct OtelTraceTriggers {
pub triggers: Arc<TokioRwLock<HashSet<Trigger>>>,
}
impl Default for OtelTraceTriggers {
fn default() -> Self {
Self::new()
}
}
impl OtelTraceTriggers {
pub fn new() -> Self {
Self {
triggers: Arc::new(TokioRwLock::new(HashSet::new())),
}
}
}
/// Input for OTEL log functions (log.info, log.warn, log.error)
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct OtelLogInput {
/// Optional trace ID for correlation
trace_id: Option<String>,
/// Optional span ID for correlation
span_id: Option<String>,
/// The log message
message: String,
/// Additional structured data/attributes
data: Option<Value>,
/// Service name (defaults to function name if not provided)
service_name: Option<String>,
}
/// Input for baggage.get function
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct BaggageGetInput {
/// The baggage key to retrieve
pub key: String,
}
/// Input for baggage.set function
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct BaggageSetInput {
/// The baggage key to set
pub key: String,
/// The baggage value to set
pub value: String,
}
/// Input for baggage.getAll function (empty)
#[derive(Serialize, Deserialize, Default, JsonSchema)]
pub struct BaggageGetAllInput {}
/// OpenTelemetry configuration module.
/// This module provides OTEL-native logging, traces, metrics, and logs access.
/// It sets the global OTEL configuration from YAML before logging is initialized.
#[derive(Clone)]
pub struct ObservabilityWorker {
/// The config.yaml block passed to `create()` (or built-in defaults).
/// Used as the seed for first-time `configuration::register` and as the
/// fetch fallback; the configuration worker entry is the runtime source
/// of truth afterwards.
_config: config::ObservabilityWorkerConfig,
triggers: Arc<OtelLogTriggers>,
trace_triggers: Arc<OtelTraceTriggers>,
engine: Arc<Engine>,
/// Shutdown signal sender for background tasks
shutdown_tx: Arc<tokio::sync::watch::Sender<bool>>,
/// The live worker shutdown receiver, stored by `start_background_tasks`
/// so `apply_config` can hand respawned tasks the same lifecycle. `None`
/// until started / after destroy — task rebuilds are refused then (the
/// other apply tiers still run).
worker_shutdown_rx: Arc<std::sync::Mutex<Option<tokio::sync::watch::Receiver<bool>>>>,
/// Stop signal for the current log-retention task instance (respawned on
/// `logs_retention_seconds` changes).
logs_retention_stop: Arc<std::sync::Mutex<Option<tokio::sync::watch::Sender<bool>>>>,
/// Stop signal for the current OTLP logs exporter task instance
/// (respawned on exporter/batch/flush/endpoint/identity changes).
logs_exporter_stop: Arc<std::sync::Mutex<Option<tokio::sync::watch::Sender<bool>>>>,
/// Stop signal for the current log-trigger subscriber task instance.
/// Respawned when `logs_enabled` flips false->true at runtime so the `log`
/// trigger fan-out reactivates without an engine restart.
logs_trigger_stop: Arc<std::sync::Mutex<Option<tokio::sync::watch::Sender<bool>>>>,
/// Serializes concurrent `apply_config` runs (rapid configuration edits).
apply_lock: Arc<tokio::sync::Mutex<()>>,
}
/// A compiled [`config::SpanCollapseRule`] with precompiled regex patterns.
struct CompiledCollapseRule {
name: regex::Regex,
service: Option<regex::Regex>,
}
impl CompiledCollapseRule {
fn matches(&self, name: &str, service: &str) -> bool {
self.name.is_match(name) && self.service.as_ref().map_or(true, |s| s.is_match(service))
}
}
/// Convert a `*`/`?` wildcard pattern into an anchored regex (mirrors the
/// sampler's wildcard handling).
fn collapse_wildcard_to_regex(pattern: &str) -> Result<regex::Regex, regex::Error> {
let escaped = regex::escape(pattern);
let regex_pattern = escaped.replace(r"\*", ".*").replace(r"\?", ".");
regex::Regex::new(&format!("^{}$", regex_pattern))
}
/// True for the engine-internal trigger fan-out wrapper spans
/// (`state_triggers`/`stream_triggers`).
fn is_trigger_wrapper(name: &str) -> bool {
name == "state_triggers" || name == "stream_triggers"
}
/// Drop NO-OP trigger fan-out wrappers from the assembled tree: a
/// `state_triggers`/`stream_triggers` span with no children fanned out to a
/// handler that produced nothing traceable (e.g. the suppressed devtools stream
/// consumers) — pure noise, and a turn step emits many. Wrappers that DID invoke
/// a handler are kept, so the "ran because of a state/stream write" causality
/// stays visible. Iterates to a fixpoint so a wrapper left childless by pruning a
/// nested wrapper also drops. Childless spans have nothing to reparent, so the
/// tree stays connected without rewriting any parent links.
fn prune_empty_trigger_spans(mut spans: Vec<otel::StoredSpan>) -> Vec<otel::StoredSpan> {
loop {
let has_child: std::collections::HashSet<String> = spans
.iter()
.filter_map(|s| s.parent_span_id.clone())
.collect();
let before = spans.len();
spans.retain(|s| !(is_trigger_wrapper(&s.name) && !has_child.contains(&s.span_id)));
if spans.len() == before {
break;
}
}
spans
}
/// Compiled collapse rules for the global config, cached after first use and
/// recompiled by `refresh_collapse_rules` when the configuration-worker
/// apply path changes them. Callers on the hot path (one per coalesce tick /
/// REST request) must not recompile the regexes each time. Returns an empty
/// set — without poisoning the cache — if the config is not set yet.
static COLLAPSE_RULES: std::sync::RwLock<Option<Arc<Vec<CompiledCollapseRule>>>> =
std::sync::RwLock::new(None);
fn cached_collapse_rules() -> Arc<Vec<CompiledCollapseRule>> {
{
let cached = COLLAPSE_RULES
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(rules) = cached.as_ref() {
return rules.clone();
}
}
match otel::get_otel_config() {
Some(config) => {
let compiled = Arc::new(compile_collapse_rules(&config.collapse_spans));
let mut cached = COLLAPSE_RULES
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
cached.get_or_insert_with(|| compiled.clone()).clone()
}
None => Arc::new(Vec::new()),
}
}
/// Recompile the collapse-rule cache from the given rules (configuration
/// apply path).
pub(crate) fn refresh_collapse_rules(rules: &[config::SpanCollapseRule]) {
let compiled = Arc::new(compile_collapse_rules(rules));
*COLLAPSE_RULES
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(compiled);
}
/// Compile the configured collapse rules, skipping any with invalid patterns.
fn compile_collapse_rules(rules: &[config::SpanCollapseRule]) -> Vec<CompiledCollapseRule> {
rules
.iter()
.filter_map(|r| {
let name = collapse_wildcard_to_regex(&r.name).ok()?;
let service = match &r.service {
Some(p) => Some(collapse_wildcard_to_regex(p).ok()?),
None => None,
};
Some(CompiledCollapseRule { name, service })
})
.collect()
}
/// Remove spans matching any collapse rule, reparenting each surviving span to
/// its nearest non-collapsed ancestor so the trace tree stays connected.
///
/// Operates on the full set of spans for a trace, so reparenting is exact
/// regardless of span arrival order. Raw spans in storage / exported to the
/// collector are untouched — this only affects the assembled tree view.
fn collapse_spans(
spans: Vec<otel::StoredSpan>,
rules: &[CompiledCollapseRule],
) -> Vec<otel::StoredSpan> {
if rules.is_empty() {
return spans;
}
let collapsed: std::collections::HashSet<String> = spans
.iter()
.filter(|s| rules.iter().any(|r| r.matches(&s.name, &s.service_name)))
.map(|s| s.span_id.clone())
.collect();
if collapsed.is_empty() {
return spans;
}
let parent_of: HashMap<String, Option<String>> = spans
.iter()
.map(|s| (s.span_id.clone(), s.parent_span_id.clone()))
.collect();
// Walk up the chain of collapsed ancestors to the first survivor (or root).
let resolve = |start: Option<String>| -> Option<String> {
let mut pid = start;
let mut guard = 0usize;
while let Some(id) = pid.clone() {
if !collapsed.contains(&id) {
break;
}
pid = parent_of.get(&id).cloned().flatten();
guard += 1;
if guard > 100_000 {
break; // cycle guard
}
}
pid
};
spans
.into_iter()
.filter(|s| !collapsed.contains(&s.span_id))
.map(|mut s| {
s.parent_span_id = resolve(s.parent_span_id.take());
s
})
.collect()
}
/// From a trace's corrected (post prune+collapse) spans and the ids that just
/// arrived in this coalesce window, select the spans to push on the detail
/// stream: each arrived survivor plus its corrected ancestor chain, walked to
/// the root.
///
/// Including the chain is what re-attaches a span whose nearest real parent is a
/// KEPT internal wrapper (e.g. `stream_triggers`) that the raw window omitted —
/// without it the consumer treats the span's absent parent as a new depth-0 root
/// (the console/web "phantom root" bug). Walking to the root keeps every frame
/// self-contained, so it survives a dropped earlier frame the same way the feed
/// already self-heals on reconnect; the cost is re-emitting ancestors, which is
/// safe because the detail feed is upsert-by-`span_id`. Returned spans carry
/// their CORRECTED `parent_span_id`, so the consumer's `buildSpanTree` nests
/// them identically to `traces::tree` instead of re-rooting.
fn detail_stream_spans(
corrected: &[otel::StoredSpan],
arrived_ids: &HashSet<String>,
) -> Vec<otel::StoredSpan> {
let parent_of: HashMap<&str, Option<&str>> = corrected
.iter()
.map(|s| (s.span_id.as_str(), s.parent_span_id.as_deref()))
.collect();
let mut emit_ids: HashSet<String> = HashSet::new();
for span in corrected {
// Start only from spans that actually arrived this window AND survived
// the pipeline; a collapsed/pruned arrival simply contributes nothing.
if !arrived_ids.contains(&span.span_id) {
continue;
}
let mut cursor: Option<&str> = Some(span.span_id.as_str());
while let Some(id) = cursor {
// Already walked this id (and therefore its ancestors) — stop.
// This also terminates parent cycles: a cycle must revisit an id.
if !emit_ids.insert(id.to_string()) {
break;
}
cursor = parent_of.get(id).copied().flatten();
}
}
corrected
.iter()
.filter(|s| emit_ids.contains(&s.span_id))
.cloned()
.collect()
}
/// Shared trace-correction pipeline: drop no-op trigger fan-out wrappers
/// (childless state_triggers/stream_triggers — wrappers that actually invoked
/// a handler are kept so trigger→handler causality stays visible), then
/// collapse user-configured pass-through spans, reparenting children to the
/// nearest survivor. Both `traces::tree` and the live detail stream go through
/// this one function so the live feed can never disagree with the REST tree.
fn correct_trace_spans(
spans: Vec<otel::StoredSpan>,
rules: &[CompiledCollapseRule],
) -> Vec<otel::StoredSpan> {
collapse_spans(prune_empty_trigger_spans(spans), rules)
}
/// Build the detail-stream payload for one trace: run the same
/// [`correct_trace_spans`] pipeline `traces::tree` uses over the FULL raw
/// trace, then keep each arrived span and its corrected ancestor chain (see
/// [`detail_stream_spans`]).
///
/// The full trace — not just the window — is required because the surviving
/// ancestor a span must reparent to may have arrived in an earlier window.
/// Pure over its inputs so the correction is unit-testable without span storage.
fn corrected_detail_spans(
full_trace: Vec<otel::StoredSpan>,
arrived_ids: &HashSet<String>,
rules: &[CompiledCollapseRule],
) -> Vec<otel::StoredSpan> {
let corrected = correct_trace_spans(full_trace, rules);
detail_stream_spans(&corrected, arrived_ids)
}
fn build_span_tree(spans: Vec<otel::StoredSpan>) -> Vec<SpanTreeNode> {
// Span ids present in this set. A span whose parent is NOT present is a
// local trace root — covers traces entering iii from an external caller via
// an incoming `traceparent`, whose server span points at the remote caller's
// span (never stored here). Without this the whole subtree is orphaned and
// the trace detail view renders nothing.
let present_ids: std::collections::HashSet<String> =
spans.iter().map(|s| s.span_id.clone()).collect();
let mut children_map: HashMap<String, Vec<otel::StoredSpan>> = HashMap::new();
let mut roots: Vec<otel::StoredSpan> = Vec::new();
for span in spans {
match &span.parent_span_id {
Some(parent_id) if present_ids.contains(parent_id) => {
children_map
.entry(parent_id.clone())
.or_default()
.push(span);
}
_ => roots.push(span),
}
}
roots
.into_iter()
.map(|root| build_span_tree_node(root, &mut children_map))
.collect()
}
fn build_span_tree_node(
span: otel::StoredSpan,
children_map: &mut HashMap<String, Vec<otel::StoredSpan>>,
) -> SpanTreeNode {
let children = children_map
.remove(&span.span_id)
.unwrap_or_default()
.into_iter()
.map(|child| build_span_tree_node(child, children_map))
.collect();
SpanTreeNode { span, children }
}
#[service(name = "otel")]
impl ObservabilityWorker {
/// The authoritative log-storage capacity: the live global configuration
/// (kept current by the configuration-worker apply path) with the yaml
/// seed as fallback. Passing the seed directly would revert a runtime
/// edit on the next lazy re-init.
fn effective_logs_max_count(&self) -> Option<usize> {
otel::get_otel_config()
.and_then(|c| c.logs_max_count)
.or(self._config.logs_max_count)
}
fn from_config(engine: Arc<Engine>, config: Option<Value>) -> anyhow::Result<Self> {
let otel_config: config::ObservabilityWorkerConfig = match config {
Some(cfg) => serde_json::from_value(cfg)?,
None => config::ObservabilityWorkerConfig::default(),
};
let otel_config = otel_config.normalized();
// Seed the global OTEL config so logging can use it. On the serve
// path the global is already populated during logging init (from the
// persisted configuration entry or this same yaml block); first-set
// semantics keep that value authoritative.
if !otel::set_otel_config(otel_config.clone()) {
tracing::debug!(
"ObservabilityWorker created with the global config already set; keeping it"
);
}
let (shutdown_tx, _) = tokio::sync::watch::channel(false);
Ok(ObservabilityWorker {
_config: otel_config,
triggers: Arc::new(OtelLogTriggers::new()),
trace_triggers: Arc::new(OtelTraceTriggers::new()),
engine,
shutdown_tx: Arc::new(shutdown_tx),
worker_shutdown_rx: Arc::new(std::sync::Mutex::new(None)),
logs_retention_stop: Arc::new(std::sync::Mutex::new(None)),
logs_exporter_stop: Arc::new(std::sync::Mutex::new(None)),
logs_trigger_stop: Arc::new(std::sync::Mutex::new(None)),
apply_lock: Arc::new(tokio::sync::Mutex::new(())),
})
}
/// Construct a worker from a raw config value — mirrors
/// `ConfigurationWorker::for_test` so integration tests in `engine/tests/`
/// can drive the concrete worker without booting the full engine.
#[doc(hidden)]
pub fn for_test(engine: Arc<Engine>, config: Option<Value>) -> anyhow::Result<Self> {
Self::from_config(engine, config)
}
/// The live effective configuration: the global snapshot kept current by
/// the configuration-worker apply path, with the yaml seed as fallback.
pub fn current_config(&self) -> config::ObservabilityWorkerConfig {
otel::get_otel_config()
.map(|cfg| (*cfg).clone())
.unwrap_or_else(|| self._config.clone())
}
/// True while the worker is started and has not been destroyed.
///
/// `worker_shutdown_rx` is set at the top of `start_background_tasks`
/// (before the change trigger that drives `on_config_change` is registered)