unison-protocol 0.1.0-alpha2

๐ŸŽต Unison Protocol - KDL-based type-safe communication framework
docs.rs failed to build unison-protocol-0.1.0-alpha2
Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.

๐ŸŽต Unison Protocol

Next-generation type-safe communication protocol framework

Crates.io Documentation Build Status License

English | ๆ—ฅๆœฌ่ชž

๐Ÿ“Œ Overview

Unison Protocol is a type-safe communication protocol framework based on KDL (KDL Document Language). Leveraging QUIC transport, it supports building fast, secure, and extensible distributed systems.

๐ŸŽฏ Key Features

  • Type-safe Communication: Automatic code generation from KDL schemas
  • Ultra-low Latency: High-speed communication via QUIC (HTTP/3) transport
  • Built-in Security: TLS 1.3 encryption with automatic development certificate generation
  • CGP (Context-Generic Programming) Support: Extensible handler system
  • Async-first: Fully asynchronous implementation based on Tokio
  • Bidirectional Streaming: Full-duplex communication via UnisonStream
  • Service-oriented: Lifecycle management via high-level Service trait

๐Ÿš€ Quick Start

Installation

[dependencies]
unison-protocol = "0.1.0-alpha1"
tokio = { version = "1.40", features = ["full"] }
serde_json = "1.0"
anyhow = "1.0"
tracing = "0.1"

Basic Usage

1. Protocol Definition (KDL)

// schemas/my_service.kdl
protocol "my-service" version="1.0.0" {
    namespace "com.example.myservice"

    service "UserService" {
        method "createUser" {
            request {
                field "name" type="string" required=true
                field "email" type="string" required=true
            }
            response {
                field "id" type="string" required=true
                field "created_at" type="timestamp" required=true
            }
        }
    }
}

2. Server Implementation

use unison_protocol::{ProtocolServer, NetworkError};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut server = ProtocolServer::new();

    // Register handler
    server.register_handler("createUser", |payload| {
        let name = payload["name"].as_str().unwrap();
        let email = payload["email"].as_str().unwrap();

        // User creation logic
        Ok(json!({
            "id": uuid::Uuid::new_v4().to_string(),
            "created_at": chrono::Utc::now().to_rfc3339()
        }))
    });

    // Start QUIC server
    server.listen("127.0.0.1:8080").await?;
    Ok(())
}

3. Client Implementation

use unison_protocol::ProtocolClient;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ProtocolClient::new();

    // Connect to server
    client.connect("127.0.0.1:8080").await?;

    // RPC call
    let response = client.call("createUser", json!({
        "name": "Alice",
        "email": "alice@example.com"
    })).await?;

    println!("Created user: {}", response);
    Ok(())
}

๐Ÿ—๏ธ Architecture

Component Structure

unison-protocol/
โ”œโ”€โ”€ ๐ŸŽฏ Core Layer
โ”‚   โ”œโ”€โ”€ parser/          # KDL schema parser
โ”‚   โ”œโ”€โ”€ codegen/        # Code generators (Rust/TypeScript)
โ”‚   โ””โ”€โ”€ types/          # Basic type definitions
โ”‚
โ”œโ”€โ”€ ๐ŸŒ Network Layer
โ”‚   โ”œโ”€โ”€ quic/           # QUIC transport implementation
โ”‚   โ”œโ”€โ”€ client/         # Protocol client
โ”‚   โ”œโ”€โ”€ server/         # Protocol server
โ”‚   โ””โ”€โ”€ service/        # Service abstraction layer
โ”‚
โ””โ”€โ”€ ๐Ÿงฉ Context Layer (CGP)
    โ”œโ”€โ”€ adapter/        # Existing system integration
    โ”œโ”€โ”€ handlers/       # Extensible handlers
    โ””โ”€โ”€ traits/         # Generic trait definitions

Core Components

1. UnisonStream - Low-level Bidirectional Streaming

pub trait UnisonStream: Send + Sync {
    async fn send(&mut self, data: Value) -> Result<(), NetworkError>;
    async fn receive(&mut self) -> Result<Value, NetworkError>;
    async fn close(&mut self) -> Result<(), NetworkError>;
    fn is_active(&self) -> bool;
}

2. Service - High-level Service Abstraction

pub trait Service: UnisonStream {
    fn service_type(&self) -> &str;
    fn version(&self) -> &str;
    async fn handle_request(&mut self, method: &str, payload: Value)
        -> Result<Value, NetworkError>;
}

3. CGP Context - Extensible Context

pub struct CgpProtocolContext<T, R, H> {
    transport: T,      // Transport layer
    registry: R,       // Service registry
    handlers: H,       // Message handlers
}

๐Ÿ“Š Performance

Benchmark Results

Metric QUIC WebSocket HTTP/2
Latency (p50) 2.3ms 5.1ms 8.2ms
Latency (p99) 12.5ms 23.4ms 45.6ms
Throughput 850K msg/s 420K msg/s 180K msg/s
CPU Usage 35% 48% 62%

Test environment: AMD Ryzen 9 5900X, 32GB RAM, localhost

๐Ÿงช Testing

Running Tests

# Run all tests
cargo test

# Integration tests only
cargo test --test quic_integration_test

# With verbose logging
RUST_LOG=debug cargo test -- --nocapture

Test Coverage

  • โœ… QUIC connection/disconnection
  • โœ… Message serialization
  • โœ… Handler registration/invocation
  • โœ… Error handling
  • โœ… SystemStream lifecycle
  • โœ… Service metadata management
  • โœ… Automatic certificate generation

๐Ÿ”ง Advanced Usage

Custom Handler Implementation

use unison_protocol::context::{Handler, HandlerRegistry};

struct MyCustomHandler;

#[async_trait]
impl Handler for MyCustomHandler {
    async fn handle(&self, input: Value) -> Result<Value, NetworkError> {
        // Custom logic
        Ok(json!({"status": "processed"}))
    }
}

// Registration
let registry = HandlerRegistry::new();
registry.register("custom", MyCustomHandler).await;

Streaming Communication

use unison_protocol::network::UnisonStream;

// Create stream
let mut stream = client.start_system_stream("data_feed", json!({})).await?;

// Async send/receive
tokio::spawn(async move {
    while stream.is_active() {
        match stream.receive().await {
            Ok(data) => println!("Received: {}", data),
            Err(e) => eprintln!("Error: {}", e),
        }
    }
});

Service Metrics

let stats = service.get_performance_stats().await?;
println!("Latency: {:?}", stats.avg_latency);
println!("Throughput: {} msg/s", stats.messages_per_second);
println!("Active streams: {}", stats.active_streams);

๐Ÿ“š Documentation

๐Ÿ› ๏ธ Development

Build Requirements

  • Rust 1.70 or higher
  • Tokio 1.40 or higher
  • OpenSSL or BoringSSL (for QUIC)

Development Environment Setup

# Clone repository
git clone https://github.com/chronista-club/unison-protocol
cd unison-protocol

# Install dependencies
cargo build

# Start development server
cargo run --example unison_ping_server

# Run tests
cargo test

Code Generation

# Generate code from KDL schema
cargo build --features codegen

# Generate TypeScript definitions
cargo run --bin generate-ts

๐Ÿค Contributing

Pull requests are welcome! Please follow these guidelines:

  1. Fork and create a feature branch
  2. Add tests (coverage 80% or higher)
  3. Run cargo fmt and cargo clippy
  4. Use Conventional Commits for commit messages
  5. Submit a pull request

๐Ÿ“„ License

MIT License - See LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Quinn - QUIC implementation
  • KDL - Configuration language
  • Tokio - Async runtime

Unison Protocol - Harmonizing communication across languages and platforms ๐ŸŽต

GitHub | Crates.io | Discord