forked from personamanagmentlayer/pcl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfallback.ts
More file actions
288 lines (246 loc) · 8.5 KB
/
Copy pathfallback.ts
File metadata and controls
288 lines (246 loc) · 8.5 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
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
/**
* Provider Fallback Chain System
*
* Automatic failover between providers for reliability
*/
import type {
AIProvider,
GenerationRequest,
GenerationResponse,
GenerationChunk,
} from './index';
import type { ProviderHealthMonitor } from './health';
// ─────────────────────────────────────────────────────────────────────────────
// Fallback Strategy
// ─────────────────────────────────────────────────────────────────────────────
export type FallbackStrategy = 'sequential' | 'fastest' | 'health-based';
export interface FallbackConfig {
/** Strategy for selecting fallback provider */
readonly strategy: FallbackStrategy;
/** Maximum retry attempts per provider */
readonly maxRetries: number;
/** Timeout for each provider attempt (ms) */
readonly timeout: number;
/** Whether to skip unhealthy providers */
readonly skipUnhealthy: boolean;
}
const DEFAULT_FALLBACK_CONFIG: FallbackConfig = {
strategy: 'sequential',
maxRetries: 1,
timeout: 30000, // 30 seconds
skipUnhealthy: true,
};
// ─────────────────────────────────────────────────────────────────────────────
// Fallback Result
// ─────────────────────────────────────────────────────────────────────────────
export interface FallbackResult<T> {
readonly result: T;
readonly provider: string;
readonly attemptCount: number;
readonly errors: Array<{ provider: string; error: Error }>;
}
// ─────────────────────────────────────────────────────────────────────────────
// Fallback Chain
// ─────────────────────────────────────────────────────────────────────────────
export class FallbackChain {
private readonly providers: Map<string, AIProvider>;
private readonly healthMonitors: Map<string, ProviderHealthMonitor>;
private readonly providerOrder: string[];
private readonly config: FallbackConfig;
constructor(
providers: Map<string, AIProvider>,
providerOrder: string[],
healthMonitors: Map<string, ProviderHealthMonitor> = new Map(),
config: Partial<FallbackConfig> = {}
) {
this.providers = providers;
this.providerOrder = providerOrder;
this.healthMonitors = healthMonitors;
this.config = { ...DEFAULT_FALLBACK_CONFIG, ...config };
// Validate all providers exist
for (const name of providerOrder) {
if (!providers.has(name)) {
throw new Error(`Provider '${name}' not found in registry`);
}
}
}
/**
* Generate response with automatic fallback
*/
async generateResponse(
request: GenerationRequest
): Promise<FallbackResult<GenerationResponse>> {
const errors: Array<{ provider: string; error: Error }> = [];
const availableProviders = this.getAvailableProviders();
if (availableProviders.length === 0) {
throw new Error('No available providers in fallback chain');
}
for (let i = 0; i < availableProviders.length; i++) {
const providerName = availableProviders[i];
const provider = this.providers.get(providerName)!;
try {
const result = await this.attemptWithTimeout(
() => provider.generateResponse(request),
this.config.timeout
);
return {
result,
provider: providerName,
attemptCount: i + 1,
errors,
};
} catch (error) {
errors.push({
provider: providerName,
error: error instanceof Error ? error : new Error(String(error)),
});
// Continue to next provider in chain
}
}
// All providers failed
throw new Error(
`All providers in fallback chain failed. Errors: ${errors
.map((e) => `${e.provider}: ${e.error.message}`)
.join('; ')}`
);
}
/**
* Stream response with automatic fallback
*/
async *streamResponse(
request: GenerationRequest
): AsyncGenerator<FallbackResult<GenerationChunk>, void, unknown> {
const errors: Array<{ provider: string; error: Error }> = [];
const availableProviders = this.getAvailableProviders();
if (availableProviders.length === 0) {
throw new Error('No available providers in fallback chain');
}
for (let i = 0; i < availableProviders.length; i++) {
const providerName = availableProviders[i];
const provider = this.providers.get(providerName)!;
try {
const stream = provider.streamResponse(request);
let chunkCount = 0;
for await (const chunk of stream) {
chunkCount++;
yield {
result: chunk,
provider: providerName,
attemptCount: i + 1,
errors,
};
}
// Successfully streamed response
return;
} catch (error) {
errors.push({
provider: providerName,
error: error instanceof Error ? error : new Error(String(error)),
});
// Continue to next provider in chain
}
}
// All providers failed
throw new Error(
`All providers in fallback chain failed. Errors: ${errors
.map((e) => `${e.provider}: ${e.error.message}`)
.join('; ')}`
);
}
/**
* Get ordered list of providers
*/
getProviderOrder(): readonly string[] {
return this.providerOrder;
}
/**
* Get available providers (filtered by health)
*/
private getAvailableProviders(): string[] {
if (!this.config.skipUnhealthy) {
return [...this.providerOrder];
}
return this.providerOrder.filter((name) => {
const monitor = this.healthMonitors.get(name);
return !monitor || monitor.isAvailable();
});
}
/**
* Execute with timeout
*/
private async attemptWithTimeout<T>(
fn: () => Promise<T>,
timeout: number
): Promise<T> {
return Promise.race([
fn(),
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('Request timeout')), timeout)
),
]);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Fallback Chain Builder
// ─────────────────────────────────────────────────────────────────────────────
export class FallbackChainBuilder {
private providerOrder: string[] = [];
private config: {
strategy?: FallbackStrategy;
maxRetries?: number;
timeout?: number;
skipUnhealthy?: boolean;
} = {};
/**
* Add providers in order
*/
withProviders(...providers: string[]): this {
this.providerOrder = providers;
return this;
}
/**
* Set fallback strategy
*/
withStrategy(strategy: FallbackStrategy): this {
this.config.strategy = strategy;
return this;
}
/**
* Set maximum retries per provider
*/
withMaxRetries(retries: number): this {
this.config.maxRetries = retries;
return this;
}
/**
* Set timeout per provider
*/
withTimeout(timeout: number): this {
this.config.timeout = timeout;
return this;
}
/**
* Set whether to skip unhealthy providers
*/
withSkipUnhealthy(skip: boolean): this {
this.config.skipUnhealthy = skip;
return this;
}
/**
* Build the fallback chain
*/
build(
providers: Map<string, AIProvider>,
healthMonitors?: Map<string, ProviderHealthMonitor>
): FallbackChain {
if (this.providerOrder.length === 0) {
throw new Error('Fallback chain must have at least one provider');
}
return new FallbackChain(
providers,
this.providerOrder,
healthMonitors,
this.config
);
}
}