dmsc/c/service_mesh.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//! # Service Mesh Module C API
19//!
20//! This module provides C language bindings for DMSC's service mesh infrastructure. The service mesh
21//! module delivers comprehensive service-to-service communication capabilities including service discovery,
22//! load balancing, circuit breaking, traffic routing, and observability for distributed systems. This
23//! C API enables C/C++ applications to leverage DMSC's service mesh functionality for building resilient,
24//! observable, and manageable microservices architectures.
25//!
26//! ## Module Architecture
27//!
28//! The service mesh module comprises three primary components that together provide complete service
29//! management capabilities:
30//!
31//! - **DMSCServiceMesh**: Central service mesh controller managing service registry, traffic routing,
32//! and communication policies across all connected services. The mesh controller handles the complete
33//! lifecycle of service communication including discovery, routing, load balancing, and failure handling.
34//!
35//! - **DMSCServiceMeshConfig**: Configuration container for service mesh parameters including discovery
36//! settings, traffic management policies, circuit breaker thresholds, and observability options.
37//! The configuration object controls mesh behavior, resource allocation, and operational characteristics.
38//!
39//! - **DMSCServiceEndpoint**: Individual service endpoint representation within the mesh, tracking
40//! service instance metadata, health status, load metrics, and communication properties. Endpoints
41//! represent actual running instances of services that can receive traffic.
42//!
43//! ## Service Discovery
44//!
45//! The service mesh provides automatic service discovery capabilities:
46//!
47//! - **Service Registration**: Services automatically register with the mesh when they start,
48//! advertising their network location, port, and metadata. Registration includes health check
49//! endpoints and load reporting.
50//!
51//! - **Instance Tracking**: The mesh maintains a live registry of all service instances with
52//! real-time health status, load metrics, and topology information.
53//!
54//! - **DNS-Based Discovery**: Services discover each other using DNS-like naming conventions.
55//! Service names resolve to healthy instances based on routing policies.
56//!
57//! - **Health Checking**: Automatic health checks verify service instance availability. Unhealthy
58//! instances are removed from the load balancer rotation until they recover.
59//!
60//! - **Service Metadata**: Rich metadata attached to service registrations including version, zone,
61//! cluster, and custom labels for sophisticated routing decisions.
62//!
63//! ## Traffic Management
64//!
65//! The mesh implements sophisticated traffic routing:
66//!
67//! - **Load Balancing**: Multiple load balancing algorithms including round-robin, least-connections,
68//! weighted distribution, and consistent hashing for session affinity.
69//!
70//! - **Canary Deployments**: Gradual traffic shifting between service versions for safe rollouts.
71//! Configure percentage-based or rules-based traffic splitting.
72//!
73//! - **A/B Testing**: Route specific percentages of traffic to different service versions
74//! for testing new features with production traffic.
75//!
76//! - **Blue-Green Deployments**: Zero-downtime deployments by switching traffic between complete
77//! service environments. Enables instant rollback capability.
78//!
79//! - **Traffic Mirroring**: Copy production traffic to shadow services for testing without
80//! affecting production responses. Useful for validating new service versions.
81//!
82//! - **Retries and Timeouts**: Configurable retry policies and timeout values for all
83//! service-to-service calls. Automatic retry for idempotent operations.
84//!
85//! ## Circuit Breaking
86//!
87//! The service mesh implements circuit breaker patterns for failure isolation:
88//!
89//! - **Failure Detection**: Automatic detection of downstream service failures through
90//! error rates, latency percentiles, and custom health indicators.
91//!
92//! - **Open Circuit**: When failure threshold is exceeded, the circuit opens and requests
93//! immediately fail without making downstream calls. Prevents cascade failures.
94//!
95//! - **Half-Open State**: After cooldown period, limited requests are allowed through to
96//! test if the downstream service has recovered.
97//!
98//! - **Close Circuit**: Successful responses during half-open state close the circuit
99//! and restore normal operation.
100//!
101//! - **Configuration**: Tunable failure thresholds, timeout values, and volume thresholds
102//! for each service dependency.
103//!
104//! - **Fallback Handling**: Configurable fallback responses or alternative service calls
105//! when circuit is open. Enables graceful degradation.
106//!
107//! ## Resilience Patterns
108//!
109//! The mesh provides comprehensive resilience mechanisms:
110//!
111//! - **Bulkhead Isolation**: Isolate critical resources by limiting concurrent requests
112//! to downstream services. Prevents one slow service from affecting others.
113//!
114//! - **Rate Limiting**: Per-service and per-instance rate limits prevent overload scenarios.
115//! Supports token bucket and sliding window algorithms.
116//!
117//! - **Retry Policies**: Configurable retry attempts, backoff strategies (fixed, exponential,
118//! jitter), and retry conditions (5xx, timeouts, connection failures).
119//!
120//! - **Timeout Management**: End-to-end timeout propagation ensures requests don't wait
121//! indefinitely. Supports deadline propagation across service boundaries.
122//!
123//! ## Security
124//!
125//! The service mesh implements zero-trust security principles:
126//!
127//! - **mTLS Encryption**: Automatic mutual TLS encryption for all service-to-service
128//! communication. Certificates automatically rotated and validated.
129//!
130//! - **Service Identity**: Strong identity verification using SPIFFE-style identifiers.
131//! Each service has verifiable credentials independent of network location.
132//!
133//! - **Authorization Policies**: Fine-grained access control policies defining which
134//! services can communicate. Default deny-all policy with explicit allow rules.
135//!
136//! - **Authentication**: JWT validation, OAuth token exchange, and custom authentication
137//! mechanisms integrated at the mesh layer.
138//!
139//! - **Network Policies**: L3/L4 network filtering restricting communication between
140//! services based on identity and metadata.
141//!
142//! ## Observability
143//!
144//! The mesh provides comprehensive observability features:
145//!
146//! - **Traffic Metrics**: Request rates, latencies (p50, p95, p99), and error rates
147//! for all service-to-service communication.
148//!
149//! - **Distributed Tracing**: Automatic trace context propagation across service
150//! boundaries with W3C Trace Context standard.
151//!
152//! - **Service Graph**: Real-time visualization of service topology and communication
153//! patterns. Identifies dependencies and communication bottlenecks.
154//!
155//! - **Access Logging**: Detailed logs of all service-to-service communication including
156//! headers, status codes, and timing information.
157//!
158//! - **Custom Metrics**: User-defined metrics collected at the mesh layer independent
159//! of application code.
160//!
161//! ## Performance Characteristics
162//!
163//! Service mesh operations are optimized for minimal overhead:
164//!
165//! - **Sidecar Pattern**: Lightweight proxy (Envoy) deployed alongside each service instance.
166//! Intercepts all traffic with minimal latency overhead.
167//!
168//! - **xDS Configuration**: Efficient configuration distribution using xDS (discovery services)
169//! protocol. Changes propagate in seconds across the mesh.
170//!
171//! - **Connection Pooling**: Efficient connection management to upstream services with
172//! configurable pool sizes and connection limits.
173//!
174//! - **Batching and Buffering**: Request batching and response buffering optimize throughput
175//! while maintaining latency SLAs.
176//!
177//! - **Zero-Copy**: Modern data plane implementations use zero-copy techniques where
178//! possible to minimize CPU overhead.
179//!
180//! ## Memory Management
181//!
182//! All C API objects use opaque pointers with manual memory management:
183//!
184//! - Constructor functions allocate new instances on the heap
185//! - Destructor functions must be called to release memory
186//! - Service endpoints are managed by the mesh controller
187//! - Configuration objects control mesh-wide settings
188//!
189//! ## Thread Safety
190//!
191//! The underlying implementations are thread-safe:
192//!
193//! - Concurrent service registration from multiple instances supported
194//! - Route configuration updates atomic across the mesh
195//! - Load balancing decisions thread-safe
196//! - Metrics collection lock-free for performance
197//!
198//! ## Usage Example
199//!
200//! ```c
201//! // Create service mesh configuration
202//! DMSCServiceMeshConfig* config = dmsc_service_mesh_config_new();
203//! if (config == NULL) {
204//! fprintf(stderr, "Failed to create service mesh config\n");
205//! return ERROR_INIT;
206//! }
207//!
208//! // Configure mesh settings
209//! dmsc_service_mesh_config_set_enable_mtls(config, true);
210//! dmsc_service_mesh_config_set_enable_circuit_breaker(config, true);
211//! dmsc_service_mesh_config_set_enable_tracing(config, true);
212//! dmsc_service_mesh_config_set_enable_metrics(config, true);
213//!
214//! // Configure circuit breaker
215//! dmsc_service_mesh_config_set_circuit_breaker_failure_rate(config, 0.5);
216//! dmsc_service_mesh_config_set_circuit_breaker_timeout_ms(config, 30000);
217//!
218//! // Configure load balancing
219//! dmsc_service_mesh_config_set_load_balancing_algorithm(config, LB_LEAST_REQUESTS);
220//!
221//! // Create service mesh controller
222//! DMSCServiceMesh* mesh = dmsc_service_mesh_new(config);
223//! if (mesh == NULL) {
224//! fprintf(stderr, "Failed to create service mesh\n");
225//! dmsc_service_mesh_config_free(config);
226//! return ERROR_INIT;
227//! }
228//!
229//! // Start the mesh controller
230//! int result = dmsc_service_mesh_start(mesh);
231//! if (result != 0) {
232//! fprintf(stderr, "Failed to start service mesh: %d\n", result);
233//! dmsc_service_mesh_free(mesh);
234//! dmsc_service_mesh_config_free(config);
235//! return ERROR_START;
236//! }
237//!
238//! printf("Service mesh started successfully\n");
239//!
240//! // Register a service endpoint
241//! DMSCServiceEndpoint* endpoint = dmsc_service_endpoint_new();
242//! if (endpoint == NULL) {
243//! fprintf(stderr, "Failed to create service endpoint\n");
244//! dmsc_service_mesh_stop(mesh);
245//! dmsc_service_mesh_free(mesh);
246//! dmsc_service_mesh_config_free(config);
247//! return ERROR_INIT;
248//! }
249//!
250//! dmsc_service_endpoint_set_name(endpoint, "user-service");
251//! dmsc_service_endpoint_set_host(endpoint, "10.0.1.5");
252//! dmsc_service_endpoint_set_port(endpoint, 8080);
253//! dmsc_service_endpoint_set_version(endpoint, "v1.2.3");
254//! dmsc_service_endpoint_set_health_check_url(endpoint, "/health");
255//!
256//! result = dmsc_service_mesh_register(mesh, endpoint);
257//! if (result != 0) {
258//! fprintf(stderr, "Failed to register endpoint: %d\n", result);
259//! dmsc_service_endpoint_free(endpoint);
260//! } else {
261//! printf("Service endpoint registered successfully\n");
262//! }
263//!
264//! // Get service information
265//! const char* service_name = dmsc_service_endpoint_get_name(endpoint);
266//! const char* service_version = dmsc_service_endpoint_get_version(endpoint);
267//! uint32_t healthy_count = dmsc_service_mesh_get_healthy_count(mesh, service_name);
268//!
269//! printf("Service: %s (version: %s), healthy instances: %u\n",
270//! service_name, service_version, healthy_count);
271//!
272//! // Discover a service
273//! DMSCServiceEndpoint* discovered = NULL;
274//! result = dmsc_service_mesh_discover(mesh, "user-service", &discovered);
275//!
276//! if (result == 0 && discovered != NULL) {
277//! const char* host = dmsc_service_endpoint_get_host(discovered);
278//! uint16_t port = dmsc_service_endpoint_get_port(discovered);
279//!
280//! printf("Discovered service at %s:%d\n", host, port);
281//!
282//! dmsc_service_endpoint_free(discovered);
283//! }
284//!
285//! // Update service mesh configuration at runtime
286//! dmsc_service_mesh_config_set_circuit_breaker_failure_rate(mesh, 0.3);
287//! dmsc_service_mesh_reload_config(mesh);
288//!
289//! // Get service mesh statistics
290//! uint64_t total_requests = dmsc_service_mesh_get_total_requests(mesh);
291//! uint64_t failed_requests = dmsc_service_mesh_get_failed_requests(mesh);
292//!
293//! printf("Mesh stats: %lu total requests, %lu failed\n",
294//! total_requests, failed_requests);
295//!
296//! // Deregister service when shutting down
297//! dmsc_service_mesh_deregister(mesh, endpoint);
298//!
299//! // Graceful shutdown
300//! dmsc_service_mesh_stop(mesh);
301//! dmsc_service_endpoint_free(endpoint);
302//! dmsc_service_mesh_free(mesh);
303//! dmsc_service_mesh_config_free(config);
304//!
305//! printf("Service mesh shutdown complete\n");
306//! ```
307//!
308//! ## Dependencies
309//!
310//! This module depends on the following DMSC components:
311//!
312//! - `crate::service_mesh`: Rust service mesh module implementation
313//! - `crate::prelude`: Common types and traits
314//! - Envoy proxy for data plane (embedded or external)
315//! - xDS protocol stack for configuration management
316//!
317//! ## Feature Flags
318//!
319//! The service mesh module is enabled by the "service-mesh" feature flag.
320//! Disable this feature to reduce binary size when service mesh is not required.
321//!
322//! Additional features:
323//!
324//! - `service-mesh-mtls`: Enable mutual TLS encryption
325//! - `service-mesh-circuit-breaker`: Enable circuit breaker functionality
326//! - `service-mesh-tracing`: Enable distributed tracing
327//! - `service-mesh-metrics`: Enable metrics collection
328//! - `service-mesh-dns`: Enable DNS-based service discovery
329
330use crate::service_mesh::{DMSCServiceEndpoint, DMSCServiceMesh, DMSCServiceMeshConfig};
331
332
333c_wrapper!(CDMSCServiceMesh, DMSCServiceMesh);
334c_wrapper!(CDMSCServiceMeshConfig, DMSCServiceMeshConfig);
335c_wrapper!(CDMSCServiceEndpoint, DMSCServiceEndpoint);
336
337// DMSCServiceMeshConfig constructors and destructors
338c_constructor!(
339 dmsc_service_mesh_config_new,
340 CDMSCServiceMeshConfig,
341 DMSCServiceMeshConfig,
342 DMSCServiceMeshConfig::default()
343);
344c_destructor!(dmsc_service_mesh_config_free, CDMSCServiceMeshConfig);