dmsc/c/protocol.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//! # Protocol Module C API
19//!
20//! This module provides C language bindings for DMSC's protocol handling infrastructure. The protocol
21//! module delivers comprehensive support for encoding, decoding, and transforming data across various
22//! wire formats and communication protocols. This C API enables C/C++ applications to leverage DMSC's
23//! protocol capabilities for building interoperable distributed systems with standardized data exchange.
24//!
25//! ## Module Architecture
26//!
27//! The protocol module comprises three primary components that together provide complete protocol
28//! management capabilities:
29//!
30//! - **DMSCProtocolConfig**: Configuration container for protocol codec parameters including encoding
31//! formats, framing options, compression settings, and validation rules. The configuration object
32//! controls how data is serialized and deserialized, ensuring consistent behavior across the
33//! application.
34//!
35//! - **DMSCProtocolManager**: Central manager for protocol registration, codec lookup, and protocol
36//! negotiation. The manager handles the complete lifecycle of protocol operations including codec
37//! selection, error handling, and protocol switching.
38//!
39//! - **DMSCFrame**: Low-level frame abstraction for message framing and boundary management. Frames
40//! provide the foundation for streaming protocols, handling message boundaries, chunking, and
41//! reassembly.
42//!
43//! ## Supported Protocols
44//!
45//! The protocol system supports a comprehensive range of wire formats:
46//!
47//! - **JSON (JavaScript Object Notation)**: Human-readable data interchange format widely used in
48//! web APIs and microservices. Supports schema validation and transformation.
49//!
50//! - **MessagePack**: Binary serialization format providing compact representation with fast
51//! encoding and decoding. Ideal for bandwidth-constrained environments.
52//!
53//! - **Protocol Buffers**: Google's language-neutral, platform-neutral, extensible mechanism for
54//! serializing structured data. Provides strong typing and backward/forward compatibility.
55//!
56//! - **CBOR (Concise Binary Object Representation)**: Binary JSON-like format designed for small
57//! code size and small message size. IETF standard (RFC 8949).
58//!
59//! - **BSON (Binary JSON)**: MongoDB's binary-encoded JSON format with additional data types
60//! like dates and binary blobs.
61//!
62//! - **Avro**: Apache Avro data serialization format with schema evolution support and
63//! compact binary encoding.
64//!
65//! ## Framing Protocols
66//!
67//! The module provides various message framing approaches:
68//!
69//! - **Length-Prefixed Framing**: Each message is prefixed with its length in bytes. Enables
70//! streaming parsing and message boundary detection without special delimiters.
71//!
72//! - **Delimiter-Based Framing**: Messages are separated by special delimiter bytes (e.g., newline
73//! for line-based protocols). Simple but requires escaping for binary data.
74//!
75//! - **Fixed-Size Framing**: All messages have identical length. Simplifies parsing but wastes
76//! bandwidth for variable-sized data.
77//!
78//! - **HTTP/1.1 Chunked Transfer**: Standard HTTP chunked encoding for streaming responses.
79//! Supports incremental processing of large payloads.
80//!
81//! - **WebSocket Framing**: Full WebSocket frame handling including control frames, continuation
82//! frames, and fragmentation support.
83//!
84//! ## Compression
85//!
86//! Built-in compression support reduces bandwidth usage:
87//!
88//! - **Gzip**: GNU zip compression with wide compatibility. Good balance of compression ratio
89//! and CPU usage.
90//!
91//! - **Snappy**: Google's compression library designed for high speeds. Lower compression
92//! ratio but very fast encoding and decoding.
93//!
94//! - **LZ4**: Extremely fast compression with reasonable ratios. Ideal for real-time systems
95//! with limited CPU budget.
96//!
97//! - **Zstandard (zstd)**: Facebook's compression algorithm offering excellent compression ratios
98//! at high speeds. Supports dictionary compression for repetitive data.
99//!
100//! - **Brotli**: Google's next-generation compression with best-in-class compression ratios.
101//! Slightly slower but excellent for static content delivery.
102//!
103//! ## Validation
104//!
105//! Comprehensive data validation ensures protocol integrity:
106//!
107//! - **Schema Validation**: Validate messages against predefined schemas before processing.
108//! Catches malformed or unexpected data early.
109//!
110//! - **Type Checking**: Verify message types match expected types for each field.
111//! Supports optional fields and type coercion.
112//!
113//! - **Range Validation**: Ensure numeric values fall within acceptable ranges.
114//! Prevents overflow and underflow issues.
115//!
116//! - **Pattern Matching**: Validate string fields against regex patterns or format strings.
117//! Ensures email, UUID, and other formatted data validity.
118//!
119//! - **Custom Validators**: User-defined validation functions for domain-specific rules.
120//! Extend built-in validation with application logic.
121//!
122//! ## Serialization Features
123//!
124//! Advanced serialization capabilities:
125//!
126//! - **Polymorphism**: Handle tagged unions and inheritance hierarchies through type tags.
127//! Enables message routing based on message type.
128//!
129//! - **Optional Fields**: Gracefully handle missing fields with optional type support.
130//! Backward compatibility maintained across schema versions.
131//!
132//! - **Default Values**: Automatic default values for missing fields when defined in schema.
133//! Simplifies client code with sensible fallbacks.
134//!
135//! - **Unknown Field Handling**: Option to preserve unknown fields during deserialization.
136//! Enables forward compatibility without data loss.
137//!
138//! - **Circular Reference Handling**: Detect and properly serialize graph structures with
139//! references between objects.
140//!
141//! ## Performance Characteristics
142//!
143//! Protocol operations are optimized for various use cases:
144//!
145//! - **JSON Parsing**: O(n) where n is message size, optimized with SIMD instructions
146//! - **Binary Codecs**: O(n) with low constant factors, ideal for high-throughput scenarios
147//! - **Framing**: O(1) per frame boundary detection
148//! - **Compression**: O(n * compression_level), configurable trade-off
149//! - **Validation**: O(n) with early termination on first error
150//!
151//! ## Memory Management
152//!
153//! All C API objects use opaque pointers with manual memory management:
154//!
155//! - Constructor functions allocate new instances on the heap
156//! - Destructor functions must be called to release memory
157//! - Codec instances are managed by the protocol manager
158//! - Frame buffers are recycled for performance
159//!
160//! ## Thread Safety
161//!
162//! The underlying implementations are thread-safe:
163//!
164//! - Protocol manager supports concurrent codec registration
165//! - Codec instances are immutable after creation
166//! - Frame allocation uses thread-local pools
167//! - Validation can be performed concurrently
168//!
169//! ## Usage Example
170//!
171//! ```c
172//! // Create protocol configuration
173//! DMSCProtocolConfig* config = dmsc_protocol_config_new();
174//! if (config == NULL) {
175//! fprintf(stderr, "Failed to create protocol config\n");
176//! return ERROR_INIT;
177//! }
178//!
179//! // Configure protocol settings
180//! dmsc_protocol_config_set_format(config, PROTOCOL_FORMAT_MSGPACK);
181//! dmsc_protocol_config_set_compression(config, COMPRESSION_SNAPPY);
182//! dmsc_protocol_config_set_validation_enabled(config, true);
183//!
184//! // Create protocol manager
185//! DMSCProtocolManager* manager = dmsc_protocol_manager_new(config);
186//! if (manager == NULL) {
187//! fprintf(stderr, "Failed to create protocol manager\n");
188//! dmsc_protocol_config_free(config);
189//! return ERROR_INIT;
190//! }
191//!
192//! // Register custom schema
193//! int result = dmsc_protocol_manager_register_schema(
194//! manager,
195//! "UserMessage",
196//! user_schema_definition,
197//! sizeof(user_schema_definition)
198//! );
199//!
200//! if (result != 0) {
201//! fprintf(stderr, "Failed to register schema\n");
202//! }
203//!
204//! // Create frame for streaming
205//! DMSCFrame* frame = dmsc_frame_new();
206//! if (frame == NULL) {
207//! fprintf(stderr, "Failed to create frame\n");
208//! dmsc_protocol_manager_free(manager);
209//! dmsc_protocol_config_free(config);
210//! return ERROR_INIT;
211//! }
212//!
213//! // Encode message
214//! const char* input_data = "{\"user_id\": 12345, \"name\": \"John\"}";
215//! size_t input_len = strlen(input_data);
216//!
217//! char* output_buffer = NULL;
218//! size_t output_len = 0;
219//!
220//! result = dmsc_protocol_manager_encode(
221//! manager,
222//! "UserMessage",
223//! input_data,
224//! input_len,
225//! &output_buffer,
226//! &output_len
227//! );
228//!
229//! if (result == 0 && output_buffer != NULL) {
230//! printf("Encoded %zu bytes\n", output_len);
231//!
232//! // Decode message back
233//! char* decoded_buffer = NULL;
234//! size_t decoded_len = 0;
235//!
236//! int decode_result = dmsc_protocol_manager_decode(
237//! manager,
238//! "UserMessage",
239//! output_buffer,
240//! output_len,
241//! &decoded_buffer,
242//! &decoded_len
243//! );
244//!
245//! if (decode_result == 0) {
246//! printf("Decoded: %.*s\n", (int)decoded_len, decoded_buffer);
247//! dmsc_string_free(decoded_buffer);
248//! }
249//!
250//! dmsc_string_free(output_buffer);
251//! }
252//!
253//! // Frame the message for transport
254//! dmsc_frame_reset(frame);
255//! dmsc_frame_append(frame, output_buffer, output_len);
256//!
257//! // Read framed data
258//! const char* frame_data = dmsc_frame_data(frame);
259//! size_t frame_size = dmsc_frame_size(frame);
260//!
261//! // Cleanup
262//! dmsc_frame_free(frame);
263//! dmsc_protocol_manager_free(manager);
264//! dmsc_protocol_config_free(config);
265//! ```
266//!
267//! ## Protocol Negotiation
268//!
269//! The protocol manager supports dynamic protocol negotiation:
270//!
271//! - **Capability Exchange**: During connection establishment, both ends advertise supported
272//! protocols and versions.
273//!
274//! - **Common Protocol Selection**: Automatically select the best mutually-supported protocol
275//! based on priority and capabilities.
276//!
277//! - **Protocol Upgrades**: Support for upgrading from a base protocol (like HTTP/1.1) to
278//! a more efficient protocol (like WebSocket or gRPC).
279//!
280//! - **Version Handling**: Manage multiple protocol versions simultaneously for backward
281//! compatibility during migrations.
282//!
283//! ## Dependencies
284//!
285//! This module depends on the following DMSC components:
286//!
287//! - `crate::protocol`: Rust protocol module implementation
288//! - `crate::prelude`: Common types and traits
289//! - serde for serialization frameworks
290//! - Various codec libraries (serde_json, rmp-serde, prost, etc.)
291//!
292//! ## Feature Flags
293//!
294//! The protocol module is enabled by default with comprehensive format support.
295//! Additional formats enabled by feature flags:
296//!
297//! - `protocol-protobuf`: Enable Protocol Buffer support (requires prost)
298//! - `protocol-avro`: Enable Apache Avro support
299//! - `protocol-cbor`: Enable CBOR support
300//! - `protocol-bson`: Enable BSON support
301//! - `protocol-compression`: Enable compression codecs
302
303use crate::protocol::{DMSCFrame, DMSCProtocolConfig, DMSCProtocolManager};
304
305
306c_wrapper!(CDMSCProtocolConfig, DMSCProtocolConfig);
307c_wrapper!(CDMSCProtocolManager, DMSCProtocolManager);
308c_wrapper!(CDMSCFrame, DMSCFrame);
309
310// DMSCProtocolConfig constructors and destructors
311c_constructor!(
312 dmsc_protocol_config_new,
313 CDMSCProtocolConfig,
314 DMSCProtocolConfig,
315 DMSCProtocolConfig::default()
316);
317c_destructor!(dmsc_protocol_config_free, CDMSCProtocolConfig);