### Complete Connectum Server Setup and Lifecycle Example Source: https://github.com/connectum-framework/docs/blob/main/en/guide/server/lifecycle.md This example demonstrates the full setup of a Connectum server, including service registration, port configuration, protocol enablement (Healthcheck, Reflection), interceptors, and graceful shutdown settings. It also shows how to listen for and respond to various server lifecycle events like 'start', 'ready', 'stopping', 'stop', and 'error'. ```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, timeout: 25_000 }, }); server.on('start', () => console.log('Starting...')); server.on('ready', () => { console.log(`Ready on port ${server.address?.port}`); healthcheckManager.update(ServingStatus.SERVING); startBackgroundWorker(server.shutdownSignal); }); server.on('stopping', () => { healthcheckManager.update(ServingStatus.NOT_SERVING); }); server.on('stop', () => console.log('Stopped')); server.on('error', (err) => console.error('Error:', err)); await server.start(); ``` -------------------------------- ### Server Lifecycle Example Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/core/types/interfaces/Server.md Example demonstrating how to create, start, and stop a server using the `createServer` function and the `Server` interface methods. ```APIDOC ## Example ```typescript import { createServer } from '@connectum/core'; const server = createServer({ services: [myRoutes], port: 5000 }); server.on('ready', () => console.log('Server ready!')); server.on('error', (err) => console.error('Error:', err)); await server.start(); // Later await server.stop(); ``` ``` -------------------------------- ### Install and Run Documentation Dev Server Source: https://github.com/connectum-framework/docs/blob/main/README.md Use these commands to install dependencies and start the VitePress development server for the Connectum documentation. ```bash cd docs pnpm install pnpm docs:dev ``` -------------------------------- ### Minimal vs. Full Connectum Setup Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/adr/003-package-decomposition.md Illustrates minimal and full stack dependency installations for the Connectum framework. ```json { "dependencies": { "@connectum/core": "^0.2.0" } } ``` ```json { "dependencies": { "@connectum/core": "^0.2.0", "@connectum/auth": "^0.2.0", "@connectum/otel": "^0.2.0", "@connectum/interceptors": "^0.2.0", "@connectum/healthcheck": "^0.2.0", "@connectum/reflection": "^0.2.0" } } ``` -------------------------------- ### Create a Connectum Server Source: https://github.com/connectum-framework/docs/blob/main/en/packages/core.md Quick start example demonstrating server creation with services, protocols, and event handlers for readiness and errors. Ensure to await server.start(). ```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(); ``` -------------------------------- ### Migrate Server Setup from Alpha to Beta Source: https://github.com/connectum-framework/docs/blob/main/en/migration/index.md Example demonstrating the migration of server setup from Connectum alpha to beta versions, including changes in imports and configuration options. ```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(); ``` -------------------------------- ### Quick Start: Create Event Bus and Publish Events Source: https://github.com/connectum-framework/docs/blob/main/en/packages/events.md This example demonstrates setting up an EventBus with a MemoryAdapter, defining event handlers, integrating with a Connectum server, and publishing typed events. ```typescript import { createServer } from '@connectum/core'; import { createEventBus, MemoryAdapter } from '@connectum/events'; import type { EventRoute } from '@connectum/events'; import { UserEventHandlers, UserCreatedSchema } from '#gen/user/v1/user_pb.js'; // 1. Define event handlers (mirrors ConnectRPC router pattern) const userEvents: EventRoute = (events) => { events.service(UserEventHandlers, { onUserCreated: async (msg, ctx) => { console.log(`User created: ${msg.id}, ${msg.email}`); await ctx.ack(); }, }); }; // 2. Create an EventBus const eventBus = createEventBus({ adapter: MemoryAdapter(), routes: [userEvents], group: 'my-service', middleware: { retry: { maxRetries: 3, backoff: 'exponential' }, dlq: { topic: 'my-service.dlq' }, }, }); // 3. Integrate with Connectum server const server = createServer({ services: [routes], eventBus, shutdown: { autoShutdown: true }, }); await server.start(); // 4. Publish typed events await eventBus.publish(UserCreatedSchema, { id: '123', email: 'alice@example.com', name: 'Alice', }); ``` -------------------------------- ### Quick Start with EventBus and AMQP Adapter Source: https://github.com/connectum-framework/docs/blob/main/en/packages/events-amqp.md Initialize the EventBus with the AMQP adapter, define routes, and start the bus. This example demonstrates publishing a typed event and gracefully shutting down. ```typescript import { createEventBus } from '@connectum/events'; import { AmqpAdapter } from '@connectum/events-amqp'; const adapter = AmqpAdapter({ url: 'amqp://guest:guest@localhost:5672', }); const bus = createEventBus({ adapter, routes: [myRoutes], group: 'my-service', }); await bus.start(); // Publish a typed event await bus.publish(UserCreatedSchema, { userId: '123', email: 'user@example.com' }); // Graceful shutdown await bus.stop(); ``` -------------------------------- ### Quick Start with NATS Adapter Source: https://github.com/connectum-framework/docs/blob/main/en/packages/events-nats.md Initialize the EventBus with the NATS adapter, configure routes, and start the bus. This example demonstrates publishing a typed event and gracefully shutting down. ```typescript import { NatsAdapter } from '@connectum/events-nats'; import { createEventBus } from '@connectum/events'; const adapter = NatsAdapter({ servers: 'nats://localhost:4222' }); const bus = createEventBus({ adapter, routes: [myRoutes], group: 'my-service', }); await bus.start(); // Publish a typed event await bus.publish(UserCreatedSchema, { userId: '123', email: 'user@example.com' }); // Graceful shutdown await bus.stop(); ``` -------------------------------- ### Install Scenarigo Source: https://github.com/connectum-framework/docs/blob/main/en/guide/testing/scenarigo.md Install the Scenarigo command-line tool using Go's install command. This is the primary method for setting up Scenarigo. ```bash go install github.com/scenarigo/scenarigo/cmd/scenarigo@latest ``` -------------------------------- ### Running Examples Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Execute example applications directly using Node.js. Supports running basic examples, examples with custom configurations, and development mode with 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 ``` -------------------------------- ### start() Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/core/types/interfaces/Server.md Starts the server. This method should be called to initiate server operations. It returns a Promise that resolves when the server has successfully started. ```APIDOC ## start() ### Description Starts the server. ### Method start() ### Returns `Promise` - A promise that resolves when the server has started. ### Throws Error if the server is not in the CREATED state. ``` -------------------------------- ### Full Gateway Authentication Example Source: https://github.com/connectum-framework/docs/blob/main/en/guide/auth/gateway.md Integrate the gateway authentication interceptor with other default interceptors and authorization logic in a Connectum server. This example demonstrates setting up services, interceptors, and starting the server. ```typescript import { createServer, } from '@connectum/core'; import { createDefaultInterceptors, } from '@connectum/interceptors'; import { createGatewayAuthInterceptor, createAuthzInterceptor, } from '@connectum/auth'; const gatewayAuth = createGatewayAuthInterceptor({ headerMapping: { subject: 'x-user-id', name: 'x-user-name', roles: 'x-user-roles', }, trustSource: { header: 'x-gateway-secret', expectedValues: [process.env.GATEWAY_SECRET], }, }); const authz = createAuthzInterceptor({ defaultPolicy: 'deny', rules: [ { name: 'admin', methods: ['admin.v1.AdminService/*'], requires: { roles: ['admin'] }, effect: 'allow' }, ], }); const server = createServer({ services: [routes], interceptors: [...createDefaultInterceptors(), gatewayAuth, authz], }); await server.start(); ``` -------------------------------- ### Install Dependencies and Run Checks Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/index.md Use these commands to set up the project locally, install dependencies, and ensure code quality and correctness. ```bash cd connectum pnpm install # Install dependencies pnpm typecheck # Type check all packages pnpm test # Run all tests pnpm lint # Check code style pnpm format # Auto-fix formatting pnpm changeset # Create a changeset for versioning ``` -------------------------------- ### Install runn with Go Source: https://github.com/connectum-framework/docs/blob/main/en/guide/testing/runn.md Install the runn CLI tool using Go. ```bash go install github.com/k1LoW/runn/cmd/runn@latest ``` -------------------------------- ### Start Development Server Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/development-setup.md Start the development server using the pnpm dev command. ```bash pnpm dev ``` -------------------------------- ### Install @connectum/core Source: https://github.com/connectum-framework/docs/blob/main/en/packages/core.md Install the core package using pnpm. ```bash pnpm add @connectum/core ``` -------------------------------- ### Check Installation Prerequisites Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Verify that Node.js, pnpm, and protoc are installed and meet the required version criteria. ```bash # Check Node.js version node --version # Should be 25+ for development # Check pnpm version pnpm --version # Should be >= 10.0.0 # Check protoc version protoc --version # Should be installed ``` -------------------------------- ### Complete Production Server Setup with Graceful Shutdown Source: https://github.com/connectum-framework/docs/blob/main/en/guide/server/graceful-shutdown.md A comprehensive example of setting up a server with graceful shutdown, including multiple shutdown hooks, lifecycle event handlers, and essential protocols and interceptors. ```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(); ``` -------------------------------- ### Install runn with Homebrew Source: https://github.com/connectum-framework/docs/blob/main/en/guide/testing/runn.md Install the runn CLI tool using Homebrew. ```bash brew install k1LoW/tap/runn ``` -------------------------------- ### Connectum Server Setup Source: https://github.com/connectum-framework/docs/blob/main/en/index.md Configures and starts a Connectum server with specified services, protocols, and interceptors. Includes healthcheck, reflection, authentication, and OpenTelemetry integration. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { createOtelInterceptor } from '@connectum/otel'; import { createJwtAuthInterceptor, createProtoAuthzInterceptor } from '@connectum/auth'; import routes from '#services/deploymentService.js'; const server = createServer({ services: [routes], port: 5000, protocols: [Healthcheck({ httpEnabled: true }), Reflection()], interceptors: [ createOtelInterceptor({ serverPort: 5000 }), createJwtAuthInterceptor({ jwksUri: process.env.JWKS_URI! }), createProtoAuthzInterceptor(), ...createDefaultInterceptors(), ], shutdown: { autoShutdown: true }, }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); await server.start(); ``` -------------------------------- ### Complete Server Example with Reflection Source: https://github.com/connectum-framework/docs/blob/main/en/guide/protocols/reflection.md A full example demonstrating how to set up a Connectum server with multiple services, including the Healthcheck and Reflection protocols. Ensure all necessary packages are imported. ```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(); ``` -------------------------------- ### Full Working Example with MemoryAdapter Source: https://github.com/connectum-framework/docs/blob/main/en/guide/events/getting-started.md A minimal two-service setup using the MemoryAdapter for local testing. The consumer handles events, and the producer publishes them. With MemoryAdapter, the consumer handler fires synchronously. ```typescript import { createEventBus, MemoryAdapter } from '@connectum/events'; import type { EventRoute } from '@connectum/events'; import { NotificationEventHandlers, UserCreatedSchema, } from '#gen/notifications/v1/events_pb.js'; // Shared in-memory adapter (for testing only) const adapter = MemoryAdapter(); // Consumer: Notification Service const notificationEvents: EventRoute = (events) => { events.service(NotificationEventHandlers, { onUserCreated: async (msg, ctx) => { console.log(`Welcome email sent to ${msg.email}`); await ctx.ack(); }, onUserDeleted: async (msg, ctx) => { console.log(`Notifications cleaned for user ${msg.id}`); await ctx.ack(); }, }); }; const consumerBus = createEventBus({ adapter, routes: [notificationEvents], group: 'notification-service', }); // Producer: User Service const producerBus = createEventBus({ adapter }); await consumerBus.start(); await producerBus.start(); // Publish — the consumer handler fires synchronously with MemoryAdapter await producerBus.publish(UserCreatedSchema, { id: '1', email: 'alice@example.com', name: 'Alice', }); // Output: "Welcome email sent to alice@example.com" await consumerBus.stop(); await producerBus.stop(); ``` -------------------------------- ### Install AMQP Adapter Source: https://github.com/connectum-framework/docs/blob/main/en/guide/events/adapters.md Installs the AMQP/RabbitMQ event adapter using pnpm. ```bash pnpm add @connectum/events-amqp ``` -------------------------------- ### Install @connectum/cli Source: https://github.com/connectum-framework/docs/blob/main/en/packages/cli.md Install the CLI tool as a development dependency. ```bash pnpm add -D @connectum/cli ``` -------------------------------- ### Quick Start Healthcheck Server Setup Source: https://github.com/connectum-framework/docs/blob/main/en/guide/health-checks.md Set up a Connectum server with health check protocols enabled and update the serving status on server ready. Requires importing necessary modules from @connectum/core and @connectum/healthcheck. ```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(); ``` -------------------------------- ### start() Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/events/types/interfaces/EventBus.md Starts the event bus, establishing connections to adapters and setting up event subscriptions. It can accept an optional signal for graceful shutdown, which can override the construction-time signal. ```APIDOC ## start() ### Description Start the event bus: connect adapter, set up subscriptions. An optional `signal` can be passed for graceful shutdown. If provided, it **overrides** the construction-time `EventBusOptions.signal`. The active signal is then composed with `AbortSignal.timeout(handlerTimeout)` via `AbortSignal.any()` for each event handler invocation, so either shutdown or per-event timeout will abort in-flight processing. ### Method `start` ### Parameters - **options?** - **signal?** (`AbortSignal`): An optional AbortSignal for graceful shutdown. ### Returns `Promise` ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/development-setup.md Navigate into the connectum directory and install project dependencies using pnpm. ```bash cd connectum pnpm install ``` -------------------------------- ### Adding Protocols Before Server Start Source: https://github.com/connectum-framework/docs/blob/main/en/guide/protocols/custom.md Demonstrates adding a custom protocol to an existing server instance before starting it. ```typescript const server = createServer({ services: [routes] }); server.addProtocol(myCustomProtocol); await server.start(); ``` -------------------------------- ### Install @connectum/reflection Source: https://github.com/connectum-framework/docs/blob/main/en/guide/protocols/reflection.md Install the reflection package using pnpm. It has a peer dependency on `@connectum/core`. ```bash pnpm add @connectum/reflection ``` -------------------------------- ### start() Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/core/types/interfaces/EventBusLike.md Starts the event bus, which includes connecting to the message broker and setting up necessary subscriptions. This method is crucial for initializing the event bus functionality. ```APIDOC ## start() ### Description Start the event bus (connect to broker, set up subscriptions). ### Method start ### Parameters #### options? - **signal** (`AbortSignal`) - Optional - Abort signal from server for graceful shutdown ### Returns `Promise` ``` -------------------------------- ### Install @connectum/testing Source: https://github.com/connectum-framework/docs/blob/main/en/packages/testing.md Install the testing utilities package as a development dependency. Requires Node.js 20+ and peer dependencies @connectrpc/connect, @bufbuild/protobuf. ```bash pnpm add -D @connectum/testing ``` -------------------------------- ### Install Kafka Adapter Source: https://github.com/connectum-framework/docs/blob/main/en/guide/events/adapters.md Install the Kafka adapter package for integration with Apache Kafka or Kafka-compatible brokers like Redpanda. ```bash pnpm add @connectum/events-kafka ``` -------------------------------- ### Install runn with Aqua Source: https://github.com/connectum-framework/docs/blob/main/en/guide/testing/runn.md Install the runn CLI tool using Aqua. ```bash aqua g -i k1LoW/runn ``` -------------------------------- ### grpcurl Usage Examples Source: https://github.com/connectum-framework/docs/blob/main/en/packages/reflection.md Examples demonstrating how to use grpcurl with a Connectum server that has the Reflection protocol enabled. Includes listing services, describing services and methods, and calling methods. ```bash # List all services grpcrl -plaintext localhost:5000 list # Describe a service grpcrl -plaintext localhost:5000 describe my.service.v1.MyService # Describe a method grpcrl -plaintext localhost:5000 describe my.service.v1.MyService.GetUser # Call a method (reflection provides the schema) grpcrl -plaintext -d '{"id": "123"}' \ localhost:5000 my.service.v1.MyService/GetUser ``` -------------------------------- ### Install Broker Adapters Source: https://github.com/connectum-framework/docs/blob/main/en/packages/events.md For production use, install at least one broker adapter package. Options include NATS, Kafka, Redis, and AMQP. ```bash # Choose one (or more) broker adapters: pnpm add @connectum/events-nats # NATS JetStream pnpm add @connectum/events-kafka # Kafka / Redpanda pnpm add @connectum/events-redis # Redis Streams / Valkey pnpm add @connectum/events-amqp # AMQP / RabbitMQ ``` -------------------------------- ### Install protoc-gen-openapi Source: https://github.com/connectum-framework/docs/blob/main/en/guide/production/envoy-gateway.md Install the protoc plugin for generating OpenAPI specifications from proto files. ```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 ``` -------------------------------- ### Example: Update All Package Versions Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md An example of using 'pnpm -r exec' to update the version of all packages. ```bash pnpm -r exec npm version patch ``` -------------------------------- ### Install Redis Adapter Source: https://github.com/connectum-framework/docs/blob/main/en/guide/events/adapters.md Installs the Redis Streams event adapter using pnpm. ```bash pnpm add @connectum/events-redis ``` -------------------------------- ### Perform Fresh Install Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Removes lock file and node_modules, then performs a clean installation. ```bash rm -rf node_modules pnpm-lock.yaml pnpm install ``` -------------------------------- ### Install All Workspace Packages Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Installs all dependencies for all packages in the workspace, linking them together. ```bash pnpm install ``` -------------------------------- ### Install Validation Packages Source: https://github.com/connectum-framework/docs/blob/main/en/guide/validation.md Install the necessary packages for validation runtime and proto dependencies. ```bash # Validation runtime pnpm add @bufbuild/protovalidate @connectrpc/validate # Proto dependency (buf.yaml) # Add buf.build/bufbuild/protovalidate to deps ``` -------------------------------- ### Full Authorization Example Source: https://github.com/connectum-framework/docs/blob/main/en/guide/auth/authorization.md A complete example demonstrating JWT authentication and authorization using declarative rules and a programmatic fallback for superadmins. ```typescript import { createServer } from '@connectum/core'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { createJwtAuthInterceptor, createAuthzInterceptor } from '@connectum/auth'; const jwtAuth = createJwtAuthInterceptor({ jwksUri: 'https://auth.example.com/.well-known/jwks.json', issuer: 'https://auth.example.com/', }); const authz = createAuthzInterceptor({ defaultPolicy: 'deny', rules: [ { name: 'public', methods: ['public.v1.PublicService/*'], effect: 'allow' }, { name: 'admin-only', methods: ['admin.v1.AdminService/*'], requires: { roles: ['admin'] }, effect: 'allow' }, { name: 'write-scope', methods: ['data.v1.DataService/Write*'], requires: { scopes: ['write'] }, effect: 'allow' }, ], authorize: (context, req) => { // Fallback: superadmins can do anything return context.roles.includes('superadmin'); }, }); const server = createServer({ services: [routes], interceptors: [...createDefaultInterceptors(), jwtAuth, authz], }); await server.start(); ``` -------------------------------- ### Native gRPC Client Example Source: https://github.com/connectum-framework/docs/blob/main/en/guide/production/envoy-gateway.md TypeScript example demonstrating how to create a gRPC client using Connect RPC for interacting with the OrderService over HTTP/2. ```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' }); ``` -------------------------------- ### Run with Breakpoint Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Starts a Node.js application and pauses execution on the first line, enabling debugging from the start. ```bash node --inspect-brk src/index.ts ``` -------------------------------- ### Install Dependencies Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Install project dependencies using pnpm. Use '--frozen-lockfile' for CI/CD environments to ensure reproducible builds. ```bash # Install all dependencies pnpm install # Install with frozen lockfile (CI/CD) pnpm install --frozen-lockfile ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://github.com/connectum-framework/docs/blob/main/en/guide/quickstart.md Sets up a new project directory and installs core Connectum, ConnectRPC, and Protobuf dependencies, along with development tools like buf and protoc-gen-es. ```bash mkdir greeter-service && cd greeter-service pnpm init ``` ```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 # Dev dependencies (buf + code generation) pnpm add -D typescript @types/node @bufbuild/buf @bufbuild/protoc-gen-es ``` -------------------------------- ### Get Order via REST using cURL Source: https://github.com/connectum-framework/docs/blob/main/en/guide/production/envoy-gateway.md Example of retrieving an order using a GET request to the /v1/orders/{orderId} REST endpoint. ```bash # Get an order via REST curl https://api.example.com/v1/orders/550e8400-e29b-41d4-a716-446655440000 ``` -------------------------------- ### Start the server Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/core/types/interfaces/Server.md Initiates the server's operation. This method should only be called when the server is in the CREATED state. It returns a Promise that resolves when the server has started. ```ts await server.start(); ``` -------------------------------- ### Install Connectum Events Packages Source: https://github.com/connectum-framework/docs/blob/main/en/guide/events/getting-started.md Install the core events package and a broker adapter for your chosen message broker. MemoryAdapter is built-in for local testing. ```bash pnpm add @connectum/events @connectum/events-nats ``` ```bash pnpm add @connectum/events @connectum/events-kafka ``` ```bash pnpm add @connectum/events @connectum/events-redis ``` ```bash pnpm add @connectum/events @connectum/events-amqp ``` ```bash # MemoryAdapter is built-in — no extra package needed pnpm add @connectum/events ``` -------------------------------- ### Full JWT Authentication Example Source: https://github.com/connectum-framework/docs/blob/main/en/guide/auth/jwt.md Integrate JWT authentication into a Connectum server. This example demonstrates setting up the JWT interceptor alongside default interceptors and starting the server. ```typescript import { createServer } from '@connectum/core'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { createJwtAuthInterceptor, createAuthzInterceptor } from '@connectum/auth'; const jwtAuth = createJwtAuthInterceptor({ jwksUri: 'https://auth.example.com/.well-known/jwks.json', issuer: 'https://auth.example.com/', audience: 'my-api', maxTokenAge: '1h', claimsMapping: { roles: 'realm_access.roles', scopes: 'scope', }, }); const server = createServer({ services: [routes], interceptors: [...createDefaultInterceptors(), jwtAuth], }); await server.start(); ``` -------------------------------- ### Create Server Entry Point Source: https://github.com/connectum-framework/docs/blob/main/en/guide/quickstart.md Sets up the main server instance with services, port, protocols, and interceptors. Includes event handlers for server lifecycle. ```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(); ``` -------------------------------- ### KafkaAdapter with Server Integration Source: https://github.com/connectum-framework/docs/blob/main/en/packages/events-kafka.md Combine the KafkaAdapter with the EventBus and the core Server for a complete application setup. The server can be started after configuration. ```typescript import { createServer } from '@connectum/core'; import { createEventBus } from '@connectum/events'; import { KafkaAdapter } from '@connectum/events-kafka'; const eventBus = createEventBus({ adapter: KafkaAdapter({ brokers: ['localhost:9092'] }), routes: [orderEvents], group: 'order-service', }); const server = createServer({ services: [routes], eventBus, shutdown: { autoShutdown: true }, }); await server.start(); ``` -------------------------------- ### Package-Specific Commands for @connectum/core Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Specific commands for the '@connectum/core' package, including starting a server example, development with watch, and running integration tests. ```bash # Start server example pnpm --filter @connectum/core start # Development with watch pnpm --filter @connectum/core dev # Run integration tests pnpm --filter @connectum/core test:integration ``` -------------------------------- ### Build and Preview Documentation Source: https://github.com/connectum-framework/docs/blob/main/README.md Commands to build the static documentation site and preview it locally. ```bash pnpm docs:build pnpm docs:preview ``` -------------------------------- ### Connectum CLI and API Examples Source: https://github.com/connectum-framework/docs/blob/main/en/index.md Demonstrates command-line operations for syncing Protobuf types, making gRPC calls with authentication, and interacting via REST using Envoy Gateway. ```bash # Sync proto types from a running server (gRPC Server Reflection) connectum proto sync --from localhost:5000 --out ./gen # gRPC call (requires platform-engineer role) grpcurl -d '{"namespace":"prod","image":"api:v2.1.0","replicas":3}' \ -H "Authorization: Bearer $TOKEN" \ localhost:5000 platform.v1.DeploymentService/CreateDeployment # REST via Envoy Gateway (gRPC-JSON transcoding from google.api.http) curl -X POST http://gateway:8080/v1/deployments \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"namespace":"prod","image":"api:v2.1.0","replicas":3}' ``` -------------------------------- ### Append Custom Interceptors to Default Chain Source: https://github.com/connectum-framework/docs/blob/main/en/guide/interceptors/custom.md Use `createDefaultInterceptors()` to get the default chain and then append your custom interceptors. This example appends a rate limiting interceptor. ```typescript import { createServer } from '@connectum/core'; import { createDefaultInterceptors } from '@connectum/interceptors'; const server = createServer({ services: [routes], port: 5000, interceptors: [ ...createDefaultInterceptors({ timeout: { duration: 10_000 } }), // Custom interceptors appended after the built-in chain createRateLimitInterceptor({ maxRequests: 100, windowMs: 60_000 }), ], }); ``` -------------------------------- ### Polyrepo Directory Structure Source: https://github.com/connectum-framework/docs/blob/main/en/guide/production/architecture.md Example directory structure for a polyrepo setup, recommended for large organizations. Each service resides in its own repository, with proto definitions managed in a separate proto registry repository. ```plaintext github.com/mycompany/ ├── proto-registry/ ├── order-service/ ├── inventory-service/ └── shared-libs/ ``` -------------------------------- ### Monorepo Directory Structure Source: https://github.com/connectum-framework/docs/blob/main/en/guide/production/architecture.md Example directory structure for a monorepo setup, recommended for small-to-medium teams. It centralizes proto definitions, shared libraries, and service code within a single repository. ```plaintext my-platform/ ├── proto/ │ ├── buf.yaml │ └── mycompany/ │ ├── orders/v1/ │ ├── inventory/v1/ │ └── payments/v1/ ├── packages/ │ ├── shared/ │ ├── order-service/ │ ├── inventory-service/ │ └── payment-service/ ├── pnpm-workspace.yaml └── turbo.json ``` -------------------------------- ### GitHub Actions CI/CD Integration for runn Source: https://github.com/connectum-framework/docs/blob/main/en/guide/testing/runn.md Integrate runn into GitHub Actions by checking out code, installing runn via Homebrew, starting your service, waiting for it to be ready, and then running API tests. ```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 ``` -------------------------------- ### Create and Use a Test Server Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/testing/index/functions/createTestServer.md Demonstrates how to create a test server with specified services, create a client using its transport, make a method call, and then close the server. ```typescript const server = await createTestServer({ services: [myRoutes] }); const client = createClient(MyService, server.transport); const response = await client.myMethod({ id: "1" }); await server.close(); ``` -------------------------------- ### createServer() Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/core/functions/createServer.md Creates a new server instance. The returned server is initially unstarted and requires a call to `server.start()` to begin accepting connections. ```APIDOC ## Function: createServer() > **createServer**(`options`): [`Server`](../types/interfaces/Server.md) Defined in: [packages/core/src/Server.ts:297](https://github.com/Connectum-Framework/connectum/blob/acbe73ae0e923dc7b46c1b4a6241f3e342535af7/packages/core/src/Server.ts#L297) Create a new server instance Returns an unstarted server. Call server.start() to begin accepting connections. ### Parameters #### options [`CreateServerOptions`](../types/interfaces/CreateServerOptions.md) Server configuration options ### Returns [`Server`](../types/interfaces/Server.md) Unstarted server instance ### Example ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; const server = createServer({ services: [myRoutes], protocols: [Healthcheck({ httpEnabled: true }), Reflection()], shutdown: { autoShutdown: true }, }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); await server.start(); ``` ``` -------------------------------- ### Test File Structure Example Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/adr/007-testing-strategy.md Illustrates the recommended directory structure for test files within a Connectum package. ```bash packages// src/ tests/ unit/ # Isolated unit tests .test.ts integration/ # Full-stack integration tests (when needed) .test.ts ``` -------------------------------- ### Create and Start a Connectum Server Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/core/functions/createServer.md Demonstrates creating a Connectum server with custom services and protocols, and then starting it. The server emits a 'ready' event which can be used to update healthcheck status. ```typescript import { createServer } from '@connectum/core'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; const server = createServer({ services: [myRoutes], protocols: [Healthcheck({ httpEnabled: true }), Reflection()], shutdown: { autoShutdown: true }, }); server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); await server.start(); ``` -------------------------------- ### Install @connectum/healthcheck Source: https://github.com/connectum-framework/docs/blob/main/en/guide/health-checks.md Install the @connectum/healthcheck package using pnpm. ```bash pnpm add @connectum/healthcheck ``` -------------------------------- ### Create Project Structure Source: https://github.com/connectum-framework/docs/blob/main/en/guide/quickstart.md Creates the necessary directories for source files, generated code, and protobuf definitions. ```bash mkdir -p src/services gen proto ``` -------------------------------- ### Create and Manage a Connectum Server Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/core/types/interfaces/Server.md Demonstrates how to create a Connectum server with services, listen for 'ready' and 'error' events, and manage its lifecycle by starting and stopping it. ```typescript import { createServer } from '@connectum/core'; const server = createServer({ services: [myRoutes], port: 5000 }); server.on('ready', () => console.log('Server ready!')); server.on('error', (err) => console.error('Error:', err)); await server.start(); // Later await server.stop(); ``` -------------------------------- ### Identify Package Installation Reason Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Determines why a specific package is installed in the project. ```bash pnpm why @bufbuild/protobuf ``` -------------------------------- ### Development .env Configuration Source: https://github.com/connectum-framework/docs/blob/main/en/guide/server/configuration.md Example environment variables for development, including port, logging levels, and feature flags. ```bash PORT=5000 NODE_ENV=development LOG_LEVEL=debug LOG_FORMAT=pretty LOG_BACKEND=console HTTP_HEALTH_ENABLED=true GRACEFUL_SHUTDOWN_ENABLED=false ``` -------------------------------- ### Install @connectum/interceptors Source: https://github.com/connectum-framework/docs/blob/main/en/packages/interceptors.md Install the interceptors package using pnpm. Requires Node.js 20+. ```bash pnpm add @connectum/interceptors ``` -------------------------------- ### Connection Modes Example Source: https://github.com/connectum-framework/docs/blob/main/en/packages/events-redis.md Demonstrates different ways to configure the Redis connection using the `RedisAdapter` factory function. ```APIDOC ## Connection Modes You can connect to Redis using a URL, explicit options, or both: ```typescript // URL only RedisAdapter({ url: 'redis://localhost:6379' }); // Options only (ioredis RedisOptions) RedisAdapter({ redisOptions: { host: '10.0.0.1', port: 6380, password: 'secret', db: 2, tls: {}, }, }); // URL with additional options merged RedisAdapter({ url: 'redis://localhost:6379', redisOptions: { password: 'secret', db: 2 }, }); // Default (localhost:6379, no auth) RedisAdapter(); ``` ``` -------------------------------- ### Create New Package Structure Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/cli-commands.md Sets up the directory structure for a new package. ```bash mkdir -p packages/my-package/{src,tests} ``` -------------------------------- ### Install Authentication Package Source: https://github.com/connectum-framework/docs/blob/main/en/guide/quickstart.md Installs the Connectum authentication package required for JWT and authorization interceptors. ```bash pnpm add @connectum/auth ``` -------------------------------- ### gRPC Testing with grpcurl Source: https://github.com/connectum-framework/docs/blob/main/en/guide/quickstart.md Demonstrates how to interact with the server using grpcurl for listing services, calling methods, and checking health. ```bash # List services (reflection) grpcurl -plaintext localhost:5000 list # Call SayHello grpcurl -plaintext -d '{"name": "Alice"}' localhost:5000 greeter.v1.GreeterService/SayHello # Health check grpcurl -plaintext localhost:5000 grpc.health.v1.Health/Check ``` -------------------------------- ### MethodFilterMap Usage Example Source: https://github.com/connectum-framework/docs/blob/main/en/api/@connectum/interceptors/type-aliases/MethodFilterMap.md An example demonstrating how to define a MethodFilterMap to apply interceptors to different method patterns. ```APIDOC ## MethodFilterMap ### Description A mapping from method patterns to an array of interceptors. ### Type Definition `Record` ### Patterns - `"*"`: Matches all methods (global). - `"package.Service/*"`: Matches all methods of a specific service. - `"package.Service/Method"`: Matches an exact method. ### Key Format Uses protobuf fully-qualified service name: `service.typeName + "/" + method.name` ### Execution Order All matching patterns are executed in order: global -> service wildcard -> exact match. Within each pattern, interceptors execute in array order. ### Example ```typescript const methods: MethodFilterMap = { "*": [logRequest], "admin.v1.AdminService/*": [requireAdmin], "user.v1.UserService/DeleteUser": [requireAdmin, auditLog], }; ``` ``` -------------------------------- ### Server Setup with New Registration API Source: https://github.com/connectum-framework/docs/blob/main/en/contributing/adr/023-uniform-registration-api.md Demonstrates setting up a Connectum server using the new uniform registration API for services, protocols, and interceptors. Interceptors can be omitted for auto-defaults. Runtime registration and readonly getters for server configurations are also shown. ```typescript import { createServer } from '@connectum/core'; import { createDefaultInterceptors } from '@connectum/interceptors'; import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck'; import { Reflection } from '@connectum/reflection'; const server = createServer({ services: [myRoutes], protocols: [Healthcheck({ httpEnabled: true }), Reflection()], // interceptors omitted -> auto-defaults }); // Runtime registration (before start) server.addInterceptor(myCustomInterceptor); server.addProtocol(myCustomProtocol); // Readonly getters console.log(server.interceptors); // ReadonlyArray console.log(server.protocols); // ReadonlyArray console.log(server.routes); // ReadonlyArray server.on('ready', () => { healthcheckManager.update(ServingStatus.SERVING); }); await server.start(); ```