forked from line/centraldogma
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathK8sAggregatorEditor.tsx
More file actions
836 lines (806 loc) · 27.3 KB
/
Copy pathK8sAggregatorEditor.tsx
File metadata and controls
836 lines (806 loc) · 27.3 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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
/*
* Copyright 2026 LY Corporation
*
* LY Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import {
Alert,
AlertIcon,
Box,
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
Button,
Checkbox,
Divider,
Flex,
FormControl,
FormErrorMessage,
FormLabel,
Heading,
HStack,
IconButton,
Input,
SimpleGrid,
Spacer,
Text,
useDisclosure,
} from '@chakra-ui/react';
import { default as RouteLink } from 'next/link';
import Router from 'next/router';
import { useEffect, useState } from 'react';
import { Control, Controller, FieldErrors, useFieldArray, useForm, UseFormRegister } from 'react-hook-form';
import { OptionBase, Select } from 'chakra-react-select';
import { AiOutlineClose, AiOutlineDelete, AiOutlineEdit, AiOutlineEye } from 'react-icons/ai';
import { FiSave } from 'react-icons/fi';
import { IoAddCircleOutline } from 'react-icons/io5';
import { Deferred } from 'dogma/common/components/Deferred';
import { DeleteConfirmationModal } from 'dogma/common/components/DeleteConfirmationModal';
import {
FileContentDto,
useCreateK8sAggregatorMutation,
useDeleteK8sAggregatorMutation,
useGetK8sAggregatorQuery,
useListCredentialsQuery,
usePreviewK8sAggregatorMutation,
useUpdateK8sAggregatorMutation,
} from 'dogma/features/xds/xdsApiSlice';
import { K8sAggregatorPreviewModal, K8sPreviewResult } from 'dogma/features/xds/K8sAggregatorPreviewModal';
import { useGroupWriteAccess } from 'dogma/features/xds/useGroupWriteAccess';
import { useAppDispatch } from 'dogma/hooks';
import { newNotification } from 'dogma/features/notification/notificationSlice';
import ErrorMessageParser from 'dogma/features/services/ErrorMessageParser';
import { K8sAggregatorStatus } from 'dogma/features/xds/K8sAggregatorStatus';
// Matches the server-side resource id pattern (XdsResourceManager.RESOURCE_ID_PATTERN_STRING).
const AGGREGATOR_ID_PATTERN = /^[a-z](?:[a-z0-9-_/]*[a-z0-9])?$/;
interface PropertyForm {
key: string;
value: string;
}
interface WatcherForm {
serviceName: string;
portName: string;
controlPlaneUrl: string;
namespace: string;
credentialId: string;
trustCerts: boolean;
priority: string;
loadBalancingWeight: string;
region: string;
zone: string;
subZone: string;
additionalProperties: PropertyForm[];
}
interface FormData {
aggregatorId: string;
watchers: WatcherForm[];
}
const emptyWatcher: WatcherForm = {
serviceName: '',
portName: '',
controlPlaneUrl: '',
namespace: '',
credentialId: '',
trustCerts: false,
priority: '',
loadBalancingWeight: '',
region: '',
zone: '',
subZone: '',
additionalProperties: [],
};
// Parses a numeric form field, rejecting non-numeric input instead of silently serializing it as null
// (JSON.stringify(NaN) === 'null'). The thrown error is surfaced to the user by the submit handler.
function toFiniteNumber(value: string, label: string): number {
const num = Number(value);
if (!Number.isFinite(num)) {
throw new Error(`${label} must be a number, but was '${value}'.`);
}
return num;
}
function buildBody(data: FormData, name?: string): string {
const localityLbEndpoints = data.watchers.map((w) => {
const kubeconfig: Record<string, unknown> = { controlPlaneUrl: w.controlPlaneUrl.trim() };
if (w.namespace.trim()) {
kubeconfig.namespace = w.namespace.trim();
}
if (w.credentialId.trim()) {
kubeconfig.credentialId = w.credentialId.trim();
}
if (w.trustCerts) {
kubeconfig.trustCerts = true;
}
const watcher: Record<string, unknown> = { serviceName: w.serviceName.trim(), kubeconfig };
if (w.portName.trim()) {
watcher.portName = w.portName.trim();
}
const additionalProperties: Record<string, string> = {};
w.additionalProperties.forEach((p) => {
if (p.key.trim()) {
additionalProperties[p.key.trim()] = p.value;
}
});
if (Object.keys(additionalProperties).length > 0) {
watcher.additionalProperties = additionalProperties;
}
const entry: Record<string, unknown> = { watcher };
const locality: Record<string, string> = {};
if (w.region.trim()) {
locality.region = w.region.trim();
}
if (w.zone.trim()) {
locality.zone = w.zone.trim();
}
if (w.subZone.trim()) {
locality.subZone = w.subZone.trim();
}
if (Object.keys(locality).length > 0) {
entry.locality = locality;
}
if (w.priority.trim()) {
entry.priority = toFiniteNumber(w.priority, 'Priority');
}
if (w.loadBalancingWeight.trim()) {
entry.loadBalancingWeight = toFiniteNumber(w.loadBalancingWeight, 'Load balancing weight');
}
return entry;
});
const body: Record<string, unknown> = { localityLbEndpoints };
if (name) {
body.name = name;
}
return JSON.stringify(body);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function parseToFormData(aggregatorId: string, content: any): FormData {
const endpoints = Array.isArray(content?.localityLbEndpoints) ? content.localityLbEndpoints : [];
const watchers: WatcherForm[] = endpoints.map(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(e: any) => ({
serviceName: e?.watcher?.serviceName ?? '',
portName: e?.watcher?.portName ?? '',
controlPlaneUrl: e?.watcher?.kubeconfig?.controlPlaneUrl ?? '',
namespace: e?.watcher?.kubeconfig?.namespace ?? '',
credentialId: e?.watcher?.kubeconfig?.credentialId ?? '',
trustCerts: !!e?.watcher?.kubeconfig?.trustCerts,
priority: e?.priority != null ? String(e.priority) : '',
loadBalancingWeight: e?.loadBalancingWeight != null ? String(e.loadBalancingWeight) : '',
region: e?.locality?.region ?? '',
zone: e?.locality?.zone ?? '',
subZone: e?.locality?.subZone ?? '',
additionalProperties: Object.entries(e?.watcher?.additionalProperties ?? {}).map(([key, value]) => ({
key,
value: String(value),
})),
}),
);
return { aggregatorId, watchers: watchers.length > 0 ? watchers : [{ ...emptyWatcher }] };
}
interface CredentialOption extends OptionBase {
value: string;
label: string;
}
interface WatcherFieldsProps {
index: number;
control: Control<FormData>;
register: UseFormRegister<FormData>;
serviceNameError: boolean;
controlPlaneUrlError: boolean;
// The group's access-token credential ids to choose from, or null when they cannot be listed
// (e.g. the user lacks the ADMIN role required by the credential API) — in which case a free-text input is
// shown so the id can still be entered.
credentialOptions: string[] | null;
onRemove: () => void;
canRemove: boolean;
readOnly: boolean;
}
const WatcherFields = ({
index,
control,
register,
serviceNameError,
controlPlaneUrlError,
credentialOptions,
onRemove,
canRemove,
readOnly,
}: WatcherFieldsProps) => {
const { fields, append, remove } = useFieldArray({
control,
name: `watchers.${index}.additionalProperties` as `watchers.${number}.additionalProperties`,
});
return (
<Box borderWidth="1px" borderRadius="md" p={4} mb={4} maxW="3xl">
<Flex mb={2} align="center">
<Text fontWeight="bold">Watcher #{index + 1}</Text>
<Spacer />
{canRemove && !readOnly && (
<Button size="xs" variant="ghost" colorScheme="red" leftIcon={<AiOutlineDelete />} onClick={onRemove}>
Remove
</Button>
)}
</Flex>
<SimpleGrid columns={2} spacing={3}>
<FormControl isInvalid={serviceNameError} isRequired>
<FormLabel fontSize="sm">Service name</FormLabel>
<Input
size="sm"
placeholder="k8s service name"
isReadOnly={readOnly}
{...register(`watchers.${index}.serviceName`, { required: true })}
/>
<FormErrorMessage>Service name is required.</FormErrorMessage>
</FormControl>
<FormControl>
<FormLabel fontSize="sm">Port name</FormLabel>
<Input
size="sm"
placeholder="optional"
isReadOnly={readOnly}
{...register(`watchers.${index}.portName`)}
/>
</FormControl>
<FormControl isInvalid={controlPlaneUrlError} isRequired>
<FormLabel fontSize="sm">Control plane URL</FormLabel>
<Input
size="sm"
placeholder="https://kubernetes.default.svc"
isReadOnly={readOnly}
{...register(`watchers.${index}.controlPlaneUrl`, { required: true })}
/>
<FormErrorMessage>Control plane URL is required.</FormErrorMessage>
</FormControl>
<FormControl>
<FormLabel fontSize="sm">Namespace</FormLabel>
<Input
size="sm"
placeholder="optional"
isReadOnly={readOnly}
{...register(`watchers.${index}.namespace`)}
/>
</FormControl>
<FormControl>
<FormLabel fontSize="sm">Credential ID</FormLabel>
{credentialOptions !== null ? (
<Controller
control={control}
name={`watchers.${index}.credentialId`}
render={({ field: { onChange, value, name, ref } }) => {
const ids = value ? [...new Set([...credentialOptions, value])] : credentialOptions;
const options: CredentialOption[] = ids.map((id) => ({ value: id, label: id }));
return (
<Select<CredentialOption>
ref={ref}
name={name}
size="sm"
options={options}
// react-select requires null (not undefined) for an empty value.
value={options.find((o) => o.value === value) || null}
onChange={(option) => onChange(option ? option.value : '')}
placeholder="select a credential (optional)"
closeMenuOnSelect
isClearable
isSearchable
isDisabled={readOnly}
/>
);
}}
/>
) : (
<Input
size="sm"
placeholder="optional"
isReadOnly={readOnly}
{...register(`watchers.${index}.credentialId`)}
/>
)}
</FormControl>
<FormControl>
<FormLabel fontSize="sm">Priority</FormLabel>
<Input
size="sm"
type="number"
placeholder="optional"
isReadOnly={readOnly}
{...register(`watchers.${index}.priority`)}
/>
</FormControl>
<FormControl>
<FormLabel fontSize="sm">Load balancing weight</FormLabel>
<Input
size="sm"
type="number"
placeholder="optional"
isReadOnly={readOnly}
{...register(`watchers.${index}.loadBalancingWeight`)}
/>
</FormControl>
<FormControl display="flex" alignItems="center" pt={6}>
<Checkbox isReadOnly={readOnly} {...register(`watchers.${index}.trustCerts`)}>
Trust certificates
</Checkbox>
</FormControl>
</SimpleGrid>
<Text mt={4} mb={1} fontSize="sm" fontWeight="semibold" color="gray.500">
Locality (optional)
</Text>
<SimpleGrid columns={3} spacing={3}>
<FormControl>
<FormLabel fontSize="sm">Region</FormLabel>
<Input
size="sm"
placeholder="optional"
isReadOnly={readOnly}
{...register(`watchers.${index}.region`)}
/>
</FormControl>
<FormControl>
<FormLabel fontSize="sm">Zone</FormLabel>
<Input
size="sm"
placeholder="optional"
isReadOnly={readOnly}
{...register(`watchers.${index}.zone`)}
/>
</FormControl>
<FormControl>
<FormLabel fontSize="sm">Sub zone</FormLabel>
<Input
size="sm"
placeholder="optional"
isReadOnly={readOnly}
{...register(`watchers.${index}.subZone`)}
/>
</FormControl>
</SimpleGrid>
<Text mt={4} mb={1} fontSize="sm" fontWeight="semibold" color="gray.500">
Additional properties (optional)
</Text>
{fields.map((field, propIndex) => (
<HStack key={field.id} mb={2}>
<Input
size="sm"
placeholder="key"
isReadOnly={readOnly}
{...register(`watchers.${index}.additionalProperties.${propIndex}.key`)}
/>
<Input
size="sm"
placeholder="value"
isReadOnly={readOnly}
{...register(`watchers.${index}.additionalProperties.${propIndex}.value`)}
/>
{!readOnly && (
<IconButton
size="sm"
variant="ghost"
colorScheme="red"
aria-label="Remove property"
icon={<AiOutlineDelete />}
onClick={() => remove(propIndex)}
/>
)}
</HStack>
))}
{!readOnly && (
<Button
size="xs"
variant="outline"
leftIcon={<IoAddCircleOutline />}
onClick={() => append({ key: '', value: '' })}
>
Add property
</Button>
)}
</Box>
);
};
interface AggregatorFormFieldsProps {
group: string;
control: Control<FormData>;
register: UseFormRegister<FormData>;
errors: FieldErrors<FormData>;
idReadOnly: boolean;
readOnly: boolean;
}
const AggregatorFormFields = ({
group,
control,
register,
errors,
idReadOnly,
readOnly,
}: AggregatorFormFieldsProps) => {
const { fields, append, remove } = useFieldArray({ control, name: 'watchers' });
// Offer the group's access-token credentials as a dropdown. Listing requires the ADMIN role, so on any error
// (e.g. 403 for non-admins) fall back to a free-text credential id input.
const { data: credentials, error: credentialsError } = useListCredentialsQuery({ group });
const credentialOptions: string[] | null = credentialsError
? null
: (credentials || []).filter((c) => c.type === 'ACCESS_TOKEN').map((c) => c.id);
return (
<>
<FormControl isInvalid={!!errors.aggregatorId} isRequired mb={4} maxW="md">
<FormLabel>Aggregator ID</FormLabel>
<Input
placeholder="e.g. my-service"
isReadOnly={idReadOnly || readOnly}
{...register('aggregatorId', { required: true, pattern: AGGREGATOR_ID_PATTERN })}
/>
<FormErrorMessage>ID must match [a-z](?:[a-z0-9-_/]*[a-z0-9])?</FormErrorMessage>
</FormControl>
{fields.map((field, index) => (
<WatcherFields
key={field.id}
index={index}
control={control}
register={register}
serviceNameError={!!errors.watchers?.[index]?.serviceName}
controlPlaneUrlError={!!errors.watchers?.[index]?.controlPlaneUrl}
credentialOptions={credentialOptions}
onRemove={() => remove(index)}
canRemove={fields.length > 1}
readOnly={readOnly}
/>
))}
{!readOnly && (
<Button
size="sm"
variant="outline"
leftIcon={<IoAddCircleOutline />}
onClick={() => append({ ...emptyWatcher })}
>
Add watcher
</Button>
)}
</>
);
};
const NewK8sAggregatorEditor = ({ group }: { group: string }) => {
const dispatch = useAppDispatch();
// Creating an aggregator requires WRITE on the group, mirroring the Edit/Delete gating in
// ExistingK8sAggregatorEditor.
const { hasWrite, isLoading: accessLoading } = useGroupWriteAccess(group);
const [createAggregator, { isLoading }] = useCreateK8sAggregatorMutation();
const [previewAggregator, { isLoading: isPreviewing }] = usePreviewK8sAggregatorMutation();
const { isOpen: previewOpen, onOpen: openPreview, onClose: closePreview } = useDisclosure();
const [previewResult, setPreviewResult] = useState<K8sPreviewResult | null>(null);
const [commitSummary, setCommitSummary] = useState('');
const {
register,
control,
handleSubmit,
formState: { errors },
} = useForm<FormData>({ defaultValues: { aggregatorId: '', watchers: [{ ...emptyWatcher }] } });
const onPreview = async (data: FormData) => {
setPreviewResult(null);
openPreview();
try {
const assignment = await previewAggregator({ group, body: buildBody(data) }).unwrap();
setPreviewResult({ ok: true, assignment });
} catch (err) {
setPreviewResult({ ok: false, error: ErrorMessageParser.parse(err) });
}
};
const onSubmit = async (data: FormData) => {
if (!hasWrite) {
return;
}
try {
await createAggregator({
group,
aggregatorId: data.aggregatorId,
body: buildBody(data),
summary: commitSummary || undefined,
}).unwrap();
dispatch(
newNotification('Aggregator created', `Aggregator '${data.aggregatorId}' is created`, 'success'),
);
Router.push(`/app/xds/group?name=${encodeURIComponent(group)}&type=k8sAggregators`);
} catch (err) {
dispatch(newNotification('Failed to create the aggregator', ErrorMessageParser.parse(err), 'error'));
}
};
if (accessLoading) {
return null;
}
if (!hasWrite) {
return (
<Alert status="warning" borderRadius="md">
<AlertIcon />
You need the WRITE role on this group to create an aggregator.
</Alert>
);
}
return (
<Box>
<AggregatorFormFields
group={group}
control={control}
register={register}
errors={errors}
idReadOnly={false}
readOnly={false}
/>
<Divider my={4} maxW="3xl" />
<FormControl mb={4} maxW="md">
<FormLabel>Commit summary</FormLabel>
<Input
value={commitSummary}
onChange={(e) => setCommitSummary(e.target.value)}
placeholder="Create kubernetes endpoint: ..."
/>
</FormControl>
<Flex maxW="3xl">
<Spacer />
<HStack spacing={3}>
<Button
variant="outline"
colorScheme="teal"
leftIcon={<AiOutlineEye />}
onClick={handleSubmit(onPreview)}
isLoading={isPreviewing}
>
Preview endpoints
</Button>
<Button
colorScheme="teal"
leftIcon={<FiSave />}
onClick={handleSubmit(onSubmit)}
isLoading={isLoading}
>
Create
</Button>
</HStack>
</Flex>
<K8sAggregatorPreviewModal
isOpen={previewOpen}
onClose={closePreview}
isLoading={isPreviewing}
result={previewResult}
/>
</Box>
);
};
const ExistingK8sAggregatorEditor = ({ group, id }: { group: string; id: string }) => {
const dispatch = useAppDispatch();
// Edit/Delete are shown only to users with WRITE on the group.
const { hasWrite } = useGroupWriteAccess(group);
const { data, isLoading, error } = useGetK8sAggregatorQuery(
{ group, id },
{ refetchOnMountOrArgChange: true },
);
const [updateAggregator, { isLoading: isSaving }] = useUpdateK8sAggregatorMutation();
const [deleteAggregator, { isLoading: isDeleting }] = useDeleteK8sAggregatorMutation();
const [previewAggregator, { isLoading: isPreviewing }] = usePreviewK8sAggregatorMutation();
const { isOpen, onOpen, onClose } = useDisclosure();
const { isOpen: previewOpen, onOpen: openPreview, onClose: closePreview } = useDisclosure();
const [previewResult, setPreviewResult] = useState<K8sPreviewResult | null>(null);
// An aggregator opens in read-only view; the user must click Edit to modify it (like the resource editors).
const [editing, setEditing] = useState(false);
const [commitSummary, setCommitSummary] = useState('');
const [deleteCommitSummary, setDeleteCommitSummary] = useState('');
const {
register,
control,
handleSubmit,
reset,
formState: { errors },
} = useForm<FormData>({ defaultValues: { aggregatorId: id, watchers: [{ ...emptyWatcher }] } });
// Sync the form to the latest fetched content, but never while editing so a background refetch cannot
// clobber unsaved edits.
useEffect(() => {
if (data && !editing) {
reset(parseToFormData(id, (data as FileContentDto).content));
}
}, [data, id, reset, editing]);
const onSubmit = async (formData: FormData) => {
const name = `groups/${group}/k8s/endpointAggregators/${id}`;
try {
await updateAggregator({
group,
id,
body: buildBody(formData, name),
summary: commitSummary || undefined,
}).unwrap();
dispatch(newNotification('Aggregator updated', `Aggregator '${id}' is updated`, 'success'));
setEditing(false);
setCommitSummary('');
} catch (err) {
dispatch(newNotification('Failed to update the aggregator', ErrorMessageParser.parse(err), 'error'));
}
};
const handleCancel = () => {
if (data) {
reset(parseToFormData(id, (data as FileContentDto).content));
}
setEditing(false);
setCommitSummary('');
};
const onPreview = async (formData: FormData) => {
setPreviewResult(null);
openPreview();
try {
const assignment = await previewAggregator({ group, body: buildBody(formData) }).unwrap();
setPreviewResult({ ok: true, assignment });
} catch (err) {
setPreviewResult({ ok: false, error: ErrorMessageParser.parse(err) });
}
};
const handleDelete = async () => {
try {
await deleteAggregator({ group, id, summary: deleteCommitSummary || undefined }).unwrap();
dispatch(newNotification('Aggregator deleted', `Aggregator '${id}' is deleted`, 'success'));
Router.push(`/app/xds/group?name=${encodeURIComponent(group)}&type=k8sAggregators`);
} catch (err) {
dispatch(newNotification('Failed to delete the aggregator', ErrorMessageParser.parse(err), 'error'));
}
};
const handleDeleteModalClose = () => {
setDeleteCommitSummary('');
onClose();
};
return (
<Deferred isLoading={isLoading} error={error}>
{() => (
<Box>
<Flex mb={2} maxW="3xl" align="center">
<Spacer />
{hasWrite &&
(editing ? (
<Button
variant="outline"
colorScheme="gray"
leftIcon={<AiOutlineClose />}
size="sm"
onClick={handleCancel}
>
Cancel
</Button>
) : (
<HStack spacing={3}>
<Button
variant="outline"
colorScheme="teal"
leftIcon={<AiOutlineEye />}
size="sm"
onClick={handleSubmit(onPreview)}
isLoading={isPreviewing}
>
Preview
</Button>
<Button
colorScheme="teal"
leftIcon={<AiOutlineEdit />}
size="sm"
onClick={() => setEditing(true)}
>
Edit
</Button>
<Button colorScheme="red" leftIcon={<AiOutlineDelete />} size="sm" onClick={onOpen}>
Delete
</Button>
</HStack>
))}
</Flex>
<K8sAggregatorStatus group={group} id={id} />
<AggregatorFormFields
group={group}
control={control}
register={register}
errors={errors}
idReadOnly
readOnly={!editing}
/>
{editing && hasWrite && (
<>
<Divider my={4} maxW="3xl" />
<FormControl mb={4} maxW="md">
<FormLabel>Commit summary</FormLabel>
<Input
value={commitSummary}
onChange={(e) => setCommitSummary(e.target.value)}
placeholder="Update kubernetes endpoint aggregator: ..."
/>
</FormControl>
<Flex maxW="3xl">
<Spacer />
<HStack spacing={3}>
<Button
variant="outline"
colorScheme="teal"
leftIcon={<AiOutlineEye />}
onClick={handleSubmit(onPreview)}
isLoading={isPreviewing}
>
Preview endpoints
</Button>
<Button
colorScheme="teal"
leftIcon={<FiSave />}
onClick={handleSubmit(onSubmit)}
isLoading={isSaving}
>
Save
</Button>
</HStack>
</Flex>
</>
)}
<K8sAggregatorPreviewModal
isOpen={previewOpen}
onClose={closePreview}
isLoading={isPreviewing}
result={previewResult}
/>
<DeleteConfirmationModal
isOpen={isOpen}
onClose={handleDeleteModalClose}
type="aggregator"
id={id}
from={group}
handleDelete={handleDelete}
isLoading={isDeleting}
>
<FormControl mt={4}>
<FormLabel>Commit summary</FormLabel>
<Input
value={deleteCommitSummary}
onChange={(e) => setDeleteCommitSummary(e.target.value)}
placeholder="Delete kubernetes endpoint aggregator: ..."
/>
</FormControl>
</DeleteConfirmationModal>
</Box>
)}
</Deferred>
);
};
export const K8sAggregatorEditor = ({ group, id, isNew }: { group: string; id?: string; isNew: boolean }) => {
const title = isNew || !id ? 'New K8s Aggregator' : id;
const listHref = `/app/xds/group?name=${encodeURIComponent(group)}&type=k8sAggregators`;
return (
<Box p="2">
<Breadcrumb mb={4} color="gray.500">
<BreadcrumbItem>
<BreadcrumbLink as={RouteLink} href="/app/xds">
Groups
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbItem>
<BreadcrumbLink as={RouteLink} href={listHref}>
{group}
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbItem>
<BreadcrumbLink as={RouteLink} href={listHref}>
K8s Aggregators
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbItem isCurrentPage>
<BreadcrumbLink href="#">{title}</BreadcrumbLink>
</BreadcrumbItem>
</Breadcrumb>
<Heading size="lg" mb={6}>
<HStack color="teal">
<Box>Kubernetes Endpoint Aggregator</Box>
</HStack>
</Heading>
{isNew || !id ? (
<NewK8sAggregatorEditor group={group} />
) : (
<ExistingK8sAggregatorEditor group={group} id={id} />
)}
</Box>
);
};