-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfetchMachine.ts
More file actions
351 lines (316 loc) · 8.73 KB
/
fetchMachine.ts
File metadata and controls
351 lines (316 loc) · 8.73 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/**
* @file Data Fetching State Machine Example
* @description Demonstrates async operations, retry logic, and error recovery
*
* This example shows a typical data fetching pattern with:
* - Loading states
* - Success and error handling
* - Retry with exponential backoff
* - Cancellation support
*/
import { MachineBase } from '../src/index';
import { transitionTo, invoke, describe, action, guarded } from '../src/primitives';
// =============================================================================
// CONTEXT TYPES
// =============================================================================
interface IdleContext {
status: 'idle';
lastFetchTime?: number;
}
interface LoadingContext {
status: 'loading';
requestId: string;
startTime: number;
}
interface SuccessContext<T = any> {
status: 'success';
data: T;
fetchedAt: number;
requestId: string;
}
interface ErrorContext {
status: 'error';
error: string;
errorCode?: number;
retryCount: number;
maxRetries: number;
lastRequestId: string;
}
interface RetryingContext {
status: 'retrying';
error: string;
retryCount: number;
maxRetries: number;
retryDelay: number;
nextRetryAt: number;
}
// =============================================================================
// STATE MACHINE CLASSES
// =============================================================================
/**
* Initial idle state - no data fetch in progress
*/
export class IdleMachine extends MachineBase<IdleContext> {
constructor(context: IdleContext = { status: 'idle' }) {
super(context);
}
/**
* Start fetching data
*/
fetch = describe(
'Initiate data fetching operation',
action(
{ name: 'startFetch', description: 'Track fetch initiation in analytics' },
transitionTo(LoadingMachine, () => {
const requestId = `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
return new LoadingMachine({
status: 'loading',
requestId,
startTime: Date.now(),
});
})
)
);
}
/**
* Loading state - fetch in progress
*/
export class LoadingMachine extends MachineBase<LoadingContext> {
constructor(context: LoadingContext) {
super(context);
}
/**
* Perform the actual fetch operation
*/
executeFetch = describe(
'Execute the HTTP request to fetch data',
invoke(
{
src: 'fetchData',
onDone: SuccessMachine,
onError: ErrorMachine,
description: 'Asynchronous data fetch from API endpoint',
},
async ({ signal }) => {
// Simulate API call with AbortSignal support
await new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, 1000);
// Handle cancellation
signal.addEventListener('abort', () => {
clearTimeout(timeout);
reject(new Error('Fetch cancelled'));
});
});
// Check if operation was cancelled after the delay
if (signal.aborted) {
throw new Error('Fetch cancelled');
}
// Simulate successful response
const mockData = {
id: this.context.requestId,
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
],
timestamp: Date.now(),
};
return new SuccessMachine({
status: 'success',
data: mockData,
fetchedAt: Date.now(),
requestId: this.context.requestId,
});
}
)
);
/**
* Cancel the ongoing fetch operation
*/
cancel = describe(
'Cancel the data fetch and return to idle',
action(
{ name: 'cancelFetch', description: 'Abort ongoing fetch request' },
transitionTo(IdleMachine, () => {
return new IdleMachine({
status: 'idle',
lastFetchTime: undefined,
});
})
)
);
}
/**
* Success state - data fetched successfully
*/
export class SuccessMachine<T = any> extends MachineBase<SuccessContext<T>> {
constructor(context: SuccessContext<T>) {
super(context);
}
/**
* Refetch the data (refresh)
*/
refetch = describe(
'Refresh the data by fetching again',
action(
{ name: 'logRefetch', description: 'Track data refresh operations' },
transitionTo(LoadingMachine, () => {
const requestId = `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
return new LoadingMachine({
status: 'loading',
requestId,
startTime: Date.now(),
});
})
)
);
/**
* Clear data and return to idle
*/
reset = describe(
'Clear the fetched data and return to idle state',
transitionTo(IdleMachine, () => {
return new IdleMachine({
status: 'idle',
lastFetchTime: this.context.fetchedAt,
});
})
);
/**
* Update data locally (optimistic update)
*/
updateData = describe(
'Update the cached data optimistically',
transitionTo(SuccessMachine, (newData: T) => {
return new SuccessMachine({
...this.context,
data: newData,
});
})
);
}
/**
* Error state - fetch failed
*/
export class ErrorMachine extends MachineBase<ErrorContext> {
constructor(context: ErrorContext) {
super(context);
}
/**
* Retry the fetch if retries are available
*/
retry = describe(
'Retry the failed fetch operation',
guarded(
{
name: 'canRetry',
description: 'Check if retry count is below max retries',
},
transitionTo(RetryingMachine, () => {
const retryCount = this.context.retryCount + 1;
const retryDelay = Math.min(1000 * Math.pow(2, retryCount), 10000); // Exponential backoff, max 10s
return new RetryingMachine({
status: 'retrying',
error: this.context.error,
retryCount,
maxRetries: this.context.maxRetries,
retryDelay,
nextRetryAt: Date.now() + retryDelay,
});
})
)
);
/**
* Give up and return to idle
*/
dismiss = describe(
'Dismiss the error and return to idle state',
action(
{ name: 'logErrorDismissed', description: 'Track when users dismiss errors' },
transitionTo(IdleMachine, () => {
return new IdleMachine({ status: 'idle' });
})
)
);
/**
* Manually refetch (bypass retry logic)
*/
refetch = describe(
'Manually trigger a new fetch, bypassing retry logic',
transitionTo(LoadingMachine, () => {
const requestId = `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
return new LoadingMachine({
status: 'loading',
requestId,
startTime: Date.now(),
});
})
);
}
/**
* Retrying state - waiting to retry after error
*/
export class RetryingMachine extends MachineBase<RetryingContext> {
constructor(context: RetryingContext) {
super(context);
}
/**
* Execute the retry after delay
*/
executeRetry = describe(
'Execute the retry attempt after delay period',
invoke(
{
src: 'retryFetch',
onDone: SuccessMachine,
onError: ErrorMachine,
description: 'Retry the fetch operation with exponential backoff',
},
async () => {
// Wait for retry delay
const now = Date.now();
const waitTime = Math.max(0, this.context.nextRetryAt - now);
await new Promise((resolve) => setTimeout(resolve, waitTime));
// Simulate retry attempt
await new Promise((resolve) => setTimeout(resolve, 1000));
// Simulate success on retry
const mockData = {
id: `retry-${this.context.retryCount}`,
items: [{ id: 1, name: 'Retry Success' }],
timestamp: Date.now(),
};
return new SuccessMachine({
status: 'success',
data: mockData,
fetchedAt: Date.now(),
requestId: `retry-${this.context.retryCount}`,
});
}
)
);
/**
* Cancel the retry
*/
cancel = describe(
'Cancel the pending retry and return to idle',
transitionTo(IdleMachine, () => {
return new IdleMachine({ status: 'idle' });
})
);
}
// =============================================================================
// FACTORY FUNCTION
// =============================================================================
/**
* Create a new fetch machine in idle state
*/
export function createFetchMachine<T = any>(): IdleMachine {
return new IdleMachine({ status: 'idle' });
}
/**
* Create a fetch machine with custom retry configuration
*/
export function createFetchMachineWithRetries<T = any>(maxRetries: number = 3): IdleMachine {
// Note: maxRetries would be stored in a config, this is simplified
return new IdleMachine({ status: 'idle' });
}