### Quick Start: Basic Server with Healthcheck Source: https://github.com/connectum-framework/connectum/blob/main/packages/healthcheck/README.md A quick start example demonstrating how to create a Connectum server with the Healthcheck protocol enabled. It shows importing necessary modules, configuring the server, and updating the health status upon readiness. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, protocols: [Healthcheck({ httpEnabled: true })], }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); await server.start(); ``` -------------------------------- ### Setup Development Environment (Bash) Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Commands to set up the local development environment for Connectum. This includes forking, cloning the repository, adding the upstream remote, installing dependencies, and verifying the setup. ```bash # 1. Fork the repository on GitHub # 2. Clone your fork git clone https://github.com/YOUR_USERNAME/connectum.git cd connectum # 3. Add upstream remote git remote add upstream https://github.com/original-org/connectum.git # 4. Install dependencies pnpm install # 5. Verify setup pnpm typecheck pnpm lint pnpm test ``` -------------------------------- ### Create Minimal Connectum Server Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md A minimal example demonstrating how to create a Connectum server using the `createServer` factory function and starting it. ```typescript import { createServer } from '@connectum/core'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, }); await server.start(); ``` -------------------------------- ### Create a Minimal Connectum Server Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Provides a basic example of creating a Connectum server with minimal configuration. It includes importing necessary modules, defining services, and starting the server. ```typescript import { createServer } from '@connectum/core'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, }); await server.start(); console.log(`Server running on ${server.address?.port}`); ``` -------------------------------- ### Install k6 via Docker Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Pulls the latest k6 Docker image, allowing you to run performance tests without local installation. This is a convenient alternative for setup. ```bash docker pull grafana/k6:latest ``` -------------------------------- ### Install @connectum/core and Peer Dependencies Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Installs the main @connectum/core package and its required peer dependencies using pnpm. ```bash pnpm add @connectum/core pnpm add @connectrpc/connect @connectrpc/connect-node @bufbuild/protobuf ``` -------------------------------- ### Verify k6 Installation Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Checks if k6 has been installed correctly by displaying its version information. This command confirms the tool is ready for use. ```bash k6 version # Expected output: k6 v0.XX.X (...) ``` -------------------------------- ### Server Creation Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Demonstrates how to create a minimal Connectum server with basic service routing and start it. ```APIDOC ## Minimal Service ### Description Creates and starts a basic Connectum server with specified services and port. ### Method `createServer` function from `@connectum/core` ### Endpoint N/A (Server configuration) ### Parameters #### Request Body - **services** (Array) - Required - An array of service routes. - **port** (number) - Optional - The port the server will listen on. Defaults to 5000. ### Request Example ```typescript import { createServer } from '@connectum/core'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, }); await server.start(); console.log(`Server running on ${server.address?.port}`); ``` ### Response #### Success Response (200) Server starts successfully and logs its address. #### Response Example ``` Server running on 5000 ``` ``` -------------------------------- ### Adding Services at Runtime Before Server Start Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Illustrates how to add services to a Connectum server dynamically before it starts. Services can be added using the `addService` method. Note that services cannot be added after the `start()` method has been called. ```typescript import { createServer } from '@connectum/core'; const server = createServer({ services: [mainRoutes], port: 5000, }); // Add more services before starting server.addService(adminRoutes); server.addService(metricsRoutes); await server.start(); // Note: Cannot add services after start() ``` -------------------------------- ### Install k6 on macOS Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Installs the k6 performance testing tool on macOS using the Homebrew package manager. This is a prerequisite for running benchmarks. ```bash brew install k6 ``` -------------------------------- ### Usage: grpcurl Client Examples Source: https://github.com/connectum-framework/connectum/blob/main/packages/reflection/README.md Provides command-line examples for using grpcurl to interact with a Connectum server that has gRPC Server Reflection enabled. Demonstrates listing services, describing services and methods, and calling methods. ```bash # List all services grpcurl -plaintext localhost:5000 list # Describe a service grpcurl -plaintext localhost:5000 describe my.service.v1.MyService # Describe a method grpcurl -plaintext localhost:5000 describe my.service.v1.MyService.GetUser # Call a method (reflection provides the schema) grpcurl -plaintext -d '{"id": "123"}' \ localhost:5000 my.service.v1.MyService/GetUser ``` -------------------------------- ### Install k6 on Linux (Debian/Ubuntu) Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Installs the k6 performance testing tool on Debian/Ubuntu-based Linux distributions. This involves adding the k6 repository and then installing the package. ```bash sudo gpg -k ``` ```bash sudo gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg \ --keyserver hkp://keyserver.ubuntu.com:80 \ --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69 ``` ```bash echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main" | \ sudo tee /etc/apt/sources.list.d/k6.list ``` ```bash sudo apt-get update ``` ```bash sudo apt-get install k6 ``` -------------------------------- ### Utilize Connectum TLS Configuration Functions Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Provides examples of using utility functions from `@connectum/core` for TLS configuration. It demonstrates how to get the TLS path from the environment using `getTLSPath()`, read TLS certificates with `readTLSCertificates()`, and retrieve the configured TLS path using `tlsPath()`. ```typescript import { getTLSPath, readTLSCertificates, tlsPath } from '@connectum/core'; // Get TLS path from environment const path = getTLSPath(); // Read TLS certificates const { key, cert } = readTLSCertificates({ keyPath: './keys/server.key', certPath: './keys/server.crt', }); // Get configured TLS path const configuredPath = tlsPath(); ``` -------------------------------- ### Usage: buf curl Client Examples Source: https://github.com/connectum-framework/connectum/blob/main/packages/reflection/README.md Provides command-line examples for using buf curl to interact with a Connectum server with gRPC Server Reflection. Shows how to list methods and call a specific method. ```bash # List services buf curl --protocol grpc --http2-prior-knowledge http://localhost:5000 --list-methods # Call a method buf curl --protocol grpc --http2-prior-knowledge \ -d '{"id": "123"}' \ http://localhost:5000/my.service.v1.MyService/GetUser ``` -------------------------------- ### PR Description Template Example (Markdown) Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md A template for pull request descriptions, guiding contributors to provide necessary information such as the description, motivation, type of change, testing performed, and a checklist. ```markdown ## Description Brief description of what this PR does. ## Motivation and Context Why is this change needed? What problem does it solve? Closes #123 ## Type of Change - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] Documentation update ## Testing How has this been tested? - [ ] Unit tests added/updated - [ ] Integration tests added/updated - [ ] Manual testing performed ## Checklist - [ ] My code follows the code style of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings or errors - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG using Changesets ``` -------------------------------- ### Start Connectum Performance Test Server Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Launches the dedicated Node.js server for performance testing. This server runs multiple instances on different ports to simulate various configurations. ```bash # From project root node examples/performance-test-server/src/index.ts ``` -------------------------------- ### Install @connectum/reflection Source: https://github.com/connectum-framework/connectum/blob/main/packages/reflection/README.md Installs the @connectum/reflection package using pnpm. This package is a peer dependency of @connectum/core. ```bash pnpm add @connectum/reflection pnpm add @connectum/core ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Illustrates various examples of commit messages using the Conventional Commits format, covering feature additions, documentation updates, and dependency upgrades. ```text feat(runner): add custom protocol support Add ability to register custom protocols alongside health check and reflection. Closes #123 --- docs(readme): update installation instructions Add missing peer dependencies and Node.js version requirement. --- chore(deps): upgrade @connectrpc/connect to v2.0.0 BREAKING CHANGE: ConnectRPC v2 has new API. See migration guide for details. ``` -------------------------------- ### Quick Start: Integrate Reflection into Connectum Server Source: https://github.com/connectum-framework/connectum/blob/main/packages/reflection/README.md Demonstrates how to integrate the gRPC Server Reflection protocol into a Connectum server. It imports necessary modules, configures the server with routes and the Reflection protocol, and starts the server. ```typescript import { createServer } from '@connectum/core'; import { Reflection } from '@connectum/reflection'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, protocols: [Reflection()], }); await server.start(); // Clients can now discover services via gRPC Server Reflection ``` -------------------------------- ### Kubernetes Deployment Configuration (YAML) Source: https://context7.com/connectum-framework/connectum/llms.txt An example Kubernetes Deployment configuration for a Connectum service. It includes environment variables, port configurations, and essential liveness and readiness probes for Kubernetes integration. ```yaml # kubernetes/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: my-service spec: replicas: 3 template: spec: containers: - name: my-service image: my-service:latest ports: - containerPort: 5000 env: - name: PORT value: "5000" - name: NODE_ENV value: "production" - name: OTEL_SERVICE_NAME value: "my-service" - name: OTEL_TRACES_EXPORTER value: "otlp" - name: OTEL_EXPORTER_OTLP_ENDPOINT value: "http://otel-collector:4318" livenessProbe: httpGet: path: /healthz port: 5000 initialDelaySeconds: 5 periodSeconds: 10 readinessProbe: httpGet: path: /readyz port: 5000 initialDelaySeconds: 3 periodSeconds: 5 resources: requests: memory: "256Mi" cpu: "100m" limits: memory: "512Mi" cpu: "500m" ``` -------------------------------- ### Get OpenTelemetry Meter Instance and Create Metrics Source: https://github.com/connectum-framework/connectum/blob/main/packages/otel/README.md Retrieves a lazy singleton OpenTelemetry meter instance for creating various types of metrics: counters, up-down counters, histograms, and observable gauges. Examples demonstrate how to configure descriptions, units, and record measurements with attributes. ```typescript import { getMeter } from "@connectum/otel"; import type { Meter } from "@opentelemetry/api"; const meter = getMeter(); // Counter const counter = meter.createCounter("metric.name", { description: "Number of requests", unit: "1", }); counter.add(1, { method: "GET" }); // UpDown Counter const activeConnections = meter.createUpDownCounter("active.connections"); activeConnections.add(1); // Connection opened activeConnections.add(-1); // Connection closed // Histogram const histogram = meter.createHistogram("request.duration", { description: "Request duration", unit: "ms", }); histogram.record(125.5, { method: "GET", status: 200 }); // Observable Gauge meter.createObservableGauge("memory.usage", { description: "Memory usage", unit: "bytes", }).addCallback((observableResult) => { const usage = process.memoryUsage(); observableResult.observe(usage.heapUsed, { type: "heap" }); }); ``` -------------------------------- ### Production Server Configuration Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Illustrates a comprehensive Connectum server setup for production, including TLS, graceful shutdown, interceptors, and lifecycle event handling. ```APIDOC ## Production Service with All Features ### Description Sets up a Connectum server with advanced features like TLS, graceful shutdown, custom interceptors, health checks, and reflection, suitable for production environments. ### Method `createServer` function from `@connectum/core` ### Endpoint N/A (Server configuration) ### Parameters #### Request Body - **services** (Array) - Required - An array of service routes. - **port** (number) - Optional - The port the server will listen on. Defaults to 5000 or from `PORT` env var. - **host** (string) - Optional - The host the server will bind to. Defaults to '0.0.0.0'. - **protocols** (Array) - Optional - List of protocols to enable (e.g., Healthcheck, Reflection). - **tls** (TLSOptions) - Optional - TLS configuration for secure connections. - **shutdown** (ShutdownOptions) - Optional - Configuration for graceful shutdown behavior. - **interceptors** (Array) - Optional - An array of interceptors to process requests. ### TLSOptions - **keyPath** (string) - Optional - Path to TLS key file. - **certPath** (string) - Optional - Path to TLS certificate file. - **dirPath** (string) - Optional - TLS directory path (alternative to keyPath/certPath). ### ShutdownOptions - **timeout** (number) - Optional - Timeout in milliseconds for graceful shutdown (default: 30000). - **signals** (Array) - Optional - Signals to listen for graceful shutdown (default: ['SIGTERM', 'SIGINT']). - **autoShutdown** (boolean) - Optional - Enable automatic graceful shutdown on signals (default: false). - **forceCloseOnTimeout** (boolean) - Optional - Force close all HTTP/2 sessions when shutdown timeout is exceeded (default: true). ### Request Example ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { Reflection } from '@connectum/reflection'; import routes from '#gen/routes.js'; // Build protocols list const protocols = [Healthcheck({ httpEnabled: true })]; if (process.env.NODE_ENV !== 'production') { protocols.push(Reflection()); } const server = createServer({ services: [routes], port: process.env.PORT ? Number(process.env.PORT) : 5000, host: '0.0.0.0', protocols, // TLS for production tls: process.env.NODE_ENV === 'production' ? { keyPath: './keys/server.key', certPath: './keys/server.crt', } : undefined, // Graceful shutdown shutdown: { autoShutdown: true, timeout: 30000, signals: ['SIGTERM', 'SIGINT'], }, // Interceptors (explicit — core has no built-in interceptors) interceptors: createDefaultInterceptors({ errorHandler: { logErrors: true }, timeout: { duration: 30_000 }, }), }); // Lifecycle hooks server.on('start', () => { console.log('Server starting...'); }); server.on('ready', () => { console.log(`Server ready on ${server.address?.port}`); healthcheckManager.update(ServingStatus.SERVING); }); server.on('stop', () => { console.log('Server stopped'); }); server.on('error', (error) => { console.error('Server error:', error); }); // Start server await server.start(); ``` ### Response #### Success Response (200) Server starts, emits lifecycle events, and becomes ready to serve traffic. #### Response Example ``` Server starting... Server ready on 5000 ``` ``` -------------------------------- ### Environment Configuration for OpenTelemetry Source: https://github.com/connectum-framework/connectum/blob/main/packages/otel/README.md Provides examples of environment variables used to configure OpenTelemetry settings, such as service name, version, and namespace. These settings are typically loaded from a .env file or directly in the environment. ```bash # .env file # Service metadata OTEL_SERVICE_NAME=my-service OTEL_SERVICE_VERSION=1.0.0 OTEL_SERVICE_NAMESPACE=production ``` -------------------------------- ### Create Production Connectum Server with Protocols and Shutdown Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md An example of a production-ready Connectum server including healthcheck and reflection protocols, along with automatic graceful shutdown configuration. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, protocols: [Healthcheck({ httpEnabled: true }), Reflection()], shutdown: { autoShutdown: true, // Graceful shutdown on SIGTERM/SIGINT timeout: 30000, }, }); // Lifecycle hooks server.on('ready', () => { console.log(`Server ready on port ${server.address?.port}`); healthcheckManager.update(ServingStatus.SERVING); }); server.on('error', (err) => { console.error('Server error:', err); }); await server.start(); ``` -------------------------------- ### Conventional Commits Format Example Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Demonstrates the structure of commit messages following the Conventional Commits specification, including type, scope, description, optional body, and optional footer. ```text (): [optional body] [optional footer] ``` -------------------------------- ### Deprecated Runner API vs. New createServer API Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Compares the deprecated `Runner()` function with the current `createServer()` API in `@connectum/core`. The new API requires explicit calls to `start()` and `.stop()`, offers lifecycle hooks via EventEmitter, and integrates with health check and reflection packages. ```typescript // Deprecated import { Runner } from '@connectum/core'; const server = await Runner(options); // New API import { createServer } from '@connectum/core'; const server = createServer(options); await server.start(); ``` -------------------------------- ### TypeScript Import Order Example Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Demonstrates the required order for imports in TypeScript files within the Connectum framework. This includes external libraries, internal workspace modules, type imports, and relative imports. ```typescript // 1. External imports import { createConnectRouter } from "@connectrpc/connect"; // 2. Internal workspace imports import { retry } from "cockatiel"; // 3. Type imports import type { RunnerOptions } from "./types.js"; // 4. Relative imports import { myFunction } from "./utils.js"; ``` -------------------------------- ### Node.js Native Test Runner Structure Example Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Demonstrates the basic structure of a test file using the Node.js native test runner. It includes imports for testing functions, assertions, and setup/teardown hooks. ```typescript // myFunction.test.ts import { describe, it, beforeEach, afterEach } from "node:test"; import assert from "node:assert"; import { myFunction } from "./myFunction.js"; describe("myFunction", () => { let context: TestContext; beforeEach(() => { context = setupTestContext(); }); afterEach(() => { cleanupTestContext(context); }); it("should handle valid input", () => { const result = myFunction("valid"); assert.strictEqual(result, "expected"); }); it("should throw on invalid input", () => { assert.throws( () => myFunction("invalid"), { message: "Invalid input" } ); }); it("should handle async operations", async () => { const result = await myFunction("async"); assert.ok(result); }); }); ``` -------------------------------- ### Context Propagation with OpenTelemetry Tracing Source: https://github.com/connectum-framework/connectum/blob/main/packages/otel/README.md Illustrates how to use OpenTelemetry tracing with context propagation for nested operations. It shows how to start active spans and ensure that child spans automatically inherit the context from their parent. ```typescript import { getTracer } from "@connectum/otel"; import { context, trace, SpanStatusCode } from "@opentelemetry/api"; // Assume fetchData is an async function that returns data async function fetchData(): Promise { /* ... */ return []; } const tracer = getTracer(); // Start root span tracer.startActiveSpan("handleRequest", async (span) => { try { span.setAttribute("http.method", "GET"); // Nested span (automatically inherits context) await tracer.startActiveSpan("fetchData", async (childSpan) => { const data = await fetchData(); childSpan.setAttribute("data.count", data.length); childSpan.end(); return data; }); span.setStatus({ code: SpanStatusCode.OK }); } catch (error) { span.recordException(error); span.setStatus({ code: SpanStatusCode.ERROR }); throw error; } finally { span.end(); } }); ``` -------------------------------- ### Get OpenTelemetry Tracer Instance Source: https://github.com/connectum-framework/connectum/blob/main/packages/otel/README.md Retrieves a lazy singleton OpenTelemetry tracer instance. This tracer can be used to start spans, either directly or by activating them within the current context, allowing for trace propagation and attribute setting. ```typescript import { getTracer } from "@connectum/otel"; import type { Tracer } from "@opentelemetry/api"; const tracer = getTracer(); // Start span const span = tracer.startSpan("operation-name", { attributes: { "user.id": "123", "http.method": "GET", }, }); // Start active span (with context propagation) await tracer.startActiveSpan("operation", async (span) => { // Your code here span.end(); }); ``` -------------------------------- ### Run Basic Load Test with k6 Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Executes a basic load test scenario using k6. This test simulates normal, sustained user load to evaluate baseline performance. ```bash k6 run tests/performance/scenarios/basic-load.js ``` -------------------------------- ### Create a Production-Ready Connectum Server with Full Features Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Illustrates the creation of a Connectum server configured for production, including TLS, graceful shutdown, interceptors, health checks, and reflection. It also demonstrates lifecycle event handling. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { Reflection } from '@connectum/reflection'; import routes from '#gen/routes.js'; // Build protocols list const protocols = [Healthcheck({ httpEnabled: true })]; if (process.env.NODE_ENV !== 'production') { protocols.push(Reflection()); } const server = createServer({ services: [routes], port: process.env.PORT ? Number(process.env.PORT) : 5000, host: '0.0.0.0', protocols, // TLS for production tls: process.env.NODE_ENV === 'production' ? { keyPath: './keys/server.key', certPath: './keys/server.crt', } : undefined, // Graceful shutdown shutdown: { autoShutdown: true, timeout: 30000, signals: ['SIGTERM', 'SIGINT'], }, // Interceptors (explicit — core has no built-in interceptors) interceptors: createDefaultInterceptors({ errorHandler: { logErrors: true }, timeout: { duration: 30_000 }, }), }); // Lifecycle hooks server.on('start', () => { console.log('Server starting...'); }); server.on('ready', () => { console.log(`Server ready on ${server.address?.port}`); healthcheckManager.update(ServingStatus.SERVING); }); server.on('stop', () => { console.log('Server stopped'); }); server.on('error', (error) => { console.error('Server error:', error); }); // Start server await server.start(); ``` -------------------------------- ### Install @connectum/interceptors and Peer Dependencies Source: https://github.com/connectum-framework/connectum/blob/main/packages/interceptors/README.md Installs the @connectum/interceptors package and its required peer dependencies, @connectrpc/connect and @bufbuild/protobuf, using pnpm. ```bash pnpm add @connectum/interceptors pnpm add @connectrpc/connect @bufbuild/protobuf ``` -------------------------------- ### Install @connectum/cli Source: https://github.com/connectum-framework/connectum/blob/main/packages/cli/README.md Installs the @connectum/cli package using pnpm. Requires Node.js version 25.2.0 or higher for native TypeScript support. ```bash pnpm add @connectum/cli ``` -------------------------------- ### Create ConnectRPC Server with TLS and Plugins Source: https://context7.com/connectum-framework/connectum/llms.txt Demonstrates creating a ConnectRPC server using `createServer` from `@connectum/core`. It includes TLS configuration, health check and reflection protocol plugins, and custom interceptors. The server lifecycle events are also handled. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import { createDefaultInterceptors } from '@connectum/interceptors'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, host: '0.0.0.0', protocols: [ Healthcheck({ httpEnabled: true }), Reflection(), ], tls: { keyPath: './keys/server.key', certPath: './keys/server.crt', }, shutdown: { autoShutdown: true, timeout: 30000, signals: ['SIGTERM', 'SIGINT'], forceCloseOnTimeout: true, }, interceptors: createDefaultInterceptors({ errorHandler: { logErrors: true }, timeout: { duration: 10000 }, retry: { maxRetries: 2 }, }), }); server.on('start', () => console.log('Server starting...')); server.on('ready', () => { console.log(`Server ready on port ${server.address?.port}`); healthcheckManager.update(ServingStatus.SERVING); }); server.on('stopping', () => { healthcheckManager.update(ServingStatus.NOT_SERVING); }); server.on('error', (err) => console.error('Server error:', err)); await server.start(); // Output: Server starting... // Output: Server ready on port 5000 ``` -------------------------------- ### Install @connectum/healthcheck and Peer Dependency Source: https://github.com/connectum-framework/connectum/blob/main/packages/healthcheck/README.md Install the @connectum/healthcheck package and its peer dependency @connectum/core using pnpm. This is the initial step to integrate health checking into your Connectum application. ```bash pnpm add @connectum/healthcheck pnpm add @connectum/core ``` -------------------------------- ### Sync Protobuf Definitions with gRPC Server (Bash) Source: https://context7.com/connectum-framework/connectum/llms.txt The `@connectum/cli` package's `proto sync` command generates TypeScript types from a running gRPC server using Server Reflection. It requires installation via pnpm and allows specifying the server address, output directory, and custom templates. Options include a dry-run mode to preview changes. ```bash # Install CLI pnpm add @connectum/cli # Full sync: generate TypeScript types from a running server connectum proto sync --from localhost:5000 --out ./gen # With custom buf.gen.yaml template connectum proto sync --from localhost:5000 --out ./gen --template ./buf.gen.yaml # Dry-run: list services and files without generating code connectum proto sync --from localhost:5000 --out ./gen --dry-run # Output: # Connected to http://localhost:5000 # Services: # -grpc.health.v1.Health # - mypackage.v1.MyService # Files: # - grpc/health/v1/health.proto # - mypackage/v1/myservice.proto # Would generate to: ./gen ``` -------------------------------- ### Create Connectum Server with TLS Configuration Source: https://github.com/connectum-framework/connectum/blob/main/packages/core/README.md Demonstrates how to configure a Connectum server to use TLS by providing paths to the server's key and certificate files. ```typescript import { createServer } from '@connectum/core'; const server = createServer({ services: [routes], port: 5000, tls: { keyPath: './keys/server.key', certPath: './keys/server.crt', }, }); await server.start(); ``` -------------------------------- ### TypeScript JSDoc Comment Example Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Shows the standard for JSDoc comments in TypeScript for public APIs. It includes explanations of parameters, return values, thrown errors, and usage examples. ```typescript /** * Retry function with exponential backoff. * * @param options - Retry configuration * @returns Promise resolving to function result * @throws {RetryExhaustedError} When max retries exceeded * * @example * ```typescript * const result = await retry({ * fn: async () => fetchData(), * maxRetries: 3, * }); * ``` */ export async function retry(options: RetryOptions): Promise ``` -------------------------------- ### Method Filter Interceptor Resilience Settings Example Source: https://github.com/connectum-framework/connectum/blob/main/packages/interceptors/README.md Provides an example of using `createMethodFilterInterceptor` to apply different resilience settings, such as timeouts and circuit breakers, to specific services or methods based on their operational characteristics. ```typescript createMethodFilterInterceptor({ // Fast operations -- timeout 5s "catalog.v1.CatalogService/GetProduct": [ createTimeoutInterceptor({ duration: 5_000 }), ], // Heavy operations -- timeout 30s + circuit breaker "report.v1.ReportService/*": [ createTimeoutInterceptor({ duration: 30_000 }), createCircuitBreakerInterceptor({ threshold: 3 }), ], }); ``` -------------------------------- ### Programmatically Sync Protobuf Definitions with gRPC Server (TypeScript) Source: https://context7.com/connectum-framework/connectum/llms.txt This TypeScript code demonstrates the programmatic API for syncing Protobuf definitions from a gRPC server. It utilizes functions like `fetchReflectionData`, `fetchFileDescriptorSetBinary`, and `executeProtoSync` from `@connectum/cli/utils/reflection` and `@connectum/cli/commands/proto-sync` to fetch server information and execute the sync process. ```typescript // Programmatic API import { fetchReflectionData, fetchFileDescriptorSetBinary } from '@connectum/cli/utils/reflection'; import { executeProtoSync } from '@connectum/cli/commands/proto-sync'; // Fetch service and file information const result = await fetchReflectionData('http://localhost:5000'); console.log(result.services); // ["grpc.health.v1.Health", "mypackage.v1.MyService"] console.log(result.fileNames); // ["grpc/health/v1/health.proto", "mypackage/v1/myservice.proto"] // Fetch binary FileDescriptorSet for custom processing const binpb = await fetchFileDescriptorSetBinary('http://localhost:5000'); // Execute full proto sync pipeline await executeProtoSync({ from: 'localhost:5000', out: './gen', dryRun: false, }); ``` -------------------------------- ### Example GitLab CI Configuration for Performance Testing (YAML) Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md This YAML snippet demonstrates a future configuration for a GitLab CI pipeline. It specifies a performance testing stage using the grafana/k6 Docker image to run JavaScript-based performance tests and store the results as an artifact. This is intended for future integration. ```yaml # .gitlab-ci.yml example (future) performance: image: grafana/k6:latest stage: test script: - node examples/performance-test-server/src/index.ts & - sleep 5 - k6 run --out json=results.json tests/performance/scenarios/basic-load.js artifacts: paths: - results.json only: - main ``` -------------------------------- ### Mocking External Dependencies in Tests Source: https://github.com/connectum-framework/connectum/blob/main/packages/testing/README.md Provides guidance on mocking external dependencies versus internal code during testing. It shows a 'GOOD' example of mocking a database interaction using `mock.fn` and a 'BAD' example of mocking internal functions, emphasizing the principle of mocking only external collaborators. ```typescript // GOOD - mock external database import { mock } from 'node:test'; const dbMock = mock.fn(async (query) => { return { rows: [{ id: 1, name: 'Test' }] }; }); // BAD - mock internal functions const myFunctionMock = mock.fn(() => 'fake result'); ``` -------------------------------- ### Graceful Server Shutdown and Lifecycle Hooks (TypeScript) Source: https://context7.com/connectum-framework/connectum/llms.txt Demonstrates how to configure graceful server shutdown with dependency-ordered hooks, automatic signal handling, and forced session termination. It also shows how to hook into server lifecycle events like 'ready', 'stopping', and 'stop'. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, protocols: [Healthcheck({ httpEnabled: true })], shutdown: { autoShutdown: true, timeout: 30000, signals: ['SIGTERM', 'SIGINT'], forceCloseOnTimeout: true, }, }); // Named shutdown hooks with dependencies server.onShutdown('database', async () => { console.log('Closing database connections...'); await db.close(); }); server.onShutdown('cache', ['database'], async () => { // Runs after 'database' hook completes console.log('Flushing cache...'); await cache.flush(); }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); server.on('stopping', () => { // Mark as not serving so load balancer stops routing traffic healthcheckManager.update(ServingStatus.NOT_SERVING); }); server.on('stop', () => { console.log('Server stopped'); }); await server.start(); // Shutdown sequence on SIGTERM: // 1. 'stopping' event emitted // 2. AbortController.abort() signals streaming RPCs to terminate // 3. Transport sends GOAWAY, stops accepting new connections // 4. Wait for in-flight requests or timeout (30s) // 5. Force destroy HTTP/2 sessions if timeout exceeded // 6. Execute shutdown hooks (respecting dependencies) // 7. 'stop' event emitted ``` -------------------------------- ### Custom Interceptor Example Source: https://github.com/connectum-framework/connectum/blob/main/packages/interceptors/README.md Demonstrates how to create a custom interceptor for dynamic filtering logic, such as conditional authentication based on service type. ```APIDOC ## POST /connectrpc/admin.v1.AdminService/VerifyAdminToken ### Description This endpoint (or rather, the logic within the interceptor) demonstrates dynamic filtering. It checks if the request is for the `admin.v1.AdminService` and applies specific authentication logic (`verifyAdminToken`) if it is. ### Method Interceptor Logic (Applied to various RPC methods) ### Endpoint N/A (Interceptor logic applied dynamically) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **req** (object) - Required - The incoming request object, containing service and method information. ### Request Example ```typescript import type { Interceptor } from "@connectrpc/connect"; const conditionalAuth: Interceptor = (next) => async (req) => { // Dynamic filtering logic if (req.service.typeName === "admin.v1.AdminService") { await verifyAdminToken(req); } return next(req); }; ``` ### Response #### Success Response (200) Depends on the underlying RPC method being called. #### Response Example N/A (Interceptor modifies request before it reaches the handler) ``` -------------------------------- ### Run Stress Test with k6 Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Executes a stress test scenario with k6. This test aims to find the breaking point of the system by gradually increasing the load. ```bash k6 run tests/performance/scenarios/stress-test.js ``` -------------------------------- ### HTTP Health Check Source: https://github.com/connectum-framework/connectum/blob/main/packages/healthcheck/README.md Check the health of a specific service using an HTTP GET request. This endpoint is commonly used for Kubernetes liveness and readiness probes. ```APIDOC ## GET /healthz ### Description Checks the health status of a specific service. ### Method GET ### Endpoint `/healthz?service=` ### Parameters #### Query Parameters - **service** (string) - Required - The name of the service to check. ### Request Example ```bash curl http://localhost:5000/healthz?service=my.service.v1.MyService ``` ### Response #### Success Response (200) Indicates the service is healthy. #### Error Response (503 Service Unavailable) Indicates the service is not serving. #### Error Response (404 Not Found) Indicates the service is unknown. ``` -------------------------------- ### Basic OpenTelemetry Usage with @connectum/otel Source: https://github.com/connectum-framework/connectum/blob/main/packages/otel/README.md Demonstrates the basic usage of tracing, metrics, and logging functionalities provided by the @connectum/otel package. It shows how to obtain tracer, meter, and logger instances and use them for instrumentation. ```typescript import { getTracer, getMeter, getLogger } from "@connectum/otel"; import { SpanStatusCode } from "@opentelemetry/api"; // Tracing const tracer = getTracer(); const span = tracer.startSpan("my-operation"); try { // Your code here span.setAttribute("user.id", "123"); span.setStatus({ code: SpanStatusCode.OK }); } finally { span.end(); } // Metrics const meter = getMeter(); const counter = meter.createCounter("requests.total"); counter.add(1, { method: "GET", status: 200 }); const histogram = meter.createHistogram("request.duration"); histogram.record(125.5, { method: "GET" }); // Logging const logger = getLogger("MyService"); logger.info("User logged in", { userId: "123", ip: "192.168.1.1" }); logger.warn("Rate limit approaching", { current: 95, max: 100 }); logger.error("Request failed", { error: "timeout" }); logger.debug("Processing details", { step: 3 }); ``` -------------------------------- ### TypeScript Named Parameters Example Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Illustrates the preferred use of named parameters for function options in TypeScript. This improves code readability and maintainability by making the purpose of each parameter explicit. ```typescript // ✅ Good async function sleep(options: { interval: number; multiplier?: number; }): Promise // ❌ Avoid async function sleep(interval: number, multiplier?: number): Promise ``` -------------------------------- ### Run Spike Test with k6 Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Executes a spike test scenario with k6. This test evaluates the system's recovery capabilities after sudden, sharp increases in load. ```bash k6 run tests/performance/scenarios/spike-test.js ``` -------------------------------- ### Export k6 Results to JSON Source: https://github.com/connectum-framework/connectum/blob/main/tests/performance/README.md Runs a k6 test and exports the results in JSON format. This JSON output can then be processed further, for example, to generate HTML reports. ```bash k6 run --out json=results/basic-load.json tests/performance/scenarios/basic-load.js # Then convert to HTML (requires k6-reporter) ``` -------------------------------- ### Running Linter and Formatter Commands Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Provides bash commands for checking code style with the linter and automatically fixing formatting issues using Biome. It also shows how to target specific packages. ```bash # Check code style pnpm lint # Auto-fix issues pnpm format # Check specific package pnpm --filter @connectum/core lint ``` -------------------------------- ### Configuration Helpers Source: https://github.com/connectum-framework/connectum/blob/main/packages/otel/README.md Environment-based configuration helpers for retrieving service metadata, OTLP settings, collector options, batch span processor options, and ignored instrumentations. ```APIDOC ## Configuration Helpers ### Description Provides functions to retrieve OpenTelemetry and service-related configuration based on environment variables. ### Methods - `getServiceMetadata(): ServiceMetadata` - `getOTLPSettings(): OTLPSettings` - `getCollectorOptions(): CollectorOptions` - `getBatchSpanProcessorOptions(): BatchSpanProcessorOptions` - `getIgnoredInstrumentations(): string[]` ### Parameters None for the helper functions themselves, configuration is read from environment variables. ### Request Example ```typescript import { getServiceMetadata, getOTLPSettings, getCollectorOptions, getBatchSpanProcessorOptions, getIgnoredInstrumentations, } from "@connectum/otel"; const metadata = getServiceMetadata(); const otlpSettings = getOTLPSettings(); const collectorOptions = getCollectorOptions(); const bspOptions = getBatchSpanProcessorOptions(); const ignored = getIgnoredInstrumentations(); ``` ### Response #### Success Response (200) Returns configuration objects or arrays based on the respective function. #### Response Example ```json { "serviceMetadata": {"name": "my-service", "version": "1.0.0", "namespace": "production"}, "otlpSettings": {"protocol": "http/protobuf", "headers": {"Authorization": "Bearer ..."}}, "collectorOptions": {"traces": {"exporter": "otlp", "endpoint": "http://localhost:4318"}, "metrics": {"exporter": "otlp"}, "logs": {"exporter": "otlp"}}, "batchSpanProcessorOptions": {"scheduledDelayMillis": 5000, "maxQueueSize": 2048}, "ignoredInstrumentations": ["fs", "dns"] } ``` ``` -------------------------------- ### createServer - Server Factory Function Source: https://context7.com/connectum-framework/connectum/llms.txt The `createServer()` function from `@connectum/core` is the primary entry point for creating ConnectRPC/gRPC servers. It returns an unstarted server instance with explicit lifecycle control through event emitters, supporting TLS configuration, protocol plugins, graceful shutdown, and custom interceptors. ```APIDOC ## POST /createServer ### Description Creates a ConnectRPC/gRPC server instance with configurable options for services, port, host, protocols, TLS, shutdown behavior, and interceptors. ### Method POST ### Endpoint /createServer ### Parameters #### Request Body - **services** (Array) - Required - An array of service definitions to be registered with the server. - **port** (number) - Required - The port number on which the server will listen. - **host** (string) - Required - The host address on which the server will bind. - **protocols** (Array) - Optional - An array of protocol plugins to enable (e.g., Healthcheck, Reflection). - **tls** (object) - Optional - TLS configuration object. - **keyPath** (string) - Required if tls is provided - Path to the TLS private key. - **certPath** (string) - Required if tls is provided - Path to the TLS certificate. - **shutdown** (object) - Optional - Graceful shutdown configuration. - **autoShutdown** (boolean) - Optional - Whether to automatically shut down the server on signals. - **timeout** (number) - Optional - Timeout in milliseconds for graceful shutdown. - **signals** (Array) - Optional - List of signals to trigger shutdown. - **forceCloseOnTimeout** (boolean) - Optional - Whether to force close connections on timeout. - **interceptors** (Array) - Optional - An array of interceptors to apply to requests. ### Request Example ```json { "services": [routes], "port": 5000, "host": "0.0.0.0", "protocols": [ { "name": "Healthcheck", "httpEnabled": true }, { "name": "Reflection" } ], "tls": { "keyPath": "./keys/server.key", "certPath": "./keys/server.crt" }, "shutdown": { "autoShutdown": true, "timeout": 30000, "signals": ["SIGTERM", "SIGINT"], "forceCloseOnTimeout": true }, "interceptors": [ { "name": "errorHandler", "options": { "logErrors": true } }, { "name": "timeout", "options": { "duration": 10000 } } ] } ``` ### Response #### Success Response (200) - **serverInstance** (object) - An unstarted server instance with explicit lifecycle control. #### Response Example ```json { "serverInstance": "" } ``` ``` -------------------------------- ### PR Title Format Example (Conventional Commits) Source: https://github.com/connectum-framework/connectum/blob/main/CONTRIBUTING.md Illustrates the recommended format for pull request titles using Conventional Commits. This helps in automatically generating changelogs and understanding the nature of changes at a glance. ```text (): Examples: feat(runner): add custom protocol support fix(database): correct WAL checkpoint timing docs(readme): update installation instructions chore(deps): upgrade @connectrpc/connect to v2.0 ``` -------------------------------- ### Proto File with Validation Constraints Source: https://github.com/connectum-framework/connectum/blob/main/packages/interceptors/README.md An example proto file defining validation constraints for fields like email format, minimum string length, and integer range using `buf.validate` annotations. ```protobuf syntax = "proto3"; import "buf/validate/validate.proto"; message CreateUserRequest { string email = 1 [(buf.validate.field).string.email = true]; string name = 2 [(buf.validate.field).string.min_len = 1]; int32 age = 3 [(buf.validate.field).int32.gte = 0]; } ```