UNPKG

@delta-base/observability

Version:

Observability framework for delta-base applications

1,126 lines (1,116 loc) 39.8 kB
import { Span, SpanKind } from '@opentelemetry/api'; import * as hono_types from 'hono/types'; import { isEventStoreAlreadyExistsError } from '@delta-base/toolkit'; export { BuildInfoOptions } from './scripts/collect-build-info.js'; declare const DEFAULT_BUILD_INFO: { readonly 'service.name': "unknown-service"; readonly 'service.version': "0.0.0"; readonly 'service.environment': "development"; }; declare function setBuildInfo(buildInfo: Record<string, string | number | boolean>): void; declare function getBuildInfo(): Record<string, string | number | boolean>; /** * Initialize build info from a generated BUILD_INFO constant * This is typically called at application startup */ declare function initializeBuildInfo(buildInfo: Record<string, string | number | boolean>): void; /** * Data categories we can track in wide events */ interface UserData { /** User identifier */ id?: string; /** User email address */ email?: string; /** User's first name */ firstName?: string; /** User's last name */ lastName?: string; /** Type of actor (user, service, system, etc.) */ actorType?: string; /** Additional user properties */ [key: string]: string | number | boolean | undefined; } interface EntityData { /** Type of entity (user, order, product, etc.) */ type: string; /** Entity identifier */ id: string; /** Entity-specific properties */ [key: string]: string | number | boolean | undefined; } interface OperationData { /** Domain operation being performed */ domain?: string; /** Operation layer (validation, business, persistence, etc.) */ layer?: string; /** Operation-specific properties */ [key: string]: string | number | boolean | undefined; } interface InfrastructureData { /** Database operation details */ database?: { operation?: string; table?: string; query?: string; duration?: number; }; /** Event store details */ eventStore?: { streamId?: string; expectedVersion?: number; nextVersion?: number; createdNewStream?: boolean; }; /** External service calls */ externalService?: { name?: string; operation?: string; duration?: number; }; /** Custom infrastructure properties */ [key: string]: string | number | boolean | object | undefined; } interface ErrorData { /** Error type/category */ type?: string; /** Error message */ message?: string; /** Validation-specific error details */ validation?: { issueCount?: number; fields?: string[]; }; /** Business rule violation details */ businessRule?: { rule?: string; violation?: string; }; /** Whether this was an unexpected error */ unexpected?: boolean; /** Additional error properties */ [key: string]: string | number | boolean | object | undefined; } /** * Simplified Wide Events wrapper for comprehensive observability. * * This class provides a fluent API for tracking different types of context * in your application operations. It automatically handles OpenTelemetry * span management and converts everything to structured wide events. * * Key methods: * - `setOperation()` - Set the operation type and context (e.g., 'user.create') * - `trackUser()` - Track user/actor information * - `trackEntity()` - Track the primary entity being operated on * - `trackInfrastructure()` - Track technical details like database operations * - `trackError()` - Track error information * * @example * ```typescript * const tracker = new WideEventsWrapper('Create User', 'user.create'); * * await tracker.execute(async (t) => { * t.setOperation('user.create', { domain: 'user-management', layer: 'api' }) * .trackUser({ id: '123', email: 'john@example.com' }) * .trackEntity({ type: 'user', id: '123' }); * * // Your business logic here * }); * ``` */ declare class WideEventsWrapper { private requestId; private rootSpan; private trackedData; private hasError; /** * Creates a new wide events wrapper for an operation. * * @param operationName - Human-readable name for the operation (e.g., "Create User") * @param operationType - Machine-readable operation type (e.g., "user.create") * @param serviceName - Name of the service (defaults to environment variable) */ constructor(operationName: string, operationType: string, serviceName?: string); /** * Set the operation type and context for this operation. * * This is the primary method for identifying what operation is being performed. * It sets both the operation type identifier and any contextual metadata. * * @param operationType - The operation type identifier (e.g., "user.create", "user.change-password") * @param context - Optional contextual information about the operation * @returns This instance for method chaining * * @example * ```typescript * // Simple operation * tracker.setOperation('user.create'); * * // With context * tracker.setOperation('user.create', { * domain: 'user-management', * layer: 'api' * }); * * // With custom properties * tracker.setOperation('user.change-password', { * domain: 'user-management', * layer: 'business-logic', * trigger: 'user-initiated' * }); * ``` */ setOperation(operationType: string, context?: OperationData): this; /** * Track user/actor information for this operation. * * Use this to record who is performing the operation, including * user details, authentication context, and actor type. * * @param userData - User and actor information * @returns This instance for method chaining * * @example * ```typescript * tracker.trackUser({ * id: '123', * email: 'john@example.com', * actorType: 'authenticated_user' * }); * ``` */ trackUser(userData: UserData): this; /** * Track the primary entity/resource being operated on. * * Use this to record what thing your operation is working with, * such as a user being created, an order being processed, etc. * * @param entityData - Entity/resource information * @returns This instance for method chaining * * @example * ```typescript * tracker.trackEntity({ * type: 'user', * id: 'user-123', * status: 'active' * }); * ``` */ trackEntity(entityData: EntityData): this; /** * Track infrastructure and technical details. * * Use this to record technical aspects of your operation, * such as database operations, external service calls, etc. * * @param infrastructureData - Infrastructure operation details * @returns This instance for method chaining * * @example * ```typescript * tracker.trackInfrastructure({ * database: { * operation: 'INSERT', * table: 'users', * duration: 45 * }, * eventStore: { * streamId: 'user-123', * expectedVersion: 0 * } * }); * ``` */ trackInfrastructure(infrastructureData: InfrastructureData): this; /** * Track error information. * * Use this to record error details, including error type, * validation failures, business rule violations, etc. * * @param errorData - Error information * @returns This instance for method chaining * * @example * ```typescript * tracker.trackError({ * type: 'ValidationError', * message: 'Email is required', * validation: { * issueCount: 2, * fields: ['email', 'firstName'] * } * }); * ``` */ trackError(errorData: ErrorData): this; /** * Record a business event during the operation. * * Use this to record significant business events that occur * during your operation, such as "validation.completed" or * "user.created". * * @param eventName - Name of the business event * @param eventData - Additional event data * @returns This instance for method chaining * * @example * ```typescript * tracker.recordEvent('user.created', { * userId: '123', * source: 'api' * }); * ``` */ recordEvent(eventName: string, eventData?: Record<string, string | number | boolean>): this; /** * Create a child span for a sub-operation. * * Use this to create detailed spans for specific parts of your * operation, such as validation, database operations, etc. * * @param name - Name of the sub-operation * @param attributes - Additional span attributes * @returns OpenTelemetry span for the sub-operation * * @example * ```typescript * const validationSpan = tracker.createOperationSpan('validation', { * 'operation.layer': 'validation' * }); * * try { * // validation logic * validationSpan.setStatus({ code: SpanStatusCode.OK }); * } catch (error) { * validationSpan.recordException(error); * } finally { * validationSpan.end(); * } * ``` */ createOperationSpan(name: string, attributes?: Record<string, string | number | boolean>): Span; /** * Automatically track HTTP request details. * * This method extracts and tracks HTTP-specific information * from the request, including method, URL, headers, etc. * * @param request - HTTP request object * @returns This instance for method chaining * * @internal This method is typically called by middleware */ trackHttpRequest(request: Request): this; /** * Automatically track HTTP response details. * * This method extracts and tracks HTTP response information, * including status code, headers, and sets appropriate span status. * * @param response - HTTP response object * @returns This instance for method chaining * * @internal This method is typically called by middleware */ trackHttpResponse(response: Response): this; /** * Execute the operation with proper OpenTelemetry context. * * This method wraps your operation in the appropriate OpenTelemetry * context and ensures spans are properly managed and exported. * * @param fn - Operation function to execute * @returns Promise with the operation result * * @example * ```typescript * const result = await tracker.execute(async (t) => { * t.trackUser({ id: '123' }); * // Your operation logic here * return { success: true }; * }); * ``` */ execute<R>(fn: (wrapper: this) => Promise<R>): Promise<R>; /** * Get all tracked data for this operation. * * @returns Copy of all tracked data * * @internal Primarily used for testing and debugging */ getTrackedData(): Record<string, string | number | boolean>; } /** * Factory function to create a wide events wrapper for user operations. * * @param operationName - Specific operation name (e.g., "create", "update") * @returns Configured wide events wrapper * * @example * ```typescript * const tracker = createUserOperationTracker('create'); * ``` */ declare function createUserOperationTracker(operationName: string): WideEventsWrapper; /** * Factory function to create a generic wide events wrapper. * * @param entity - Entity type (e.g., "user", "order") * @param operation - Operation name (e.g., "create", "update") * @returns Configured wide events wrapper * * @example * ```typescript * const tracker = createOperationTracker('order', 'create'); * ``` */ declare function createOperationTracker(entity: string, operation: string): WideEventsWrapper; /** * Configuration for context schema - defines which fields are tracked for each category */ interface ContextSchemaConfig { /** User-related context fields */ user: string[]; /** Entity-related context fields */ entity: string[]; /** Operation-related context fields */ operation: string[]; /** Infrastructure-related context fields */ infrastructure: string[]; /** Error-related context fields */ error: string[]; /** HTTP-related context fields */ http: string[]; /** Performance/timing-related context fields */ performance: string[]; /** Service-related context fields */ service: string[]; } /** * Error response pattern for automatic error detection and categorization */ interface ErrorResponsePattern { /** Human-readable name for the error pattern */ name: string; /** Function that tests if a response body matches this error pattern */ matcher: (body: any) => boolean; /** Function that tracks the error with appropriate context and categorization */ tracker: (wideEvent: WideEventsWrapper, body: any) => void; } /** * Tracing configuration options */ interface TracingConfig { /** Whether to enable OpenTelemetry tracing */ enabled: boolean; /** Service name for tracing */ serviceName?: string; /** Service version for tracing */ serviceVersion?: string; /** Environment name */ environment?: string; /** Custom attributes to add to all spans */ defaultAttributes?: Record<string, string | number | boolean>; } /** * HTTP tracking configuration */ interface HttpTrackingConfig { /** Whether to automatically track HTTP request details */ trackRequests: boolean; /** Whether to automatically track HTTP response details */ trackResponses: boolean; /** Whether to track request/response bodies */ trackBodies: boolean; /** Maximum body size to track (in bytes) */ maxBodySize: number; /** Headers to exclude from tracking */ excludeHeaders: string[]; /** Headers to include in tracking (if specified, only these will be tracked) */ includeHeaders?: string[]; } /** * Error tracking configuration */ interface ErrorTrackingConfig { /** Whether to automatically detect and track error responses */ autoTrackErrorResponses: boolean; /** Whether to automatically categorize errors as expected/unexpected */ autoCategorizeErrors: boolean; /** Custom error response patterns */ errorPatterns: ErrorResponsePattern[]; /** Default error categorization for unknown errors */ defaultUnexpected: boolean; } /** * Performance tracking configuration */ interface PerformanceConfig { /** Whether to automatically track operation timing */ trackTiming: boolean; /** Whether to categorize performance (fast, slow, etc.) */ categorizePerformance: boolean; /** Thresholds for performance categorization (in milliseconds) */ performanceThresholds: { fast: number; slow: number; }; /** Whether to automatically create spans for common operations */ autoCreateSpans: boolean; } /** * Comprehensive observability configuration */ interface ObservabilityConfig { /** Context schema configuration */ contextSchema: ContextSchemaConfig; /** Tracing configuration */ tracing: TracingConfig; /** HTTP tracking configuration */ http: HttpTrackingConfig; /** Error tracking configuration */ errors: ErrorTrackingConfig; /** Performance tracking configuration */ performance: PerformanceConfig; /** Whether to log debug information */ debug: boolean; } /** * Simplified options interface for backward compatibility */ interface ObservabilityOptions$1 { /** Custom service name (defaults to environment variable SERVICE_NAME) */ serviceName?: string; /** Whether to automatically track HTTP request/response (defaults to true) */ autoTrackHttp?: boolean; /** Whether to automatically detect and track error responses (defaults to true) */ autoTrackErrorResponses?: boolean; /** Whether to enable debug logging (defaults to false) */ debug?: boolean; /** Build info to initialize (optional) */ buildInfo?: Record<string, string | number | boolean>; } /** * Default context schema configuration */ declare const DEFAULT_CONTEXT_SCHEMA: ContextSchemaConfig; /** * Default error response patterns */ declare const DEFAULT_ERROR_PATTERNS: ErrorResponsePattern[]; /** * Default observability configuration */ declare const DEFAULT_OBSERVABILITY_CONFIG: ObservabilityConfig; /** * Create observability configuration from simplified options */ declare function createObservabilityConfig(options?: ObservabilityOptions$1): ObservabilityConfig; /** * Utility class for managing observability configuration */ declare class ObservabilityConfigManager { private config; constructor(config?: ObservabilityConfig); /** * Get current configuration */ getConfig(): ObservabilityConfig; /** * Update configuration */ updateConfig(updates: Partial<ObservabilityConfig>): void; /** * Add custom context schema fields */ addContextFields(category: keyof ContextSchemaConfig, fields: string[]): void; /** * Add custom error pattern */ addErrorPattern(pattern: ErrorResponsePattern): void; /** * Remove error pattern by name */ removeErrorPattern(name: string): void; /** * Get context schema for a category */ getContextSchema(category: keyof ContextSchemaConfig): string[]; /** * Get all context schema fields (flattened) */ getAllContextFields(): string[]; /** * Get error patterns */ getErrorPatterns(): ErrorResponsePattern[]; } /** * Global configuration manager instance */ declare const observabilityConfig: ObservabilityConfigManager; /** * Configure observability framework with simple options */ declare function configureObservability(options: ObservabilityOptions$1): void; /** * Configure observability framework with comprehensive configuration */ declare function configureObservabilityAdvanced(config: Partial<ObservabilityConfig>): void; /** * Base Hono variables that all services using observability will have */ interface BaseHonoVariables { wideEvent: WideEventsWrapper; } /** * Generic Hono bindings interface that can be extended by consuming services */ interface BaseHonoBindings { SERVICE_NAME?: string; SERVICE_VERSION?: string; ENVIRONMENT?: string; DEBUG?: string; } /** * Utility type to extend base variables with service-specific ones */ type ExtendHonoVariables<T = {}> = BaseHonoVariables & T; /** * Utility type to extend base bindings with service-specific ones */ type ExtendHonoBindings<T = {}> = BaseHonoBindings & T; /** * Known error response patterns that we can detect and track. * * This registry provides a clean, extensible way to detect different types of * error responses and track them with appropriate context and categorization. * Each pattern includes a matcher function and a tracker function that properly * categorizes errors as expected (user/client errors) or unexpected (system errors). * * Note: Error patterns are now defined in config.ts and can be customized. */ /** * Registry of error response patterns for clean detection and tracking. * * This registry enables clean, maintainable error detection by: * - Separating error detection logic from tracking logic * - Properly categorizing errors as expected vs unexpected * - Providing extensible pattern matching for different error types * - Avoiding brittle if-statement chains * * Expected errors (unexpected: false) include: * - Validation errors (user submitted invalid data) * - Business rule violations (duplicate email, insufficient permissions) * - Authentication/authorization failures * - Rate limiting * * Unexpected errors (unexpected: true) include: * - System failures (database down, network issues) * - Programming errors (null pointer exceptions, type errors) * - Infrastructure issues (service unavailable, timeouts) * - Unhandled edge cases * * Note: Error patterns are now configurable via the observability config system. * Use observabilityConfig.addErrorPattern() to add custom patterns. */ /** * Configuration options for the observability middleware (simplified interface) * * For more advanced configuration, use configureObservabilityAdvanced() * or import and modify the observabilityConfig directly. */ interface ObservabilityOptions { /** * Custom service name (defaults to environment variable SERVICE_NAME) */ serviceName?: string; /** * Whether to automatically track HTTP request/response (defaults to true) */ autoTrackHttp?: boolean; /** * Whether to automatically detect and track error responses (defaults to true) */ autoTrackErrorResponses?: boolean; /** * Whether to enable debug logging (defaults to false) */ debug?: boolean; /** * Build info to initialize (optional) */ buildInfo?: Record<string, string | number | boolean>; } /** * Middleware that automatically sets up wide events tracking for all routes. * * This middleware: * - Initializes OpenTelemetry tracing * - Creates a WideEventsWrapper for the request * - Automatically tracks HTTP request/response details * - Detects and tracks error responses using pattern matching * - Makes the tracker available via `c.get('wideEvent')` * - Provides a simple fallback for operation type derivation * * @param options - Configuration options for the middleware * @returns Hono middleware function * * @example * ```typescript * const app = new OpenAPIHono(); * app.use('*', observabilityMiddleware()); * * // Optional: Add the error handler for exceptions that bypass validation * app.onError(createObservabilityErrorHandler()); * * // Set operation type explicitly in your route handlers: * app.post('/users/:id/change-password', async (c) => { * const tracker = c.get('wideEvent'); * tracker.setOperationType('user.change-password'); * // ... route logic * }); * ``` */ declare function observabilityMiddleware(options?: ObservabilityOptions): hono_types.MiddlewareHandler<{ Bindings: BaseHonoBindings; Variables: BaseHonoVariables; }, string, {}, Response>; /** * Create a Hono error handler that integrates with observability tracking. * * This handler should be used with app.onError() to catch exceptions * that bypass the normal response flow (like thrown errors in middleware). * * @param options - Configuration options * @returns Hono error handler function * * @example * ```typescript * const app = new OpenAPIHono(); * app.use('*', observabilityMiddleware()); * app.onError(createObservabilityErrorHandler()); * ``` */ declare function createObservabilityErrorHandler(options?: ObservabilityOptions): (error: Error, c: any) => Response; /** * Create a custom observability middleware with specific configuration. * * Use this when you need to customize the behavior of the observability * middleware for specific routes or applications. * * @param options - Custom configuration for the middleware * @returns Configured observability middleware * * @example * ```typescript * const customObservability = createObservabilityMiddleware({ * serviceName: 'my-custom-service', * autoTrackHttp: true, * autoTrackErrorResponses: true * }); * * app.use('*', customObservability); * ``` */ declare function createObservabilityMiddleware(options: ObservabilityOptions): hono_types.MiddlewareHandler<{ Bindings: BaseHonoBindings; Variables: BaseHonoVariables; }, string, {}, Response>; /** * Add a custom error response pattern to the global configuration. * * This allows you to extend the automatic error detection with domain-specific * error patterns that properly categorize errors as expected or unexpected. * * @param pattern - The error response pattern to add * * @example * ```typescript * addErrorPattern({ * name: 'CustomBusinessError', * matcher: (body) => body?.error?.type === 'BUSINESS_RULE_VIOLATION', * tracker: (wideEvent, body) => { * wideEvent.trackError({ * type: 'BusinessRuleViolation', * message: body.error.message, * businessRule: { * rule: body.error.code, * violation: body.error.details * }, * unexpected: false // Expected - business rule violation * }); * } * }); * ``` */ declare function addErrorPattern(pattern: ErrorResponsePattern): void; /** * Add custom context schema fields to a specific category. * * This allows you to extend the context schema with domain-specific fields * that will be automatically extracted and tracked. * * @param category - The context category to extend * @param fields - Array of field names to add * * @example * ```typescript * addContextFields('user', ['role', 'organization_id']); * addContextFields('operation', ['tenant_id', 'workspace_id']); * ``` */ declare function addContextFields(category: keyof ContextSchemaConfig, fields: string[]): void; /** * Utility function to extract user context from common request patterns. * * This can be used in route handlers to automatically extract and track * user information from request headers, JWT tokens, etc. * * @param request - HTTP request object * @returns User data extracted from request, or undefined if not available * * @example * ```typescript * app.get('/users', async (c) => { * const tracker = c.get('wideEvent'); * const userContext = extractUserContext(c.req.raw); * if (userContext) { * tracker.trackUser(userContext); * } * }); * ``` */ declare function extractUserContext(request: Request): { actorType: string; id?: string; } | undefined; /** * Utility function to track operation timing automatically. * * This function wraps an operation and automatically tracks its execution time. * * @param tracker - Wide events wrapper * @param operationName - Name of the operation being timed * @param fn - Function to execute and time * @returns Promise with the operation result * * @example * ```typescript * const result = await trackOperationTiming(tracker, 'database-query', async () => { * return await database.query('SELECT * FROM users'); * }); * ``` */ declare function trackOperationTiming<T>(tracker: WideEventsWrapper, operationName: string, fn: () => Promise<T>): Promise<T>; /** * Utility function to track a domain operation with automatic span management. * * This function creates a domain span and automatically handles success/error states. * Note: This is for tracking domain layer execution, not setting the main operation type. * Use setOperation() at the route level to set the main operation type. * * @param tracker - Wide events wrapper (optional) * @param aggregate - Domain aggregate name (e.g., 'user', 'order') * @param operation - Operation name (e.g., 'create', 'update') * @param fn - Function to execute within the domain operation * @returns Promise with the operation result * * @example * ```typescript * // At route level * tracker.setOperation('user.create', { domain: 'user-management', layer: 'api' }); * * // In domain layer * const result = await withDomainTracking(tracker, 'user', 'create', async () => { * // Domain logic here * return await createUser(data); * }); * ``` */ declare function withDomainTracking<T>(tracker: WideEventsWrapper | undefined, aggregate: string, operation: string, fn: () => Promise<T>): Promise<T>; /** * Utility function to track event store operations with automatic span management. * * This function creates an event store span, tracks infrastructure details, * and automatically handles success/error states. * * @param tracker - Wide events wrapper (optional) * @param streamId - Event store stream ID * @param operation - Operation name (e.g., 'append', 'read') * @param fn - Function to execute within the event store operation * @returns Promise with the operation result * * @example * ```typescript * const result = await withEventStoreTracking(tracker, 'user-123', 'append', async () => { * return await eventStore.append(streamId, events); * }); * ``` */ declare function withEventStoreTracking<T>(tracker: WideEventsWrapper | undefined, streamId: string, operation: string, fn: () => Promise<T>): Promise<T>; /** * Utility function to track validation operations with automatic error handling and categorization. * * This function creates a validation span and automatically tracks validation * errors with appropriate context and categorization. Validation errors are * automatically categorized as expected errors (unexpected: false) since they * typically represent user input issues rather than system failures. * * **Error Categorization:** * - ValidationError/ZodError: Expected (unexpected: false) - user input issues * - Other errors: Unexpected (unexpected: true) - system/programming issues * * This is for tracking validation layer execution. * Use setOperation() at the route level to set the main operation type. * * @param tracker - Wide events wrapper (optional) * @param validationType - Type of validation (e.g., 'input', 'business', 'schema') * @param fn - Function to execute validation * @returns Promise with the validation result * * @example * ```typescript * // At route level * tracker.setOperation('user.create', { domain: 'user-management', layer: 'api' }); * * // In validation layer * const validatedData = await withValidationTracking(tracker, 'input', async () => { * return await validateUserInput(data); * }); * ``` */ declare function withValidationTracking<T>(tracker: WideEventsWrapper | undefined, validationType: string, fn: () => Promise<T>): Promise<T>; /** * Utility function to track external service calls with automatic timing and error handling. * * This function creates an external service span, tracks timing, and automatically * handles success/error states. * * @param tracker - Wide events wrapper (optional) * @param serviceName - Name of the external service * @param operation - Operation being performed on the service * @param fn - Function to execute the external call * @returns Promise with the external call result * * @example * ```typescript * const result = await withExternalServiceTracking(tracker, 'user-service', 'create', async () => { * return await userService.createUser(data); * }); * ``` */ declare function withExternalServiceTracking<T>(tracker: WideEventsWrapper | undefined, serviceName: string, operation: string, fn: () => Promise<T>): Promise<T>; /** * Utility function to track database operations with automatic timing and error handling. * * This function creates a database span, tracks timing and query details, * and automatically handles success/error states. * * @param tracker - Wide events wrapper (optional) * @param operation - Database operation (e.g., 'SELECT', 'INSERT', 'UPDATE') * @param table - Database table name * @param fn - Function to execute the database operation * @returns Promise with the database operation result * * @example * ```typescript * const result = await withDatabaseTracking(tracker, 'INSERT', 'users', async () => { * return await db.insert(userData); * }); * ``` */ declare function withDatabaseTracking<T>(tracker: WideEventsWrapper | undefined, operation: string, table: string, fn: () => Promise<T>): Promise<T>; /** * Utility function to automatically track user context from various sources. * * This function attempts to extract user information from common sources * and automatically tracks it with the wide events wrapper. * * @param tracker - Wide events wrapper * @param sources - Object containing potential user data sources * @returns The tracker for method chaining * * @example * ```typescript * trackUserFromSources(tracker, { * request: c.req.raw, // HTTP request * body: requestBody, // Request body * headers: customHeaders, // Custom headers * }); * ``` */ declare function trackUserFromSources(tracker: WideEventsWrapper, sources: { request?: Request; body?: any; headers?: Record<string, string>; context?: any; }): WideEventsWrapper; /** * Utility function to create a simple operation tracker with common defaults. * * This function creates a tracker with sensible defaults for common operations * and automatically sets the operation type using the new setOperation() API. * The tracker will automatically categorize errors appropriately when they occur. * * @param entity - Entity type (e.g., 'user', 'order') * @param operation - Operation name (e.g., 'create', 'update') * @param serviceName - Service name (optional) * @returns Configured wide events wrapper with operation already set * * @example * ```typescript * const tracker = createSimpleTracker('user', 'create'); * // Operation type is automatically set to 'user.create' * // Error categorization is automatic when errors occur * ``` */ declare function createSimpleTracker(entity: string, operation: string, serviceName?: string): WideEventsWrapper; /** * Configuration for error categorization */ interface ErrorCategorizationConfig { /** Additional expected error type guards specific to the handler */ expectedErrorGuards?: Array<(error: unknown) => boolean>; /** Custom error type guards for domain-specific errors */ customExpectedErrorGuards?: Array<(error: unknown) => boolean>; } /** * Default expected error type guards that are common across handlers * These are all DeltaBase errors that are considered "expected" business/system errors * rather than unexpected programming errors */ declare const DEFAULT_EXPECTED_ERROR_GUARDS: (typeof isEventStoreAlreadyExistsError)[]; /** * Handles error tracking and categorization for command handlers * * This function provides intelligent error categorization by: * - Distinguishing between expected and unexpected errors * - Tracking errors with appropriate context * - Supporting custom error type guards for domain-specific errors * * @param error - The error that occurred * @param tracker - Wide events wrapper for tracking (optional) * @param config - Configuration for error categorization * @returns Never (always throws the error) * * @example * ```typescript * try { * await someOperation(); * } catch (error) { * handleAndTrackError(error, tracker, { * expectedErrorGuards: [isUserNotFoundError] * }); * } * ``` */ declare function handleAndTrackError(error: unknown, tracker?: WideEventsWrapper, config?: ErrorCategorizationConfig): never; /** * Type guard factory for creating domain-specific error guards * * @param ErrorClass - The error class to check for * @returns Type guard function * * @example * ```typescript * class UserNotFoundError extends Error {} * const isUserNotFoundError = createErrorGuard(UserNotFoundError); * * handleAndTrackError(error, tracker, { * expectedErrorGuards: [isUserNotFoundError] * }); * ``` */ declare function createErrorGuard<T extends Error>(ErrorClass: new (...args: any[]) => T): (error: unknown) => error is T; /** * Utility function to determine if an error should be considered expected * * @param error - The error to check * @param additionalGuards - Additional type guards to check * @returns true if the error is expected, false if unexpected * * @example * ```typescript * const isExpected = isExpectedError(error, [isUserNotFoundError]); * console.log(isExpected ? 'Expected error' : 'Unexpected error'); * ``` */ declare function isExpectedError(error: unknown, additionalGuards?: Array<(error: unknown) => boolean>): boolean; /** * Utility function to categorize errors for metrics and monitoring * * @param error - The error to categorize * @param additionalGuards - Additional type guards for expected errors * @returns Error category information * * @example * ```typescript * const category = categorizeError(error); * console.log(`Error category: ${category.category}, type: ${category.type}`); * ``` */ declare function categorizeError(error: unknown, additionalGuards?: Array<(error: unknown) => boolean>): { category: 'expected' | 'unexpected'; type: string; message: string; }; declare function initializeTracing(): void; interface TraceOptions { name: string; kind?: SpanKind; attributes?: Record<string, string | number | boolean>; parentSpan?: Span; } declare function createSpan(options: TraceOptions): Span; declare function withSpan<T>(span: Span, fn: (span: Span) => Promise<T>): Promise<T>; /** * Quick start function for new services. * * This function provides a one-line setup for basic observability in new services. * * @param serviceName - Name of your service * @param options - Optional configuration options * @returns Configured observability middleware * * @example * ```typescript * import { quickStart } from '@delta-base/observability'; * * const app = new OpenAPIHono(); * app.use('*', quickStart('my-service')); * * // With additional options * app.use('*', quickStart('my-service', { debug: true })); * ``` */ declare function quickStart(serviceName: string, options?: Omit<ObservabilityOptions, 'serviceName'>): hono_types.MiddlewareHandler<{ Bindings: BaseHonoBindings; Variables: BaseHonoVariables; }, string, {}, Response>; /** * Default export for convenient importing */ declare const _default: { middleware: typeof observabilityMiddleware; WideEventsWrapper: typeof WideEventsWrapper; createOperationTracker: typeof createOperationTracker; quickStart: typeof quickStart; configure: typeof configureObservability; configureAdvanced: typeof configureObservabilityAdvanced; config: ObservabilityConfigManager; addErrorPattern: typeof addErrorPattern; addContextFields: typeof addContextFields; withDomainTracking: typeof withDomainTracking; withEventStoreTracking: typeof withEventStoreTracking; withValidationTracking: typeof withValidationTracking; initializeBuildInfo: typeof initializeBuildInfo; setBuildInfo: typeof setBuildInfo; getBuildInfo: typeof getBuildInfo; }; export { type BaseHonoBindings, type BaseHonoVariables, type ContextSchemaConfig, DEFAULT_BUILD_INFO, DEFAULT_CONTEXT_SCHEMA, DEFAULT_ERROR_PATTERNS, DEFAULT_EXPECTED_ERROR_GUARDS, DEFAULT_OBSERVABILITY_CONFIG, type EntityData, type ErrorCategorizationConfig, type ErrorData, type ErrorResponsePattern, type ErrorTrackingConfig, type ExtendHonoBindings, type ExtendHonoVariables, type HttpTrackingConfig, type InfrastructureData, type ObservabilityConfig, ObservabilityConfigManager, type ObservabilityOptions, type OperationData, type PerformanceConfig, type TraceOptions, type TracingConfig, type UserData, WideEventsWrapper, addContextFields, addErrorPattern, categorizeError, configureObservability, configureObservabilityAdvanced, createErrorGuard, createObservabilityConfig, createObservabilityErrorHandler, createObservabilityMiddleware, createOperationTracker, createSimpleTracker, createSpan, createUserOperationTracker, _default as default, extractUserContext, getBuildInfo, handleAndTrackError, initializeBuildInfo, initializeTracing, isExpectedError, observabilityConfig, observabilityMiddleware, quickStart, setBuildInfo, trackOperationTiming, trackUserFromSources, withDatabaseTracking, withDomainTracking, withEventStoreTracking, withExternalServiceTracking, withSpan, withValidationTracking };