dmsc/c/grpc.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//! # gRPC Module C API
19//!
20//! This module provides C language bindings for DMSC's gRPC communication layer. The gRPC module
21//! delivers high-performance Remote Procedure Call (RPC) capabilities using Protocol Buffers for
22//! efficient serialization and HTTP/2 for transport. This C API enables C/C++ applications to
23//! leverage DMSC's gRPC functionality for building distributed systems with strongly-typed service
24//! contracts and bidirectional streaming support.
25//!
26//! ## Module Architecture
27//!
28//! The gRPC module comprises three primary components that together provide complete gRPC
29//! functionality:
30//!
31//! - **DMSCGrpcServer**: gRPC server implementation handling service registration, request
32//! processing, and response streaming. The server manages the complete lifecycle of gRPC
33//! services including method dispatch, interceptor chaining, and connection management.
34//!
35//! - **DMSCGrpcClient**: gRPC client implementation for invoking remote procedures with automatic
36//! serialization, connection pooling, and retry logic. The client supports all gRPC calling
37//! patterns including unary calls, server streaming, client streaming, and bidirectional
38//! streaming.
39//!
40//! - **DMSCGrpcChannel**: Low-level channel abstraction managing the underlying HTTP/2 connection
41//! pool, transport security, and protocol negotiation. Channels provide the foundation for
42//! client communication and can be shared across multiple client instances.
43//!
44//! ## gRPC Communication Patterns
45//!
46//! The module supports all four standard gRPC communication patterns:
47//!
48//! - **Unary Calls**: Simple request-response pattern where client sends a single request and
49//! receives a single response. The most common pattern for traditional RPC operations.
50//!
51//! - **Server Streaming**: Client sends a single request and receives a stream of responses.
52//! Useful for scenarios like streaming updates, real-time notifications, or large dataset
53//! retrieval.
54//!
55//! - **Client Streaming**: Client sends a stream of requests and receives a single response.
56//! Useful for scenarios like batch uploads, upload with aggregation, or time-series data
57//! collection.
58//!
59//! - **Bidirectional Streaming**: Both client and server send streams of messages independently.
60//! Each side can send messages in any order. Useful for real-time communication, chat
61//! systems, or interactive data processing.
62//!
63//! ## Protocol Buffer Integration
64//!
65//! The gRPC module integrates tightly with Protocol Buffers:
66//!
67//! - **Message Serialization**: Automatic encoding and decoding of Protocol Buffer messages
68//! using the generated code from .proto files.
69//!
70//! - **Service Definition**: Service interfaces generated from .proto files define the
71//! available remote procedures and message types.
72//!
73//! - **Schema Evolution**: Support for backward and forward compatible schema changes
74//! through Protocol Buffers' field rules and unknown field handling.
75//!
76//! - **Custom Serialization**: Extension points for using alternative serialization formats
77//! like JSON, MessagePack, or custom binary formats.
78//!
79//! ## Transport Features
80//!
81//! The gRPC transport implements comprehensive HTTP/2 features:
82//!
83//! - **Connection Multiplexing**: Multiple requests and streams share a single TCP connection,
84//! reducing connection overhead and improving throughput.
85//!
86//! - **Flow Control**: Automatic flow control prevents fast senders from overwhelming slow
87//! receivers using HTTP/2 window updates.
88//!
89//! - **Header Compression**: HPACK header compression reduces bandwidth usage for repeated
90//! metadata in requests and responses.
91//!
92//! - **Stream Prioritization**: Clients can prioritize streams to ensure important requests
93//! get timely responses when connection capacity is limited.
94//!
95//! - **Ping/Pong Frames**: Keepalive mechanism detects dead connections and enables timely
96//! cleanup of stale resources.
97//!
98//! ## Security Features
99//!
100//! The gRPC module provides comprehensive security capabilities:
101//!
102//! - **TLS Encryption**: Full TLS encryption for all communication with configurable
103//! cipher suites and certificate validation.
104//!
105//! - **Certificate Management**: Support for PEM certificates, certificate chains, and
106//! custom certificate authorities.
107//!
108//! - **Client Authentication**: Multiple authentication mechanisms including:
109//! - JWT token authentication
110//! - OAuth 2.0 token exchange
111//! - mTLS (mutual TLS) with client certificates
112//! - Custom authentication interceptor
113//!
114//! - **Authorization**: Fine-grained authorization using interceptors for checking
115//! permissions before method execution.
116//!
117//! ## Connection Management
118//!
119//! The module implements sophisticated connection management:
120//!
121//! - **Connection Pooling**: Reuse of established connections to reduce latency and
122//! resource consumption across multiple requests.
123//!
124//! - **Load Balancing**: Client-side load distribution across multiple server instances
125//! with configurable policies (round-robin, pick-first, weighted).
126//!
127//! - **Health Checking**: Active health checks detect unhealthy server instances and
128//! remove them from the load balancer rotation.
129//!
130//! - **Retry Logic**: Automatic retry for idempotent requests with configurable retry
131//! policies, backoff strategies, and retry limits.
132//!
133//! - **Deadline Propagation**: Automatic deadline propagation across service boundaries
134//! ensures requests don't wait indefinitely for responses.
135//!
136//! ## Interceptors
137//!
138//! Interceptors provide extensibility for cross-cutting concerns:
139//!
140//! - **Server Interceptors**: Process incoming requests before they reach the handler
141//! and transform responses before they return to the client. Common uses include:
142//! - Authentication and authorization
143//! - Request/response logging
144//! - Metrics collection
145//! - Request validation
146//! - Response transformation
147//!
148//! - **Client Interceptors**: Process outgoing requests before they are sent and
149//! transform incoming responses before they reach the application. Common uses include:
150//! - Authentication token injection
151//! - Request tracing headers
152//! - Metrics collection
153//! - Retry handling
154//! - Response validation
155//!
156//! ## Memory Management
157//!
158//! All C API objects use opaque pointers with manual memory management:
159//!
160//! - Constructor functions allocate new instances on the heap
161//! - Destructor functions must be called to release memory
162//! - Client stubs must be properly shutdown before freeing
163//! - Stream objects must be properly closed when complete
164//!
165//! ## Thread Safety
166//!
167//! The underlying implementations are thread-safe:
168//!
169//! - Channels can be shared across threads for concurrent requests
170//! - Client stubs support concurrent method invocations
171//! - Server handlers are invoked concurrently for each request
172//! - Interceptors should be stateless for thread safety
173//!
174//! ## Performance Characteristics
175//!
176//! gRPC operations have the following performance profiles:
177//!
178//! - Connection establishment: O(1) for pooled connections, O(1 TCP handshake + TLS)
179//! - Unary call latency: O(message_size) for serialization, O(1) network
180//! - Streaming throughput: O(message_size) per message with flow control
181//! - Concurrent streams: Hundreds to thousands per connection
182//!
183//! ## Usage Example
184//!
185//! ```c
186//! // Create gRPC channel with connection pooling
187//! DMSCGrpcChannel* channel = dmsc_grpc_channel_new("localhost", 50051);
188//! dmsc_grpc_channel_set_tls_enabled(channel, true);
189//! dmsc_grpc_channel_set_connection_pool_size(channel, 10);
190//!
191//! // Create client stub
192//! DMSCGrpcClient* client = dmsc_grpc_client_new(channel);
193//!
194//! // Configure request
195//! DMSCUserRequest request = DMSCGUSER_REQUEST_INIT;
196//! request.user_id = 12345;
197//! request.include_profile = true;
198//!
199//! // Execute unary call
200//! DMSCUserResponse response = DMSCGUSER_RESPONSE_INIT;
201//! int status = dmsc_grpc_client_unary_call(
202//! client,
203//! "UserService.GetUser",
204//! &request,
205//! &response,
206//! 5000 // timeout in milliseconds
207//! );
208//!
209//! if (status == 0) {
210//! printf("User: %s %s\n", response.first_name, response.last_name);
211//! } else {
212//! const char* error = dmsc_grpc_client_last_error(client);
213//! fprintf(stderr, "gRPC error: %s (code: %d)\n", error, status);
214//! }
215//!
216//! // Create stream for server streaming
217//! DMSCNotificationRequest stream_request = DMSCGNOTIFICATION_REQUEST_INIT;
218//! stream_request.notification_type = NOTIFICATION_TYPE_ALL;
219//! stream_request.start_time = time(NULL);
220//!
221//! DMSCGrpcStream* stream = dmsc_grpc_client_server_stream(
222//! client,
223//! "NotificationService.Subscribe",
224//! &stream_request
225//! );
226//!
227//! // Read streaming responses
228//! DMSCNotification notification;
229//! while (dmsc_grpc_stream_read(stream, ¬ification) == 0) {
230//! printf("Notification: %s\n", notification.message);
231//! dmsc_grpc_notification_destroy(¬ification);
232//! }
233//!
234//! dmsc_grpc_stream_free(stream);
235//!
236//! // Cleanup
237//! dmsc_grpc_client_free(client);
238//! dmsc_grpc_channel_free(channel);
239//! ```
240//!
241//! ## Dependencies
242//!
243//! This module depends on the following DMSC components and external libraries:
244//!
245//! - `crate::grpc`: Rust gRPC module implementation
246//! - `crate::prelude`: Common types and traits
247//! - tonic for gRPC protocol implementation
248//! - prost for Protocol Buffer encoding/decoding
249//! - tokio for asynchronous runtime
250//! - h2 for HTTP/2 transport
251//!
252//! ## Feature Flags
253//!
254//! The gRPC module is enabled by the "grpc" feature flag:
255//!
256//! - grpc: Enable gRPC server and client functionality
257//! - grpc-tls: Enable TLS support for gRPC (requires native-tls or rustls)
258//!
259//! Disable these features to reduce binary size when gRPC is not required.
260
261use crate::grpc::{DMSCGrpcClient, DMSCGrpcServer};
262
263
264c_wrapper!(CDMSCGrpcServer, DMSCGrpcServer);
265
266c_wrapper!(CDMSCGrpcClient, DMSCGrpcClient);
267
268