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
//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
//!
//! This file is part of Ri.
//! The Ri project belongs to the Dunimd Team.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! You may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
//! # Module RPC C API
//!
//! This module provides C language bindings for Ri's module RPC (Remote Procedure Call) system.
//! The module RPC system enables communication between different modules within the Ri framework,
//! providing a high-performance, type-safe mechanism for inter-module service calls. This C API
//! enables C/C++ modules to participate in Ri's distributed architecture by registering services,
//! making remote calls, and handling asynchronous responses.
//!
//! ## Module Architecture
//!
//! The module RPC system comprises three primary components:
//!
//! - **RiModuleRPC**: Central RPC router and dispatcher managing service registration, method
//! routing, and call dispatch across modules. The router handles the complete lifecycle of
//! RPC operations including request routing, response aggregation, and error handling.
//!
//! - **RiModuleClient**: Client interface for making RPC calls to registered services. The
//! client provides synchronous and asynchronous call capabilities with automatic serialization,
//! connection management, and retry logic.
//!
//! - **RiModuleEndpoint**: Connection endpoint for module communication, managing the transport
//! layer, protocol negotiation, and message framing. Endpoints can be local (in-process) or
//! remote (network-based).
//!
//! ## RPC Communication Model
//!
//! The module RPC system implements a request-response communication model:
//!
//! - **Service Registration**: Modules register services with method signatures, enabling
//! discovery and invocation by other modules.
//!
//! - **Method Invocation**: Clients call registered methods with serialized parameters,
//! receiving serialized results or errors.
//!
//! - **Request Routing**: The router dispatches requests to the appropriate service
//! based on module and method names.
//!
//! - **Response Handling**: Results are serialized and returned to the calling client,
//! with support for streaming responses.
//!
//! ## Module Discovery
//!
//! The RPC system provides automatic module discovery:
//!
//! - **Service Registry**: Central registry tracks all registered services and their
//! availability status.
//!
//! - **Health Monitoring**: Automatic health checks detect unavailable services and
//! remove them from the routing table.
//!
//! - **Load Balancing**: Requests distributed across multiple service instances when
//! available.
//!
//! - **Service Dependencies**: Dependency graph tracks module relationships for
//! proper initialization and shutdown sequencing.
//!
//! ## Serialization
//!
//! The RPC system supports multiple serialization formats:
//!
//! - **Protocol Buffers**: Default serialization with schema-based type safety.
//! Provides efficient binary encoding with backward/forward compatibility.
//!
//! - **MessagePack**: Binary serialization format for compact payloads with
//! schema-less flexibility.
//!
//! - **JSON**: Human-readable serialization for debugging and HTTP interoperability.
//!
//! - **Custom Codecs**: Extension point for application-specific serialization.
//!
//! ## Transport Mechanisms
//!
//! The module RPC supports multiple transport mechanisms:
//!
//! - **In-Process**: Zero-copy communication between modules in the same process.
//! Fastest option for co-located modules.
//!
//! - **Shared Memory**: High-performance communication using shared memory segments.
//! Suitable for high-throughput, low-latency scenarios.
//!
//! - **TCP/IP**: Network-based communication for distributed deployments.
//! Supports TLS encryption and compression.
//!
//! - **Unix Domain Sockets**: Local socket communication with near-in-process
//! performance. Available on Unix-like systems.
//!
//! ## Request Patterns
//!
//! The RPC system supports various request patterns:
//!
//! - **Unary Calls**: Simple request-response pattern with single request and response.
//! Most common pattern for traditional RPC operations.
//!
//! - **Streaming Calls**: Bidirectional streaming for large data transfers or
//! real-time communication patterns.
//!
//! - **Batch Calls**: Multiple independent requests batched into a single network
//! round-trip for efficiency.
//!
//! - **Subscription Calls**: Long-polling or push-based subscriptions for event
//! notification patterns.
//!
//! ## Error Handling
//!
//! The RPC system implements comprehensive error handling:
//!
//! - **Transport Errors**: Connection failures, timeouts, and protocol errors.
//!
//! - **Serialization Errors**: Invalid input data, schema mismatches, codec failures.
//!
//! - **Service Errors**: Application-level errors returned by the service handler.
//!
//! - **Routing Errors**: Service not found, method not found, invalid parameters.
//!
//! ## Performance Characteristics
//!
//! RPC operations have the following performance profiles:
//!
//! - In-process call latency: Near-zero, single function call overhead
//! - Serialization overhead: O(n) where n is message size
//! - Transport latency: O(1) for local, O(network) for remote
//! - Concurrent calls: Hundreds to thousands per endpoint
//!
//! ## Memory Management
//!
//! All C API objects use opaque pointers with manual memory management:
//!
//! - Constructor functions allocate new instances on the heap
//! - Destructor functions must be called to release memory
//! - Client stubs must be properly cleaned up after use
//! - Request/response buffers must be freed appropriately
//!
//! ## Thread Safety
//!
//! The underlying implementations are thread-safe:
//!
//! - RPC router handles concurrent requests from multiple threads
//! - Client stubs support concurrent method invocations
//! - Service handlers invoked concurrently for each request
//! - Endpoint management uses internal synchronization
//!
//! ## Usage Example
//!
//! ```c
//! // Create RPC router instance
//! RiModuleRPC* rpc = ri_module_rpc_new();
//! if (rpc == NULL) {
//! fprintf(stderr, "Failed to create RPC router\n");
//! return ERROR_INIT;
//! }
//!
//! // Register a service module
//! int result = ri_module_rpc_register_service(
//! rpc,
//! "UserService",
//! user_service_handler,
//! NULL // user data passed to handler
//! );
//!
//! if (result != 0) {
//! fprintf(stderr, "Failed to register service\n");
//! }
//!
//! // Create client for remote service
//! RiModuleClient* client = ri_module_client_new(rpc);
//! if (client == NULL) {
//! fprintf(stderr, "Failed to create RPC client\n");
//! ri_module_rpc_free(rpc);
//! return ERROR_INIT;
//! }
//!
//! // Configure request
//! RiUserRequest request = RiUSER_REQUEST_INIT;
//! request.user_id = 12345;
//! request.include_profile = true;
//!
//! // Execute synchronous RPC call
//! RiUserResponse response = RiUSER_RESPONSE_INIT;
//! int status = ri_module_client_call(
//! client,
//! "UserService.GetUser",
//! &request,
//! &response,
//! 5000 // timeout in milliseconds
//! );
//!
//! if (status == 0) {
//! printf("User: %s %s\n", response.first_name, response.last_name);
//! } else {
//! const char* error = ri_module_client_last_error(client);
//! fprintf(stderr, "RPC error: %s (code: %d)\n", error, status);
//! }
//!
//! // Cleanup
//! ri_module_client_free(client);
//! ri_module_rpc_free(rpc);
//! ```
//!
//! ## Dependencies
//!
//! This module depends on the following Ri components:
//!
//! - `crate::module_rpc`: Rust module RPC implementation
//! - `crate::prelude`: Common types and traits
//! - Serialization framework (prost, serde, or custom)
//!
//! ## Feature Flags
//!
//! The module RPC module is enabled by the "module-rpc" feature flag.
//! Disable this feature to reduce binary size when module RPC is not required.
//!
//! Additional features:
//!
//! - module-rpc-tls: Enable TLS for network transport
//! - module-rpc-streaming: Enable streaming RPC calls
//! - module-rpc-metrics: Enable RPC metrics collection
use crate;
c_wrapper!;
c_wrapper!;
c_wrapper!;
// RiModuleRPC constructors and destructors
pub extern "C"
c_destructor!;