csilk:基于 libuv 和 llhttp 的轻量级高性能 HTTP Web 框架项目

A lightweight, high-performance HTTP web framework written in C and built on top of libuv, llhttp, and cJSON.

分支1Tags1
文件最后提交记录最后更新时间
fix: resolve test failures, compilation warnings and optimize ASan integration - Fixed test_workflow_persistence by ensuring robust WAL logging and parsing. - Refactored wal_log_event to ensure consistent null-termination of payload fields. - Added boundary checks when parsing WAL NODE_FINISH events to prevent overflows. - Optimized ASan integration in CMakeLists.txt using static linking to avoid manual LD_PRELOAD. - Enhanced CI workflow with ASAN_OPTIONS for better diagnostics. - Resolved -Wcomment warnings by fixing nested block comments in documentation. - Added Doxygen documentation for csilk_arena_get_stats. - Fixed driver setter declaration order in csilk.h. 12 小时前
feat: test quality, feature enhancement, and dev experience - ci.yml: add clang-tidy step - CMakeLists.txt: register example_ai_providers - CONTRIBUTING.md: expand to 250 lines with debugging/architecture guide - cmake/tests.cmake: register test_config_load, test_multi_worker - share/csilk/admin_ui.html: WebSocket auto-reconnect with exponential backoff - src/core/server.c: multi-worker shutdown fix (per-worker uv_async_t + barrier) - ABI_REPORT.md: ABI stability assessment (partial opaquing deferred to v1.0) - benchmarks/: wrk-based benchmark automation with make bench target - examples/example_ai_providers.c: multi-provider AI demo (Echo, OpenAI, Ollama) - scripts/run_benchmarks.sh: benchmark runner with JSON output and comparison - tests/: config YAML load test, multi-worker integration test 22 小时前
feat: HTTP/2 session scaffolding and client write refactor - Extract csilk_client_write from _csilk_send_data for direct client access - Add _csilk_ctx_init to properly initialise context with server pointers - Add h2_streams linked list to client struct for multiplexed streams - Add stream_id and next_stream to context for HTTP/2 stream tracking - Create h2.c/h2.h with nghttp2 session init and callback stubs - Register h2.c in cmake/sources.cmake 6 小时前
feat: add test_file and HTTP/2 research - Add test_file to test registration in cmake/tests.cmake - Mark 14.4 (sendfile zero-copy) and 15.1 (HTTP/2 research) as completed in PLAN.md 8 小时前
feat: architecture optimization and opaque context refactoring - Refactored csilk_ctx_t to be an opaque structure in the public API to ensure ABI stability. - Moved context_internal.h from include/csilk/core/ to src/core/ to hide implementation details. - Added comprehensive accessor and setter APIs for csilk_ctx_t in csilk.h. - Refactored all internal middlewares (Logger, Gzip, Auth, CORS, CSRF, etc.) to use public APIs. - Updated all unit tests and examples to use new opaque API and test helpers from csilk/test/test.h. - Implemented optimization plan (Track 1): - Completed csilk_config_free logic and added TLS field support. - Added boundary protection and tests for URL parameters and context storage. - Fixed a critical stack-use-after-return bug in connection rejection logic (heap-allocated rejected handles). - Improved robustness of csilk_next with NULL checks. - Enhanced OOM resilience and connection limit handling in the server. - Updated PLAN.md with the new v1.0 evolution roadmap. - Fixed various race conditions and memory leaks discovered during validation. 13 小时前
feat: add admin topology/profiler endpoints and route collection API - Add csilk_router_collect_routes to dump registered routes as JSON - Add csilk_server_get_router accessor for router lookup from server - Add /admin/topology endpoint returning route graph - Add /admin/profile placeholder endpoint for CPU flamegraph data 7 小时前
fix: correct benchmark port from 9090 to 8080 example_server listens on port 8080, but the benchmark script was using port 9090, causing all results to show 0 req/s. 21 小时前
feat: test quality, feature enhancement, and dev experience - ci.yml: add clang-tidy step - CMakeLists.txt: register example_ai_providers - CONTRIBUTING.md: expand to 250 lines with debugging/architecture guide - cmake/tests.cmake: register test_config_load, test_multi_worker - share/csilk/admin_ui.html: WebSocket auto-reconnect with exponential backoff - src/core/server.c: multi-worker shutdown fix (per-worker uv_async_t + barrier) - ABI_REPORT.md: ABI stability assessment (partial opaquing deferred to v1.0) - benchmarks/: wrk-based benchmark automation with make bench target - examples/example_ai_providers.c: multi-provider AI demo (Echo, OpenAI, Ollama) - scripts/run_benchmarks.sh: benchmark runner with JSON output and comparison - tests/: config YAML load test, multi-worker integration test 22 小时前
feat: wire up HTTP/2 session init and data processing - Include h2.h in server.c for HTTP/2 integration - Call csilk_h2_free_streams in pool_put to clean up on client reuse - Initialize nghttp2 session after ALPN negotiation completes - Route decrypted TLS data to h2_process_data for HTTP/2 connections - Use CSILK_DEFAULT_ARENA_SIZE constant instead of config field 6 小时前
test: add on_ws_send callback and improve ws_room tests - Add csilk_set_on_ws_send to intercept outgoing WebSocket frames for testing - Invoke on_ws_send callback in csilk_ws_send before sending - Register test_ws_room in cmake/tests.cmake - Improve test_ws_room broadcast stability with bounded retry loop - Add debug logging in ws_room for MQ subscription visibility 7 小时前
style: switch to Linux kernel coding style with clang-format - IndentWidth: 8 with UseTab: Always (tab indentation) - BreakBeforeBraces: Linux (function brace on new line) - InsertBraces: true (mandatory braces on control statements) - ColumnLimit: 100 - Continuation uses tab-aligned indentation - Trailing comments aligned within structs 1 天前
fix: resolve ASan memory leaks across library and tests - logger.c: free csilk_json_marshal result in build_json_entry - sqlite.c: free row->values and strdup'd strings in sqlite_free_result - mq.c: null-terminate payload in _mq_enqueue to prevent buffer overread - workflow.c: free csilk_ai_config_t (user_data) via node_free callback - free output_schema in node_free - close node_work_t timers before free to avoid use-after-free - reorder mutex destroy after context cleanup in csilk_wf_free - test_jwt.c: free old arena before overwriting - test_metrics.c: free response body (test bypasses framework lifecycle) - test_ws.c: avoid dummy uv_tcp_t that triggers unprocessed uv_write - test_mq*.c: save router pointer for explicit cleanup after server_free - test_mq_monitor.c: use sizeof(csilk_ctx_t) instead of hardcoded 1024 - test_workflow_distributed.c: use %.*s for non-null-terminated payload 22 小时前
feat: test quality, feature enhancement, and dev experience - ci.yml: add clang-tidy step - CMakeLists.txt: register example_ai_providers - CONTRIBUTING.md: expand to 250 lines with debugging/architecture guide - cmake/tests.cmake: register test_config_load, test_multi_worker - share/csilk/admin_ui.html: WebSocket auto-reconnect with exponential backoff - src/core/server.c: multi-worker shutdown fix (per-worker uv_async_t + barrier) - ABI_REPORT.md: ABI stability assessment (partial opaquing deferred to v1.0) - benchmarks/: wrk-based benchmark automation with make bench target - examples/example_ai_providers.c: multi-provider AI demo (Echo, OpenAI, Ollama) - scripts/run_benchmarks.sh: benchmark runner with JSON output and comparison - tests/: config YAML load test, multi-worker integration test 22 小时前
docs: update all documentation for pool_mutex thread-safety fix Update architecture docs, module design, and user manual to document the client pool data race fix in multi-worker mode: - CHANGELOG.md: add 0.2.5 entry - PLAN.md: add P0-5 item, update status table and session log - CODEPEC.md: add 6.4 Multi-Worker Pool Protection with code example - docs/ARCH.md: add 9.1 Client Pool Thread Safety - docs/architecture.md: add Thread Safety note after multi-worker diagram - docs/index.md: bump version to 0.2.5 - docs/module-design/context.md: add pool_get/pool_put to lifecycle diagram - docs/user-manual/advanced-usage.md: add Multi-Worker Mode section - docs/user-manual/configuration.md: annotate worker_threads thread safety - Doxygen: rebuild HTML output 10 小时前
feat: HTTP/2 ALPN negotiation and nghttp2 dependency - Add nghttp2 library as FetchContent dependency in CMakeLists.txt - Add ALPN callback (alpn_select_cb) to negotiate h2 or http/1.1 over TLS - Add csilk_protocol_t enum and h2_session field to client struct - Initialize protocol after TLS handshake via SSL_get0_alpn_selected - Clean up nghttp2 session in pool_put on client reuse 6 小时前
docs: update all documentation for pool_mutex thread-safety fix Update architecture docs, module design, and user manual to document the client pool data race fix in multi-worker mode: - CHANGELOG.md: add 0.2.5 entry - PLAN.md: add P0-5 item, update status table and session log - CODEPEC.md: add 6.4 Multi-Worker Pool Protection with code example - docs/ARCH.md: add 9.1 Client Pool Thread Safety - docs/architecture.md: add Thread Safety note after multi-worker diagram - docs/index.md: bump version to 0.2.5 - docs/module-design/context.md: add pool_get/pool_put to lifecycle diagram - docs/user-manual/advanced-usage.md: add Multi-Worker Mode section - docs/user-manual/configuration.md: annotate worker_threads thread safety - Doxygen: rebuild HTML output 10 小时前
feat: test quality, feature enhancement, and dev experience - ci.yml: add clang-tidy step - CMakeLists.txt: register example_ai_providers - CONTRIBUTING.md: expand to 250 lines with debugging/architecture guide - cmake/tests.cmake: register test_config_load, test_multi_worker - share/csilk/admin_ui.html: WebSocket auto-reconnect with exponential backoff - src/core/server.c: multi-worker shutdown fix (per-worker uv_async_t + barrier) - ABI_REPORT.md: ABI stability assessment (partial opaquing deferred to v1.0) - benchmarks/: wrk-based benchmark automation with make bench target - examples/example_ai_providers.c: multi-provider AI demo (Echo, OpenAI, Ollama) - scripts/run_benchmarks.sh: benchmark runner with JSON output and comparison - tests/: config YAML load test, multi-worker integration test 22 小时前
docs: render Mermaid diagrams in Doxygen HTML output Add runtime Mermaid rendering for Doxygen-generated documentation: - docs/doxy-header.html: custom Doxygen HTML header with mermaid.min.js and a DOMContentLoaded script that converts <div class="fragment"> mermaid code blocks to <div class="mermaid">, then initializes the Mermaid renderer with dark-mode awareness - docs/doxy-mermaid.css: CSS styling for mermaid diagram containers with dark mode filter support - CMakeLists.txt: docs target now auto-downloads mermaid.min.js from CDN via curl before running Doxygen (no committed binary assets) - Doxyfile: set HTML_HEADER, HTML_EXTRA_STYLESHEET, HTML_EXTRA_FILES - .gitignore: ignore docs/assets/ (downloaded at build time) - .github/workflows/docs.yml: add Mermaid validation step 1 天前
docs: mark all v1.0 tracks as completed in PLAN.md 7 小时前
feat(drivers): implement Redis database driver via hiredis - Add src/drivers/redis.c with full csilk_db_driver_t vtable - Support DSN format: host=...;port=...;password=...;db=... - Map Redis reply types to tabular results (GET, HGETALL, KEYS, etc.) - Transactions via MULTI/EXEC/DISCARD - Conditional compilation via HAS_REDIS (requires hiredis) - Update CMakeLists.txt with hiredis detection and linking - Register driver in csilk_db_init() and declare in db.h 1 天前
feat(ai): implement unified AI interface with OpenAI driver support - Add agnostic AI interface in csilk_ai.h for chat completions - Implement driver-based AI core in ai.c with auto-registration - Add default OpenAI driver in ai_openai.c using libcurl - Integrate libcurl dependency into CMakeLists.txt and scaffolding - Add example_ai.c and test_ai.c for verification 3 天前
feat: refine server config with read/write timeouts, max_url_size, max_headers_count, max_connections Config struct (csilk_server_config_t) expanded with: - read_timeout_ms: max time to receive a complete request (default 30s) - write_timeout_ms: max time to flush a response (default 30s) - request_timeout_ms: max time for full request/response cycle (default 0=disabled) - max_url_size: URL length limit (default 8192) - max_headers_count: header count limit (default 100) - max_connections: concurrent connection limit in YAML config (was API-only) Server implementation: - read_timer resets on each data arrival; fires if request incomplete - write_timer starts on uv_write, stops on write completion callback - max_url_size checked in on_url parser callback - max_headers_count tracked via header_count in on_header_field - max_connections respected from config field (precedence: config then API) - All timer handles properly cleaned up with refcounted close logic YAML (config_multi.yaml) updated with all server config fields. 5 天前

csilk

A lightweight, high-performance HTTP web framework written in C, inspired by Gin (Golang) and built on top of libuv, llhttp, and cJSON.

Features

  • 🚀 High performance using libuv for asynchronous I/O
  • 🚀 Zero-copy Static File Serving via sendfile integration
  • 📬 Internal Event Bus - Asynchronous, thread-safe Message Queue with middleware and subscriber support
  • 📈 Native Prometheus Metrics - Built-in observability for QPS, latency, and status codes
  • 🖥️ Unified Admin Dashboard - Web-based real-time monitoring of HTTP, AI Workflows, and MQ
  • 🛡️ Native HTTPS/TLS support via OpenSSL integration
  • 🔑 JWT (JSON Web Token) authentication middleware (HS256)
  • 🔌 Extensible Hook system for lifecycle events (Server, Connection, Request)
  • 🔧 Pluggable Crypto Driver for custom hashing and UUID algorithms
  • 🔐 Pluggable Cipher Driver for AES-256-GCM, RSA-OAEP, and RSA-PSS
  • 🗄️ Pluggable Database Drivers - SQLite, MySQL, PostgreSQL, MongoDB, Redis
  • 🔧 Middleware support (logger, recovery, auth, CORS, CSRF, rate limiting, static files)
  • 🌐 RESTful API routing with parameter handling and route groups
  • 📦 JSON support via cJSON (parse, serialize, error responses, reflection binding)
  • 🍪 Cookie parsing and setting (with Max-Age, Secure, HttpOnly, etc.)
  • 🔌 WebSocket support (RFC 6455 handshake, frame send/receive)
  • 📡 Server-Sent Events (SSE) with csilk_sse_init/send/close
  • 📦 Gzip response compression middleware (with intelligent skipping for media)
  • 📤 Multipart/form-data file upload parsing
  • 🔍 URL parsing and query string handling
  • ⚡ Keep-alive connection support
  • 🛡️ Graceful error handling with crash recovery (setjmp/longjmp)
  • 📋 YAML configuration (server, logger, CORS, rate limit, static files, middleware)
  • 🏗️ Arena allocator for request-scoped memory management
  • 🤖 Unified AI Interface - Provider-agnostic API for Chat, Embeddings, and Tool Calling (OpenAI & Ollama)
  • 🗂️ Reflection engine for automatic struct <-> JSON conversion (including basic types and arrays)
  • 🔐 Built-in CSRF protection, CORS, and rate limiting
  • 📝 Complete Doxygen documentation for all public APIs and internals
  • 🧵 Thread-safe logging with file rotation and ANSI colors
  • 🔍 Configurable connection timeout and body/header size limits
  • 🎯 Global (server-level) and per-route middleware support
  • 🌲 Radix Tree router with :param and *wildcard matching
  • 📝 Form URL-encoded body parsing (application/x-www-form-urlencoded)
  • 🍪 Session management with thread-safe mutex protection
  • 🔀 HTTP redirect helper (csilk_redirect)
  • 📄 HTTP Range request support (206 Partial Content) for static files
  • ✅ Request parameter validation middleware (required, int, string, email)
  • 🆔 Request ID middleware for end-to-end tracing (X-Request-Id)
  • 🩺 Built-in Health Check handler (/healthz)
  • 📦 Opaque Context API for ABI stability

Dependencies

  • libuv - Asynchronous I/O library
  • llhttp - HTTP parser
  • cJSON - JSON parser
  • libyaml - YAML parser
  • OpenSSL - TLS/SSL and Cryptographic library (Required for HTTPS and JWT)

libuv and cJSON are automatically fetched during build via CMake's FetchContent. llhttp is used from the system if available, otherwise fetched. libyaml and OpenSSL must be installed as system dependencies.

Installation (Debian/Ubuntu)

sudo apt install libyaml-dev libssl-dev

Building

Prerequisites

  • CMake 3.11 or higher
  • C compiler (supporting C11)
  • Git (for fetching dependencies)
  • libyaml development headers (apt install libyaml-dev on Debian/Ubuntu)

Build Steps

# Clone the repository
git clone https://github.com/yourusername/csilk.git
cd csilk

# Create a build directory
mkdir build && cd build

# Configure with CMake
cmake ..

# Build
make

# By default, csilk builds as a static library.
# To build as a shared library, use:
# cmake .. -DBUILD_SHARED_LIBS=ON
#
# Other available options:
#   -DUSE_ASAN=ON          Enable AddressSanitizer (default OFF)
#   -DCSILK_BUILD_SHARED=ON Build shared library (default OFF)
#   -DUSE_FUZZER=ON        Enable libFuzzer (default OFF)

# Optional: Run tests
make run_tests     # Runs all tests via ctest
# or: ctest --test-dir . --output-on-failure

# Optional: Run individual test
./tests/test_logger
# ... other test executables

# Optional: Build documentation
make docs  # Requires Doxygen

# Optional: Format code
make format  # Requires clang-format

Documentation

API documentation is written using Doxygen comments throughout the codebase. All public API functions, types, enums, and macros in the headers (include/csilk/csilk.h, include/csilk/app/app.h, include/csilk/core/internal.h, include/csilk/reflection/reflect.h) are fully documented with @brief, @param, and @return tags. Implementation files in src/ subdirectories also carry complete Doxygen documentation with consistent @copyright and license annotations.

Online documentation is available at: https://quintin-lee.github.io/csilk/

To generate HTML documentation locally:

cd build && cmake .. && make docs     # Or: doxygen Doxyfile

Open docs/html/index.html in your browser to browse the API reference.

Documentation Coverage

Component Status
include/csilk/ (public API hierarchy) Fully documented
src/core/ (kernel implementation) Fully documented
src/app/ (app layer) Fully documented
src/ai/, src/data/, src/security/ Fully documented
src/middleware/ (middleware) Fully documented
examples/ (example code) Fully documented

Usage

Simple Server Example

#include "csilk/csilk.h"

void hello_handler(csilk_ctx_t* c) {
    csilk_string(c, 200, "Hello World!");
}

void ping_handler(csilk_ctx_t* c) {
    csilk_string(c, 200, "pong");
}

int main() {
    // Create router
    csilk_router_t* router = csilk_router_new();

    // Define routes
    csilk_handler_t hello_handlers[] = {hello_handler};
    csilk_router_add(router, "GET", "/", hello_handlers, 1);

    csilk_handler_t ping_handlers[] = {ping_handler};
    csilk_router_add(router, "GET", "/ping", ping_handlers, 1);

    // Create and run server
    csilk_server_t* server = csilk_server_new(router);
    csilk_server_run(server, 8080);

    // Cleanup (never reached in this example)
    csilk_server_free(server);
    csilk_router_free(router);

    return 0;
}

Route Groups

// Define handlers
void data_handler(csilk_ctx_t* c) {
    csilk_string(c, 200, "data response");
}

int main() {
    csilk_router_t* router = csilk_router_new();

    // Create a route group with "/api" prefix
    csilk_group_t* api = csilk_group_new(router, "/api");

    // Use convenience macros to add routes
    csilk_GET(api, "/data", data_handler);
    // -> matches GET /api/data

    // ...
}

Middleware Usage

void my_middleware(csilk_ctx_t* c) {
    // Custom logic before next handler
    csilk_next(c);
}

// Built-in middleware handlers:
//   csilk_logger_handler   - Request logging
//   csilk_recovery_handler - Panic recovery (500 on panic)
//   csilk_auth_middleware  - Token authentication (with validator callback)
//   csilk_static           - Static file serving (with root directory)

// Middleware is applied to route groups:
csilk_group_t* group = csilk_group_new(router, "/api");
csilk_group_use(group, csilk_logger_handler);
csilk_group_use(group, csilk_recovery_handler);

HTTPS & JWT Example

#include "csilk/csilk.h"

void secure_handler(csilk_ctx_t* c) {
    cJSON* payload = (cJSON*)csilk_get(c, "jwt_payload");
    const char* user = cJSON_GetObjectItem(payload, "sub")->valuestring;
    char msg[64];
    snprintf(msg, sizeof(msg), "Hello secure user: %s", user);
    csilk_string(c, 200, msg);
}

int main() {
    csilk_router_t* router = csilk_router_new();
    csilk_group_t* api = csilk_group_new(router, "/api");
    
    // Apply JWT middleware to /api group
    csilk_group_use(api, (csilk_handler_t)csilk_jwt_middleware, "secret_key");
    csilk_GET(api, "/profile", secure_handler);

    csilk_server_t* server = csilk_server_new(router);
    
    // Configure HTTPS
    csilk_server_config_t config = {0};
    config.enable_tls = 1;
    config.tls_cert_file = "cert.pem";
    config.tls_key_file = "key.pem";
    csilk_server_set_config(server, &config);

    csilk_server_run(server, 443);
    return 0;
}

Project Structure

src/
  ├── core/           # Kernel (libuv TCP, Router, Arena, Logger, Config)
  ├── app/            # Application Layer (app, admin dashboard, workflow engine)
  ├── ai/             # AI Unified Interface Engine
  ├── crypto/         # Cipher Driver (AES, RSA, sign/verify)
  ├── data/           # Database Abstraction Layer
  ├── messaging/      # Internal Event Bus (Message Queue)
  ├── security/       # Permission & Security Core
  ├── reflection/     # Reflection Engine implementation
  ├── protocols/      # Protocol Extensions (WebSocket, Swagger)
  ├── drivers/        # Concrete Drivers (OpenAI, Ollama, SQLite, MySQL, PostgreSQL, MongoDB)
  └── middleware/     # 15 built-in middleware modules

include/csilk/        # Public Hierarchical Headers
  ├── core/           # Core internal definitions
  ├── app/            # App API, Admin, Workflow, WAL
  ├── drivers/        # Driver interfaces (AI, Cipher, DB, Perm)
  ├── reflection/     # Reflection engine API
  ├── test/           # OOM simulation test framework
  └── csilk.h         # Main entry point (includes all modules)

tests/                # 98+ comprehensive unit tests
examples/             # Functional usage examples

Testing

The project includes a comprehensive test suite. After building, run individual test executables:

./tests/test_context
./tests/test_router
./tests/test_server
# ... and others

Features Legend

Emoji Meaning
🚀 Performance / Async I/O
📬 Internal Event Bus (MQ)
📈 Prometheus Metrics
🔧 Middleware / Tooling
🌐 Networking / Routing
📦 JSON / Data serialization
🍪 Cookie management
🔌 WebSocket support
📡 Server-Sent Events (SSE)
📤 File upload / Multipart
🔍 URL / Query parsing
Connection keep-alive
🛡️ Error handling / Security
🔐 Crypto / Cipher drivers
📋 Configuration (YAML)
🏗 Memory management (Arena)
🗂️ Reflection engine
🤖 AI Unified Interface
🔐 CSRF / CORS / Rate limiting
📝 Documentation (Doxygen)
🧵 Thread-safe logging
🔍 Timeouts / Limits
🎯 Per-route middleware
🌲 Radix Tree router
📝 Form URL-encoded parsing
🍪 Session management
🔀 HTTP redirect
📄 HTTP Range / 206 Partial Content
Parameter validation

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Inspired by Gin web framework
  • Built upon excellent C libraries: libuv, llhttp, and cJSON

项目介绍

A lightweight, high-performance HTTP web framework written in C and built on top of libuv, llhttp, and cJSON.

定制我的领域

下载使用量

0

项目总下载次数(含Clone、Pull、 zip 包及 release 下载),每日凌晨更新

语言类型

C92.29%
Shell3.03%
HTML2.6%
CMake1.66%
Python0.4%