dmsc/c/mod.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//! # C/C++ API Module
19//!
20//! This module provides comprehensive C language bindings for the DMSC framework, enabling
21//! C and C++ applications to leverage DMSC's capabilities including application lifecycle
22//! management, authentication, caching, database access, file operations, gateway services,
23//! gRPC communication, event hooks, logging, module RPC, observability, protocol handling,
24//! message queuing, service mesh integration, validation, and WebSocket communication.
25//!
26//! The C API follows C conventions for memory management, error handling, and type conventions
27//! while providing access to DMSC's robust Rust implementation. This allows applications written
28//! in C or C++ to benefit from DMSC's safety guarantees, performance optimizations, and
29//! architectural patterns without requiring a full Rust codebase.
30//!
31//! ## Module Architecture
32//!
33//! The C API module is organized into functional submodules, each providing bindings for a
34//! specific DMSC capability. The module also provides global initialization functions,
35//! version information, and utility functions for managing C strings returned by the API.
36//!
37//! ### Core Submodules
38//!
39//! - **core**: Application initialization, configuration management, and lifecycle control.
40//! Provides the entry point for DMSC-based applications with automatic resource management.
41//!
42//! - **auth**: Authentication and authorization services including JWT token handling,
43//! session management, credential validation, and permission checking.
44//!
45//! - **cache**: In-memory caching with configurable eviction policies (LRU, LFU, TTL-based).
46//! Provides high-performance data caching with thread-safe concurrent access.
47//!
48//! - **database**: Database connection pooling and query execution support. Manages
49//! connection lifecycle with automatic health checking and failover.
50//!
51//! - **device**: Device abstraction layer for managing computational resources with
52//! scheduling, capability tracking, and state management.
53//!
54//! - **fs**: Cross-platform file system operations including path manipulation, file I/O,
55//! directory management, and symbolic link handling.
56//!
57//! ### Communication Submodules
58//!
59//! - **gateway**: HTTP API gateway with request routing, middleware chains, load balancing,
60//! rate limiting, and circuit breaker patterns.
61//!
62//! - **grpc**: gRPC server and client support for RPC communication with Protocol Buffer
63//! serialization, streaming, and connection management.
64//!
65//! - **module_rpc**: Inter-module RPC communication within the DMSC framework for
66//! distributed service coordination.
67//!
68//! - **ws**: WebSocket protocol support for full-duplex communication with session
69//! management and heartbeat mechanisms.
70//!
71//! ### System Submodules
72//!
73//! - **hooks**: Event hook system for extensibility through callback registration and
74//! event dispatching at key lifecycle points.
75//!
76//! - **log**: Structured logging infrastructure with multiple output destinations,
77//! configurable log levels, and structured field support.
78//!
79//! - **observability**: Metrics collection, tracing integration, and health check
80//! endpoints for system monitoring.
81//!
82//! - **protocol**: Protocol handling for various wire formats and serialization
83//! schemes with codec implementations.
84//!
85//! - **queue**: Message queue operations for asynchronous task processing with
86//! reliable delivery semantics.
87//!
88//! - **service_mesh**: Service mesh integration for distributed systems with service
89//! discovery, load balancing, and traffic management.
90//!
91//! - **validation**: Data validation with schema definitions, type checking, and
92//! custom validation rules.
93//!
94//! ## Global Initialization
95//!
96//! The DMSC library must be initialized before using any other API functions:
97//!
98//! ```c
99//! int result = dmsc_init();
100//! if (result != 0) {
101//! fprintf(stderr, "Failed to initialize DMSC library\n");
102//! return result;
103//! }
104//! ```
105//!
106//! Initialization prepares internal resources including:
107//! - Global thread pool configuration
108//! - Default logger setup
109//! - Signal handler registration
110//! - Runtime state initialization
111//!
112//! When the application is finished using DMSC, cleanup must be called:
113//!
114//! ```c
115//! dmsc_cleanup();
116//! ```
117//!
118//! Cleanup releases all global resources and ensures proper shutdown sequence.
119//! All DMSC objects must be freed before calling cleanup to prevent resource leaks.
120//!
121//! ## Memory Management
122//!
123//! The C API uses manual memory management following C conventions:
124//!
125//! - **Object Creation**: Constructor functions return newly allocated objects.
126//! All objects must be freed using the corresponding destructor function.
127//!
128//! - **String Handling**: String-returning functions allocate C strings that must
129//! be freed using dmsc_string_free(). Do not use standard free() on these strings.
130//!
131//! - **NULL Safety**: All functions handle NULL pointers gracefully, returning
132//! error codes or NULL outputs rather than causing undefined behavior.
133//!
134//! - **Error Codes**: Functions return 0 for success, negative values for errors.
135//! Specific error codes are documented for each function.
136//!
137//! ### Memory Management Pattern
138//!
139//! ```c
140//! // Create an object
141//! DMSCLogger* logger = dmsc_logger_new(config);
142//! if (logger == NULL) {
143//! fprintf(stderr, "Failed to create logger\n");
144//! dmsc_log_config_free(config);
145//! return ERROR_ALLOCATION;
146//! }
147//!
148//! // Use the object...
149//!
150//! // Free when done
151//! dmsc_logger_free(logger);
152//!
153//! // For strings returned by the API
154//! const char* version = dmsc_version();
155//! printf("DMSC version: %s\n", version);
156//! dmsc_string_free((char*)version); // Cast to non-const for free
157//! ```
158//!
159//! ## Error Handling
160//!
161//! All DMSC C API functions follow consistent error handling patterns:
162//!
163//! - **Return Codes**: Integer return codes where 0 indicates success
164//! - **NULL Objects**: Constructor functions return NULL on allocation failure
165//! - **Error Messages**: Last error information available through type-specific functions
166//! - **Error Propagation**: Errors should be checked and handled at each API call
167//!
168//! Standard error codes:
169//! - 0: Success
170//! - -1: General error
171//! - -2: Invalid argument
172//! - -3: Memory allocation failure
173//! - -4: Resource not found
174//! - -5: Permission denied
175//! - -6: Timeout
176//! - -7: Network error
177//!
178//! ## Thread Safety
179//!
180//! The DMSC C API is designed for thread-safe concurrent access:
181//!
182//! - **Object-Level Safety**: Individual objects are safe for concurrent use from
183//! multiple threads unless documented otherwise.
184//!
185//! - **Global State**: Global initialization is thread-safe; subsequent calls to
186//! dmsc_init() from multiple threads are handled correctly.
187//!
188//! - **Resource Sharing**: Objects can be shared across threads following the
189//! same patterns as the underlying Rust implementation.
190//!
191//! - **Synchronization**: Internal synchronization primitives prevent data races
192//! in multi-threaded scenarios.
193//!
194//! ## Usage Example
195//!
196//! A complete example demonstrating DMSC C API usage:
197//!
198//! ```c
199//! #include <stdio.h>
200//! #include "dmsc.h"
201//!
202//! int main(int argc, char* argv[]) {
203//! // Initialize DMSC library
204//! int result = dmsc_init();
205//! if (result != 0) {
206//! fprintf(stderr, "DMSC initialization failed: %d\n", result);
207//! return 1;
208//! }
209//!
210//! // Get version information
211//! const char* version = dmsc_version();
212//! printf("DMSC Version: %s\n", version);
213//! dmsc_string_free((char*)version);
214//!
215//! // Create configuration
216//! DMSCAppConfig* config = dmsc_app_config_new();
217//! dmsc_app_config_set_name(config, "MyApplication");
218//! dmsc_app_config_set_environment(config, "production");
219//!
220//! // Create application instance
221//! DMSCApplication* app = dmsc_application_new(config);
222//! dmsc_app_config_free(config);
223//!
224//! if (app == NULL) {
225//! fprintf(stderr, "Failed to create application\n");
226//! dmsc_cleanup();
227//! return 1;
228//! }
229//!
230//! // Start application
231//! result = dmsc_application_start(app);
232//! if (result != 0) {
233//! fprintf(stderr, "Failed to start application: %d\n", result);
234//! dmsc_application_free(app);
235//! dmsc_cleanup();
236//! return 1;
237//! }
238//!
239//! printf("Application running. Press Ctrl+C to stop.\n");
240//!
241//! // Wait for shutdown signal
242//! // Application runs until dmsc_application_stop() is called
243//!
244//! // Graceful shutdown
245//! dmsc_application_stop(app);
246//! dmsc_application_free(app);
247//!
248//! // Cleanup library
249//! dmsc_cleanup();
250//!
251//! printf("DMSC shutdown complete.\n");
252//! return 0;
253//! }
254//! ```
255//!
256//! ## Build Integration
257//!
258//! To use the DMSC C API in a C/C++ project:
259//!
260//! 1. **Compilation**: Include the generated C headers and link against the
261//! DMSC shared or static library.
262//!
263//! 2. **Header Files**: Include the main DMSC header which provides access
264//! to all submodule interfaces through a unified API surface.
265//!
266//! 3. **Linking**: Link against the DMSC library using appropriate linker flags
267//! for your build system.
268//!
269//! ## Dependencies
270//!
271//! The C API module depends on:
272//!
273//! - **Rust Core**: Standard Rust library types and traits
274//! - **FFI Bindings**: Rust's foreign function interface capabilities
275//! - **Submodule Implementations**: Each submodule's corresponding Rust implementation
276//!
277//! No external C/C++ dependencies are required beyond the C standard library.
278//!
279//! ## Feature Flags
280//!
281//! The DMSC C API supports feature flags for conditional compilation:
282//!
283//! - **default**: Core functionality with common features
284//! - **gateway**: Enable API gateway features
285//! - **grpc**: Enable gRPC server and client support
286//! - **observability**: Enable metrics and tracing
287//! - **service-mesh**: Enable service mesh integration
288//! - **websocket**: Enable WebSocket support
289//!
290//! Feature flags control which submodule bindings are compiled into the library.
291//! Disable unused features to reduce binary size.
292
293use std::ffi::{c_char, c_int, CString};
294
295#[macro_use]
296pub mod macros;
297pub mod core;
298pub mod auth;
299pub mod cache;
300pub mod database;
301pub mod device;
302pub mod fs;
303pub mod gateway;
304
305#[cfg(feature = "grpc")]
306pub mod grpc;
307
308pub mod hooks;
309pub mod log;
310pub mod module_rpc;
311pub mod observability;
312
313#[cfg(feature = "protocol")]
314pub mod protocol;
315
316pub mod queue;
317pub mod service_mesh;
318pub mod validation;
319
320#[cfg(feature = "websocket")]
321pub mod ws;
322
323/// Initialize the DMSC library
324#[no_mangle]
325pub extern "C" fn dmsc_init() -> c_int {
326 0
327}
328
329/// Cleanup the DMSC library
330#[no_mangle]
331pub extern "C" fn dmsc_cleanup() {
332}
333
334/// Get DMSC version
335#[no_mangle]
336pub extern "C" fn dmsc_version() -> *mut c_char {
337 let c_str = CString::new(env!("CARGO_PKG_VERSION")).unwrap();
338 c_str.into_raw()
339}
340
341/// Free a string returned by DMSC
342#[no_mangle]
343pub extern "C" fn dmsc_string_free(s: *mut c_char) {
344 if !s.is_null() {
345 unsafe {
346 let _ = CString::from_raw(s);
347 }
348 }
349}