{"id":30840909,"url":"https://github.com/bug-ops/pjs","last_synced_at":"2025-09-06T19:48:01.458Z","repository":{"id":309239411,"uuid":"1035504488","full_name":"bug-ops/pjs","owner":"bug-ops","description":"Priority JSON Streaming Protocol","archived":false,"fork":false,"pushed_at":"2025-08-10T19:05:21.000Z","size":108,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-10T19:30:53.876Z","etag":null,"topics":["json","priority","protocol","streaming"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bug-ops.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-08-10T14:41:59.000Z","updated_at":"2025-08-10T19:05:25.000Z","dependencies_parsed_at":"2025-08-11T07:45:56.730Z","dependency_job_id":null,"html_url":"https://github.com/bug-ops/pjs","commit_stats":null,"previous_names":["bug-ops/sjsp"],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/bug-ops/pjs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bug-ops%2Fpjs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bug-ops%2Fpjs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bug-ops%2Fpjs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bug-ops%2Fpjs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bug-ops","download_url":"https://codeload.github.com/bug-ops/pjs/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bug-ops%2Fpjs/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273955717,"owners_count":25197579,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-06T02:00:13.247Z","response_time":2576,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json","priority","protocol","streaming"],"created_at":"2025-09-06T19:47:58.252Z","updated_at":"2025-09-06T19:48:01.444Z","avatar_url":"https://github.com/bug-ops.png","language":"Rust","readme":"\u003c!-- markdownlint-disable MD024 --\u003e\n# PJS - Priority JSON Streaming Protocol\n\n[![Crates.io](https://img.shields.io/crates/v/pjson-rs.svg)](https://crates.io/crates/pjson-rs)\n[![Documentation](https://docs.rs/pjson-rs/badge.svg)](https://docs.rs/pjson-rs)\n[![Rust Build](https://github.com/bug-ops/pjs/actions/workflows/rust.yml/badge.svg)](https://github.com/bug-ops/pjs/actions/workflows/rust.yml)\n[![codecov](https://codecov.io/gh/bug-ops/pjs/branch/main/graph/badge.svg)](https://codecov.io/gh/bug-ops/pjs)\n[![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg)](LICENSE)\n[![Rust Version](https://img.shields.io/badge/rust-nightly-orange.svg)](https://www.rust-lang.org)\n\n**🚀 6.3x faster than serde_json | 🎯 5.3x faster progressive loading | 💾 Bounded memory usage | 🏗️ Production Ready**\n\n\u003e **New in v0.3.0**: Production-ready code quality with zero clippy warnings, Clean Architecture compliance, and comprehensive test coverage (196 tests). **Now requires nightly Rust for zero-cost abstractions**.\n\n\u003c/div\u003e\n\n## 🌟 Key Features\n\n\u003ctable\u003e\n\u003ctr\u003e\n\u003ctd\u003e\n\n### ⚡ Blazing Fast\n\n- **6.3x faster** than serde_json\n- **1.71 GiB/s** throughput\n- SIMD-accelerated parsing\n\n\u003c/td\u003e\n\u003ctd\u003e\n\n### 🎯 Smart Streaming\n\n- Skeleton-first delivery\n- Priority-based transmission\n- Progressive enhancement\n\n\u003c/td\u003e\n\u003ctd\u003e\n\n### 💾 Memory Efficient\n\n- **5.3x** faster progressive loading\n- Bounded memory usage\n- Zero-copy operations\n\n\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\n\n### 🔧 Production Ready\n\n- All tests passing\n- Clean Architecture\n\n\u003c/td\u003e\n\u003ctd\u003e\n\n### 📊 Schema Aware\n\n- Automatic compression\n- Semantic analysis\n- Type optimization\n\n\u003c/td\u003e\n\u003ctd\u003e\n\n### 🚀 Developer Friendly\n\n- Simple API\n- Drop-in replacement\n- Extensive documentation\n\n\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n## 🎯 The Problem\n\nModern web applications face a fundamental challenge: **large JSON responses block UI rendering**.\n\n### Current State\n\n- 📊 Analytics dashboard loads 5MB of JSON\n- ⏱️ User waits 2-3 seconds seeing nothing\n- 😤 User thinks app is broken and refreshes\n- 🔄 The cycle repeats\n\n### Why existing solutions fall short\n\n| Solution | Problem |\n|----------|---------|\n| **Pagination** | Requires multiple round-trips, complex state management |\n| **GraphQL** | Still sends complete response, just smaller |\n| **JSON streaming** | No semantic understanding, can't prioritize |\n| **Compression** | Reduces size but not time-to-first-byte |\n\n## ✨ The Solution: PJS\n\nPJS revolutionizes JSON transmission by **understanding your data semantically** and **prioritizing what matters**.\n\n### Core Innovation: Semantic Prioritization\n\n```rust\n#[derive(JsonPriority)]\nstruct UserDashboard {\n    #[priority(critical)]  // Sent in first 10ms\n    user_id: u64,\n    user_name: String,\n    \n    #[priority(high)]      // Sent in next 50ms\n    recent_activity: Vec\u003cActivity\u003e,\n    notifications: Vec\u003cNotification\u003e,\n    \n    #[priority(low)]       // Sent when available\n    detailed_analytics: Analytics,  // 4MB of data\n}\n```\n\n### Real-World Impact\n\n```plain\nTraditional JSON Loading:\n[████████████████████] 100% - 2000ms - Full UI renders\n\nPJS Loading:\n[██░░░░░░░░░░░░░░░░░░] 10%  - 10ms   - Critical UI visible\n[██████░░░░░░░░░░░░░░] 30%  - 50ms   - Interactive UI\n[████████████████████] 100% - 2000ms - Full data loaded\n\nUser Experience: ⚡ Instant → 😊 Happy\n```\n\n## Key Features\n\n### 🚀 Complete HTTP Server Integration\n\nProduction-ready Axum integration with full REST API, session management, and real-time streaming.\n\n### 🎯 Advanced Streaming Implementations\n\n- **AdaptiveFrameStream**: Client capability-based optimization\n- **BatchFrameStream**: High-throughput batch processing  \n- **PriorityFrameStream**: Priority-based frame ordering with buffering\n\n### 🏗️ Domain-Driven Design Architecture\n\nClean architecture with CQRS pattern, event sourcing, and ports \u0026 adapters for maximum testability and maintainability.\n\n### 📊 Production-Ready Infrastructure\n\n- Thread-safe in-memory storage and metrics collection\n- Event publishing with subscription support\n- Prometheus metrics integration\n- Comprehensive middleware stack (CORS, security, compression)\n\n### 🔄 Multiple Response Formats\n\nAutomatic format detection supporting JSON, NDJSON, and Server-Sent Events based on client Accept headers.\n\n### ⚡ SIMD-Accelerated Parsing\n\nPowered by `sonic-rs` for blazing fast JSON processing with zero-copy operations.\n\n### 🔄 Real-Time WebSocket Streaming\n\nComplete WebSocket implementation with priority-based frame delivery:\n\n- **Session Management**: Track active WebSocket connections with metrics\n- **Priority-Based Delivery**: Critical data sent first with adaptive delays\n- **Schema-Based Compression**: Intelligent compression using multiple strategies  \n- **Progressive Enhancement**: Skeleton-first streaming with incremental updates\n- **Demo Servers**: Interactive demonstrations of real-time streaming capabilities\n\n## 🎉 What's New in v0.3.0\n\n### 🛠️ Production-Ready Code Quality\n\n- **Zero Clippy Warnings**: All 44+ clippy warnings resolved across entire codebase\n- **Modern Format Strings**: Updated to `format!(\"{var}\")` syntax throughout\n- **Enhanced Error Handling**: Proper Result patterns and async trait compatibility\n- **Memory Safety**: Fixed await-holding lock patterns and buffer alignment issues\n- **196 Tests Passing**: Complete test suite with all features enabled\n\n### 🏗️ Clean Architecture Enforcement\n\n- **Domain Layer Isolation**: Custom `JsonData` value object replacing `serde_json::Value`\n- **Type Safety**: Eliminated all architecture violations in domain layer\n- **Seamless Conversion**: `From` trait implementations for `JsonData ↔ serde_json::Value`\n- **Proper Boundaries**: Clear separation between domain and infrastructure errors\n\n### 🌐 HTTP/WebSocket Modernization\n\n- **Axum v0.8 Compatibility**: Updated route syntax from `:param` to `{param}` format\n- **StreamExt Integration**: Fixed async stream processing with proper trait imports\n- **Body Type Updates**: Modern HTTP body handling for latest axum/hyper versions\n- **All Tests Passing**: Complete HTTP integration test suite validation\n\n### 🔧 Technical Debt Resolution\n\n- **Architecture Compliance**: Resolved all Clean Architecture violations\n- **Lint Standards**: Zero warnings with strict linting enabled (`-D warnings`)\n- **Async Patterns**: Fixed await-across-locks and other async safety issues\n- **Type System**: Enhanced type safety with better generic bounds and aliases\n\n## Benchmarks\n\n### 🚀 **Actual Performance Results**\n\n| Metric | serde_json | sonic-rs | PJS | PJS Advantage |\n|--------|------------|----------|-----|---------------|\n| **Small JSON (43B)** | 275ns | 129ns | 312ns | Competitive |\n| **Medium JSON (351B)** | 1,662ns | 434ns | 590ns | **2.8x vs serde** |\n| **Large JSON (357KB)** | 1,294μs | 216μs | 204μs | **6.3x vs serde, 1.06x vs sonic** |\n| **Memory Efficiency** | Baseline | Fast | **5.3x faster** progressive | **Bounded memory** |\n| **Progressive Loading** | Batch-only | Batch-only | **37μs** vs 198μs | **5.3x faster** |\n\n### 🎯 **Key Performance Achievements**\n\n- **6.3x faster** than serde_json for large JSON processing\n- **1.06x faster** than sonic-rs (SIMD library) on large datasets  \n- **5.3x faster** progressive loading vs traditional batch processing\n- **1.71 GiB/s** sustained throughput (exceeding sonic-rs 1.61 GiB/s)\n\n## Installation\n\nAdd PJS to your `Cargo.toml`:\n\n```toml\n[dependencies]\npjson-rs = \"0.3.0\"\n\n# Optional: for HTTP server integration\naxum = \"0.8\"\ntokio = { version = \"1\", features = [\"full\"] }\n```\n\nOr use cargo:\n\n```bash\ncargo add pjson-rs\n```\n\n## Quick Start\n\n### HTTP Server with Axum Integration\n\n```rust\nuse std::sync::Arc;\nuse pjson_rs::{\n    application::{\n        handlers::{InMemoryCommandHandler, InMemoryQueryHandler},\n        services::{SessionService, StreamingService},\n    },\n    infrastructure::{\n        adapters::{InMemoryStreamRepository, InMemoryEventPublisher, InMemoryMetricsCollector},\n        http::axum_adapter::{create_pjs_router, PjsAppState},\n    },\n};\n\n#[tokio::main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error + Send + Sync\u003e\u003e {\n    // Create infrastructure\n    let repository = Arc::new(InMemoryStreamRepository::new());\n    let event_publisher = Arc::new(InMemoryEventPublisher::new());\n    let metrics_collector = Arc::new(InMemoryMetricsCollector::new());\n    \n    // Create CQRS handlers\n    let command_handler = Arc::new(InMemoryCommandHandler::new(\n        repository.clone(), event_publisher, metrics_collector.clone()\n    ));\n    let query_handler = Arc::new(InMemoryQueryHandler::new(repository, metrics_collector));\n    \n    // Create services\n    let session_service = Arc::new(SessionService::new(command_handler.clone(), query_handler.clone()));\n    let streaming_service = Arc::new(StreamingService::new(command_handler));\n    \n    // Build Axum app\n    let app = create_pjs_router()\n        .with_state(PjsAppState::new(session_service, streaming_service));\n    \n    // Start server\n    let listener = tokio::net::TcpListener::bind(\"127.0.0.1:3000\").await?;\n    println!(\"🚀 PJS Server running on http://127.0.0.1:3000\");\n    axum::serve(listener, app).await?;\n    \n    Ok(())\n}\n```\n\n### JavaScript/TypeScript Client Library\n\nUse the official PJS client library for seamless integration:\n\n```bash\nnpm install @pjs/client\n```\n\n#### HTTP Streaming\n\n```typescript\nimport { PjsClient, createHttpTransport } from '@pjs/client';\n\n// Create client with HTTP transport\nconst client = new PjsClient({\n    transport: createHttpTransport({\n        baseUrl: 'http://localhost:3000',\n        format: 'sse' // or 'json', 'ndjson'\n    })\n});\n\n// Stream data with priority-based delivery\nawait client.stream({\n    data: { \n        users: [/* large array */],\n        dashboard: { /* complex object */ }\n    },\n    onFrame: (frame) =\u003e {\n        // Frames arrive in priority order\n        if (frame.priority \u003e= 90) {\n            updateUI(frame.data); // Critical data first\n        }\n    }\n});\n```\n\n#### WebSocket Real-Time Streaming\n\n```typescript\nimport { PjsClient, createWebSocketTransport } from '@pjs/client';\n\nconst client = new PjsClient({\n    transport: createWebSocketTransport({\n        url: 'ws://localhost:3001/ws'\n    })\n});\n\n// Real-time streaming with priority handling\nawait client.connect();\n\nclient.onFrame((frame) =\u003e {\n    console.log(`Priority ${frame.priority}:`, frame.data);\n    \n    // Handle based on priority\n    switch (frame.priority) {\n        case 'critical':\n            showImmediate(frame.data);\n            break;\n        case 'high':\n            queueForNextFrame(frame.data);\n            break;\n        default:\n            processInBackground(frame.data);\n    }\n});\n```\n\n### WebSocket Streaming\n\n```rust\nuse pjson_rs::{\n    ApplicationResult,\n    domain::value_objects::SessionId,\n};\nuse futures::{SinkExt, StreamExt};\nuse tokio_tungstenite::{connect_async, tungstenite::Message};\n\n#[tokio::main]\nasync fn main() -\u003e ApplicationResult\u003c()\u003e {\n    // Connect to WebSocket streaming server\n    let (ws_stream, _) = connect_async(\"ws://127.0.0.1:3001/ws\")\n        .await\n        .expect(\"Failed to connect\");\n    \n    let (mut write, mut read) = ws_stream.split();\n    \n    // Receive prioritized frames\n    while let Some(message) = read.next().await {\n        match message? {\n            Message::Text(text) =\u003e {\n                let frame: serde_json::Value = serde_json::from_str(\u0026text)?;\n                \n                match frame[\"@type\"].as_str() {\n                    Some(\"pjs_frame\") =\u003e {\n                        let priority = frame[\"@priority\"].as_u64().unwrap_or(0);\n                        \n                        if priority \u003e= 200 {\n                            println!(\"🚨 Critical data: {}\", frame[\"data\"]);\n                        } else if priority \u003e= 100 {\n                            println!(\"📊 High priority: {}\", frame[\"data\"]);\n                        } else {\n                            println!(\"📝 Background data received\");\n                        }\n                    }\n                    Some(\"stream_complete\") =\u003e {\n                        println!(\"✅ Stream completed!\");\n                        break;\n                    }\n                    _ =\u003e {}\n                }\n            }\n            _ =\u003e {}\n        }\n    }\n    \n    Ok(())\n}\n```\n\n### Demo Servers\n\nStart the interactive demos to see PJS in action:\n\n```bash\n# WebSocket streaming server with priority-based delivery\ncargo run --bin websocket_streaming --manifest-path crates/pjs-demo/Cargo.toml\n\n# Interactive demo with HTML interface and real-time visualization\ncargo run --bin interactive_demo --manifest-path crates/pjs-demo/Cargo.toml\n\n# Simple demo server with basic streaming\ncargo run --bin simple_demo --manifest-path crates/pjs-demo/Cargo.toml\n\n# Performance comparison demo (PJS vs traditional JSON)\ncargo run --bin performance_comparison --manifest-path crates/pjs-demo/Cargo.toml\n```\n\nOr run root-level examples:\n\n```bash\n# Complete Axum HTTP server\ncargo run --example axum_server\n\n# Advanced streaming demo server  \ncargo run --example streaming_demo_server\n\n# Simple usage patterns\ncargo run --example simple_usage\n```\n\nThen visit `http://127.0.0.1:3000` to see priority-based streaming in action.\n\n## Use Cases\n\nPerfect for:\n\n- 📊 **Real-time dashboards** - Show key metrics instantly\n- 📱 **Mobile apps** - Optimize for slow networks\n- 🛍️ **E-commerce** - Load product essentials first\n- 📈 **Financial platforms** - Prioritize critical trading data\n- 🎮 **Gaming leaderboards** - Show player's rank immediately\n\n## Architecture\n\nPJS implements a clean, layered architecture following Domain-Driven Design principles:\n\n### 1. Domain Layer\n\nCore business logic with value objects (Priority, SessionId, JsonPath) and aggregates (StreamSession) ensuring data consistency.\n\n### 2. Application Layer  \n\nCQRS pattern with separate Command and Query handlers, plus high-level services (SessionService, StreamingService) orchestrating workflows.\n\n### 3. Infrastructure Layer\n\nAdapters implementing domain ports:\n\n- **Storage**: In-memory repositories with thread-safe concurrent access\n- **Events**: Publisher/subscriber pattern for domain event distribution  \n- **Metrics**: Performance monitoring with Prometheus integration\n- **HTTP**: Complete Axum server with middleware stack\n\n### 4. Transport Abstraction\n\nMulti-format streaming support:\n\n- **JSON**: Standard response format\n- **NDJSON**: Newline-delimited for efficient processing\n- **Server-Sent Events**: Real-time browser compatibility\n- Automatic format detection via Accept headers\n\n### 5. Advanced Streaming\n\nIntelligent frame processing:\n\n- **Priority-based delivery**: Critical data first\n- **Adaptive buffering**: Dynamic sizing based on client performance\n- **Batch processing**: High-throughput chunk aggregation\n\n## Technical Architecture\n\n```plain\npjs/\n├── crates/\n│   ├── pjs-core/           # Core protocol, domain logic, and HTTP integration\n│   │   ├── src/\n│   │   │   ├── application/    # CQRS handlers, services, DTOs\n│   │   │   ├── domain/         # Value objects, entities, aggregates\n│   │   │   ├── infrastructure/ # HTTP, WebSocket, repositories, adapters\n│   │   │   ├── parser/         # SIMD, zero-copy, buffer pools\n│   │   │   ├── stream/         # Priority streaming, reconstruction\n│   │   │   └── compression/    # Schema-based compression\n│   │   ├── examples/           # Standalone demos (zero-copy, compression)\n│   │   └── tests/              # Integration tests\n│   ├── pjs-demo/           # Interactive demo servers with WebSocket streaming\n│   │   └── src/\n│   │       ├── servers/        # Demo server implementations\n│   │       ├── clients/        # WebSocket client demos  \n│   │       ├── data/           # Sample data generators (analytics, ecommerce)\n│   │       └── static/         # HTML interfaces\n│   ├── pjs-js-client/      # JavaScript/TypeScript client library ✅ IMPLEMENTED\n│   │   ├── src/            # TypeScript source code with transport layers\n│   │   ├── tests/          # Jest test suite with full coverage\n│   │   └── package.json    # NPM configuration and dependencies\n│   └── pjs-bench/          # Benchmarking suite\n│       └── benches/        # Criterion.rs performance benchmarks\n└── examples/               # Root-level usage examples\n    ├── axum_server.rs      # Complete HTTP server demo\n    ├── simple_usage.rs     # Basic usage patterns  \n    └── streaming_demo_server.rs # Advanced streaming demo\n```\n\n### Current Implementation Status\n\n- **Phase 1**: ✅ Core foundation (100% complete)\n- **Phase 2**: ✅ Protocol layer (100% complete)  \n- **Phase 3**: ✅ Client/Server framework (100% complete)\n- **Phase 4**: ✅ Transport layer (100% complete)\n- **Phase 5**: ✅ Production features (100% complete)\n- **Phase 6**: ✅ Real-Time Streaming (100% complete)\n- **Phase 7**: ✅ JavaScript/TypeScript Client SDK (100% complete)\n- **Phase 8**: ✅ Code Quality \u0026 Production Readiness (100% complete)\n- **Overall**: ~98% of core functionality implemented\n\n### Implemented Components\n\n- **✅ pjs-core**: Complete Rust implementation with Clean Architecture\n- **✅ pjs-demo**: Interactive demo servers with real-time WebSocket streaming  \n- **✅ pjs-js-client**: Full TypeScript/JavaScript client library with transport layers\n- **✅ pjs-bench**: Comprehensive benchmarking suite with performance validation\n- **✅ Examples**: Multiple working examples from simple to advanced usage\n\n## API Examples\n\n### HTTP Endpoints\n\nThe server provides a complete REST API:\n\n```bash\n# Create a new session\nPOST /pjs/sessions\nContent-Type: application/json\n{\n  \"max_concurrent_streams\": 10,\n  \"timeout_seconds\": 3600,\n  \"client_info\": \"My App v1.0\"\n}\n\n# Response: { \"session_id\": \"sess_abc123\", \"expires_at\": \"...\" }\n\n# Get session info  \nGET /pjs/sessions/{session_id}\n\n# Start streaming data\nPOST /pjs/stream/{session_id}\nContent-Type: application/json\n{\n  \"data\": { \"users\": [...], \"products\": [...] },\n  \"priority_threshold\": 50,\n  \"max_frames\": 100\n}\n\n# Stream frames (JSON format)\nGET /pjs/stream/{session_id}/frames?format=json\u0026priority=80\n\n# Real-time Server-Sent Events\nGET /pjs/stream/{session_id}/sse\nAccept: text/event-stream\n\n# System health check\nGET /pjs/health\n# Response: { \"status\": \"healthy\", \"version\": \"0.3.0\" }\n```\n\n### Working Example\n\nA complete working server is available at `examples/axum_server.rs`. To run it:\n\n```bash\n# Start the server\ncargo run --example axum_server\n\n# Test endpoints\ncurl -X POST http://localhost:3000/pjs/sessions \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"max_concurrent_streams\": 5}'\n\n# Check health  \ncurl http://localhost:3000/pjs/health\n\n# View metrics\ncurl http://localhost:3000/examples/metrics\n```\n\n## Performance Goals\n\n- **Throughput**: \u003e4 GB/s with sonic-rs\n- **Time to First Byte**: \u003c10ms for critical data\n- **Memory Efficiency**: 5-10x reduction vs traditional parsing\n- **CPU Utilization**: Full SIMD acceleration\n\n## Building\n\n### Prerequisites\n\n- **Rust nightly** (required for `impl Trait` in associated types)\n- CPU with AVX2 support (recommended for SIMD acceleration)\n\n### Setting up Rust Nightly\n\n```bash\n# Install nightly Rust\nrustup install nightly\n\n# Set nightly for this project\nrustup override set nightly\n\n# Or use nightly globally\nrustup default nightly\n```\n\n### Quick Start\n\n```bash\n# Clone repository\ngit clone https://github.com/bug-ops/pjs\ncd pjs\n\n# Ensure nightly Rust is active\nrustup override set nightly\n\n# Build with optimizations\ncargo build --release\n\n# Run tests\ncargo test --workspace\n\n# Run the complete HTTP server example\ncargo run --example axum_server\n\n# Build with optional features\ncargo build --features \"http-client,prometheus-metrics\"\n```\n\n### Feature Flags\n\n- `http-client`: Enable HTTP-based event publishing\n- `prometheus-metrics`: Enable Prometheus metrics collection\n- `simd-auto`: Auto-detect best SIMD support (default)\n- `compression`: Enable compression middleware\n\n## Framework Integration\n\n### Universal Integration Layer with Zero-Cost Abstractions\n\nPJS provides true zero-cost abstractions using **nightly Rust features** for maximum performance. The Universal Framework Integration Layer uses Generic Associated Types (GATs) with `impl Trait` to eliminate all runtime overhead:\n\n```rust\nuse pjson_rs::infrastructure::integration::StreamingAdapter;\nuse std::future::Future;\n\n// Zero-cost framework integration with GATs\nimpl StreamingAdapter for YourFramework {\n    type Request = YourRequest;\n    type Response = YourResponse;\n    type Error = YourError;\n\n    // TRUE zero-cost futures - no Box allocation!\n    type StreamingResponseFuture\u003c'a\u003e = impl Future\u003cOutput = IntegrationResult\u003cSelf::Response\u003e\u003e + Send + 'a\n    where\n        Self: 'a;\n\n    fn create_streaming_response\u003c'a\u003e(\n        \u0026'a self,\n        session_id: SessionId,\n        frames: Vec\u003cStreamFrame\u003e,\n        format: StreamingFormat,\n    ) -\u003e Self::StreamingResponseFuture\u003c'a\u003e {\n        // Direct async block - compiler generates optimal Future type\n        async move {\n            // Your framework-specific logic here\n            Ok(your_response)\n        }\n    }\n\n    fn framework_name(\u0026self) -\u003e \u0026'static str {\n        \"your_framework\"\n    }\n}\n```\n\n### Performance Benefits of Nightly Rust\n\n**Zero-Cost Abstractions:**\n- **1.82x faster** trait dispatch vs async_trait\n- **Zero heap allocations** for futures\n- **Pure stack allocation** - no runtime overhead\n- **Static dispatch** eliminates vtables\n- **Complete inlining** for hot paths\n\n### Currently Supported\n\n- **✅ Axum**: Full native integration with zero-cost GAT futures\n- **🔧 Any Framework**: Universal adapter with true zero-cost abstractions\n- **📋 Planned**: Helper macros for popular frameworks (Actix, Warp, Tide)\n\n### Integration Examples\n\n```rust\n// Axum (native support)\nuse pjson_rs::infrastructure::http::axum_adapter::create_pjs_router;\nlet app = create_pjs_router().with_state(app_state);\n\n// Custom framework integration\nuse pjson_rs::infrastructure::adapters::UniversalAdapter;\nlet adapter = UniversalAdapter::new()\n    .with_serializer(your_serializer)\n    .with_transport(your_transport);\n```\n\n## Production Features\n\n### Middleware Stack\n\nThe HTTP server includes production-ready middleware:\n\n```rust\nuse pjson_rs::infrastructure::http::middleware::*;\n\nlet app = create_pjs_router()\n    .layer(axum::middleware::from_fn(pjs_cors_middleware))\n    .layer(axum::middleware::from_fn(security_middleware))\n    .layer(axum::middleware::from_fn(health_check_middleware))\n    .layer(PjsMiddleware::new()\n        .with_compression(true)\n        .with_metrics(true)\n        .with_max_request_size(10 * 1024 * 1024))\n    .with_state(app_state);\n```\n\n### Monitoring \u0026 Metrics\n\nBuilt-in Prometheus metrics support:\n\n```rust\n// Automatically tracks:\n// - pjs_active_sessions\n// - pjs_total_sessions_created  \n// - pjs_frames_processed_total\n// - pjs_bytes_streamed_total\n// - pjs_frame_processing_time_ms\n\nlet metrics = collector.export_prometheus();\n// Expose at /metrics endpoint for Prometheus scraping\n```\n\n### Event System\n\nComprehensive domain event tracking:\n\n```rust\n// Events automatically generated:\n// - SessionCreated, SessionActivated, SessionEnded\n// - StreamStarted, StreamCompleted, FrameGenerated\n// - PriorityAdjusted, ErrorOccurred\n\npublisher.subscribe(\"SessionCreated\", |event| {\n    println!(\"New session: {}\", event.session_id());\n});\n```\n\n## Contributing\n\nWe welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n### Development Setup\n\n```bash\n# Install development tools\nrustup component add clippy rustfmt\n\n# Run checks\ncargo clippy --workspace\ncargo fmt --check\n\n# Run all tests\ncargo test --workspace --all-features\n```\n\n## License\n\nLicensed under either of:\n\n- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))\n- MIT License ([LICENSE-MIT](LICENSE-MIT))\n\nat your option.\n\n## Getting Started Right Now\n\nWant to try PJS immediately? Here's the fastest way:\n\n```bash\n# Clone and run\ngit clone https://github.com/bug-ops/pjs\ncd pjs\n\n# Set nightly Rust (required)\nrustup override set nightly\n\n# Run the server\ncargo run --example axum_server\n\n# In another terminal, test the API\ncurl -X POST http://localhost:3000/pjs/sessions \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"max_concurrent_streams\": 5}'\n\n# Try Server-Sent Events streaming  \ncurl -N -H \"Accept: text/event-stream\" \\\n  http://localhost:3000/pjs/stream/{session_id}/sse\n```\n\n### Running Performance Benchmarks\n\nTo verify the performance claims, run the comprehensive benchmark suite:\n\n```bash\n# Run all benchmarks\ncargo bench -p pjs-bench\n\n# Or run specific benchmarks:\ncargo bench -p pjs-bench --bench simple_throughput    # Core parsing speed\ncargo bench -p pjs-bench --bench memory_benchmarks    # Memory efficiency  \ncargo bench -p pjs-bench --bench streaming_benchmarks # Progressive loading\n```\n\nResults show PJS **6.3x faster** than serde_json and **1.06x faster** than sonic-rs on large JSON.\n\nThe server will show:\n\n- 🚀 Server starting message\n- 📊 Health check endpoint\n- 📝 Available API endpoints\n- 🎯 Demo data streaming capabilities\n\n## Roadmap\n\n### Next Steps\n\n- [x] Connection lifecycle management ✅\n- [x] WebSocket real-time streaming ✅\n- [x] Performance benchmarks vs alternatives ✅\n- [x] JavaScript/TypeScript client library ✅\n- [ ] Universal framework integration layer\n- [ ] Schema validation engine  \n- [ ] Custom priority strategies\n\n## Acknowledgments\n\nBuilt with:\n\n- [sonic-rs](https://github.com/cloudwego/sonic-rs) - Lightning fast SIMD JSON parser\n- [axum](https://github.com/tokio-rs/axum) - Ergonomic web framework for Rust  \n- [tokio](https://github.com/tokio-rs/tokio) - Async runtime for Rust\n- [bytes](https://github.com/tokio-rs/bytes) - Efficient byte buffer management\n\n## Community\n\n- 📖 [Documentation](SPECIFICATION.md) - Complete protocol specification\n- 📋 [Changelog](CHANGELOG.md) - Detailed version history\n- 📊 [Benchmarks](crates/pjs-bench/README.md) - Comprehensive performance results\n- 💬 [Discussions](https://github.com/bug-ops/pjs/discussions) - Questions and ideas\n\n---\n\n*PJS: Because users shouldn't wait for data they don't need yet.*\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbug-ops%2Fpjs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbug-ops%2Fpjs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbug-ops%2Fpjs/lists"}