### Project Setup Source: https://connectum.dev/en/guide/quickstart Steps to initialize a new project and install necessary dependencies for a gRPC/ConnectRPC microservice using Connectum and pnpm. ```APIDOC ## Project Setup ### Description Initialize a new project directory, set up a new Node.js project using pnpm, and install core Connectum packages, ConnectRPC runtime, validation libraries, and development dependencies. ### Commands 1. **Create and navigate to project directory:** ```bash mkdir greeter-service && cd greeter-service ``` 2. **Initialize Node.js project:** ```bash pnpm init ``` 3. **Install core dependencies:** ```bash # Core framework pnpm add @connectum/core @connectum/healthcheck @connectum/reflection @connectum/interceptors # ConnectRPC runtime pnpm add @connectrpc/connect @connectrpc/connect-node @bufbuild/protobuf # Validation (recommended: @connectrpc/validate) pnpm add @bufbuild/protovalidate @connectrpc/validate ``` 4. **Install development dependencies:** ```bash pnpm add -D typescript @types/node @bufbuild/buf @bufbuild/protoc-gen-es ``` ### Configuration **`package.json` configuration:** ```json { "name": "greeter-service", "version": "1.0.0", "type": "module", "scripts": { "start": "node src/index.ts", "dev": "node --watch src/index.ts", "typecheck": "tsc --noEmit", "build:proto": "buf generate proto" }, "engines": { "node": ">=25.2.0" } } ``` **`tsconfig.json` configuration:** ```json { "compilerOptions": { "noEmit": true, "target": "esnext", "module": "nodenext", "moduleResolution": "nodenext", "rewriteRelativeImportExtensions": true, "erasableSyntaxOnly": true, "verbatimModuleSyntax": true, "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*.ts", "gen/**/*.ts"], "exclude": ["node_modules"] } ``` **Create project structure:** ```bash mkdir -p src/services gen proto ``` ``` -------------------------------- ### Project Setup: Initialize and Install Dependencies (Bash) Source: https://connectum.dev/en/guide/quickstart Initializes a new Node.js project and installs core Connectum, ConnectRPC, protobuf, and validation dependencies. It also includes dev dependencies for TypeScript and code generation. ```bash mkdir greeter-service && cd greeter-service pnpm init # Core framework pnpm add @connectum/core @connectum/healthcheck @connectum/reflection @connectum/interceptors # ConnectRPC runtime pnpm add @connectrpc/connect @connectrpc/connect-node @bufbuild/protobuf # Validation (recommended: @connectrpc/validate) pnpm add @bufbuild/protovalidate @connectrpc/validate # Dev dependencies (buf + code generation) pnpm add -D typescript @types/node @bufbuild/buf @bufbuild/protoc-gen-es ``` -------------------------------- ### Run Service: Start in Development Mode (Bash) Source: https://connectum.dev/en/guide/quickstart Starts the Connectum microservice in development mode, enabling hot-reloading for faster iteration during development. ```bash pnpm dev ``` -------------------------------- ### Server Entry Point: index.ts (TypeScript) Source: https://connectum.dev/en/guide/quickstart Sets up and starts the Connectum server. It configures services, port, protocols (health check, reflection), interceptors, and shutdown behavior. It also logs server status and manages health checks. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { greeterServiceRoutes } from './services/greeterService.ts'; const server = createServer({ services: [greeterServiceRoutes], port: 5000, protocols: [Healthcheck({ httpEnabled: true }), Reflection()], interceptors: createDefaultInterceptors(), shutdown: { autoShutdown: true }, }); 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(err)); await server.start(); ``` -------------------------------- ### Quick Setup for Connectum Server Reflection Source: https://connectum.dev/en/guide/server-reflection Demonstrates the basic setup for enabling gRPC Server Reflection in a Connectum server. It imports necessary modules from `@connectum/core` and `@connectum/reflection`, creates a server instance, and includes `Reflection()` in the `protocols` array. The server is then started on port 5000. ```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(); ``` -------------------------------- ### Run & Test Source: https://connectum.dev/en/guide/quickstart Instructions on how to run the microservice and test its functionality using `grpcurl`. ```APIDOC ## Run & Test ### Description Start the developed microservice in development mode and test its RPC endpoints using `grpcurl`. ### Commands 1. **Run the server:** ```bash pnpm dev ``` 2. **Test with `grpcurl`:** **List services (requires reflection enabled):** ```bash grpcurl -plaintext localhost:5000 list ``` **Call the `SayHello` RPC:** ```bash grpcurl -plaintext -d '{"name": "Alice"}' localhost:5000 greeter.v1.GreeterService/SayHello ``` ``` -------------------------------- ### Service Handler Source: https://connectum.dev/en/guide/quickstart Implement the service logic for the `GreeterService` in TypeScript. ```APIDOC ## Service Handler ### Description Implement the `GreeterService` by defining the `sayHello` RPC handler. This function takes a `SayHelloRequest`, constructs a greeting message, and returns a `SayHelloResponse`. ### File **`src/services/greeterService.ts`:** ```typescript import { create } from '@bufbuild/protobuf'; import type { ConnectRouter } from '@connectrpc/connect'; import { GreeterService, SayHelloResponseSchema } from '#gen/greeter_pb.ts'; import type { SayHelloRequest } from '#gen/greeter_pb.ts'; export function greeterServiceRoutes(router: ConnectRouter): void { router.service(GreeterService, { async sayHello(request: SayHelloRequest) { const name = request.name || 'World'; return create(SayHelloResponseSchema, { message: `Hello, ${name}`, }); }, }); } ``` ``` -------------------------------- ### Project Configuration: package.json (JSON) Source: https://connectum.dev/en/guide/quickstart Configures the Node.js project's package.json file, defining scripts for starting, developing, type checking, and building protobuf definitions. It also specifies the required Node.js engine version. ```json { "name": "greeter-service", "version": "1.0.0", "type": "module", "scripts": { "start": "node src/index.ts", "dev": "node --watch src/index.ts", "typecheck": "tsc --noEmit", "build:proto": "buf generate proto" }, "engines": { "node": ">=25.2.0" } } ``` -------------------------------- ### Server Entry Point Source: https://connectum.dev/en/guide/quickstart Set up the Connectum server, including integrating the defined services and enabling features like health checks and reflection. ```APIDOC ## Server Entry Point ### Description Configure and start the Connectum server. This involves creating the server instance, registering the `greeterServiceRoutes`, enabling essential protocols like health checks and reflection, and setting up interceptors and shutdown behavior. ### File **`src/index.ts`:** ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { greeterServiceRoutes } from './services/greeterService.ts'; const server = createServer({ services: [greeterServiceRoutes], port: 5000, protocols: [Healthcheck({ httpEnabled: true }), Reflection()], interceptors: createDefaultInterceptors(), shutdown: { autoShutdown: true }, }); 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(err)); await server.start(); ``` ``` -------------------------------- ### Example REST Client Request using curl Source: https://connectum.dev/en/guide/production/envoy-gateway Demonstrates how to send POST and GET requests to the OrderService API using curl, simulating REST client interactions. ```bash # Create an order via REST curl -X POST https://api.example.com/v1/orders \ -H "Content-Type: application/json" \ -d '{ "customer_id": "cust-123", "items": [ {"sku": "ITEM-001", "quantity": 2} ] }' # Get an order via REST curl https://api.example.com/v1/orders/550e8400-e29b-41d4-a716-446655440000 ``` -------------------------------- ### Proto Definition Source: https://connectum.dev/en/guide/quickstart Define the gRPC service and message structures using Protocol Buffers, including validation rules. ```APIDOC ## Proto Definition ### Description Define the `GreeterService` with a `SayHello` RPC method and its corresponding request and response messages using Protocol Buffers syntax. Includes validation for the `name` field in the request. ### Files **`proto/greeter.proto`:** ```protobuf syntax = "proto3"; package greeter.v1; import "buf/validate/validate.proto"; service GreeterService { rpc SayHello(SayHelloRequest) returns (SayHelloResponse) {} } message SayHelloRequest { string name = 1 [(buf.validate.field).string.min_len = 1]; } message SayHelloResponse { string message = 1; } ``` **`buf.yaml`:** ```yaml version: v2 deps: - buf.build/bufbuild/protovalidate ``` ### Commands **Fetch proto dependencies:** ```bash npx buf dep update ``` ``` -------------------------------- ### Install scenarigo CLI Source: https://connectum.dev/en/guide/testing Command to install the scenarigo CLI tool using Go's install command. This makes the scenarigo executable available in your system's PATH. ```bash go install github.com/scenarigo/scenarigo/cmd/scenarigo@latest ``` -------------------------------- ### mTLS Client Configuration Example Source: https://connectum.dev/en/guide/tls Example of how to configure a client (using grpcurl) to connect to an mTLS-enabled server, providing necessary client certificates. ```APIDOC ## mTLS Client Configuration Example ### Description Example of how to configure a client (using grpcurl) to connect to an mTLS-enabled server, providing necessary client certificates. ### Method N/A (Client Configuration) ### Endpoint N/A (Client Configuration) ### Parameters #### grpcurl Options - **`-cacert`** (path) - Required - Path to the CA certificate. - **`-cert`** (path) - Required - Path to the client certificate. - **`-key`** (path) - Required - Path to the client private key. ### Request Example ```bash # grpcurl with client certificate grpcurl \ -cacert keys/ca.crt \ -cert keys/client.crt \ -key keys/client.key \ localhost:5000 list ``` ### Response N/A (Client Configuration) ``` -------------------------------- ### Install runn Tool Source: https://connectum.dev/en/guide/testing Provides multiple methods for installing the runn testing tool, including package managers like Homebrew, Go, Aqua, and Docker. Choose the method that best suits your environment. ```bash brew install k1LoW/tap/runn ``` ```bash go install github.com/k1LoW/runn/cmd/runn@latest ``` ```bash aqua g -i k1LoW/runn ``` ```bash docker pull ghcr.io/k1low/runn:latest ``` -------------------------------- ### Complete Connectum Server Setup with Reflection and Healthcheck (TypeScript) Source: https://connectum.dev/en/guide/server-reflection A full example of creating a Connectum server with multiple services, health checks, reflection, and default interceptors. It uses packages like `@connectum/core`, `@connectum/healthcheck`, `@connectum/reflection`, and `@connectum/interceptors`. The server logs its readiness and provides grpcurl commands for verification. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { greeterServiceRoutes } from './services/greeterService.ts'; import { orderServiceRoutes } from './services/orderService.ts'; const server = createServer({ services: [greeterServiceRoutes, orderServiceRoutes], port: 5000, protocols: [ Healthcheck({ httpEnabled: true }), Reflection(), ], interceptors: createDefaultInterceptors(), shutdown: { autoShutdown: true }, }); server.on('ready', () => { const port = server.address?.port; console.log(`Server ready on port ${port}`); console.log(` grpcurl -plaintext localhost:${port} list`); healthcheckManager.update(ServingStatus.SERVING); }); await server.start(); ``` -------------------------------- ### Test Service: List Services with grpcurl (Bash) Source: https://connectum.dev/en/guide/quickstart Uses grpcurl to interact with the running gRPC server. This command lists all available services exposed by the server, leveraging server reflection. ```bash # List services (reflection) grpcurl -plaintext localhost:5000 list ``` -------------------------------- ### Troubleshooting - Verify Setup Source: https://connectum.dev/en/contributing/cli-commands Commands to verify the correct installation and functionality of essential development tools like Node.js, TypeScript, pnpm, protobuf compiler, and Biome. ```bash # Verify Node.js version node --version # Verify TypeScript can be stripped node --eval "import './test.ts'" 2>&1 | grep -q "Error" || echo "Type stripping works!" # Verify pnpm workspace pnpm list --depth 0 # Verify proto compiler protoc --version # Verify Biome biome --version ``` -------------------------------- ### Code Generation Source: https://connectum.dev/en/guide/quickstart Configure and run the code generation process using buf to generate TypeScript code from proto definitions. ```APIDOC ## Code Generation ### Description Configure `buf` to generate TypeScript code for messages and service definitions from your Protocol Buffers files using the `protoc-gen-es` plugin. ### Configuration **`buf.gen.yaml`:** ```yaml version: v2 plugins: - local: protoc-gen-es out: gen opt: target=ts inputs: - directory: proto ``` ### Commands **Run code generation:** ```bash pnpm run build:proto ``` ### Output This command generates: - `gen/greeter_pb.ts`: Contains message and schema definitions. - `gen/greeter_connect.ts`: Contains the service definition. ::: warning Proto enums and native TypeScript If your proto files use `enum`, the generated code contains non-erasable TypeScript. Use a [two-step generation process](/en/guide/typescript#proto-generation-and-enums). ::: ``` -------------------------------- ### Test Service: Call SayHello with grpcurl (Bash) Source: https://connectum.dev/en/guide/quickstart Calls the 'SayHello' RPC method on the 'GreeterService' using grpcurl. It sends a JSON payload with a 'name' field and displays the response. ```bash # Call SayHello grpcurl -plaintext -d '{"name": "Alice"}' localhost:5000 greeter.v1.GreeterService/SayHello ``` -------------------------------- ### GitHub Actions CI/CD Workflow with runn Source: https://connectum.dev/en/guide/testing A GitHub Actions workflow that checks out code, installs the 'runn' CLI tool, starts a service, waits for it to become available, and then runs API tests defined in YAML files. ```yaml jobs: api-tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install runn run: | brew install k1LoW/tap/runn - name: Start service run: node src/index.ts & - name: Wait for service run: | for i in $(seq 1 30); do curl -sf http://localhost:5000/healthz && break sleep 1 done - name: Run API tests run: runn run tests/**/*.yml ``` -------------------------------- ### Quick Start: Create and Run Connectum Server Source: https://connectum.dev/en/packages/core Demonstrates how to create a Connectum server instance using `createServer()`. It configures services, port, protocols (healthcheck, reflection), and enables automatic graceful shutdown. The example also shows how to handle server 'ready' and 'error' events and starts the server. ```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 }, }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); console.log(`Server ready on port ${server.address?.port}`); }); server.on('error', (err) => console.error(err)); await server.start(); ``` -------------------------------- ### SayHello RPC (HTTP) Source: https://connectum.dev/en/guide/quickstart Calls the SayHello RPC method via ConnectRPC HTTP. ```APIDOC ## SayHello RPC (HTTP) ### Description Calls the SayHello RPC method exposed via ConnectRPC using an HTTP POST request. ### Method POST ### Endpoint http://localhost:5000/greeter.v1.GreeterService/SayHello ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name to greet. ### Request Example ```json { "name": "Bob" } ``` ### Response #### Success Response (200) - **greeting** (string) - The greeting message. #### Response Example ```json { "greeting": "Hello, Bob" } ``` ``` -------------------------------- ### Troubleshooting - Clean Everything Source: https://connectum.dev/en/contributing/cli-commands Commands to perform a clean slate setup, including removing build artifacts, node_modules, and pnpm store contents, followed by a fresh installation. ```bash # Clean all build outputs and caches pnpm clean # Remove node_modules rm -rf node_modules packages/*/node_modules # Clean pnpm store pnpm store prune # Fresh install rm -rf node_modules pnpm-lock.yaml pnpm install ``` -------------------------------- ### Example Native gRPC Client using Connect RPC Source: https://connectum.dev/en/guide/production/envoy-gateway Provides a TypeScript example of a native gRPC client using the Connect RPC library to interact with the OrderService. It sets up a gRPC transport and creates a client instance. ```typescript import { createClient } from '@connectrpc/connect'; import { createGrpcTransport } from '@connectrpc/connect-node'; import { OrderService } from '#gen/mycompany/orders/v1/orders_pb.js'; const transport = createGrpcTransport({ baseUrl: 'http://api.example.com:9090', httpVersion: '2', }); const client = createClient(OrderService, transport); const order = await client.getOrder({ orderId: '550e8400-e29b-41d4-a716-446655440000' }); ``` -------------------------------- ### Practical Example: Different Resilience Per Method Source: https://connectum.dev/en/guide/advanced/method-filtering Provides a practical example of using `createMethodFilterInterceptor` to configure different resilience strategies, such as timeouts and circuit breakers, for specific methods and services. It also shows how to combine this with default interceptors. ```typescript import { createDefaultInterceptors, createMethodFilterInterceptor, createTimeoutInterceptor, createCircuitBreakerInterceptor, } from '@connectum/interceptors'; const resilience = createMethodFilterInterceptor({ // Fast reads: 5 second timeout 'catalog.v1.CatalogService/GetProduct': [ createTimeoutInterceptor({ duration: 5_000 }), ], // Heavy reports: 60 second timeout + circuit breaker 'report.v1.ReportService/*': [ createTimeoutInterceptor({ duration: 60_000 }), createCircuitBreakerInterceptor({ threshold: 3 }), ], // Admin mutations: audit logging 'admin.v1.AdminService/*': [ createAuditLogInterceptor(), ], }); const server = createServer({ services: [routes], interceptors: [ // Default chain with global timeout as fallback ...createDefaultInterceptors({ timeout: { duration: 30_000 } }), resilience, ], }); ``` -------------------------------- ### Install Connectum Reflection Package Source: https://connectum.dev/en/guide/server-reflection Installs the `@connectum/reflection` package using pnpm. This package is required to enable gRPC Server Reflection in your Connectum application. It has `@connectum/core` as a peer dependency. ```bash pnpm add @connectum/reflection ``` -------------------------------- ### Proto Definition: greeter.proto (Protobuf) Source: https://connectum.dev/en/guide/quickstart Defines a simple gRPC service 'GreeterService' with a 'SayHello' RPC method. It includes request and response messages and uses buf validation for the 'name' field. ```protobuf syntax = "proto3"; package greeter.v1; import "buf/validate/validate.proto"; service GreeterService { rpc SayHello(SayHelloRequest) returns (SayHelloResponse) {} } message SayHelloRequest { string name = 1 [(buf.validate.field).string.min_len = 1]; } message SayHelloResponse { string message = 1; } ``` -------------------------------- ### Create Basic Connectum Server (TypeScript) Source: https://connectum.dev/en/guide/about This snippet demonstrates the minimal setup for a Connectum server using TypeScript. It initializes the server with provided routes and starts it on a specified port. Dependencies include '@connectum/core' and generated route definitions. ```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 at ${server.address?.port}`); ``` -------------------------------- ### Quick Setup for Graceful Shutdown in Connectum Source: https://connectum.dev/en/guide/graceful-shutdown Demonstrates the basic setup for graceful shutdown using Connectum's createServer function. It enables automatic signal handling and sets a timeout for draining connections. This snippet requires `@connectum/core` and `@connectum/healthcheck`. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; const server = createServer({ services: [routes], protocols: [Healthcheck({ httpEnabled: true })], shutdown: { autoShutdown: true, // Handle SIGTERM/SIGINT automatically timeout: 30000, // 30 seconds to drain connections }, }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); server.on('stopping', () => { healthcheckManager.update(ServingStatus.NOT_SERVING); }); await server.start(); ``` -------------------------------- ### Create Multi-Step Scenarios with runn Source: https://connectum.dev/en/guide/testing Demonstrates how to create multi-step test scenarios in runn, where the output of one step can be used as input for subsequent steps. This example chains a greeting step with a message verification step. ```yaml desc: Multi-step gRPC scenario runners: greq: grpc://localhost:5000 vars: username: Charlie steps: greet: desc: Greet user greq: greeter.v1.GreeterService/SayHello: message: name: "{{ vars.username }}" test: current.res.status == 0 verify_message: desc: Verify greeting format test: | steps.greet.res.message.message == 'Hello, Charlie!' ``` -------------------------------- ### Create Minimal gRPC Service Protocol Source: https://connectum.dev/en/guide/advanced/custom-protocols This example demonstrates creating a minimal custom protocol that registers a gRPC service to provide server metadata, including its start time and a list of registered services. ```typescript import type { ConnectRouter } from '@connectrpc/connect'; import type { ProtocolRegistration, ProtocolContext } from '@connectum/core'; import { InfoService } from '#gen/info_pb.js'; function ServerInfo(): ProtocolRegistration { const startedAt = new Date().toISOString(); return { name: 'server-info', register(router: ConnectRouter, context: ProtocolContext): void { const serviceNames = context.registry.flatMap( (file) => file.services.map((s) => s.typeName), ); router.service(InfoService, { getInfo: () => ({ startedAt, serviceCount: serviceNames.length, services: serviceNames, }), }); }, }; } ``` -------------------------------- ### Dockerfile for Connectum Production Deployment Source: https://connectum.dev/en/guide/advanced/configuration A sample Dockerfile for building a production-ready Connectum application. It sets up the Node.js environment, installs dependencies, sets the NODE_ENV to production, exposes the application port, and defines the command to run the application. ```dockerfile FROM node:25-slim WORKDIR /app COPY . . RUN corepack enable && pnpm install --frozen-lockfile ENV NODE_ENV=production EXPOSE 5000 CMD ["node", "--experimental-strip-types", "src/index.ts"] ``` -------------------------------- ### List Services with buf curl Source: https://connectum.dev/en/guide/server-reflection Uses the `buf curl` command to list services on a Connectum server. This example specifies the Connect protocol and uses HTTP/2 prior knowledge. It's an alternative to `grpcurl` for interacting with ConnectRPC services. ```bash buf curl --protocol connect --http2-prior-knowledge \ http://localhost:5000 --list-services ``` -------------------------------- ### Complete Connectum Production Server Example (TypeScript) Source: https://connectum.dev/en/guide/graceful-shutdown A full-fledged Connectum server setup demonstrating integration with health checks, reflection, interceptors, OpenTelemetry, and custom shutdown hooks. It includes server creation, lifecycle event handling, and starting the server. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { shutdownProvider } from '@connectum/otel'; import routes from '#gen/routes.js'; const server = createServer({ services: [routes], port: 5000, protocols: [Healthcheck({ httpEnabled: true }), Reflection()], interceptors: createDefaultInterceptors(), shutdown: { autoShutdown: true, timeout: 25000, forceCloseOnTimeout: true, }, }); // Register shutdown hooks with dependencies server.onShutdown('database', async () => { await db.close(); }); server.onShutdown('cache', async () => { await redis.quit(); }); server.onShutdown('otel', ['database', 'cache'], async () => { await shutdownProvider(); }); // Lifecycle hooks server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); server.on('stopping', () => { healthcheckManager.update(ServingStatus.NOT_SERVING); }); server.on('stop', () => { console.log('Server stopped'); }); server.on('error', (err) => { console.error('Server error:', err); }); await server.start(); ``` -------------------------------- ### Connectum Proto Sync CLI Examples Source: https://connectum.dev/en/packages/cli Provides examples of using the `connectum proto sync` command with different options, including a custom buf template and a dry run. ```bash # Basic sync npx connectum proto sync --from localhost:5000 --out ./src/gen # With custom buf template npx connectum proto sync \ --from localhost:5000 \ --out ./src/gen \ --template ./buf.gen.custom.yaml # Dry run to inspect services npx connectum proto sync --from http://localhost:5000 --out ./gen --dry-run ``` -------------------------------- ### Isolated Connectum Healthcheck Manager for Testing Source: https://connectum.dev/en/guide/health-checks Utilizes `createHealthcheckManager()` to generate isolated health check instances, suitable for testing or managing multiple server setups. Includes examples for tracking service status and integration with `createServer`. ```typescript import { describe, it } from 'node:test'; import assert from 'node:assert'; import { Healthcheck, createHealthcheckManager, ServingStatus, } from '@connectum/healthcheck'; import { createServer } from '@connectum/core'; describe('health check', () => { it('should track service status', () => { const manager = createHealthcheckManager(); manager.initialize(['my.service.v1.MyService']); manager.update(ServingStatus.SERVING, 'my.service.v1.MyService'); assert.ok(manager.areAllHealthy()); manager.update(ServingStatus.NOT_SERVING, 'my.service.v1.MyService'); assert.ok(!manager.areAllHealthy()); }); it('should work with createServer', async () => { const manager = createHealthcheckManager(); const server = createServer({ services: [routes], protocols: [Healthcheck({ httpEnabled: true, manager })], }); server.on('ready', () => { manager.update(ServingStatus.SERVING); }); await server.start(); // ... test assertions ... await server.stop(); }); }); ``` -------------------------------- ### Set up Connectum Server with Healthcheck and Reflection (TypeScript) Source: https://connectum.dev/en This snippet demonstrates initializing a Connectum server. It includes setting up services, port, protocols like Healthcheck and Reflection, and interceptors. The server is configured for automatic shutdown and logs a 'ready' message upon successful startup. ```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, protocols: [Healthcheck({ httpEnabled: true }), Reflection()], interceptors: createDefaultInterceptors(), shutdown: { autoShutdown: true }, }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); console.log(`Server ready on port ${server.address?.port}`); }); await server.start(); ``` -------------------------------- ### Install protoc-gen-openapi Plugin Source: https://connectum.dev/en/guide/production/envoy-gateway Installs the protoc plugin for generating OpenAPI v3 specifications from proto files. This is a prerequisite for generating the OpenAPI spec. It can be installed using 'go install' or configured as a buf plugin. ```bash # Install the protoc plugin go install github.com/google/gnostic/cmd/protoc-gen-openapi@latest # Or via buf plugin # Add to buf.gen.yaml ``` -------------------------------- ### Connectum Server Configuration with TypeScript Source: https://connectum.dev/en/guide/production/kubernetes Demonstrates how to configure and start a Connectum server using TypeScript. It includes setting up services, ports, protocols (Healthcheck, Reflection), and defining a graceful shutdown process with custom hooks and dependency ordering. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import { shutdownProvider } from '@connectum/otel'; const server = createServer({ services: [routes], port: 5000, protocols: [ Healthcheck({ httpEnabled: true }), Reflection(), ], shutdown: { autoShutdown: true, // Catch SIGTERM and SIGINT timeout: 30000, // 30s to drain connections signals: ['SIGTERM', 'SIGINT'], forceCloseOnTimeout: true, // Force-close after timeout }, }); // Register shutdown hooks with dependency ordering server.onShutdown('otel', async () => { await shutdownProvider(); }); server.onShutdown('database', async () => { await db.close(); }); // OTel depends on database (database shuts down first) server.onShutdown('otel', ['database'], async () => { await shutdownProvider(); }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); server.on('stopping', () => { // Kubernetes readiness probe will start failing // because healthcheckManager transitions to NOT_SERVING console.log('Server is shutting down...'); }); await server.start(); ``` -------------------------------- ### Quick Start: Connectum Proto Sync CLI Source: https://connectum.dev/en/packages/cli Demonstrates how to use the `connectum proto sync` command for discovering services and generating TypeScript types from a running Connectum server. ```bash # Dry run: list discovered services and files npx connectum proto sync --from localhost:5000 --out ./gen --dry-run # Full sync: generate TypeScript types from a running server npx connectum proto sync --from localhost:5000 --out ./gen ``` -------------------------------- ### Health Check (gRPC) Source: https://connectum.dev/en/guide/quickstart Performs a health check using gRPC. ```APIDOC ## Health Check (gRPC) ### Description Performs a health check using the gRPC Health Checking Protocol. ### Method POST ### Endpoint localhost:5000/grpc.health.v1.Health/Check ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash grpc -plaintext localhost:5000 grpc.health.v1.Health/Check ``` ### Response #### Success Response (200) Details of the health check status. #### Response Example ```json { "status": "SERVING" } ``` ``` -------------------------------- ### Health Check (HTTP) Source: https://connectum.dev/en/guide/quickstart Performs a health check using an HTTP endpoint. ```APIDOC ## Health Check (HTTP) ### Description Performs a health check using a dedicated HTTP endpoint. ### Method GET ### Endpoint http://localhost:5000/healthz ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:5000/healthz ``` ### Response #### Success Response (200) Indicates the service is healthy. #### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### List All Services with grpcurl Source: https://connectum.dev/en/guide/server-reflection Uses the `grpcurl` command-line tool to list all available services exposed by a Connectum server with reflection enabled. Assumes the server is running on `localhost:5000` and uses plaintext communication. ```bash grpcurl -plaintext localhost:5000 list ``` -------------------------------- ### Server Creation with TLS Source: https://connectum.dev/en/guide/tls Demonstrates how to create a Connectum server with TLS enabled using explicit key and certificate file paths. ```APIDOC ## POST /createServer (TLS Configuration) ### Description Configures and starts a Connectum server with TLS enabled, using specified paths for the private key and certificate. ### Method POST ### Endpoint /createServer ### Parameters #### Request Body - **services** (Array) - Required - The array of services to be served. - **port** (number) - Required - The port number for the server to listen on. - **tls** (TLSOptions) - Required - TLS configuration options. - **keyPath** (string) - Optional - Path to the TLS private key file. - **certPath** (string) - Optional - Path to the TLS certificate file. - **dirPath** (string) - Optional - Directory path containing `server.key` and `server.crt`. ### Request Example ```json { "services": [routes], "port": 5000, "tls": { "keyPath": "./keys/server.key", "certPath": "./keys/server.crt" } } ``` ### Response #### Success Response (200) - **server** (Server) - The started Connectum server instance. #### Response Example ```json { "message": "Server started successfully" } ``` ``` -------------------------------- ### scenarigo gRPC Test Example Source: https://connectum.dev/en/guide/testing An example scenario for testing a gRPC service using scenarigo. It defines a title, the protocol, the request method and body, and the expected response code and body. ```yaml title: Greeter gRPC test steps: - title: SayHello protocol: grpc request: method: greeter.v1.GreeterService/SayHello body: name: Alice expect: code: OK body: message: "Hello, Alice!" ``` -------------------------------- ### Describe a Service with grpcurl Source: https://connectum.dev/en/guide/server-reflection Uses `grpcurl` to describe a specific gRPC service, in this case `greeter.v1.GreeterService`. This command retrieves the service definition, including its methods and message types, from the reflection service. Requires the server to be running and reflection enabled. ```bash grpcurl -plaintext localhost:5000 describe greeter.v1.GreeterService ``` -------------------------------- ### scenarigo HTTP Test Example Source: https://connectum.dev/en/guide/testing An example scenario for testing an HTTP endpoint using scenarigo. It specifies the protocol, request method, URL, headers, body, and expected HTTP status code and response body. ```yaml title: Greeter HTTP test steps: - title: SayHello via ConnectRPC protocol: http request: method: POST url: "http://localhost:5000/greeter.v1.GreeterService/SayHello" header: Content-Type: application/json body: name: Bob expect: code: OK body: message: "Hello, Bob!" ``` -------------------------------- ### Install Connectum Healthcheck Package (Bash) Source: https://connectum.dev/en/guide/health-checks This command installs the `@connectum/healthcheck` package using the pnpm package manager. This package is essential for implementing health check functionalities within a Connectum application. It has `@connectum/core` as a peer dependency. ```bash pnpm add @connectum/healthcheck ``` -------------------------------- ### Migrate Connectum Server Setup from Alpha to Beta Source: https://connectum.dev/en/migration Demonstrates the transition of a Connectum server initialization from an older alpha version to the newer beta version. This includes changes in function names, import paths, and the way protocols and interceptors are configured. It highlights the shift from `Runner` to `createServer` and the explicit configuration of healthcheck and reflection protocols. ```typescript import { Runner } from '@connectum/core'; const server = Runner({ services: [routes], port: 5000, builtinInterceptors: { errorHandler: true, logger: { level: 'debug' }, tracing: true, }, health: { enabled: true }, reflection: true, }); server.on('ready', () => { server.health.update(ServingStatus.SERVING); }); await server.start(); ``` ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import { createDefaultInterceptors } from '@connectum/interceptors'; const server = createServer({ services: [routes], port: 5000, protocols: [Healthcheck({ httpEnabled: true }), Reflection()], interceptors: createDefaultInterceptors(), shutdown: { autoShutdown: true }, }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); await server.start(); ``` -------------------------------- ### Testing TLS with grpcurl Source: https://connectum.dev/en/guide/tls Illustrates how to test a TLS-enabled server using grpcurl, including options for skipping verification or providing a CA certificate. ```APIDOC ## Testing TLS with grpcurl ### Description Provides examples of using `grpcurl` to interact with a TLS-enabled Connectum server, demonstrating how to handle self-signed certificates during testing. ### Method N/A (Shell Command) ### Endpoint N/A ### Commands 1. **Skip certificate verification (for development only):** ```bash grpcurl -insecure localhost:5000 list ``` 2. **Provide the CA certificate for verification:** ```bash grpcurl -cacert keys/server.crt localhost:5000 list ``` ### Note Ensure `keys/server.crt` contains the correct CA certificate or the self-signed certificate itself if used as the CA. ``` -------------------------------- ### Verify Server Reflection and Services using grpcurl (Bash) Source: https://connectum.dev/en/guide/server-reflection Commands to verify the functionality of a running Connectum server that has reflection enabled. These commands use `grpcurl` to list available services and describe a specific service. Ensure `grpcurl` is installed and the server is running on `localhost:5000`. ```bash # List all services grpcurl -plaintext localhost:5000 list # greeter.v1.GreeterService # order.v1.OrderService # grpc.health.v1.Health # grpc.reflection.v1.ServerReflection # Describe the order service grpcurl -plaintext localhost:5000 describe order.v1.OrderService ``` -------------------------------- ### Kubernetes TLS with Secrets Source: https://connectum.dev/en/guide/tls Example of mounting TLS certificates as Kubernetes secrets and configuring the Connectum server to use them. ```APIDOC ## Kubernetes TLS with Secrets ### Description Example of mounting TLS certificates as Kubernetes secrets and configuring the Connectum server to use them. ### Method N/A (Kubernetes Configuration & Server Configuration) ### Endpoint N/A ### Parameters #### Kubernetes Pod Spec - **`env`** (array) - Environment variables for the container. - **`name`**: `TLS_DIR_PATH` - **`value`**: `/etc/tls` - **`volumeMounts`** (array) - Mounts for volumes. - **`name`**: `tls-certs` - **`mountPath`**: `/etc/tls` - **`readOnly`**: `true` - **`volumes`** (array) - Volumes definition. - **`name`**: `tls-certs` - **`secret`**: - **`secretName`**: `my-service-tls` #### Server Options - **`tls`** (object) - TLS configuration. - **`dirPath`** (string) - Path to the directory containing TLS certificates, typically mounted from Kubernetes secrets. ### Request Example (Kubernetes YAML) ```yaml apiVersion: v1 kind: Pod spec: containers: - name: my-service image: my-service:latest env: - name: TLS_DIR_PATH value: /etc/tls volumeMounts: - name: tls-certs mountPath: /etc/tls readOnly: true volumes: - name: tls-certs secret: secretName: my-service-tls ``` ### Request Example (Server Configuration) ```typescript const server = createServer({ services: [routes], tls: { dirPath: process.env.TLS_DIR_PATH, }, }); ``` ### Response N/A (Configuration) ``` -------------------------------- ### Call a Method with grpcurl Source: https://connectum.dev/en/guide/server-reflection Demonstrates calling a gRPC method (`SayHello`) on a Connectum server using `grpcurl`. With reflection enabled, `grpcurl` can automatically resolve the service and method without needing `.proto` files. The request payload is provided using the `-d` flag. ```bash grpcurl -plaintext \ -d '{"name": "Alice"}' \ localhost:5000 \ greeter.v1.GreeterService/SayHello ``` -------------------------------- ### Buf Configuration: buf.yaml (YAML) Source: https://connectum.dev/en/guide/quickstart Configures buf to use the protovalidate dependency, which is required for field validation defined in the proto files. ```yaml version: v2 deps: - buf.build/bufbuild/protovalidate ``` -------------------------------- ### Run Example Scripts (Bash) Source: https://connectum.dev/en/contributing/cli-commands Executes example Node.js scripts directly, including basic examples, examples with custom interceptors, and running scripts in watch mode using `node --watch`. ```bash # Run basic example node examples/basic-service/src/index.ts # Run example with custom interceptor node examples/with-custom-interceptor/src/index.ts # Development mode with watch node --watch examples/basic-service/src/index.ts ``` -------------------------------- ### Service Handler: greeterService.ts (TypeScript) Source: https://connectum.dev/en/guide/quickstart Implements the 'GreeterService' handler. It defines the 'sayHello' RPC method, which takes a 'SayHelloRequest' and returns a 'SayHelloResponse' with a greeting message. ```typescript import { create } from '@bufbuild/protobuf'; import type { ConnectRouter } from '@connectrpc/connect'; import { GreeterService, SayHelloResponseSchema } from '#gen/greeter_pb.ts'; import type { SayHelloRequest } from '#gen/greeter_pb.ts'; export function greeterServiceRoutes(router: ConnectRouter): void { router.service(GreeterService, { async sayHello(request: SayHelloRequest) { const name = request.name || 'World'; return create(SayHelloResponseSchema, { message: `Hello, ${name}!`, }); }, }); } ``` -------------------------------- ### Code Generation Configuration: buf.gen.yaml (YAML) Source: https://connectum.dev/en/guide/quickstart Specifies the protoc-gen-es plugin for generating TypeScript code from proto definitions and directs the output to the 'gen' directory. ```yaml version: v2 plugins: - local: protoc-gen-es out: gen opt: target=ts inputs: - directory: proto ```