dmsc/c/
observability.rs

1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//!     http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # Observability Module C API
19//!
20//! This module provides C language bindings for DMSC's observability infrastructure. The observability
21//! module delivers comprehensive system monitoring capabilities including distributed tracing, metrics
22//! collection, and health checking. This C API enables C/C++ applications to leverage DMSC's
23//! observability features for understanding system behavior, debugging issues, and monitoring performance
24//! in production environments.
25//!
26//! ## Module Architecture
27//!
28//! The observability module comprises three primary components that together provide complete
29//! monitoring and tracing capabilities:
30//!
31//! - **DMSCObservabilityConfig**: Configuration container for observability infrastructure parameters
32//!   including tracing settings, metrics collection options, export destinations, and sampling
33//!   configurations. The configuration object controls resource allocation, export strategies, and
34//!   behavioral characteristics for all observability features.
35//!
36//! - **DMSCTracer**: Distributed tracing interface for creating and managing trace spans, propagating
37//!   context across service boundaries, and exporting trace data to analysis systems. The tracer
38//!   implements OpenTelemetry-compatible tracing with automatic instrumentation support.
39//!
40//! - **DMSCMetricsRegistry**: Metrics collection and aggregation system supporting multiple metric types
41//!   including counters, gauges, histograms, and summaries. The registry manages metric lifecycle,
42//!   provides dimensional labeling, and exports metrics to monitoring backends.
43//!
44//! ## Distributed Tracing
45//!
46//! The tracing system implements comprehensive distributed tracing capabilities:
47//!
48//! - **Span Creation**: Create trace spans with parent-child relationships to model request flows
49//!   across service boundaries. Spans capture timing, status, attributes, and events.
50//!
51//! - **Context Propagation**: Propagate trace context across process boundaries using W3C Trace Context
52//!   standard. Supports propagation via HTTP headers, gRPC metadata, and message queue properties.
53//!
54//! - **Automatic Instrumentation**: Built-in instrumentation for common frameworks and libraries
55//!   including HTTP servers/clients, database drivers, and message queues.
56//!
57//! - **Sampling Strategies**: Configurable sampling to balance observability with performance impact.
58//!   Supports rate-based, probabilistic, and tail-based sampling strategies.
59//!
60//! - **Span Attributes**: Attach key-value attributes to spans for filtering and aggregating traces.
61//!   Supports automatic attributes (HTTP method, status code) and custom application attributes.
62//!
63//! - **Span Events**: Record timestamped events within spans for debugging and audit trails.
64//!   Events capture discrete occurrences during span execution.
65//!
66//! - **Error Recording**: Automatic error capturing with stack traces and error attributes.
67//!   Errors are marked on spans with full exception information.
68//!
69//! ## Metrics System
70//!
71//! The metrics system provides comprehensive performance and operational monitoring:
72//!
73//! - **Counter Metrics**: Increment-only metrics for counting events like requests, errors, or
74//!   operations. Useful for tracking cumulative totals and rates.
75//!
76//! - **Gauge Metrics**: Arbitrary value metrics that can increase or decrease over time.
77//!   Suitable for tracking current values like queue depth, memory usage, or active connections.
78//!
79//! - **Histogram Metrics**: Statistical distribution metrics that bucket values into configurable
80//!   quantiles. Useful for tracking latency distributions, request sizes, and response times.
81//!
82//! - **Summary Metrics**: Client-side calculated quantiles with optional sum tracking.
83//!   Provides pre-computed percentiles for high-cardinality metrics.
84//!
85//! - **Dimensional Labels**: Attach multiple key-value labels to metrics for flexible filtering
86//!   and aggregation. Labels enable drill-down analysis across service versions, regions, or
87//!   deployment environments.
88//!
89//! - **Metric Views**: Define custom aggregations and label combinations to control storage
90//!   costs and query performance.
91//!
92//! ## Health Checking
93//!
94//! The observability module includes health check infrastructure:
95//!
96//! - **Liveness Probes**: Indicate whether the service is running. Used by orchestrators like
97//!   Kubernetes to restart unhealthy containers.
98//!
99//! - **Readiness Probes**: Indicate whether the service is ready to accept traffic. Prevents
100//!   routing requests to services that are still initializing or overloaded.
101//!
102//! - **Startup Probes**: Slow-startup detection for applications with long initialization times.
103//!   Allows services time to become ready before liveness checks begin.
104//!
105//! - **Custom Health Checks**: Register application-specific health check functions that examine
106//!   dependencies like database connectivity, cache availability, or external services.
107//!
108//! ## Export Pipelines
109//!
110//! The observability system supports multiple export destinations:
111//!
112//! - **OpenTelemetry Protocol**: Standardized export format for compatibility with observability
113//!   backends. Supports both push and pull-based export models.
114//!
115//! - **Prometheus**: Pull-based metrics export compatible with Prometheus and related tools.
116//!   Supports both metrics and trace exposition endpoints.
117//!
118//! - **Jaeger**: Direct export to Jaeger tracing backend for distributed tracing visualization.
119//!
120//! - **Zipkin**: Export to Zipkin tracing backend for distributed tracing analysis.
121//!
122//! - **Logging Export**: Export traces and metrics to application logs for unified log analysis.
123//!
124//! - **Custom Exporters**: User-defined exporters for integration with proprietary monitoring
125//!   systems or specialized analysis pipelines.
126//!
127//! ## Performance Characteristics
128//!
129//! Observability operations are designed for minimal performance impact:
130//!
131//! - **Async Export**: Non-blocking metric and trace export using background threads.
132//!   Producer-consumer patterns prevent slow exporters from impacting application performance.
133//!
134//! - **Sampling**: Configurable sampling reduces trace volume for high-traffic services.
135//!   Default conservative sampling minimizes overhead while preserving important traces.
136//!
137//! - **Batching**: Multiple metrics and traces batched together for efficient network export.
138//!   Reduces connection overhead and improves throughput.
139//!
140//! - **Lazy Initialization**: Observability infrastructure initialized on first use when possible.
141//!   Reduces startup time and memory footprint for unused features.
142//!
143//! - **Memory Bounds**: Internal buffers and queues have configurable size limits to prevent
144//!   unbounded memory growth under high load or exporter failures.
145//!
146//! ## Memory Management
147//!
148//! All C API objects use opaque pointers with manual memory management:
149//!
150//! - Constructor functions allocate new instances on the heap
151//! - Destructor functions must be called to release memory
152//! - Tracer instances should be properly shut down before freeing
153//! - Metrics registries can be shared across components
154//!
155//! ## Thread Safety
156//!
157//! The underlying implementations are thread-safe:
158//!
159//! - Concurrent span creation from multiple threads is supported
160//! - Metric recording operations are lock-free for performance
161//! - Export pipelines handle concurrent data from multiple threads
162//! - Configuration can be modified at runtime for some parameters
163//!
164//! ## Usage Example
165//!
166//! ```c
167//! // Create observability configuration
168//! DMSCObservabilityConfig* config = dmsc_observability_config_new();
169//! if (config == NULL) {
170//!     fprintf(stderr, "Failed to create observability config\n");
171//!     return ERROR_INIT;
172//! }
173//!
174//! // Configure tracing
175//! dmsc_observability_config_set_tracing_enabled(config, true);
176//! dmsc_observability_config_set_tracing_samplerate(config, 0.1);  // 10% sampling
177//! dmsc_observability_config_set_tracing_exporter(config, "otlp");
178//!
179//! // Configure metrics
180//! dmsc_observability_config_set_metrics_enabled(config, true);
181//! dmsc_observability_config_set_metrics_export_interval(config, 60000);  // 60 seconds
182//!
183//! // Configure health checks
184//! dmsc_observability_config_set_health_check_enabled(config, true);
185//!
186//! // Create tracer instance
187//! DMSCTracer* tracer = dmsc_tracer_new(config);
188//! if (tracer == NULL) {
189//!     fprintf(stderr, "Failed to create tracer\n");
190//!     dmsc_observability_config_free(config);
191//!     return ERROR_INIT;
192//! }
193//!
194//! // Create metrics registry
195//! DMSCMetricsRegistry* metrics = dmsc_metrics_registry_new(config);
196//! if (metrics == NULL) {
197//!     fprintf(stderr, "Failed to create metrics registry\n");
198//!     dmsc_tracer_free(tracer);
199//!     dmsc_observability_config_free(config);
200//!     return ERROR_INIT;
201//! }
202//!
203//! // Create a span for tracing
204//! DMSCTraceSpan* span = dmsc_tracer_start_span(tracer, "handle_request");
205//! dmsc_trace_span_set_attribute(span, "http.method", "GET");
206//! dmsc_trace_span_set_attribute(span, "http.url", "/api/users");
207//!
208//! // Record metrics
209//! dmsc_metrics_registry_counter_increment(metrics, "http_requests_total",
210//!     1,  // value
211//!     2,  // label count
212//!     "method", "GET",       // label name, value
213//!     "path", "/api/users"  // label name, value
214//! );
215//!
216//! // Simulate work
217//! // ... application logic ...
218//!
219//! // End span
220//! dmsc_trace_span_end(span);
221//!
222//! // Graceful shutdown
223//! dmsc_tracer_shutdown(tracer);  // Flush remaining traces
224//! dmsc_tracer_free(tracer);
225//! dmsc_metrics_registry_free(metrics);
226//! dmsc_observability_config_free(config);
227//! ```
228//!
229//! ## Dependencies
230//!
231//! This module depends on the following DMSC components:
232//!
233//! - `crate::observability`: Rust observability module implementation
234//! - `crate::prelude`: Common types and traits
235//! - OpenTelemetry SDK for tracing
236//! - Metrics library for metric collection
237//!
238//! ## Feature Flags
239//!
240//! The observability module is enabled by the "observability" feature flag.
241//! Disable this feature to reduce binary size when observability is not required.
242//!
243//! Additional features:
244//!
245//! - observability-tracing: Enable distributed tracing
246//! - observability-metrics: Enable metrics collection
247//! - observability-health: Enable health check endpoints
248//! - observability-opentelemetry: Enable OpenTelemetry export
249//! - observability-prometheus: Enable Prometheus export
250
251use crate::observability::{DMSCMetricsRegistry, DMSCObservabilityConfig, DMSCTracer};
252
253
254c_wrapper!(CDMSCObservabilityConfig, DMSCObservabilityConfig);
255c_wrapper!(CDMSCTracer, DMSCTracer);
256c_wrapper!(CDMSCMetricsRegistry, DMSCMetricsRegistry);
257
258// DMSCObservabilityConfig constructors and destructors
259c_constructor!(
260    dmsc_observability_config_new,
261    CDMSCObservabilityConfig,
262    DMSCObservabilityConfig,
263    DMSCObservabilityConfig::default()
264);
265c_destructor!(dmsc_observability_config_free, CDMSCObservabilityConfig);