cqi

module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2025 License: MIT

README

CQI - Crypto Quant Infrastructure

Part of the Crypto Quant Platform - Professional-grade crypto trading infrastructure.

Overview

CQI is a shared infrastructure library for Go services in the Crypto Quant platform. It provides production-ready components for event bus, database, cache, observability (logging, metrics, tracing), configuration management, authentication, and error handling with native CQC protobuf integration.

Key Features:

  • Service Lifecycle: HTTP/gRPC server abstractions with graceful shutdown and signal handling
  • Service Orchestration: Multi-service runner with dependency management and automatic restart
  • Service Discovery: Registry for dynamic service registration with local and Redis backends
  • Event Bus: NATS JetStream & in-memory backends with automatic protobuf serialization
  • Data Storage: PostgreSQL connection pooling with transaction helpers
  • Caching: Redis client with native protobuf serialization
  • Observability: Structured logging (zerolog), Prometheus metrics, OpenTelemetry tracing
  • Configuration: Environment variables + YAML/JSON with validation
  • Authentication: API key & JWT middleware for HTTP/gRPC
  • Reliability: Exponential backoff retry, typed errors, panic recovery, health checks

Installation

go get github.com/Combine-Capital/cqi@latest

Quick Start

package main

import (
    "context"
    "net/http"
    
    "github.com/Combine-Capital/cqi/pkg/config"
    "github.com/Combine-Capital/cqi/pkg/service"
    "github.com/Combine-Capital/cqi/pkg/runner"
)

func main() {
    ctx := context.Background()
    
    // Load configuration
    cfg := config.MustLoad("config.yaml", "MYSERVICE")
    
    // Create HTTP service with handler
    httpSvc := service.NewHTTPService("api", ":8080", http.HandlerFunc(handler))
    
    // Create runner and add services with dependencies
    r := runner.New("my-app")
    r.Add(httpSvc, runner.WithRestartPolicy(runner.RestartOnFailure))
    
    // Start all services
    if err := r.Start(ctx); err != nil {
        panic(err)
    }
    
    // Wait for shutdown signal
    service.WaitForShutdown(ctx, r)
}

func handler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello from CQI!"))
}

See examples/ for complete working examples with database, cache, and event bus integration.

Repository Structure

cqi/
├── cmd/           # Application entrypoints
├── internal/      # Private application code
├── pkg/           # Public libraries
│   ├── auth/      # API key & JWT authentication
│   ├── bus/       # Event bus (NATS JetStream, in-memory)
│   ├── cache/     # Redis cache client
│   ├── config/    # Configuration loading
│   ├── database/  # PostgreSQL connection pool
│   ├── errors/    # Error types and handling
│   ├── health/    # Health check framework
│   ├── logging/   # Structured logging
│   ├── metrics/   # Prometheus metrics
│   ├── registry/  # Service discovery and registration
│   ├── retry/     # Retry with backoff
│   ├── runner/    # Multi-service orchestration
│   ├── service/   # Service lifecycle management
│   └── tracing/   # OpenTelemetry tracing
├── examples/      # Working code examples
│   ├── simple/    # Minimal usage example
│   └── full/      # Complete integration example
├── test/          # Integration tests
│   ├── integration/  # Integration test suites
│   └── testdata/     # Test fixtures
└── docs/          # Documentation

Architecture

CQI provides a layered architecture for building microservices:

Service Layer
  • service: HTTP/gRPC server lifecycle with graceful shutdown
  • runner: Orchestrate multiple services with dependency resolution
  • registry: Dynamic service discovery (local/Redis backends)
Infrastructure Layer
  • database: PostgreSQL connection pooling with transactions
  • cache: Redis client with protobuf serialization
  • bus: Event bus (NATS JetStream) for async messaging
Observability Layer
  • logging: Structured logging with trace context
  • metrics: Prometheus metrics collection
  • tracing: OpenTelemetry distributed tracing
  • health: Liveness and readiness health checks
Foundation Layer
  • config: Configuration management (env + files)
  • auth: Authentication middleware (API key + JWT)
  • errors: Typed errors with classification
  • retry: Exponential backoff retry logic

Configuration

CQI uses environment variables with prefix support and YAML/JSON configuration files:

# config.yaml
database:
  host: localhost
  port: 5432
  database: mydb
  user: user
  password: ${DB_PASSWORD}  # From environment
  max_connections: 25

cache:
  address: localhost:6379
  password: ${REDIS_PASSWORD}
  db: 0

log:
  level: info
  format: json

metrics:
  enabled: true
  port: 9090
  path: /metrics

Environment variables override config file values using the prefix:

export MYSERVICE_DATABASE_HOST=prod-db.example.com
export MYSERVICE_LOG_LEVEL=debug

Documentation

  • CQ Hub - Platform Documentation
  • CQC - Platform Contracts

License

MIT License - see LICENSE for details

Directories

Path Synopsis
cmd
server command
examples
full command
Full example demonstrating comprehensive CQI usage with all infrastructure packages.
Full example demonstrating comprehensive CQI usage with all infrastructure packages.
httpclient command
HTTP client example demonstrating CQI HTTP client usage with retry, rate limiting, circuit breaker, and comprehensive middleware support.
HTTP client example demonstrating CQI HTTP client usage with retry, rate limiting, circuit breaker, and comprehensive middleware support.
simple command
Simple example demonstrating minimal CQI usage with config, logging, and database.
Simple example demonstrating minimal CQI usage with config, logging, and database.
websocket command
WebSocket client example demonstrating CQI WebSocket client usage with auto-reconnect, message handlers, and graceful shutdown.
WebSocket client example demonstrating CQI WebSocket client usage with auto-reconnect, message handlers, and graceful shutdown.
pkg
auth
Package auth provides HTTP and gRPC authentication middleware with API key and JWT validation.
Package auth provides HTTP and gRPC authentication middleware with API key and JWT validation.
bus
Package bus provides event bus functionality for publish/subscribe messaging with CQC protobuf events.
Package bus provides event bus functionality for publish/subscribe messaging with CQC protobuf events.
cache
Package cache provides Redis caching with protobuf serialization for CQI infrastructure.
Package cache provides Redis caching with protobuf serialization for CQI infrastructure.
config
Package config provides configuration management for CQI infrastructure components.
Package config provides configuration management for CQI infrastructure components.
database
Package database provides PostgreSQL connection pooling with transaction management and health checks.
Package database provides PostgreSQL connection pooling with transaction management and health checks.
errors
Package errors provides structured error types for the CQI infrastructure library.
Package errors provides structured error types for the CQI infrastructure library.
health
Package health provides a health check framework for monitoring service and infrastructure component health.
Package health provides a health check framework for monitoring service and infrastructure component health.
httpclient
Package httpclient provides an HTTP/REST client with retry, circuit breaker, rate limiting, and comprehensive middleware support for CQI infrastructure.
Package httpclient provides an HTTP/REST client with retry, circuit breaker, rate limiting, and comprehensive middleware support for CQI infrastructure.
logging
Package logging provides structured logging with zerolog for trace context propagation.
Package logging provides structured logging with zerolog for trace context propagation.
metrics
Package metrics provides Prometheus metrics collection with standardized naming conventions and automatic HTTP/gRPC middleware for observability.
Package metrics provides Prometheus metrics collection with standardized naming conventions and automatic HTTP/gRPC middleware for observability.
registry
Package registry provides service discovery and registration capabilities.
Package registry provides service discovery and registration capabilities.
retry
Package retry provides retry logic with exponential backoff for transient failures.
Package retry provides retry logic with exponential backoff for transient failures.
runner
Package runner provides orchestration for managing multiple services with dependency handling, restart logic, and aggregate health checks.
Package runner provides orchestration for managing multiple services with dependency handling, restart logic, and aggregate health checks.
service
Package service provides abstractions for microservice lifecycle management.
Package service provides abstractions for microservice lifecycle management.
tracing
Package tracing provides OpenTelemetry distributed tracing with W3C trace context propagation.
Package tracing provides OpenTelemetry distributed tracing with W3C trace context propagation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL