@consciousclouds/node-sdk
v1.0.1
Published
Conscious Clouds Platform Node.js SDK - Framework-agnostic backend SDK for microservices
Readme
@cc/node-sdk
Framework-agnostic platform SDK for Node.js microservices.
Provides standardized infrastructure for error taxonomy, protocol envelopes, configuration, context propagation, observability, transport clients, caching, rate limiting, authentication, event publishing, lifecycle management, and utilities.
Installation
npm install @cc/node-sdk
# or
bun add @cc/node-sdkQuick Start
import { ErrorCode, PlatformException } from '@cc/node-sdk/core/errors';
import { HttpClient } from '@cc/node-sdk/transport/http';
import { createLogger } from '@cc/node-sdk/observability/logging';
// Structured logging
const logger = createLogger({ serviceName: 'my-service', environment: 'dev' });
logger.info({ userId: '123' }, 'user_created');
// HTTP client with circuit breaker and retry
const client = new HttpClient({ baseUrl: 'https://api.example.com' });
const response = await client.get('/api/v1/users/123');
// Platform errors with error codes
throw new PlatformException({
code: ErrorCode.RESOURCE_NOT_FOUND,
message: 'User not found',
httpStatus: 404,
});Subpath Exports
Import from subpath exports for tree-shaking and minimal dependency loading.
| Export | Description |
|--------|-------------|
| @cc/node-sdk | Barrel re-export of all modules |
| @cc/node-sdk/core/errors | Error codes (50 codes, 10 categories), catalog, exceptions, HTTP/gRPC protocol mappings |
| @cc/node-sdk/core/protocol | Request/response envelopes, service tiers, retry configuration |
| @cc/node-sdk/core/config | BaseServiceSettings, environment detection helpers (isProduction, isDevelopment, isStaging) |
| @cc/node-sdk/core/context | RequestContext propagation, correlation IDs, traceparent parsing, context-to-headers/gRPC-metadata conversion |
| @cc/node-sdk/observability | Vendor-neutral observability interfaces (Logger, MetricsRecorder, Tracer), no-op defaults, envelope helpers, diagnostics collector, instrumentation hooks, correlation propagation |
| @cc/node-sdk/observability/logging | Structured JSON logging via pino (createLogger, getLogger, childLogger) |
| @cc/node-sdk/observability/metrics | Prometheus MetricRegistry with auto-injected service/env labels |
| @cc/node-sdk/observability/tracing | OpenTelemetry tracing integration (initTracing, getTracer, withSpan) |
| @cc/node-sdk/transport/http | HttpClient with circuit breaker, retry policies, transport error classification |
| @cc/node-sdk/transport/grpc | gRPC client wrapper with context-propagating interceptors |
| @cc/node-sdk/transport/kafka | KafkaProducer and KafkaConsumer with event envelope serialization |
| @cc/node-sdk/transport/service-client | Transport-agnostic service client abstraction with service discovery |
| @cc/node-sdk/infra/cache | Redis cache helpers with JSON get/set, health checks, and connection management |
| @cc/node-sdk/infra/ratelimit | Tenant-aware rate limiting with token bucket algorithm and admin bypass |
| @cc/node-sdk/auth | JWT/JWKS validation with key rotation, cookie management, CSRF protection, acting-user HMAC signing |
| @cc/node-sdk/events | Event envelope creation and event type validation |
| @cc/node-sdk/utils | ID generation (UUID), UTC time helpers, JSON serialization utilities |
| @cc/node-sdk/lifecycle | Hook-based service lifecycle (ordered startup, reverse shutdown, health check aggregation) |
Usage Examples
Error Handling
import { ErrorCode, PlatformException, getErrorEntry } from '@cc/node-sdk/core/errors';
// Look up error metadata
const entry = getErrorEntry(ErrorCode.VALIDATION_FAILED);
console.log(entry.httpStatus); // 400
console.log(entry.grpcStatus); // 3 (INVALID_ARGUMENT)
// Throw a platform exception
throw new PlatformException({
code: ErrorCode.VALIDATION_FAILED,
message: 'Email is required',
httpStatus: 400,
});Context Propagation
import {
createRequestContext,
withContext,
getCorrelationId,
contextToHeaders,
} from '@cc/node-sdk/core/context';
const ctx = createRequestContext({
correlationId: 'req_abc123def456',
tenantId: 'tenant-1',
userId: 'user-42',
});
withContext(ctx, () => {
console.log(getCorrelationId()); // "req_abc123def456"
// Propagate context to outbound HTTP calls
const headers = contextToHeaders();
// headers: { 'x-correlation-id': 'req_abc123def456', 'x-tenant-id': 'tenant-1', ... }
});Service Lifecycle
import { ServiceLifecycle } from '@cc/node-sdk/lifecycle';
const lifecycle = new ServiceLifecycle({ name: 'my-service' });
lifecycle.register({
name: 'database',
initialize: async () => { /* connect to DB */ },
healthCheck: async () => { /* ping DB */ return true; },
shutdown: async () => { /* close DB pool */ },
});
await lifecycle.start(); // Runs hooks in registration order
// ... serve requests ...
await lifecycle.stop(); // Runs hooks in reverse orderMetrics
import { MetricRegistry } from '@cc/node-sdk/observability/metrics';
const registry = new MetricRegistry({
namespace: 'my_service',
serviceName: 'my-service',
env: 'production',
});
const requestsTotal = registry.counter(
'requests_total',
'Total HTTP requests',
['method', 'status'],
);
requestsTotal.labels({ method: 'GET', status: '200' }).inc();Events
import { createEventEnvelope } from '@cc/node-sdk/events';
import { KafkaProducer } from '@cc/node-sdk/transport/kafka';
const envelope = createEventEnvelope({
eventType: 'user.created',
source: 'my-service',
payload: { userId: 'user-42', email: '[email protected]' },
});Requirements
- Node.js >= 18.0.0
- TypeScript >= 5.3
Testing
See @cc/node-sdk-testing for
test harnesses and mock utilities designed for consumers of this SDK.
License
Apache 2.0 -- see LICENSE.
