@naman_deep_singh/communication-core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +345 -0
  2. package/dist/cjs/abstract/BaseCircuitBreaker.js +253 -0
  3. package/dist/cjs/abstract/BaseClient.js +298 -0
  4. package/dist/cjs/abstract/BaseCompressionManager.js +377 -0
  5. package/dist/cjs/abstract/BaseConnectionPool.js +543 -0
  6. package/dist/cjs/abstract/BaseInterceptor.js +235 -0
  7. package/dist/cjs/abstract/BaseLoadBalancer.js +269 -0
  8. package/dist/cjs/abstract/BaseProtocol.js +269 -0
  9. package/dist/cjs/abstract/BaseRetryStrategy.js +255 -0
  10. package/dist/cjs/abstract/BaseSerializer.js +341 -0
  11. package/dist/cjs/abstract/BaseServiceDiscoverer.js +254 -0
  12. package/dist/cjs/abstract/BaseTimeoutManager.js +295 -0
  13. package/dist/cjs/abstract/index.js +25 -0
  14. package/dist/cjs/errors/CircuitBreakerError.js +16 -0
  15. package/dist/cjs/errors/CommunicationError.js +15 -0
  16. package/dist/cjs/errors/ConnectionError.js +15 -0
  17. package/dist/cjs/errors/DiscoveryError.js +15 -0
  18. package/dist/cjs/errors/LoadBalancerError.js +15 -0
  19. package/dist/cjs/errors/ProtocolError.js +15 -0
  20. package/dist/cjs/errors/RetryError.js +16 -0
  21. package/dist/cjs/errors/SerializationError.js +15 -0
  22. package/dist/cjs/errors/ServiceUnavailableError.js +15 -0
  23. package/dist/cjs/errors/TimeoutError.js +16 -0
  24. package/dist/cjs/errors/communicationErrorCodes.js +35 -0
  25. package/dist/cjs/errors/index.js +31 -0
  26. package/dist/cjs/index.js +38 -0
  27. package/dist/cjs/interfaces/CircuitBreaker.interface.js +6 -0
  28. package/dist/cjs/interfaces/Client.interface.js +6 -0
  29. package/dist/cjs/interfaces/Compression.interface.js +6 -0
  30. package/dist/cjs/interfaces/ConnectionPool.interface.js +6 -0
  31. package/dist/cjs/interfaces/Interceptor.interface.js +6 -0
  32. package/dist/cjs/interfaces/LoadBalancer.interface.js +2 -0
  33. package/dist/cjs/interfaces/Protocol.interface.js +6 -0
  34. package/dist/cjs/interfaces/RetryStrategy.interface.js +6 -0
  35. package/dist/cjs/interfaces/Serializer.interface.js +2 -0
  36. package/dist/cjs/interfaces/ServiceDiscovery.interface.js +6 -0
  37. package/dist/cjs/interfaces/Timeout.interface.js +6 -0
  38. package/dist/cjs/interfaces/index.js +6 -0
  39. package/dist/cjs/types/config.js +6 -0
  40. package/dist/cjs/types/events.js +6 -0
  41. package/dist/cjs/types/index.js +6 -0
  42. package/dist/cjs/types/request.js +6 -0
  43. package/dist/cjs/types/response.js +6 -0
  44. package/dist/cjs/types/service.js +6 -0
  45. package/dist/cjs/utils.js +200 -0
  46. package/dist/esm/abstract/BaseCircuitBreaker.js +249 -0
  47. package/dist/esm/abstract/BaseClient.js +294 -0
  48. package/dist/esm/abstract/BaseCompressionManager.js +373 -0
  49. package/dist/esm/abstract/BaseConnectionPool.js +539 -0
  50. package/dist/esm/abstract/BaseInterceptor.js +231 -0
  51. package/dist/esm/abstract/BaseLoadBalancer.js +265 -0
  52. package/dist/esm/abstract/BaseProtocol.js +265 -0
  53. package/dist/esm/abstract/BaseRetryStrategy.js +251 -0
  54. package/dist/esm/abstract/BaseSerializer.js +337 -0
  55. package/dist/esm/abstract/BaseServiceDiscoverer.js +250 -0
  56. package/dist/esm/abstract/BaseTimeoutManager.js +291 -0
  57. package/dist/esm/abstract/index.js +11 -0
  58. package/dist/esm/errors/CircuitBreakerError.js +12 -0
  59. package/dist/esm/errors/CommunicationError.js +11 -0
  60. package/dist/esm/errors/ConnectionError.js +11 -0
  61. package/dist/esm/errors/DiscoveryError.js +11 -0
  62. package/dist/esm/errors/LoadBalancerError.js +11 -0
  63. package/dist/esm/errors/ProtocolError.js +11 -0
  64. package/dist/esm/errors/RetryError.js +12 -0
  65. package/dist/esm/errors/SerializationError.js +11 -0
  66. package/dist/esm/errors/ServiceUnavailableError.js +11 -0
  67. package/dist/esm/errors/TimeoutError.js +12 -0
  68. package/dist/esm/errors/communicationErrorCodes.js +32 -0
  69. package/dist/esm/errors/index.js +17 -0
  70. package/dist/esm/index.js +18 -0
  71. package/dist/esm/interfaces/CircuitBreaker.interface.js +5 -0
  72. package/dist/esm/interfaces/Client.interface.js +5 -0
  73. package/dist/esm/interfaces/Compression.interface.js +5 -0
  74. package/dist/esm/interfaces/ConnectionPool.interface.js +5 -0
  75. package/dist/esm/interfaces/Interceptor.interface.js +5 -0
  76. package/dist/esm/interfaces/LoadBalancer.interface.js +1 -0
  77. package/dist/esm/interfaces/Protocol.interface.js +5 -0
  78. package/dist/esm/interfaces/RetryStrategy.interface.js +5 -0
  79. package/dist/esm/interfaces/Serializer.interface.js +1 -0
  80. package/dist/esm/interfaces/ServiceDiscovery.interface.js +5 -0
  81. package/dist/esm/interfaces/Timeout.interface.js +5 -0
  82. package/dist/esm/interfaces/index.js +5 -0
  83. package/dist/esm/types/config.js +5 -0
  84. package/dist/esm/types/events.js +5 -0
  85. package/dist/esm/types/index.js +5 -0
  86. package/dist/esm/types/request.js +5 -0
  87. package/dist/esm/types/response.js +5 -0
  88. package/dist/esm/types/service.js +5 -0
  89. package/dist/esm/utils.js +193 -0
  90. package/dist/types/abstract/BaseCircuitBreaker.d.ts +167 -0
  91. package/dist/types/abstract/BaseClient.d.ts +197 -0
  92. package/dist/types/abstract/BaseCompressionManager.d.ts +180 -0
  93. package/dist/types/abstract/BaseConnectionPool.d.ts +210 -0
  94. package/dist/types/abstract/BaseInterceptor.d.ts +150 -0
  95. package/dist/types/abstract/BaseLoadBalancer.d.ts +167 -0
  96. package/dist/types/abstract/BaseProtocol.d.ts +163 -0
  97. package/dist/types/abstract/BaseRetryStrategy.d.ts +130 -0
  98. package/dist/types/abstract/BaseSerializer.d.ts +181 -0
  99. package/dist/types/abstract/BaseServiceDiscoverer.d.ts +161 -0
  100. package/dist/types/abstract/BaseTimeoutManager.d.ts +145 -0
  101. package/dist/types/abstract/index.d.ts +11 -0
  102. package/dist/types/errors/CircuitBreakerError.d.ts +8 -0
  103. package/dist/types/errors/CommunicationError.d.ts +10 -0
  104. package/dist/types/errors/ConnectionError.d.ts +9 -0
  105. package/dist/types/errors/DiscoveryError.d.ts +9 -0
  106. package/dist/types/errors/LoadBalancerError.d.ts +9 -0
  107. package/dist/types/errors/ProtocolError.d.ts +9 -0
  108. package/dist/types/errors/RetryError.d.ts +11 -0
  109. package/dist/types/errors/SerializationError.d.ts +9 -0
  110. package/dist/types/errors/ServiceUnavailableError.d.ts +12 -0
  111. package/dist/types/errors/TimeoutError.d.ts +11 -0
  112. package/dist/types/errors/communicationErrorCodes.d.ts +27 -0
  113. package/dist/types/errors/index.d.ts +11 -0
  114. package/dist/types/index.d.ts +13 -0
  115. package/dist/types/interfaces/CircuitBreaker.interface.d.ts +150 -0
  116. package/dist/types/interfaces/Client.interface.d.ts +153 -0
  117. package/dist/types/interfaces/Compression.interface.d.ts +190 -0
  118. package/dist/types/interfaces/ConnectionPool.interface.d.ts +191 -0
  119. package/dist/types/interfaces/Interceptor.interface.d.ts +220 -0
  120. package/dist/types/interfaces/LoadBalancer.interface.d.ts +153 -0
  121. package/dist/types/interfaces/Protocol.interface.d.ts +117 -0
  122. package/dist/types/interfaces/RetryStrategy.interface.d.ts +160 -0
  123. package/dist/types/interfaces/Serializer.interface.d.ts +176 -0
  124. package/dist/types/interfaces/ServiceDiscovery.interface.d.ts +189 -0
  125. package/dist/types/interfaces/Timeout.interface.d.ts +135 -0
  126. package/dist/types/interfaces/index.d.ts +15 -0
  127. package/dist/types/types/config.d.ts +540 -0
  128. package/dist/types/types/events.d.ts +204 -0
  129. package/dist/types/types/index.d.ts +9 -0
  130. package/dist/types/types/request.d.ts +143 -0
  131. package/dist/types/types/response.d.ts +155 -0
  132. package/dist/types/types/service.d.ts +279 -0
  133. package/dist/types/utils.d.ts +179 -0
  134. package/package.json +88 -0
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Abstract base service discoverer implementation
3
+ * @packageDocumentation
4
+ */
5
+ import type { IServiceDiscoverer } from '../interfaces/ServiceDiscovery.interface.js';
6
+ import type { ServiceInstance, ServiceDiscoveryResult, ServiceInstanceFilter, HealthCheckResult, WatchCallback, UnwatchFunction, ServiceRegistryConfig } from '../types/service.js';
7
+ /**
8
+ * Abstract base service discoverer implementation
9
+ * Provides common functionality for all service discovery implementations
10
+ */
11
+ export declare abstract class BaseServiceDiscoverer implements IServiceDiscoverer {
12
+ /** Discovery type */
13
+ readonly type: string;
14
+ /** Discovery configuration */
15
+ config: ServiceRegistryConfig;
16
+ /** Whether discovery is currently active */
17
+ isActive: boolean;
18
+ /** Last discovery timestamp */
19
+ lastDiscoveryTime?: number;
20
+ /** Total services discovered */
21
+ totalServicesDiscovered: number;
22
+ /** Total instances discovered */
23
+ totalInstancesDiscovered: number;
24
+ /** Service cache */
25
+ protected cache: Map<string, ServiceInstance[]>;
26
+ /** Cache timestamps */
27
+ protected cacheTimestamps: Map<string, number>;
28
+ /** Watch callbacks */
29
+ protected watchers: Map<string, Set<WatchCallback>>;
30
+ /** Discovery statistics */
31
+ protected stats: {
32
+ totalResolves: number;
33
+ totalWatches: number;
34
+ cacheHits: number;
35
+ cacheMisses: number;
36
+ cacheHitRate: number;
37
+ averageResolveTime: number;
38
+ totalResolveTime: number;
39
+ lastError?: string;
40
+ uptime: number;
41
+ startTime: number;
42
+ };
43
+ /**
44
+ * Create a new base service discoverer instance
45
+ * @param type Discovery type
46
+ * @param config Discovery configuration
47
+ */
48
+ constructor(type: string, config: ServiceRegistryConfig);
49
+ /**
50
+ * Initialize service discoverer
51
+ */
52
+ protected initialize(): void;
53
+ /**
54
+ * Resolve service instances for a given service name
55
+ * @param serviceName Service name to resolve
56
+ * @param filter Optional filter for instances
57
+ * @returns Promise resolving to service discovery result
58
+ */
59
+ abstract resolve(serviceName: string, filter?: ServiceInstanceFilter): Promise<ServiceDiscoveryResult>;
60
+ /**
61
+ * Resolve all instances for multiple services
62
+ * @param serviceNames Array of service names
63
+ * @returns Promise resolving to map of service names to instances
64
+ */
65
+ resolveAll(serviceNames: string[]): Promise<Map<string, ServiceInstance[]>>;
66
+ /**
67
+ * Watch for changes to service instances
68
+ * @param serviceName Service name to watch
69
+ * @param callback Callback function for changes
70
+ * @returns Unwatch function
71
+ */
72
+ watch(serviceName: string, callback: WatchCallback): UnwatchFunction;
73
+ /**
74
+ * Stop watching a service
75
+ * @param serviceName Service name to stop watching
76
+ */
77
+ unwatch(serviceName: string): void;
78
+ /**
79
+ * Stop watching all services
80
+ */
81
+ unwatchAll(): void;
82
+ /**
83
+ * Perform health check on service instances
84
+ * @param serviceName Optional service name to check
85
+ * @returns Promise resolving to health check results
86
+ */
87
+ abstract healthCheck(serviceName?: string): Promise<Map<string, HealthCheckResult[]>>;
88
+ /**
89
+ * Get cached service instances
90
+ * @param serviceName Service name
91
+ * @returns Cached instances or empty array
92
+ */
93
+ getCachedInstances(serviceName: string): ServiceInstance[];
94
+ /**
95
+ * Clear cache for a service
96
+ * @param serviceName Service name
97
+ */
98
+ clearCache(serviceName?: string): void;
99
+ /**
100
+ * Refresh cache for a service
101
+ * @param serviceName Service name
102
+ * @returns Promise resolving when cache is refreshed
103
+ */
104
+ refreshCache(serviceName?: string): Promise<void>;
105
+ /**
106
+ * Check if cache is valid for a service
107
+ * @param serviceName Service name
108
+ * @returns True if cache is valid
109
+ */
110
+ protected isCacheValid(serviceName: string): boolean;
111
+ /**
112
+ * Update cache for a service
113
+ * @param serviceName Service name
114
+ * @param instances Service instances
115
+ */
116
+ protected updateCache(serviceName: string, instances: ServiceInstance[]): void;
117
+ /**
118
+ * Notify watchers of service changes
119
+ * @param serviceName Service name
120
+ * @param instances Updated instances
121
+ */
122
+ protected notifyWatchers(serviceName: string, instances: ServiceInstance[]): void;
123
+ /**
124
+ * Get service discovery statistics
125
+ */
126
+ getStats(): {
127
+ totalResolves: number;
128
+ totalWatches: number;
129
+ cacheHits: number;
130
+ cacheMisses: number;
131
+ cacheHitRate: number;
132
+ averageResolveTime: number;
133
+ lastError?: string;
134
+ uptime: number;
135
+ };
136
+ /**
137
+ * Reset service discovery statistics
138
+ */
139
+ resetStats(): void;
140
+ /**
141
+ * Update service discovery configuration
142
+ * @param config New configuration
143
+ */
144
+ updateConfig(config: Partial<ServiceRegistryConfig>): void;
145
+ /**
146
+ * Health check for the service discoverer itself
147
+ */
148
+ healthCheckSelf(): Promise<{
149
+ healthy: boolean;
150
+ message?: string;
151
+ details?: Record<string, unknown>;
152
+ }>;
153
+ /**
154
+ * Close/cleanup service discovery resources
155
+ */
156
+ close(): Promise<void>;
157
+ /**
158
+ * Hook for cleanup logic
159
+ */
160
+ protected onClose(): Promise<void>;
161
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Abstract base timeout manager implementation
3
+ * @packageDocumentation
4
+ */
5
+ import type { ITimeoutManager, TimeoutOptions } from '../interfaces/Timeout.interface.js';
6
+ import type { TimeoutConfig } from '../types/config.js';
7
+ /**
8
+ * Abstract base timeout manager implementation
9
+ * Provides common functionality for timeout management
10
+ */
11
+ export declare abstract class BaseTimeoutManager implements ITimeoutManager {
12
+ /** Timeout manager name */
13
+ readonly name: string;
14
+ /** Timeout configuration */
15
+ config: TimeoutConfig;
16
+ /** Operation-specific timeouts */
17
+ protected operationTimeouts: Map<string, number>;
18
+ /** Timeout statistics */
19
+ protected stats: {
20
+ totalOperations: number;
21
+ timedOutOperations: number;
22
+ totalOperationTime: number;
23
+ averageOperationTime: number;
24
+ timeoutRate: number;
25
+ perOperationStats: Map<string, {
26
+ calls: number;
27
+ timeouts: number;
28
+ totalTime: number;
29
+ averageTime: number;
30
+ }>;
31
+ };
32
+ /**
33
+ * Create a new base timeout manager instance
34
+ * @param name Timeout manager name
35
+ * @param config Timeout configuration
36
+ */
37
+ constructor(name: string, config: TimeoutConfig);
38
+ /**
39
+ * Initialize timeout manager
40
+ */
41
+ protected initialize(): void;
42
+ /**
43
+ * Execute a function with timeout
44
+ * @param fn Function to execute
45
+ * @param options Timeout options
46
+ * @returns Promise resolving to function result
47
+ * @throws {CommunicationError} If timeout occurs
48
+ */
49
+ execute<T>(fn: () => Promise<T>, options?: TimeoutOptions): Promise<T>;
50
+ /**
51
+ * Create a timeout promise
52
+ * @param timeout Timeout in milliseconds
53
+ * @param message Error message
54
+ * @returns Promise that rejects after timeout
55
+ */
56
+ createTimeout(timeout: number, message?: string): Promise<never>;
57
+ /**
58
+ * Create an abort signal for timeout
59
+ * @param timeout Timeout in milliseconds
60
+ * @returns AbortSignal
61
+ */
62
+ createAbortSignal(timeout: number): AbortSignal;
63
+ /**
64
+ * Execute multiple promises with timeout
65
+ * @param promises Array of promises
66
+ * @param timeout Timeout in milliseconds
67
+ * @returns Promise that resolves when first promise resolves or times out
68
+ */
69
+ race<T>(promises: Promise<T>[], timeout: number): Promise<T>;
70
+ /**
71
+ * Delay execution for specified time
72
+ * @param delay Delay in milliseconds
73
+ * @returns Promise that resolves after delay
74
+ */
75
+ delay(delay: number): Promise<void>;
76
+ /**
77
+ * Set operation timeout
78
+ * @param operation Operation identifier
79
+ * @param timeout Timeout in milliseconds
80
+ */
81
+ setOperationTimeout(operation: string, timeout: number): void;
82
+ /**
83
+ * Get operation timeout
84
+ * @param operation Operation identifier
85
+ * @returns Timeout in milliseconds or undefined
86
+ */
87
+ getOperationTimeout(operation: string): number | undefined;
88
+ /**
89
+ * Record successful operation
90
+ * @param operation Operation name
91
+ * @param duration Duration in milliseconds
92
+ */
93
+ protected recordSuccess(operation: string, duration: number): void;
94
+ /**
95
+ * Record timed out operation
96
+ * @param operation Operation name
97
+ * @param duration Duration in milliseconds
98
+ */
99
+ protected recordTimeout(operation: string, duration: number): void;
100
+ /**
101
+ * Record failed operation (not timeout)
102
+ * @param operation Operation name
103
+ * @param duration Duration in milliseconds
104
+ * @param error Error that occurred
105
+ */
106
+ protected recordFailure(operation: string, duration: number, error: Error): void;
107
+ /**
108
+ * Update operation-specific statistics
109
+ * @param operation Operation name
110
+ * @param duration Duration in milliseconds
111
+ * @param isTimeout Whether operation timed out
112
+ */
113
+ protected updateOperationStats(operation: string, duration: number, isTimeout: boolean): void;
114
+ /**
115
+ * Update timeout configuration
116
+ * @param config New configuration
117
+ */
118
+ updateConfig(config: Partial<TimeoutConfig>): void;
119
+ /**
120
+ * Get timeout statistics
121
+ */
122
+ getStats(): {
123
+ totalOperations: number;
124
+ timedOutOperations: number;
125
+ averageOperationTime: number;
126
+ timeoutRate: number;
127
+ perOperationStats: Record<string, {
128
+ calls: number;
129
+ timeouts: number;
130
+ averageTime: number;
131
+ }>;
132
+ };
133
+ /**
134
+ * Reset timeout statistics
135
+ */
136
+ resetStats(): void;
137
+ /**
138
+ * Health check for timeout manager
139
+ */
140
+ healthCheck(): {
141
+ healthy: boolean;
142
+ message?: string;
143
+ details?: Record<string, unknown>;
144
+ };
145
+ }
@@ -0,0 +1,11 @@
1
+ export { BaseProtocol } from './BaseProtocol.js';
2
+ export { BaseClient } from './BaseClient.js';
3
+ export { BaseCircuitBreaker } from './BaseCircuitBreaker.js';
4
+ export { BaseRetryStrategy } from './BaseRetryStrategy.js';
5
+ export { BaseLoadBalancer } from './BaseLoadBalancer.js';
6
+ export { BaseSerializer } from './BaseSerializer.js';
7
+ export { BaseServiceDiscoverer } from './BaseServiceDiscoverer.js';
8
+ export { BaseInterceptor } from './BaseInterceptor.js';
9
+ export { BaseTimeoutManager } from './BaseTimeoutManager.js';
10
+ export { BaseConnectionPool } from './BaseConnectionPool.js';
11
+ export { BaseCompressionManager } from './BaseCompressionManager.js';
@@ -0,0 +1,8 @@
1
+ import { CommunicationError } from "./CommunicationError.js";
2
+ /**
3
+ * Circuit breaker error - when circuit is open
4
+ */
5
+ export declare class CircuitBreakerError extends CommunicationError {
6
+ constructor(details?: unknown, cause?: Error);
7
+ }
8
+ export type CircuitBreakerErrorType = CircuitBreakerError;
@@ -0,0 +1,10 @@
1
+ import { AppError } from "@naman_deep_singh/errors";
2
+ import { type CommunicationErrorCode } from "./communicationErrorCodes.js";
3
+ /**
4
+ * Base communication error class
5
+ * Extends AppError from errors package
6
+ */
7
+ export declare class CommunicationError extends AppError {
8
+ constructor(code: CommunicationErrorCode, statusCode?: number, details?: unknown, cause?: Error);
9
+ }
10
+ export type CommunicationErrorType = CommunicationError;
@@ -0,0 +1,9 @@
1
+ import { CommunicationError } from "./CommunicationError.js";
2
+ import { type CommunicationErrorCode } from "./communicationErrorCodes.js";
3
+ /**
4
+ * Connection error - when connection fails
5
+ */
6
+ export declare class ConnectionError extends CommunicationError {
7
+ constructor(code?: CommunicationErrorCode, details?: unknown, cause?: Error);
8
+ }
9
+ export type ConnectionErrorType = ConnectionError;
@@ -0,0 +1,9 @@
1
+ import { CommunicationError } from "./CommunicationError.js";
2
+ import { type CommunicationErrorCode } from "./communicationErrorCodes.js";
3
+ /**
4
+ * Service discovery error
5
+ */
6
+ export declare class DiscoveryError extends CommunicationError {
7
+ constructor(code?: CommunicationErrorCode, details?: unknown, cause?: Error);
8
+ }
9
+ export type DiscoveryErrorType = DiscoveryError;
@@ -0,0 +1,9 @@
1
+ import { CommunicationError } from "./CommunicationError.js";
2
+ import { type CommunicationErrorCode } from "./communicationErrorCodes.js";
3
+ /**
4
+ * Load balancer error - when load balancing fails
5
+ */
6
+ export declare class LoadBalancerError extends CommunicationError {
7
+ constructor(code?: CommunicationErrorCode, details?: unknown, cause?: Error);
8
+ }
9
+ export type LoadBalancerErrorType = LoadBalancerError;
@@ -0,0 +1,9 @@
1
+ import { CommunicationError } from "./CommunicationError.js";
2
+ import { type CommunicationErrorCode } from "./communicationErrorCodes.js";
3
+ /**
4
+ * Protocol error - when protocol communication fails
5
+ */
6
+ export declare class ProtocolError extends CommunicationError {
7
+ constructor(code?: CommunicationErrorCode, details?: unknown, cause?: Error);
8
+ }
9
+ export type ProtocolErrorType = ProtocolError;
@@ -0,0 +1,11 @@
1
+ import { CommunicationError } from "./CommunicationError.js";
2
+ /**
3
+ * Retry exhausted error - when all retry attempts fail
4
+ */
5
+ export declare class RetryError extends CommunicationError {
6
+ constructor(details?: {
7
+ attempts: number;
8
+ lastError?: Error;
9
+ }, cause?: Error);
10
+ }
11
+ export type RetryErrorType = RetryError;
@@ -0,0 +1,9 @@
1
+ import { CommunicationError } from "./CommunicationError.js";
2
+ import { type CommunicationErrorCode } from "./communicationErrorCodes.js";
3
+ /**
4
+ * Serialization error - when serialization/deserialization fails
5
+ */
6
+ export declare class SerializationError extends CommunicationError {
7
+ constructor(code?: CommunicationErrorCode, details?: unknown, cause?: Error);
8
+ }
9
+ export type SerializationErrorType = SerializationError;
@@ -0,0 +1,12 @@
1
+ import { ServiceUnavailableError as BaseServiceUnavailableError } from '@naman_deep_singh/errors';
2
+ /**
3
+ * Service unavailable error for communication layer
4
+ * Extends the existing ServiceUnavailableError
5
+ */
6
+ export declare class ServiceUnavailableError extends BaseServiceUnavailableError {
7
+ constructor(details?: {
8
+ service: string;
9
+ reason?: string;
10
+ }, cause?: Error);
11
+ }
12
+ export type ServiceUnavailableErrorType = ServiceUnavailableError;
@@ -0,0 +1,11 @@
1
+ import { CommunicationError } from "./CommunicationError.js";
2
+ /**
3
+ * Timeout error - when operation times out
4
+ */
5
+ export declare class TimeoutError extends CommunicationError {
6
+ constructor(details?: {
7
+ timeout: number;
8
+ operation: string;
9
+ }, cause?: Error);
10
+ }
11
+ export type TimeoutErrorType = TimeoutError;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Communication-specific error codes
3
+ * Extends the existing ERROR_CODES
4
+ */
5
+ export declare const COMMUNICATION_ERROR_CODES: {
6
+ readonly PROTOCOL_ERROR: "Protocol communication failed";
7
+ readonly HTTP_PROTOCOL_ERROR: "HTTP protocol error occurred";
8
+ readonly GRPC_PROTOCOL_ERROR: "gRPC protocol error occurred";
9
+ readonly WEBSOCKET_PROTOCOL_ERROR: "WebSocket protocol error occurred";
10
+ readonly DISCOVERY_ERROR: "Service discovery failed";
11
+ readonly SERVICE_NOT_FOUND: "Service not found in registry";
12
+ readonly NO_AVAILABLE_INSTANCES: "No available service instances";
13
+ readonly DISCOVERY_TIMEOUT: "Service discovery timed out";
14
+ readonly CIRCUIT_BREAKER_OPEN: "Circuit breaker is open, request blocked";
15
+ readonly CIRCUIT_BREAKER_ERROR: "Circuit breaker encountered an error";
16
+ readonly RETRY_EXHAUSTED: "Retry attempts exhausted";
17
+ readonly BULKHEAD_FULL: "Bulkhead is full, request rejected";
18
+ readonly TIMEOUT_EXHAUSTED: "Operation timeout exceeded";
19
+ readonly LOAD_BALANCER_ERROR: "Load balancing failed";
20
+ readonly NO_HEALTHY_INSTANCES: "No healthy instances available";
21
+ readonly SERIALIZATION_ERROR: "Serialization failed";
22
+ readonly DESERIALIZATION_ERROR: "Deserialization failed";
23
+ readonly CONNECTION_ERROR: "Connection failed";
24
+ readonly CONNECTION_TIMEOUT: "Connection timeout";
25
+ readonly CONNECTION_REFUSED: "Connection refused";
26
+ };
27
+ export type CommunicationErrorCode = typeof COMMUNICATION_ERROR_CODES[keyof typeof COMMUNICATION_ERROR_CODES];
@@ -0,0 +1,11 @@
1
+ export { CircuitBreakerError, type CircuitBreakerErrorType } from "./CircuitBreakerError.js";
2
+ export { CommunicationError, type CommunicationErrorType } from "./CommunicationError.js";
3
+ export { ConnectionError, type ConnectionErrorType } from "./ConnectionError.js";
4
+ export { DiscoveryError, type DiscoveryErrorType } from "./DiscoveryError.js";
5
+ export { LoadBalancerError, type LoadBalancerErrorType } from "./LoadBalancerError.js";
6
+ export { ProtocolError, type ProtocolErrorType } from "./ProtocolError.js";
7
+ export { RetryError, type RetryErrorType } from "./RetryError.js";
8
+ export { SerializationError, type SerializationErrorType } from "./SerializationError.js";
9
+ export { ServiceUnavailableError, type ServiceUnavailableErrorType } from "./ServiceUnavailableError.js";
10
+ export { TimeoutError, type TimeoutErrorType } from "./TimeoutError.js";
11
+ export { COMMUNICATION_ERROR_CODES, type CommunicationErrorCode } from "./communicationErrorCodes.js";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Communication Core Package
3
+ * @packageDocumentation
4
+ *
5
+ * Core interfaces and abstract implementations for service-to-service communication.
6
+ * This package provides the foundation for communication protocols, resilience patterns,
7
+ * service discovery, load balancing, and interceptors.
8
+ */
9
+ export * from './interfaces/index.js';
10
+ export * from './abstract/index.js';
11
+ export * from './types/index.js';
12
+ export * from './errors/index.js';
13
+ export { TimeoutUtils, ConnectionPoolUtils, CompressionUtils, type Connection, type BaseConnection, } from './utils.js';
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Circuit breaker interface for communication layer
3
+ * @packageDocumentation
4
+ */
5
+ import type { CommunicationError } from '../errors/CommunicationError.js';
6
+ import type { CircuitBreakerConfig, CircuitBreakerState } from '../types/config.js';
7
+ import type { CircuitBreakerEvent } from '../types/events.js';
8
+ /**
9
+ * Circuit breaker interface for resilience pattern
10
+ * Prevents cascading failures by stopping requests when failures exceed threshold
11
+ */
12
+ export interface ICircuitBreaker {
13
+ /** Circuit breaker name */
14
+ readonly name: string;
15
+ /** Current state */
16
+ readonly state: CircuitBreakerState;
17
+ /** Circuit breaker configuration */
18
+ readonly config: CircuitBreakerConfig;
19
+ /** Failure count */
20
+ readonly failureCount: number;
21
+ /** Success count */
22
+ readonly successCount: number;
23
+ /** Last failure timestamp */
24
+ readonly lastFailureTime?: number;
25
+ /** Last success timestamp */
26
+ readonly lastSuccessTime?: number;
27
+ /** Time when circuit will attempt to reset */
28
+ readonly nextResetTime?: number;
29
+ /**
30
+ * Execute a function with circuit breaker protection
31
+ * @param fn Function to execute
32
+ * @returns Promise resolving to function result
33
+ * @throws {CommunicationError} If circuit is open or function fails
34
+ */
35
+ execute<T>(fn: () => Promise<T>): Promise<T>;
36
+ /**
37
+ * Execute a function with circuit breaker protection and context
38
+ * @param fn Function to execute
39
+ * @param context Execution context
40
+ * @returns Promise resolving to function result
41
+ */
42
+ executeWithContext<T, C = unknown>(fn: (context: C) => Promise<T>, context: C): Promise<T>;
43
+ /**
44
+ * Manually trip the circuit breaker to open state
45
+ * @param error Error that caused the trip
46
+ */
47
+ trip(error?: CommunicationError): void;
48
+ /**
49
+ * Manually reset the circuit breaker to closed state
50
+ */
51
+ reset(): void;
52
+ /**
53
+ * Check if circuit breaker is currently open
54
+ */
55
+ isOpen(): boolean;
56
+ /**
57
+ * Check if circuit breaker is currently closed
58
+ */
59
+ isClosed(): boolean;
60
+ /**
61
+ * Check if circuit breaker is in half-open state
62
+ */
63
+ isHalfOpen(): boolean;
64
+ /**
65
+ * Record a successful execution
66
+ */
67
+ recordSuccess(): void;
68
+ /**
69
+ * Record a failed execution
70
+ * @param error Error that occurred
71
+ */
72
+ recordFailure(error: CommunicationError): void;
73
+ /**
74
+ * Get circuit breaker statistics
75
+ */
76
+ getStats(): {
77
+ totalExecutions: number;
78
+ totalSuccesses: number;
79
+ totalFailures: number;
80
+ successRate: number;
81
+ failureRate: number;
82
+ totalTimeOpen: number;
83
+ totalTimeClosed: number;
84
+ lastStateChange: number;
85
+ };
86
+ /**
87
+ * Reset circuit breaker statistics
88
+ */
89
+ resetStats(): void;
90
+ /**
91
+ * Update circuit breaker configuration
92
+ * @param config New configuration
93
+ */
94
+ updateConfig(config: Partial<CircuitBreakerConfig>): void;
95
+ /**
96
+ * Health check for the circuit breaker
97
+ */
98
+ healthCheck(): {
99
+ healthy: boolean;
100
+ state: CircuitBreakerState;
101
+ message?: string;
102
+ details?: Record<string, unknown>;
103
+ };
104
+ /**
105
+ * Event emitter for circuit breaker events
106
+ */
107
+ readonly events?: {
108
+ /**
109
+ * Subscribe to circuit breaker events
110
+ * @param event Event name or array of events
111
+ * @param listener Event listener
112
+ */
113
+ on(event: string | string[], listener: (event: CircuitBreakerEvent) => void): void;
114
+ /**
115
+ * Unsubscribe from circuit breaker events
116
+ * @param event Event name or array of events
117
+ * @param listener Event listener
118
+ */
119
+ off(event: string | string[], listener: (event: CircuitBreakerEvent) => void): void;
120
+ };
121
+ }
122
+ /**
123
+ * Circuit breaker factory interface
124
+ */
125
+ export interface ICircuitBreakerFactory {
126
+ /**
127
+ * Create a new circuit breaker instance
128
+ * @param name Circuit breaker name
129
+ * @param config Circuit breaker configuration
130
+ * @returns New circuit breaker instance
131
+ */
132
+ create(name: string, config?: Partial<CircuitBreakerConfig>): ICircuitBreaker;
133
+ /**
134
+ * Get an existing circuit breaker instance
135
+ * @param name Circuit breaker name
136
+ */
137
+ get(name: string): ICircuitBreaker | undefined;
138
+ /**
139
+ * Get all circuit breaker instances
140
+ */
141
+ getAll(): ICircuitBreaker[];
142
+ /**
143
+ * Reset all circuit breaker instances
144
+ */
145
+ resetAll(): void;
146
+ /**
147
+ * Close all circuit breaker instances
148
+ */
149
+ closeAll(): Promise<void>;
150
+ }