Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | 1x 1x 268x 268x 268x 268x 268x 268x 268x 268x 1x 1x 1x 5x 5x 5x 1x 1x 1x 53x 53x 53x 1x 1x 1x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 1x 527x 527x 527x 527x 527x 527x 191x 13x 13x 178x 178x 165x 161x 158x 158x 158x 191x 527x 527x 527x 527x 527x 527x 527x 527x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 305x 465x 465x 465x 465x 465x 214x 424x 251x 251x 251x 251x 202x 251x 63x 63x 188x 251x 251x 251x 251x 251x 160x 465x 305x 527x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 465x 527x 63x 10x 10x 63x 3x 3x 63x 4x 4x 63x 1x 1x 63x 63x 1x 1x 1x 1x 1x 63x 1x 1x 1x 1x 1x 1x 1x 63x 43x 43x 43x 43x 43x 43x 63x 527x 188x 188x 527x 210x 210x 210x 210x 27x 27x 183x 210x 527x 156x 156x 156x 156x 156x 156x 156x 156x 156x 134x 156x 527x 54x 54x 54x 54x 54x 54x 1x 1x 54x 6x 6x 6x 6x 54x 42x 54x 527x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 9x 9x 527x 193x 193x 193x 193x 193x 193x 527x | // Logger will be initialized in subclasses as needed
export interface RetryOptions {
maxRetries?: number;
baseDelay?: number;
maxDelay?: number;
backoffMultiplier?: number;
retryCondition?: (error: Error) => boolean;
}
export interface ServiceOptions {
retryOptions?: RetryOptions;
timeout?: number;
}
export class ServiceError extends Error {
constructor(
message: string,
public code?: string,
public statusCode?: number,
public originalError?: Error,
) {
super(message);
this.name = "ServiceError";
}
}
export class NetworkError extends ServiceError {
constructor(message: string, originalError?: Error) {
super(message, "NETWORK_ERROR", undefined, originalError);
this.name = "NetworkError";
}
}
export class ValidationError extends ServiceError {
constructor(message: string, originalError?: Error) {
super(message, "VALIDATION_ERROR", 400, originalError);
this.name = "ValidationError";
}
}
export class NotFoundError extends ServiceError {
constructor(message: string, originalError?: Error) {
super(message, "NOT_FOUND", 404, originalError);
this.name = "NotFoundError";
}
}
export class UnauthorizedError extends ServiceError {
constructor(message: string, originalError?: Error) {
super(message, "UNAUTHORIZED", 401, originalError);
this.name = "UnauthorizedError";
}
}
export abstract class BaseService {
protected defaultRetryOptions: RetryOptions = {
maxRetries: 3,
baseDelay: 1000,
maxDelay: 30000,
backoffMultiplier: 2,
retryCondition: (error: Error) => {
// Do not retry specific client-side or unrecoverable errors by their name
if (error.name === 'NotFoundError' || error.name === 'ValidationError' || error.name === 'UnauthorizedError') {
return false;
}
// Retry on network errors, timeout errors, or server errors (5xx)
// NetworkError name check is also good here.
return !!(
error.name === 'NetworkError' ||
(error as Error & { code?: string }).code === "NETWORK_ERROR" || // For generic errors that are network related
(error as Error & { code?: string }).code === "TIMEOUT" ||
((error as Error & { statusCode?: number }).statusCode &&
(error as Error & { statusCode?: number }).statusCode! >= 500) ||
// Add a condition to retry generic errors that don't match above but aren't explicitly excluded
(error.name !== 'NotFoundError' && error.name !== 'ValidationError' && error.name !== 'UnauthorizedError' &&
error.name !== 'ServiceError' && !((error as Error & { statusCode?: number }).statusCode && (error as Error & { statusCode?: number }).statusCode! < 500 && (error as Error & { statusCode?: number }).statusCode! >= 400))
);
},
};
constructor(protected options: ServiceOptions = {}) {
this.options = {
retryOptions: { ...this.defaultRetryOptions, ...options.retryOptions },
timeout: options.timeout || 30000,
};
}
protected async withRetry<T>(
operation: () => Promise<T>,
operationName: string,
customRetryOptions?: RetryOptions,
): Promise<T> {
const retryOptions = {
...this.defaultRetryOptions,
...this.options.retryOptions,
...customRetryOptions,
};
let lastError: Error;
let attempt = 0;
while (attempt <= (retryOptions.maxRetries || 3)) {
try {
const result = await this.withTimeout(
operation(),
this.options.timeout,
);
return result;
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
attempt++;
const shouldRetry =
attempt <= (retryOptions.maxRetries || 3) &&
(retryOptions.retryCondition?.(lastError) ?? true);
if (!shouldRetry) {
throw this.normalizeError(lastError, operationName);
}
const delay = Math.min(
(retryOptions.baseDelay || 1000) *
Math.pow(retryOptions.backoffMultiplier || 2, attempt - 1),
retryOptions.maxDelay || 30000,
);
await this.delay(delay);
}
}
throw this.normalizeError(lastError!, operationName);
}
protected async withTimeout<T>(
promise: Promise<T>,
timeoutMs?: number,
): Promise<T> {
const timeout = timeoutMs || this.options.timeout || 30000;
return Promise.race([
promise,
new Promise<never>((_, reject) =>
setTimeout(
() => reject(new ServiceError("Operation timed out", "TIMEOUT")),
timeout,
),
),
]);
}
protected normalizeError(error: Error, operationName: string): ServiceError {
// Check by name first to preserve specific error types if they are already set
if (error.name === 'NotFoundError') {
return new NotFoundError(error.message, error);
}
if (error.name === 'ValidationError') {
return new ValidationError(error.message, error);
}
if (error.name === 'NetworkError') {
return new NetworkError(error.message, error);
}
if (error.name === 'UnauthorizedError') {
return new UnauthorizedError(error.message, error);
}
if (error.name === 'ServiceError' && (error as ServiceError).code) {
return error as ServiceError;
}
// Handle common patterns for generic Error instances and wrap them appropriately
if (error.message?.includes("fetch") || error.message?.toLowerCase().includes("network error")) {
return new NetworkError(
`Network error during ${operationName}: ${error.message}`,
error,
);
}
if (error.message?.toLowerCase().includes("timeout")) {
return new ServiceError(
`Timeout during ${operationName}: ${error.message}`,
"TIMEOUT",
undefined,
error,
);
}
if (error.message?.toLowerCase().includes("unauthorized")) {
return new UnauthorizedError(
`Unauthorized during ${operationName}: ${error.message}`,
error,
);
}
// Default to generic service error for anything else
return new ServiceError(
`Error during ${operationName}: ${error.message}`,
"GENERIC_ERROR",
undefined,
error,
);
}
protected delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
protected validateRequired<T>(
value: T | null | undefined,
fieldName: string,
): T {
if (value === null || value === undefined || (typeof value === "string" && value.trim().length === 0)) {
throw new ValidationError(`${fieldName} is required`);
}
return value;
}
protected validateString(
value: string | null | undefined,
fieldName: string,
options: { minLength?: number; maxLength?: number; pattern?: RegExp } = {},
): string {
const validatedValue = this.validateRequired(value, fieldName);
if (typeof validatedValue !== "string") {
throw new ValidationError(`${fieldName} must be a string`);
}
if (options.minLength && validatedValue.length < options.minLength) {
throw new ValidationError(
`${fieldName} must be at least ${options.minLength} characters long`,
);
}
if (options.maxLength && validatedValue.length > options.maxLength) {
throw new ValidationError(
`${fieldName} must be at most ${options.maxLength} characters long`,
);
}
if (options.pattern && !options.pattern.test(validatedValue)) {
throw new ValidationError(
`${fieldName} does not match the required pattern`,
);
}
return validatedValue;
}
protected validateArray<T>(
value: T[] | null | undefined,
fieldName: string,
options: { minLength?: number; maxLength?: number } = {},
): T[] {
const validatedValue = this.validateRequired(value, fieldName);
if (!Array.isArray(validatedValue)) {
throw new ValidationError(`${fieldName} must be an array`);
}
if (options.minLength && validatedValue.length < options.minLength) {
throw new ValidationError(
`${fieldName} must have at least ${options.minLength} items`,
);
}
if (options.maxLength && validatedValue.length > options.maxLength) {
throw new ValidationError(
`${fieldName} must have at most ${options.maxLength} items`,
);
}
return validatedValue;
}
protected createBatchProcessor<T, R>(
batchSize: number = 50,
processor: (batch: T[]) => Promise<R[]>,
) {
return async (items: T[]): Promise<R[]> => {
const results: R[] = [];
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
const batchResults = await this.withRetry(
() => processor(batch),
`batch-process-${i / batchSize + 1}`,
);
results.push(...batchResults);
}
return results;
};
}
protected async executeWithLogging<T>(
operation: () => Promise<T>,
_operationName: string,
_metadata?: Record<string, unknown>,
): Promise<T> {
// Subclasses should implement their own logging
return await operation();
}
}
|