forked from Vatix-Protocol/vatix-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout-utils.ts
More file actions
206 lines (184 loc) · 5.19 KB
/
Copy pathtimeout-utils.ts
File metadata and controls
206 lines (184 loc) · 5.19 KB
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
/**
* Shared Timeout Utility
*
* Provides consistent timeout and cancellation handling for provider calls.
* Used by all provider adapters to ensure uniform timeout behavior.
*
* @module apps/oracle/timeout-utils
*/
/**
* Default timeout for provider calls (30 seconds).
*/
export const DEFAULT_TIMEOUT_MS = 30_000;
/**
* Minimum allowed timeout (1 second).
*/
export const MIN_TIMEOUT_MS = 1_000;
/**
* Maximum allowed timeout (5 minutes).
*/
export const MAX_TIMEOUT_MS = 300_000;
/**
* Timeout configuration options.
*/
export interface TimeoutConfig {
/** Timeout duration in milliseconds */
timeoutMs: number;
/** Optional custom error message */
errorMessage?: string;
}
/**
* Result of a timed operation.
*/
export interface TimedResult<T> {
/** The result value if the operation completed */
value?: T;
/** Whether the operation timed out */
timedOut: boolean;
/** Duration of the operation in milliseconds */
durationMs: number;
/** Error if the operation failed */
error?: Error;
}
export class TimeoutValidationError extends Error {
readonly statusCode = 400;
constructor(message: string) {
super(message);
this.name = "TimeoutValidationError";
}
}
/**
* Validate that a timeout value is within acceptable bounds.
*
* @param timeoutMs - Timeout value to validate
* @returns The validated timeout value (clamped to bounds)
*/
export function validateTimeout(timeoutMs: unknown): number {
if (typeof timeoutMs !== "number" || isNaN(timeoutMs as number)) {
throw new TimeoutValidationError(
`Invalid timeout value: ${timeoutMs}`
);
}
if (timeoutMs < MIN_TIMEOUT_MS) {
console.warn(
`Timeout ${timeoutMs}ms is below minimum ${MIN_TIMEOUT_MS}ms, clamping`
);
return MIN_TIMEOUT_MS;
}
if (timeoutMs > MAX_TIMEOUT_MS) {
console.warn(
`Timeout ${timeoutMs}ms exceeds maximum ${MAX_TIMEOUT_MS}ms, clamping`
);
return MAX_TIMEOUT_MS;
}
return timeoutMs;
}
/**
* Create an AbortSignal that triggers after the specified timeout.
* Combines with an existing signal if provided.
*
* @param timeoutMs - Timeout in milliseconds
* @param existingSignal - Optional existing AbortSignal to combine with
* @returns Object containing the combined signal and cleanup function
*/
export function createTimeoutSignal(
timeoutMs: number,
existingSignal?: AbortSignal
): { signal: AbortSignal; clear: () => void } {
const controller = new AbortController();
const validatedTimeout = validateTimeout(timeoutMs);
const timeoutId = setTimeout(() => {
controller.abort(
new Error(`Request timed out after ${validatedTimeout}ms`)
);
}, validatedTimeout);
// Forward abort from existing signal
const onExistingAbort = () => {
clearTimeout(timeoutId);
controller.abort(existingSignal?.reason);
};
if (existingSignal) {
if (existingSignal.aborted) {
clearTimeout(timeoutId);
controller.abort(existingSignal.reason);
} else {
existingSignal.addEventListener("abort", onExistingAbort, {
once: true,
});
}
}
const clear = () => {
clearTimeout(timeoutId);
if (existingSignal) {
existingSignal.removeEventListener("abort", onExistingAbort);
}
};
return { signal: controller.signal, clear };
}
/**
* Execute an async operation with a timeout.
* If the operation exceeds the timeout, it is aborted and a timeout error is returned.
*
* @param operation - Async operation to execute
* @param config - Timeout configuration
* @returns Promise resolving to a TimedResult
*/
export async function withTimeout<T>(
operation: (signal: AbortSignal) => Promise<T>,
config: TimeoutConfig
): Promise<TimedResult<T>> {
const startTime = performance.now();
const { signal, clear } = createTimeoutSignal(config.timeoutMs);
try {
const value = await Promise.race([
operation(signal),
new Promise<never>((_, reject) => {
signal.addEventListener(
"abort",
() => {
reject(
new Error(
config.errorMessage ??
`Operation timed out after ${config.timeoutMs}ms`
)
);
},
{ once: true }
);
}),
]);
const durationMs = performance.now() - startTime;
return { value, timedOut: false, durationMs };
} catch (error) {
const durationMs = performance.now() - startTime;
const isTimeout =
error instanceof Error &&
(error.message.includes("timed out") ||
error.message.includes("abort") ||
error.message === config.errorMessage);
if (isTimeout) {
console.warn(
`[TimeoutUtils] Operation timed out after ${config.timeoutMs}ms (${durationMs.toFixed(0)}ms elapsed)`
);
}
return {
timedOut: isTimeout,
durationMs,
error: error instanceof Error ? error : new Error(String(error)),
};
} finally {
clear();
}
}
/**
* Format duration for logging/metrics.
*
* @param durationMs - Duration in milliseconds
* @returns Formatted duration string
*/
export function formatDuration(durationMs: number): string {
if (durationMs < 1000) {
return `${durationMs.toFixed(0)}ms`;
}
return `${(durationMs / 1000).toFixed(2)}s`;
}