-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathdata_fetching.ts
More file actions
721 lines (618 loc) · 19 KB
/
Copy pathdata_fetching.ts
File metadata and controls
721 lines (618 loc) · 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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
import useSWR, { mutate as globalMutate } from 'swr';
import useSWRInfinite from 'swr/infinite';
import { components, paths } from '../gen/api-types';
import createClient from 'openapi-fetch';
import { LocalUdf } from '../udf_state';
import { useRef } from 'react';
type schemas = components['schemas'];
export type Pipeline = schemas['Pipeline'];
export type Job = schemas['Job'];
export type StopType = schemas['StopType'];
export type PipelineGraph = schemas['PipelineGraph'];
export type JobLogMessage = schemas['JobLogMessage'];
export type PipelineNode = schemas['PipelineNode'];
export type OutputData = schemas['OutputData'];
export type MetricGroup = schemas['MetricGroup'];
export type Metric = schemas['Metric'];
export type OperatorMetricGroup = schemas['OperatorMetricGroup'];
export type Connector = schemas['Connector'];
export type Checkpoint = schemas['Checkpoint'];
export type ConnectionProfile = schemas['ConnectionProfile'];
export type ConnectionTable = schemas['ConnectionTable'];
export type Format = schemas['Format'];
export type TestSourceMessage = schemas['TestSourceMessage'];
export type ConnectionTablePost = schemas['ConnectionTablePost'];
export type ConnectionSchema = schemas['ConnectionSchema'];
export type SourceField = schemas['SourceField'];
export type OperatorCheckpointGroup = schemas['OperatorCheckpointGroup'];
export type SubtaskCheckpointGroup = schemas['SubtaskCheckpointGroup'];
export type GlobalUdf = schemas['GlobalUdf'];
export type PipelineLocalUdf = schemas['Udf'];
export type UdfValidationResult = schemas['UdfValidationResult'];
const base = window.__ARROYO_BASENAME.replace(/\/$/, '') || '';
const BASE_URL = `${base}/api`;
export const { get, post, patch, del } = createClient<paths>({ baseUrl: BASE_URL });
const processResponse = (data: any | undefined, error: any | undefined, response?: Response) => {
// SWR expects fetchers to throw errors, but openapi-fetch returns the error as a named field,
// so this function throws the error if it exists
if (error) {
if (typeof error === 'object' && error != null) {
throw { ...error, status: response?.status };
}
throw { error: String(error), status: response?.status };
}
return data;
};
// Keys
const connectorsKey = () => {
return { key: 'Connectors' };
};
const connectionProfilesKey = () => {
return { key: 'Connections' };
};
const connectionProfileAutocompleteKey = (id: string) => {
return { key: `ConnectionProfileAutocomplete`, connectionProfileId: id };
};
const connectionTablesKey = (limit: number) => {
return (pageIndex: number, previousPageData: schemas['ConnectionTableCollection']) => {
if (previousPageData && !previousPageData.hasMore) return null;
if (pageIndex === 0) {
return { key: 'ConnectionTables', startingAfter: undefined, limit };
}
return {
key: 'ConnectionTables',
startingAfter: previousPageData.data[previousPageData.data.length - 1].id,
limit,
};
};
};
const pipelinesKey = (
pageIndex: number,
previousPageData: schemas['PipelineCollection'] | undefined
) => {
if (previousPageData && !previousPageData.hasMore) return null;
if (pageIndex === 0 || !previousPageData) {
return { key: 'Pipelines', startingAfter: undefined };
}
return {
key: 'Pipelines',
startingAfter: previousPageData.data[previousPageData.data.length - 1].id,
};
};
const jobMetricsKey = (pipelineId?: string, jobId?: string) => {
return pipelineId && jobId ? { key: 'JobMetrics', pipelineId, jobId } : null;
};
const jobCheckpointsKey = (pipelineId?: string, jobId?: string) => {
return pipelineId && jobId ? { key: 'JobCheckpoints', pipelineId, jobId } : null;
};
const checkpointDetailsKey = (pipelineId?: string, jobId?: string, epoch?: number) => {
return pipelineId && jobId && epoch
? { key: 'CheckpointDetails', pipelineId, jobId, epoch }
: null;
};
const operatorErrorsKey = (pipelineId?: string, jobId?: string) => {
return (pageIndex: number, previousPageData: schemas['JobLogMessageCollection']) => {
if (!pipelineId || !jobId) return null;
if (previousPageData && !previousPageData.hasMore) return null;
if (pageIndex === 0) {
return { key: 'OperatorErrors', pipelineId, jobId, startingAfter: undefined };
}
return {
key: 'OperatorErrors',
pipelineId,
jobId,
startingAfter: previousPageData.data[previousPageData.data.length - 1].id,
};
};
};
const queryValidationKey = (query?: string, localUdfs?: LocalUdf[]) => {
return query != undefined ? { key: 'PipelineGraph', query, localUdfs } : null;
};
const udfValidationKey = (definition: string, language: 'python' | 'rust') => {
return { key: 'UdfValidation', definition, language };
};
const pipelineKey = (pipelineId?: string) => {
return pipelineId ? { key: 'Pipeline', pipelineId } : null;
};
const pipelineJobsKey = (pipelineId?: string) => {
return pipelineId ? { key: 'PipelineJobs', pipelineId } : null;
};
// Ping
const pingFetcher = async () => {
const { data, error } = await get('/v1/ping', {});
return processResponse(data, error);
};
export const usePing = () => {
const { data, error, isLoading } = useSWR('ping', pingFetcher, {
refreshInterval: 1000,
onErrorRetry: (error, key, config, revalidate, {}) => {
// explicitly define this function to override the exponential backoff
setTimeout(() => revalidate(), 1000);
},
});
return {
ping: data,
pingLoading: isLoading,
pingError: error,
};
};
// Connectors
const connectorsFetcher = async () => {
const { data, error } = await get('/v1/connectors', {});
return processResponse(data, error);
};
export const useConnectors = () => {
const { data, isLoading } = useSWR<schemas['ConnectorCollection']>(
connectorsKey(),
connectorsFetcher
);
return {
connectors: data?.data,
connectorsLoading: isLoading,
};
};
// Connections
const connectionProfilesFetcher = async () => {
const { data, error } = await get('/v1/connection_profiles', {});
return processResponse(data, error);
};
export const useConnectionProfiles = () => {
const { data, isLoading, mutate } = useSWR<schemas['ConnectionProfileCollection']>(
connectionProfilesKey(),
connectionProfilesFetcher
);
return {
connectionProfiles: data?.data,
connectionProfilesLoading: isLoading,
mutateConnectionProfiles: mutate,
};
};
// ConnectionTables
const connectionTablesFetcher = () => {
return async (params: { key: string; startingAfter?: string; limit: number }) => {
const { data, error } = await get('/v1/connection_tables', {
params: {
query: {
starting_after: params.startingAfter,
limit: params.limit,
},
},
});
return processResponse(data, error);
};
};
export const useConnectionTables = (limit: number, refresh?: boolean) => {
const options = refresh ? { refreshInterval: 5000 } : {};
const { data, isLoading, mutate, size, setSize } = useSWRInfinite<
schemas['ConnectionTableCollection']
>(connectionTablesKey(limit), connectionTablesFetcher(), options);
return {
connectionTablePages: data,
connectionTablesLoading: isLoading,
mutateConnectionTables: mutate,
connectionTablesTotalPages: size,
setConnectionTablesMaxPages: setSize,
};
};
// ConnectionProfile autocomplete
const connectionProfileAutocompleteFetcher = () => {
return async (params: { connectionProfileId: string }) => {
const { data, error } = await get('/v1/connection_profiles/{id}/autocomplete', {
params: {
path: {
id: params.connectionProfileId,
},
},
});
return processResponse(data, error);
};
};
export const useConnectionProfileAutocomplete = (id: string) => {
const { data, error } = useSWR<schemas['ConnectionAutocompleteResp']>(
connectionProfileAutocompleteKey(id),
connectionProfileAutocompleteFetcher(),
{
revalidateOnMount: true,
}
);
return {
autocompleteData: data,
autocompleteError: error,
};
};
// Jobs
const jobsFetcher = async () => {
const { data, error } = await get('/v1/jobs', {});
return processResponse(data, error);
};
export const useJobs = () => {
const { data, isLoading } = useSWR<schemas['JobCollection']>('jobs', jobsFetcher);
return {
jobs: data?.data,
jobsLoading: isLoading,
};
};
// Job Metrics
const jobMetricsFetcher = () => {
return async (params: { key: string; pipelineId: string; jobId: string }) => {
const { data, error } = await get(
'/v1/pipelines/{pipeline_id}/jobs/{job_id}/operator_metric_groups',
{
params: {
path: {
pipeline_id: params.pipelineId,
job_id: params.jobId,
},
},
}
);
return processResponse(data, error);
};
};
export const useJobMetrics = (pipelineId?: string, jobId?: string) => {
const { data, isLoading, error } = useSWR<schemas['OperatorMetricGroupCollection']>(
jobMetricsKey(pipelineId, jobId),
jobMetricsFetcher(),
{
refreshInterval: 1000,
}
);
return {
operatorMetricGroups: data?.data,
operatorMetricGroupsLoading: isLoading,
operatorMetricGroupsError: error,
};
};
// JobCheckpointsReq
const jobCheckpointsFetcher = () => {
return async (params: { key: string; pipelineId: string; jobId: string }) => {
const { data, error, response } = await get(
'/v1/pipelines/{pipeline_id}/jobs/{job_id}/checkpoints',
{
params: {
path: {
pipeline_id: params.pipelineId,
job_id: params.jobId,
},
},
}
);
return processResponse(data, error, response);
};
};
export const useJobCheckpoints = (pipelineId?: string, jobId?: string) => {
const { data, error } = useSWR<schemas['CheckpointCollection']>(
jobCheckpointsKey(pipelineId, jobId),
jobCheckpointsFetcher(),
{
refreshInterval: 5000,
}
);
return {
checkpoints: data?.data,
checkpointsError: error,
};
};
// CheckpointDetailsReq
const checkpointDetailsFetcher = () => {
return async (params: { key: string; pipelineId: string; jobId: string; epoch: number }) => {
const { data, error, response } = await get(
'/v1/pipelines/{pipeline_id}/jobs/{job_id}/checkpoints/{epoch}/operator_checkpoint_groups',
{
params: {
path: { pipeline_id: params.pipelineId, job_id: params.jobId, epoch: params.epoch },
},
}
);
return processResponse(data, error, response);
};
};
export const useCheckpointDetails = (pipelineId?: string, jobId?: string, epoch?: number) => {
const { data, isLoading, error } = useSWR<schemas['OperatorCheckpointGroupCollection']>(
checkpointDetailsKey(pipelineId, jobId, epoch),
checkpointDetailsFetcher(),
{ revalidateOnFocus: false, shouldRetryOnError: false }
);
return {
checkpointDetails: data?.data,
checkpointLoading: isLoading,
checkpointDetailsError: error,
};
};
const queryValidationFetcher = () => {
return async (params: { key: string; query?: string; localUdfs?: LocalUdf[] }) => {
let udfs: PipelineLocalUdf[] = [];
if (params.localUdfs) {
udfs = params.localUdfs.map(udf => {
return { definition: udf.definition, language: udf.language };
});
}
const { data, error } = await post('/v1/pipelines/validate_query', {
body: {
query: params.query ?? '',
udfs: udfs,
},
});
return processResponse(data, error);
};
};
export const useQueryValidation = (query?: string, localUdfs?: LocalUdf[]) => {
const { data, error, isLoading } = useSWR<schemas['QueryValidationResult']>(
queryValidationKey(query, localUdfs),
queryValidationFetcher(),
{ revalidateOnFocus: false, revalidateIfStale: false, shouldRetryOnError: false }
);
return {
queryValidation: data,
queryValidationError: error,
queryValidationLoading: isLoading,
};
};
const udfValidationFetcher = () => {
const controller = useRef<AbortController>();
return async (params: { key: string; definition: string; language: 'python' | 'rust' }) => {
controller.current?.abort();
controller.current = new AbortController();
const { data, error } = await post('/v1/udfs/validate', {
body: {
definition: params.definition,
language: params.language,
},
signal: controller.current?.signal,
});
return processResponse(data, error);
};
};
export const useUdfValidation = (
onSuccess: (data: UdfValidationResult, key: any, config: any) => void,
definition: string,
language: 'rust' | 'python'
) => {
const { data, error, isLoading } = useSWR<schemas['UdfValidationResult']>(
udfValidationKey(definition, language),
udfValidationFetcher(),
{ revalidateOnFocus: false, revalidateIfStale: false, shouldRetryOnError: false, onSuccess }
);
return {
udfValidation: data,
udfValidationError: error,
udfValidationLoading: isLoading,
};
};
const pipelinesFetcher = () => {
return async (params: { key: string; startingAfter?: string }) => {
const { data, error } = await get('/v1/pipelines', {
params: {
query: {
limit: 100,
starting_after: params.startingAfter,
},
},
});
return processResponse(data, error);
};
};
export const usePipelines = () => {
const { data, isLoading, error, size, setSize } = useSWRInfinite<schemas['PipelineCollection']>(
pipelinesKey,
pipelinesFetcher(),
{
refreshInterval: 5000,
}
);
return {
pipelinePages: data,
pipelinesLoading: isLoading,
piplinesError: error,
pipelineTotalPages: size,
setPipelinesMaxPages: setSize,
};
};
const pipelineFetcher = () => {
return async (params: { key: string; pipelineId?: string }) => {
if (!params.pipelineId) {
return;
}
const { data, error } = await get(`/v1/pipelines/{id}`, {
params: { path: { id: params.pipelineId } },
});
return processResponse(data, error);
};
};
export const usePipeline = (pipelineId?: string, refresh: boolean = false) => {
const options = refresh ? { refreshInterval: 2000 } : {};
const { data, error, isLoading, mutate } = useSWR<schemas['Pipeline']>(
pipelineKey(pipelineId),
pipelineFetcher(),
options
);
const updatePipeline = async (params: { stop?: StopType; parallelism?: number }) => {
if (!pipelineId) {
return;
}
await patch('/v1/pipelines/{id}', {
params: { path: { id: pipelineId } },
body: { stop: params.stop, parallelism: params.parallelism },
});
await mutate();
};
const restartPipeline = async (ignoreState?: boolean) => {
if (!pipelineId) {
return;
}
await post('/v1/pipelines/{id}/restart', {
params: { path: { id: pipelineId } },
body: { ignore_state: ignoreState ?? false },
});
await Promise.all([mutate(), globalMutate(pipelineJobsKey(pipelineId))]);
};
const deletePipeline = async () => {
if (!pipelineId) {
return { error: undefined };
}
const { error } = await del('/v1/pipelines/{id}', {
params: { path: { id: pipelineId } },
});
await globalMutate(pipelinesKey(1, undefined));
return { error };
};
return {
pipeline: data,
pipelineError: error,
pipelineLoading: isLoading,
updatePipeline,
deletePipeline,
restartPipeline,
};
};
const pipelineJobsFetcher = () => {
return async (params: { key: string; pipelineId?: string }) => {
if (!params.pipelineId) {
return;
}
const { data, error } = await get(`/v1/pipelines/{id}/jobs`, {
params: { path: { id: params.pipelineId } },
});
return processResponse(data, error);
};
};
export const usePipelineJobs = (
pipelineId?: string,
refresh: boolean = false,
refreshInterval?: number
) => {
const options = refresh ? { refreshInterval: refreshInterval || 2000 } : {};
const { data, error } = useSWR<schemas['JobCollection']>(
pipelineJobsKey(pipelineId),
pipelineJobsFetcher(),
options
);
return { jobs: data?.data, jobsError: error };
};
const operatorErrorsFetcher = () => {
return async (params: {
key: string;
pipelineId: string;
jobId: string;
startingAfter?: string;
}) => {
const { data, error } = await get('/v1/pipelines/{pipeline_id}/jobs/{job_id}/errors', {
params: {
path: {
pipeline_id: params.pipelineId,
job_id: params.jobId,
},
query: {
starting_after: params.startingAfter,
},
},
});
return processResponse(data, error);
};
};
export const useOperatorErrors = (pipelineId?: string, jobId?: string) => {
const { data, isLoading, size, setSize } = useSWRInfinite<schemas['JobLogMessageCollection']>(
operatorErrorsKey(pipelineId, jobId),
operatorErrorsFetcher(),
{
refreshInterval: 5000,
}
);
return {
operatorErrorsPages: data,
operatorErrorsLoading: isLoading,
operatorErrorsTotalPages: size,
setOperatorErrorsMaxPages: setSize,
};
};
export const useConnectionTableTest = async (
handler: (event: TestSourceMessage) => void,
req: ConnectionTablePost
) => {
const url = `${BASE_URL}/v1/connection_tables/test`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'text/event-stream',
},
body: JSON.stringify(req),
});
if (!response.ok || !response.body) {
const text = await response.text();
let message;
try {
message = (JSON.parse(text) as { error: string }).error;
} catch {
message = text;
}
handler({
done: true,
error: true,
message,
});
return;
}
const reader = response.body.getReader();
const textDecoder = new TextDecoder();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
buffer += textDecoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
const value = line.substring('data:'.length);
if (value) {
try {
const parsed = JSON.parse(value) as TestSourceMessage;
handler(parsed);
} catch {}
}
}
}
};
const udfsFetcher = async () => {
const { data, error } = await get('/v1/udfs', {});
return processResponse(data, error);
};
export const useGlobalUdfs = () => {
const { data, isLoading, error, mutate } = useSWR<schemas['GlobalUdfCollection']>(
'udfs',
udfsFetcher
);
const createGlobalUdf = async (
prefix: string,
definition: string,
language: 'python' | 'rust',
description: string
) => {
const { data, error } = await post('/v1/udfs', {
body: {
prefix,
definition,
language,
description,
},
});
await mutate();
return { data, error };
};
const deleteGlobalUdf = async (udf: GlobalUdf) => {
const { error } = await del('/v1/udfs/{id}', {
params: { path: { id: udf.id } },
});
await mutate();
return { error };
};
return {
globalUdfs: data?.data,
udfsLoading: isLoading,
udfError: error,
createGlobalUdf,
deleteGlobalUdf,
};
};