dmsc/c/
module_rpc.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//! # Module RPC C API
19//!
20//! This module provides C language bindings for DMSC's module RPC (Remote Procedure Call) system.
21//! The module RPC system enables communication between different modules within the DMSC framework,
22//! providing a high-performance, type-safe mechanism for inter-module service calls. This C API
23//! enables C/C++ modules to participate in DMSC's distributed architecture by registering services,
24//! making remote calls, and handling asynchronous responses.
25//!
26//! ## Module Architecture
27//!
28//! The module RPC system comprises three primary components:
29//!
30//! - **DMSCModuleRPC**: Central RPC router and dispatcher managing service registration, method
31//!   routing, and call dispatch across modules. The router handles the complete lifecycle of
32//!   RPC operations including request routing, response aggregation, and error handling.
33//!
34//! - **DMSCModuleClient**: Client interface for making RPC calls to registered services. The
35//!   client provides synchronous and asynchronous call capabilities with automatic serialization,
36//!   connection management, and retry logic.
37//!
38//! - **DMSCModuleEndpoint**: Connection endpoint for module communication, managing the transport
39//!   layer, protocol negotiation, and message framing. Endpoints can be local (in-process) or
40//!   remote (network-based).
41//!
42//! ## RPC Communication Model
43//!
44//! The module RPC system implements a request-response communication model:
45//!
46//! - **Service Registration**: Modules register services with method signatures, enabling
47//!   discovery and invocation by other modules.
48//!
49//! - **Method Invocation**: Clients call registered methods with serialized parameters,
50//!   receiving serialized results or errors.
51//!
52//! - **Request Routing**: The router dispatches requests to the appropriate service
53//!   based on module and method names.
54//!
55//! - **Response Handling**: Results are serialized and returned to the calling client,
56//!   with support for streaming responses.
57//!
58//! ## Module Discovery
59//!
60//! The RPC system provides automatic module discovery:
61//!
62//! - **Service Registry**: Central registry tracks all registered services and their
63//!   availability status.
64//!
65//! - **Health Monitoring**: Automatic health checks detect unavailable services and
66//!   remove them from the routing table.
67//!
68//! - **Load Balancing**: Requests distributed across multiple service instances when
69//!   available.
70//!
71//! - **Service Dependencies**: Dependency graph tracks module relationships for
72//!   proper initialization and shutdown sequencing.
73//!
74//! ## Serialization
75//!
76//! The RPC system supports multiple serialization formats:
77//!
78//! - **Protocol Buffers**: Default serialization with schema-based type safety.
79//!   Provides efficient binary encoding with backward/forward compatibility.
80//!
81//! - **MessagePack**: Binary serialization format for compact payloads with
82//!   schema-less flexibility.
83//!
84//! - **JSON**: Human-readable serialization for debugging and HTTP interoperability.
85//!
86//! - **Custom Codecs**: Extension point for application-specific serialization.
87//!
88//! ## Transport Mechanisms
89//!
90//! The module RPC supports multiple transport mechanisms:
91//!
92//! - **In-Process**: Zero-copy communication between modules in the same process.
93//!   Fastest option for co-located modules.
94//!
95//! - **Shared Memory**: High-performance communication using shared memory segments.
96//!   Suitable for high-throughput, low-latency scenarios.
97//!
98//! - **TCP/IP**: Network-based communication for distributed deployments.
99//!   Supports TLS encryption and compression.
100//!
101//! - **Unix Domain Sockets**: Local socket communication with near-in-process
102//!   performance. Available on Unix-like systems.
103//!
104//! ## Request Patterns
105//!
106//! The RPC system supports various request patterns:
107//!
108//! - **Unary Calls**: Simple request-response pattern with single request and response.
109//!   Most common pattern for traditional RPC operations.
110//!
111//! - **Streaming Calls**: Bidirectional streaming for large data transfers or
112//!   real-time communication patterns.
113//!
114//! - **Batch Calls**: Multiple independent requests batched into a single network
115//!   round-trip for efficiency.
116//!
117//! - **Subscription Calls**: Long-polling or push-based subscriptions for event
118//!   notification patterns.
119//!
120//! ## Error Handling
121//!
122//! The RPC system implements comprehensive error handling:
123//!
124//! - **Transport Errors**: Connection failures, timeouts, and protocol errors.
125//!
126//! - **Serialization Errors**: Invalid input data, schema mismatches, codec failures.
127//!
128//! - **Service Errors**: Application-level errors returned by the service handler.
129//!
130//! - **Routing Errors**: Service not found, method not found, invalid parameters.
131//!
132//! ## Performance Characteristics
133//!
134//! RPC operations have the following performance profiles:
135//!
136//! - In-process call latency: Near-zero, single function call overhead
137//! - Serialization overhead: O(n) where n is message size
138//! - Transport latency: O(1) for local, O(network) for remote
139//! - Concurrent calls: Hundreds to thousands per endpoint
140//!
141//! ## Memory Management
142//!
143//! All C API objects use opaque pointers with manual memory management:
144//!
145//! - Constructor functions allocate new instances on the heap
146//! - Destructor functions must be called to release memory
147//! - Client stubs must be properly cleaned up after use
148//! - Request/response buffers must be freed appropriately
149//!
150//! ## Thread Safety
151//!
152//! The underlying implementations are thread-safe:
153//!
154//! - RPC router handles concurrent requests from multiple threads
155//! - Client stubs support concurrent method invocations
156//! - Service handlers invoked concurrently for each request
157//! - Endpoint management uses internal synchronization
158//!
159//! ## Usage Example
160//!
161//! ```c
162//! // Create RPC router instance
163//! DMSCModuleRPC* rpc = dmsc_module_rpc_new();
164//! if (rpc == NULL) {
165//!     fprintf(stderr, "Failed to create RPC router\n");
166//!     return ERROR_INIT;
167//! }
168//!
169//! // Register a service module
170//! int result = dmsc_module_rpc_register_service(
171//!     rpc,
172//!     "UserService",
173//!     user_service_handler,
174//!     NULL  // user data passed to handler
175//! );
176//!
177//! if (result != 0) {
178//!     fprintf(stderr, "Failed to register service\n");
179//! }
180//!
181//! // Create client for remote service
182//! DMSCModuleClient* client = dmsc_module_client_new(rpc);
183//! if (client == NULL) {
184//!     fprintf(stderr, "Failed to create RPC client\n");
185//!     dmsc_module_rpc_free(rpc);
186//!     return ERROR_INIT;
187//! }
188//!
189//! // Configure request
190//! DMSCUserRequest request = DMSCUSER_REQUEST_INIT;
191//! request.user_id = 12345;
192//! request.include_profile = true;
193//!
194//! // Execute synchronous RPC call
195//! DMSCUserResponse response = DMSCUSER_RESPONSE_INIT;
196//! int status = dmsc_module_client_call(
197//!     client,
198//!     "UserService.GetUser",
199//!     &request,
200//!     &response,
201//!     5000  // timeout in milliseconds
202//! );
203//!
204//! if (status == 0) {
205//!     printf("User: %s %s\n", response.first_name, response.last_name);
206//! } else {
207//!     const char* error = dmsc_module_client_last_error(client);
208//!     fprintf(stderr, "RPC error: %s (code: %d)\n", error, status);
209//! }
210//!
211//! // Cleanup
212//! dmsc_module_client_free(client);
213//! dmsc_module_rpc_free(rpc);
214//! ```
215//!
216//! ## Dependencies
217//!
218//! This module depends on the following DMSC components:
219//!
220//! - `crate::module_rpc`: Rust module RPC implementation
221//! - `crate::prelude`: Common types and traits
222//! - Serialization framework (prost, serde, or custom)
223//!
224//! ## Feature Flags
225//!
226//! The module RPC module is enabled by the "module-rpc" feature flag.
227//! Disable this feature to reduce binary size when module RPC is not required.
228//!
229//! Additional features:
230//!
231//! - module-rpc-tls: Enable TLS for network transport
232//! - module-rpc-streaming: Enable streaming RPC calls
233//! - module-rpc-metrics: Enable RPC metrics collection
234
235use crate::module_rpc::{DMSCModuleClient, DMSCModuleEndpoint, DMSCModuleRPC};
236
237
238c_wrapper!(CDMSCModuleRPC, DMSCModuleRPC);
239c_wrapper!(CDMSCModuleClient, DMSCModuleClient);
240c_wrapper!(CDMSCModuleEndpoint, DMSCModuleEndpoint);
241
242// DMSCModuleRPC constructors and destructors
243#[no_mangle]
244pub extern "C" fn dmsc_module_rpc_new() -> *mut CDMSCModuleRPC {
245    let rpc = DMSCModuleRPC::new();
246    Box::into_raw(Box::new(CDMSCModuleRPC::new(rpc)))
247}
248c_destructor!(dmsc_module_rpc_free, CDMSCModuleRPC);