-
Notifications
You must be signed in to change notification settings - Fork 428
Expand file tree
/
Copy pathschema-create.tsx
More file actions
1117 lines (1029 loc) · 40.4 KB
/
Copy pathschema-create.tsx
File metadata and controls
1117 lines (1029 loc) · 40.4 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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2022 Redpanda Data, Inc.
*
* Use of this software is governed by the Business Source License
* included in the file https://github.com/redpanda-data/redpanda/blob/dev/licenses/bsl.md
*
* As of the Change Date specified in that file, in accordance with
* the Business Source License, use of this software will be governed
* by the Apache License, Version 2.0
*/
import { useQueryClient } from '@tanstack/react-query';
import { TrashIcon } from 'components/icons';
import { Alert, AlertDescription, AlertTitle } from 'components/redpanda-ui/components/alert';
import { Button } from 'components/redpanda-ui/components/button';
import { Combobox } from 'components/redpanda-ui/components/combobox';
import { Field, FieldDescription, FieldError, FieldLabel } from 'components/redpanda-ui/components/field';
import { Input } from 'components/redpanda-ui/components/input';
import { KeyValueField } from 'components/redpanda-ui/components/key-value-field';
import { Label } from 'components/redpanda-ui/components/label';
import { RadioGroup, RadioGroupItem } from 'components/redpanda-ui/components/radio-group';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from 'components/redpanda-ui/components/select';
import { Separator } from 'components/redpanda-ui/components/separator';
import { Switch } from 'components/redpanda-ui/components/switch';
import { ToggleGroup, ToggleGroupItem } from 'components/redpanda-ui/components/toggle-group';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from 'components/redpanda-ui/components/tooltip';
import { AlertCircle, InfoIcon, X } from 'lucide-react';
import { type Dispatch, type SetStateAction, useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import { ContextsNotSupportedPage } from './contexts-not-supported-page';
import { SwitchSchemaFormatDialog, ValidationErrorsDialog } from './modals';
import {
ALL_CONTEXT_ID,
buildQualifiedReferences,
buildQualifiedSubjectName,
contextIdToLabel,
contextLabelToId,
contextNameToId,
deriveContexts,
isNamedContext,
parseSubjectContext,
} from './schema-context-utils';
import {
useListSchemasQuery,
useSchemaRegistryContextsQuery,
useSchemaTypesQuery,
} from '../../../react-query/api/schema-registry';
import { appGlobal } from '../../../state/app-global';
import { api, useApiStoreHook } from '../../../state/backend-api';
import {
type SchemaRegistryValidateSchemaResponse,
SchemaType,
type SchemaTypeType,
} from '../../../state/rest-interfaces';
import { useSupportedFeaturesStore } from '../../../state/supported-features';
import { DefaultSkeleton } from '../../../utils/tsx-utils';
import KowlEditor from '../../misc/kowl-editor';
import PageContent from '../../misc/page-content';
import { PageComponent, type PageInitHelper } from '../page';
// Regex for extracting record names from schema text
const JSON_NAME_REGEX = /"name"\s*:\s*"(.*)"/;
const PROTOBUF_MESSAGE_NAME_REGEX = /message\s+(\S+)\s*\{/;
type NamingStrategy =
| 'TOPIC' // only topic name
| 'RECORD_NAME' // take name from the record
| 'TOPIC_RECORD_NAME' // both topic and record name
| 'CUSTOM'; // essentially no strategy / arbitrary name
type SchemaEditorStateData = {
strategy: NamingStrategy;
userInput: string; // holds either topicName or custom input
keyOrValue: 'KEY' | 'VALUE' | undefined;
format: 'AVRO' | 'PROTOBUF' | 'JSON';
schemaText: string;
references: { id: string; name: string; subject: string; version: number; context: string }[];
normalize: boolean;
metadataProperties: { id: string; key: string; value: string }[];
context: string;
};
type SchemaEditorStateHelper = SchemaEditorStateData & {
computedMetadata: { properties: Record<string, string> } | undefined;
isInvalidKeyOrValue: boolean;
computedSubjectName: string;
qualifiedSubjectName: string;
};
type SetSchemaState = Dispatch<SetStateAction<SchemaEditorStateData>>;
function createInitialSchemaState(): SchemaEditorStateData {
return {
strategy: 'TOPIC',
userInput: '',
keyOrValue: undefined,
format: 'AVRO',
schemaText: exampleSchema.AVRO,
references: [{ id: crypto.randomUUID(), name: '', subject: '', version: 1, context: '' }],
normalize: false,
metadataProperties: [{ id: crypto.randomUUID(), key: '', value: '' }],
context: '',
};
}
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: complex business logic
function computeRecordName(state: SchemaEditorStateData): string {
if (state.format === 'AVRO' || state.format === 'JSON') {
try {
const obj = JSON.parse(state.schemaText);
const name = obj.name;
return name;
} catch {
// no op - schema may be incomplete during editing
}
const ar = JSON_NAME_REGEX.exec(state.schemaText);
if (!ar) return '';
if (ar.length < 2) return '';
return ar[1];
}
const ar = PROTOBUF_MESSAGE_NAME_REGEX.exec(state.schemaText);
if (!ar) return '';
if (ar.length < 2) return '';
return ar[1];
}
function deriveSchemaEditorState(state: SchemaEditorStateData): SchemaEditorStateHelper {
const properties: Record<string, string> = {};
for (const prop of state.metadataProperties) {
if (prop.key && prop.value) {
properties[prop.key] = prop.value;
}
}
const computedMetadata = Object.keys(properties).length > 0 ? { properties } : undefined;
const isInvalidKeyOrValue = state.strategy === 'TOPIC' && state.userInput.length > 0 && !state.keyOrValue;
const recordName = computeRecordName(state);
let subjectName = '';
if (state.strategy === 'TOPIC') {
subjectName = state.userInput;
} else if (state.strategy === 'RECORD_NAME') {
subjectName = recordName;
} else if (state.strategy === 'TOPIC_RECORD_NAME') {
subjectName = `${state.userInput}-${recordName}`;
} else {
subjectName = state.userInput;
}
if (state.strategy !== 'CUSTOM' && state.keyOrValue !== undefined && subjectName) {
subjectName += `-${state.keyOrValue.toLowerCase()}`;
}
const qualifiedSubjectName = buildQualifiedSubjectName(state.context, subjectName);
return { ...state, computedMetadata, isInvalidKeyOrValue, computedSubjectName: subjectName, qualifiedSubjectName };
}
export class SchemaCreatePage extends PageComponent<{ contextName?: string }> {
initPage(p: PageInitHelper): void {
p.title = 'Create schema';
p.addBreadcrumb('Schema Registry', '/schema-registry');
const contextName = this.props.contextName ? decodeURIComponent(this.props.contextName) : undefined;
if (contextName) {
p.addBreadcrumb('Create schema', `/schema-registry/contexts/${encodeURIComponent(contextName)}/create`);
} else {
p.addBreadcrumb('Create schema', '/schema-registry/create');
}
this.refreshData(true);
appGlobal.onRefresh = () => this.refreshData(true);
}
refreshData(force?: boolean) {
api.refreshSchemaSubjects(force); // for references editor -> subject selector
api.refreshTopics(force); // for the topics selector
}
render() {
return (
<SchemaCreatePageContent
contextName={this.props.contextName ? decodeURIComponent(this.props.contextName) : undefined}
/>
);
}
}
export class SchemaAddVersionPage extends PageComponent<{ subjectName: string }> {
initPage(p: PageInitHelper): void {
const subjectName = decodeURIComponent(this.props.subjectName);
const encodedSubjectName = encodeURIComponent(subjectName);
p.title = 'Add schema version';
p.addBreadcrumb('Schema Registry', '/schema-registry');
p.addBreadcrumb(subjectName, `/schema-registry/subjects/${encodedSubjectName}`, undefined, {
canBeTruncated: true,
});
p.addBreadcrumb('Create schema', `/schema-registry/subjects/${encodedSubjectName}/add-version`);
this.refreshData(true);
appGlobal.onRefresh = () => this.refreshData(true);
}
refreshData(force?: boolean) {
api.refreshSchemaCompatibilityConfig();
api.refreshSchemaMode();
api.refreshSchemaSubjects(force);
api.refreshSchemaTypes(force);
const subjectName = decodeURIComponent(this.props.subjectName);
api.refreshSchemaDetails(subjectName, force);
}
render() {
return <SchemaAddVersionPageContent subjectName={decodeURIComponent(this.props.subjectName)} />;
}
}
const SchemaCreatePageContent = ({ contextName }: { contextName?: string }) => {
const srContextsEnabled = useSupportedFeaturesStore((s) => s.schemaRegistryContexts);
const [stateData, setStateData] = useState<SchemaEditorStateData>(() => {
const initial = createInitialSchemaState();
if (contextName) {
const contextId = contextNameToId(contextName);
return {
...initial,
context: contextId,
references: [{ id: crypto.randomUUID(), name: '', subject: '', version: 1, context: contextId }],
};
}
return initial;
});
const state = deriveSchemaEditorState(stateData);
if (contextName && !srContextsEnabled) {
return <ContextsNotSupportedPage />;
}
return (
<PageContent key="b">
<SchemaEditor mode="CREATE" onStateChange={setStateData} state={state} />
<SchemaPageButtons editorState={state} />
</PageContent>
);
};
const SchemaAddVersionPageContent = ({ subjectName }: { subjectName: string }) => {
const [stateData, setStateData] = useState<SchemaEditorStateData | null>(null);
const subject = useApiStoreHook((s) => s.schemaDetails.get(subjectName));
const srContextsEnabled = useSupportedFeaturesStore((s) => s.schemaRegistryContexts);
useEffect(() => {
if (!subject || stateData !== null) return;
const schema = subject.schemas.first((x) => x.version === subject.latestActiveVersion);
if (!schema) {
// biome-ignore lint/suspicious/noConsole: intentional console usage
console.error('Cannot find last active schema version of subject', {
name: subject.name,
lastActiveVersion: subject.latestActiveVersion,
schemas: subject.schemas,
});
return;
}
const schemaText =
schema.type === SchemaType.AVRO || schema.type === SchemaType.JSON
? JSON.stringify(JSON.parse(schema.schema), undefined, 4)
: schema.schema;
const metadataProperties: SchemaEditorStateData['metadataProperties'] = schema.metadata?.properties
? [
...Object.entries(schema.metadata.properties).map(([key, value]) => ({
id: crypto.randomUUID(),
key,
value,
})),
{ id: crypto.randomUUID(), key: '', value: '' },
]
: [{ id: crypto.randomUUID(), key: '', value: '' }];
let userInput: string;
let contextId: string;
if (srContextsEnabled) {
const parsed = parseSubjectContext(subject.name);
contextId = contextNameToId(parsed.context);
userInput = parsed.displayName;
} else {
contextId = '';
userInput = subject.name;
}
queueMicrotask(() =>
setStateData({
strategy: 'CUSTOM',
userInput,
keyOrValue: undefined,
format: schema.type as 'AVRO' | 'PROTOBUF',
schemaText,
references: schema.references.map((r) => ({ ...r, id: crypto.randomUUID(), context: contextId })),
normalize: false,
metadataProperties,
context: contextId,
})
);
}, [subject, stateData, srContextsEnabled]);
if (!subject || stateData === null) return DefaultSkeleton;
const state = deriveSchemaEditorState(stateData);
const setNonNullStateData = setStateData as SetSchemaState;
return (
<PageContent key="b">
<h1 className="text-heading-xl" data-testid="schema-add-version-heading">
Add schema version
</h1>
<SchemaEditor mode="ADD_VERSION" onStateChange={setNonNullStateData} state={state} />
<SchemaPageButtons editorState={state} parentSubjectName={subjectName} />
</PageContent>
);
};
/*
This component is about the "Save", "Validate", and "Cancel" buttons at the bottom of the page.
Those buttons are shared across both page variants, thus it was extracted into its own component
*/
const SchemaPageButtons = (p: {
parentSubjectName?: string; // cancel button needs to know where to navigate to; was the page reached though 'New schema' or 'Add version'?
editorState: SchemaEditorStateHelper;
}) => {
const queryClient = useQueryClient();
const [isValidating, setValidating] = useState(false);
const [isCreating, setCreating] = useState(false);
const [persistentValidationError, setPersistentValidationError] = useState<{
isValid: boolean;
errorDetails?: string;
isCompatible?: boolean;
compatibilityError?: { errorType: string; description: string };
} | null>(null);
const [validationDialogResult, setValidationDialogResult] = useState<typeof persistentValidationError>(null);
const srContextsEnabled = useSupportedFeaturesStore((s) => s.schemaRegistryContexts);
const { editorState } = p;
const isMissingName = !editorState.computedSubjectName;
const isMissingContext = srContextsEnabled && !editorState.context;
return (
<>
{persistentValidationError ? (
<Alert className="my-4" testId="schema-create-validation-error-alert" variant="destructive">
<AlertCircle />
<AlertTitle>
{persistentValidationError.compatibilityError?.errorType
? persistentValidationError.compatibilityError.errorType.replace(/_/g, ' ')
: 'Schema Validation Error'}
</AlertTitle>
<AlertDescription>
{persistentValidationError.compatibilityError?.description ||
persistentValidationError.errorDetails ||
'Schema validation failed'}
</AlertDescription>
<Button
aria-label="Close"
className="absolute top-2 right-2"
onClick={() => setPersistentValidationError(null)}
size="icon-xs"
testId="schema-create-error-close-btn"
variant="ghost"
>
<X />
</Button>
</Alert>
) : null}
<div className="mt-4 flex gap-4">
<Button
disabled={isCreating || isMissingName || isMissingContext || isValidating || editorState.isInvalidKeyOrValue}
onClick={async () => {
// We must validate first, "create" does not properly check and just gives internal server error if anything is wrong with the schema
setValidating(true);
const validationResponse = await validateSchema(editorState).finally(() => setValidating(false));
if (!validationResponse.isValid || validationResponse.isCompatible === false) {
// Something is wrong with the schema, abort
// Persist error only after user closes the modal
setValidationDialogResult(validationResponse);
return;
}
// Clear any previous validation errors
setPersistentValidationError(null);
// try to create the schema
setCreating(true);
try {
const subjectName = editorState.qualifiedSubjectName;
await api
.createSchema(subjectName, {
schemaType: editorState.format as SchemaTypeType,
schema: editorState.schemaText,
references: buildQualifiedReferences(editorState.references, editorState.context),
metadata: editorState.computedMetadata,
params: {
normalize: editorState.normalize,
},
})
.finally(() => setCreating(false));
await Promise.all([
api.refreshSchemaDetails(subjectName, true),
// Invalidate React Query cache so details page shows latest data
queryClient.invalidateQueries({
queryKey: ['schemaRegistry', 'subjects', subjectName, 'details'],
}),
]);
// success: navigate to details with "latest" so it picks up the new version
appGlobal.historyReplace(`/schema-registry/subjects/${encodeURIComponent(subjectName)}?version=latest`);
} catch (err) {
toast.error('Error creating schema', { description: String(err) });
}
}}
testId="schema-create-save-btn"
variant="primary"
>
{isCreating ? 'Creating...' : 'Save'}
</Button>
<Button
disabled={isValidating || isMissingName || isMissingContext || editorState.isInvalidKeyOrValue}
onClick={async () => {
setValidating(true);
const r = await validateSchema(editorState).finally(() => setValidating(false));
if (r.isValid && r.isCompatible !== false) {
// Clear any previous validation errors on successful validation
setPersistentValidationError(null);
toast.success('Schema validated');
} else {
// Persist error only after user closes the modal
setValidationDialogResult(r);
}
}}
testId="schema-create-validate-btn"
variant="outline"
>
{isValidating ? 'Validating...' : 'Validate'}
</Button>
<Button
onClick={() => {
if (p.parentSubjectName) {
appGlobal.historyReplace(`/schema-registry/subjects/${encodeURIComponent(p.parentSubjectName)}`);
} else {
appGlobal.historyReplace('/schema-registry');
}
}}
testId="schema-create-cancel-btn"
variant="link"
>
Cancel
</Button>
</div>
<ValidationErrorsDialog
onClose={() => {
if (validationDialogResult) {
setPersistentValidationError(validationDialogResult);
}
}}
onOpenChange={(open) => {
if (!open) setValidationDialogResult(null);
}}
open={validationDialogResult !== null}
result={validationDialogResult}
/>
</>
);
};
async function validateSchema(state: SchemaEditorStateHelper): Promise<{
isValid: boolean; // is the schema valid at all (can be parsed, no unknown types etc)
errorDetails?: string; // details about why the schema is not valid
isCompatible?: boolean; // is the new schema not compatible with older versions; only set when the schema is valid
compatibilityError?: { errorType: string; description: string }; // detailed compatibility error from schema registry
}> {
if (!state.computedSubjectName) {
return { isValid: false, errorDetails: 'Missing subject name' };
}
const r = await api
.validateSchema(state.qualifiedSubjectName, 'latest', {
schemaType: state.format as SchemaTypeType,
schema: state.schemaText,
references: buildQualifiedReferences(state.references, state.context),
})
.catch(
(err) =>
({
compatibility: { isCompatible: false },
isValid: false,
parsingError: String(err),
}) as SchemaRegistryValidateSchemaResponse
);
return {
isValid: r.isValid,
errorDetails: r.parsingError,
isCompatible: r.isValid ? r.compatibility.isCompatible : undefined,
compatibilityError: r.compatibility.error,
};
}
const SchemaEditor = (p: {
state: SchemaEditorStateHelper;
mode: 'CREATE' | 'ADD_VERSION';
onStateChange: SetSchemaState;
}) => {
const { data: schemaTypes } = useSchemaTypesQuery();
const srContextsEnabled = useSupportedFeaturesStore((s) => s.schemaRegistryContexts);
const { data: apiContexts } = useSchemaRegistryContextsQuery(srContextsEnabled);
const { data: subjects } = useListSchemasQuery();
useEffect(() => {
api.refreshSchemaTypes(true);
}, []);
const { state, mode } = p;
const isAddVersion = mode === 'ADD_VERSION';
const [contextWarning, setContextWarning] = useState('');
const [switchFormatOpen, setSwitchFormatOpen] = useState(false);
const [pendingFormat, setPendingFormat] = useState<string | null>(null);
// Only surface "required" errors after the user has interacted with a field, not on mount.
const [touched, setTouched] = useState<{ context: boolean; topic: boolean }>({ context: false, topic: false });
const availableContexts = useMemo(() => {
if (!(srContextsEnabled && apiContexts && subjects)) return [];
return deriveContexts(apiContexts, subjects).filter((c) => c.id !== ALL_CONTEXT_ID);
}, [srContextsEnabled, apiContexts, subjects]);
const contextOptions = useMemo(
() => availableContexts.map((c) => ({ value: c.label, label: c.label })),
[availableContexts]
);
const contextSelectOptions = useMemo(
() => availableContexts.map((c) => ({ value: c.id, label: c.label })),
[availableContexts]
);
const showTopicNameInput = state.strategy === 'TOPIC' || state.strategy === 'TOPIC_RECORD_NAME';
const isCustom = state.strategy === 'CUSTOM';
const formatOptions = [
{ value: 'AVRO', label: 'Avro' },
{ value: 'PROTOBUF', label: 'Protobuf' },
];
if (schemaTypes?.includes('JSON') || api.schemaTypes?.includes('JSON')) {
formatOptions.push({ value: 'JSON', label: 'JSON' });
}
return (
<>
<h2 className="text-heading-lg">Subject Settings</h2>
{Boolean(isAddVersion) && (
<Alert variant="info">
<InfoIcon />
<AlertDescription>
When adding a new schema version, the only thing that can be changed is the schema definition and its
references. The rest of the fields have been disabled.
</AlertDescription>
</Alert>
)}
<div className="flex max-w-[650px] flex-col gap-8">
{srContextsEnabled && !isAddVersion && (
<Field data-invalid={(touched.context && !state.context) || undefined}>
<FieldLabel>Context</FieldLabel>
<FieldDescription>Select an existing context or type a new name to create one.</FieldDescription>
<Combobox
// Our chakra UI has a global override for SVGs that make icons look off-center in UI registry components.
className="[&_svg]:block! [&_input]:pl-8!"
creatable
createLabel="context"
onChange={(value) => {
const contextId = contextLabelToId(value);
setTouched((t) => ({ ...t, context: true }));
setContextWarning('');
p.onStateChange((prev) => ({
...prev,
context: contextId,
references: prev.references.map((r) => ({ ...r, context: contextId })),
}));
}}
onCreateOption={(value) => {
if (value.startsWith('.')) {
setContextWarning('');
} else {
setContextWarning('Context name must start with a dot (for example, ".staging")');
}
}}
options={contextOptions}
placeholder="Select or create a context..."
testId="schema-create-context-select"
value={contextIdToLabel(state.context)}
/>
{contextWarning && <div className="mt-1 text-body text-destructive">{contextWarning}</div>}
{touched.context && !state.context && <FieldError>Context is required</FieldError>}
</Field>
)}
{srContextsEnabled && isAddVersion && (
<Field>
<FieldLabel>Context</FieldLabel>
<Input disabled value={contextIdToLabel(state.context) || 'None'} />
</Field>
)}
<Field>
<FieldLabel>Strategy</FieldLabel>
<Select
disabled={isAddVersion}
items={{
TOPIC: 'Topic Name',
RECORD_NAME: 'Record Name',
TOPIC_RECORD_NAME: 'Topic-Record Name',
CUSTOM: 'Custom',
}}
onValueChange={(e) => {
setTouched((t) => ({ ...t, topic: false }));
p.onStateChange((prev) => ({ ...prev, userInput: '', strategy: e as NamingStrategy }));
}}
value={state.strategy}
>
<SelectTrigger data-testid="schema-create-strategy-select">
<SelectValue placeholder="Select a strategy..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="TOPIC">Topic Name</SelectItem>
<SelectItem value="RECORD_NAME">Record Name</SelectItem>
<SelectItem value="TOPIC_RECORD_NAME">Topic-Record Name</SelectItem>
<SelectItem value="CUSTOM">Custom</SelectItem>
</SelectContent>
</Select>
</Field>
{showTopicNameInput && (
<Field data-invalid={(touched.topic && !state.userInput) || undefined}>
<FieldLabel>Topic name</FieldLabel>
<Select
disabled={isAddVersion}
onValueChange={(e) => {
setTouched((t) => ({ ...t, topic: true }));
p.onStateChange((prev) => ({ ...prev, userInput: e }));
}}
value={state.userInput}
>
<SelectTrigger data-testid="schema-create-topic-select">
<SelectValue placeholder="Select a topic..." />
</SelectTrigger>
<SelectContent>
{(api.topics?.filter((x) => !x.topicName.startsWith('_')) ?? []).map((x) => (
<SelectItem key={x.topicName} value={x.topicName}>
{x.topicName}
</SelectItem>
))}
</SelectContent>
</Select>
{touched.topic && !state.userInput && <FieldError>Topic name is required</FieldError>}
</Field>
)}
{!isCustom && (
<Field data-invalid={state.isInvalidKeyOrValue || undefined}>
<FieldLabel>Schema applies to</FieldLabel>
<RadioGroup
className="mt-3 flex"
data-testid="schema-create-key-value-radio"
disabled={isAddVersion}
onValueChange={(e) => {
p.onStateChange((prev) => ({ ...prev, keyOrValue: e as 'KEY' | 'VALUE' }));
}}
orientation="horizontal"
value={state.keyOrValue}
>
<div className="flex items-center gap-2">
<RadioGroupItem disabled={isAddVersion} id="key-or-value-key" value="KEY" />
<Label htmlFor="key-or-value-key">Key</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem disabled={isAddVersion} id="key-or-value-value" value="VALUE" />
<Label htmlFor="key-or-value-value">Value</Label>
</div>
</RadioGroup>
<FieldDescription>
Determines whether this schema is registered for the topic's key or value messages.
</FieldDescription>
{state.isInvalidKeyOrValue && <FieldError>Required</FieldError>}
</Field>
)}
{isCustom && (
<Field data-invalid={!state.computedSubjectName || undefined}>
<FieldLabel>Subject name</FieldLabel>
<Input
disabled={isAddVersion}
onChange={(e) => {
p.onStateChange((prev) => ({ ...prev, userInput: e.target.value }));
}}
testId="schema-create-subject-name-input"
value={state.computedSubjectName}
/>
{!state.computedSubjectName && <FieldError>Subject name is required</FieldError>}
</Field>
)}
{!isCustom && state.computedSubjectName && (
<>
<Separator />
<div className="flex flex-col gap-0.5">
<div className="font-medium text-body-sm uppercase">Subject name</div>
<div className="font-mono text-body">{state.computedSubjectName}</div>
</div>
</>
)}
{srContextsEnabled &&
state.qualifiedSubjectName &&
state.qualifiedSubjectName !== state.computedSubjectName && (
<div className="flex flex-col gap-0.5">
<div className="font-medium text-body-sm uppercase">Qualified subject name</div>
<div className="font-mono text-body">
{isNamedContext(state.context) ? (
<>
<span className="font-mono text-body text-gray-400">:{state.context}:</span>
<span className="font-mono text-body">{state.computedSubjectName}</span>
</>
) : (
state.qualifiedSubjectName
)}
</div>
</div>
)}
</div>
<h2 className="mt-8 text-heading-lg">Schema definition</h2>
<div className="flex max-w-[1000px] flex-col gap-4">
<Field>
<FieldLabel>Format</FieldLabel>
<ToggleGroup
className="w-fit! divide-x divide-border p-0"
data-testid="schema-create-format-radio"
disabled={isAddVersion}
onValueChange={([e]) => {
if (!e || state.format === e) {
return;
}
// Let user confirm
setPendingFormat(e);
setSwitchFormatOpen(true);
}}
value={[state.format]}
variant="outline"
>
{formatOptions.map((opt) => (
<ToggleGroupItem className="px-4" disabled={isAddVersion} key={opt.value} value={opt.value}>
{opt.label}
</ToggleGroupItem>
))}
</ToggleGroup>
</Field>
<div data-testid="schema-create-schema-editor">
<KowlEditor
height="400px"
language={state.format === 'PROTOBUF' ? 'proto' : 'json'}
onChange={(e) => {
p.onStateChange((prev) => ({ ...prev, schemaText: e ?? '' }));
}}
value={state.schemaText}
/>
</div>
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<span className="font-semibold">Normalize schema</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={<InfoIcon className="h-4 w-4 cursor-help text-gray-500" />} />
<TooltipContent side="right">
When enabled, the schema will be normalized to a canonical form before registration, reducing
duplicate schema versions
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<Switch
checked={state.normalize}
onCheckedChange={(checked) => {
p.onStateChange((prev) => ({ ...prev, normalize: checked === true }));
}}
/>
</div>
<h2 className="mt-8 text-heading-lg">Schema references</h2>
<div className="text-body">
Link other schemas that this schema depends on. References allow schemas to reuse types defined in other
subjects.
</div>
<ReferencesEditor
contextSelectOptions={contextSelectOptions}
onStateChange={p.onStateChange}
parentContext={state.context}
srContextsEnabled={srContextsEnabled}
state={state}
/>
<h2 className="mt-8 text-heading-lg">Schema metadata</h2>
<div className="w-1/2 text-body">
Optional key-value properties to associate with this schema. Metadata will be ignored if not supported by
Schema Registry.
</div>
<MetadataPropertiesEditor onStateChange={p.onStateChange} state={state} />
</div>
<SwitchSchemaFormatDialog
onConfirm={() => {
if (pendingFormat) {
p.onStateChange((prev) => ({
...prev,
format: pendingFormat as 'AVRO' | 'PROTOBUF' | 'JSON',
schemaText: exampleSchema[pendingFormat as SchemaTypeType],
}));
setPendingFormat(null);
}
}}
onOpenChange={setSwitchFormatOpen}
open={switchFormatOpen}
/>
</>
);
};
const ReferencesEditor = (p: {
state: SchemaEditorStateHelper;
onStateChange: SetSchemaState;
srContextsEnabled: boolean;
parentContext: string;
contextSelectOptions: { value: string; label: string }[];
}) => {
const refs = p.state.references;
const subjectsByContext = useMemo(() => {
const allSubjects = api.schemaSubjects?.filter((x) => !x.isSoftDeleted) ?? [];
if (!p.srContextsEnabled) return new Map([['__all__', allSubjects.map((x) => ({ value: x.name }))]]);
const map = new Map<string, { value: string }[]>();
for (const s of allSubjects) {
const parsed = parseSubjectContext(s.name);
const key = contextNameToId(parsed.context);
const list = map.get(key) ?? [];
list.push({ value: parsed.displayName });
map.set(key, list);
}
return map;
}, [p.srContextsEnabled, api.schemaSubjects]);
const getSubjectsForContext = (contextId: string) => {
if (!p.srContextsEnabled) return subjectsByContext.get('__all__') ?? [];
return subjectsByContext.get(contextId) ?? [];
};
const renderRow = (ref: (typeof refs)[number], index: number) => {
const refQualified =
p.srContextsEnabled && ref.context !== p.parentContext
? buildQualifiedSubjectName(ref.context, ref.subject)
: null;
return (
<div className="flex flex-col gap-2" key={ref.id}>
<div className="flex items-end gap-4">
<Field>
<FieldLabel>Schema reference name</FieldLabel>
<Input
data-testid={`schema-create-reference-name-input-${index}`}
onChange={(e) => {
p.onStateChange((prev) => ({
...prev,
references: prev.references.map((r, i) => (i === index ? { ...r, name: e.target.value } : r)),
}));
}}
value={ref.name}
/>
</Field>
{p.srContextsEnabled && (
<Field>
<FieldLabel>Context</FieldLabel>
<Select
items={p.contextSelectOptions}
onValueChange={(contextId) => {
p.onStateChange((prev) => ({
...prev,
references: prev.references.map((r, i) =>
i === index ? { ...r, context: contextId, subject: '' } : r
),
}));
}}
value={ref.context}
>
<SelectTrigger data-testid={`schema-create-reference-context-select-${index}`}>
<SelectValue placeholder="Context..." />
</SelectTrigger>
<SelectContent>
{p.contextSelectOptions.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)}
<Field>
<FieldLabel>Subject</FieldLabel>
<Select
onValueChange={async (e) => {
p.onStateChange((prev) => ({
...prev,
references: prev.references.map((r, i) => (i === index ? { ...r, subject: e } : r)),
}));
// For fetching details, we need the qualified name
const qualifiedRefSubject = buildQualifiedSubjectName(ref.context, e);
let details = api.schemaDetails.get(qualifiedRefSubject);
if (!details) {
await api.refreshSchemaDetails(qualifiedRefSubject, true);
details = api.schemaDetails.get(qualifiedRefSubject);
}
if (!details) {
return; // failed to get details
}
p.onStateChange((prev) => {
const r = prev.references[index];
// Need to make sure that, after refreshing, the subject is still the same
if (r?.subject !== e) return prev;
return {
...prev,
references: prev.references.map((r, i) =>
i === index ? { ...r, version: details.latestActiveVersion } : r
),
};
});
}}
value={ref.subject}
>
<SelectTrigger data-testid={`schema-create-reference-subject-select-${index}`}>
<SelectValue placeholder="Select a subject..." />
</SelectTrigger>
<SelectContent>
{getSubjectsForContext(ref.context).map((x) => (
<SelectItem key={x.value} value={x.value}>
{x.value}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel>Version</FieldLabel>
<Select
onValueChange={(e) => {
p.onStateChange((prev) => ({
...prev,
references: prev.references.map((r, i) => (i === index ? { ...r, version: Number(e) } : r)),
}));
}}
value={String(ref.version)}
>
<SelectTrigger data-testid={`schema-create-reference-version-select-${index}`}>
<SelectValue placeholder="Version" />
</SelectTrigger>
<SelectContent>
{(
api.schemaDetails
.get(buildQualifiedSubjectName(ref.context, ref.subject))
?.versions.filter((v) => !v.isSoftDeleted) ?? []
).map((x) => (
<SelectItem key={x.version} value={String(x.version)}>
{x.version}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Button
aria-label="delete"