-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathutils.tsx
1001 lines (937 loc) · 30.8 KB
/
utils.tsx
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 OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
import React, { ReactNode, useEffect, useState } from 'react';
import yaml from 'js-yaml';
import jsonpath from 'jsonpath';
import { capitalize, escape, findKey, get, isEmpty, set, unset } from 'lodash';
import { EuiText } from '@elastic/eui';
import semver from 'semver';
import queryString from 'query-string';
import { useLocation } from 'react-router-dom';
import {
JSONPATH_ROOT_SELECTOR,
MODEL_OUTPUT_SCHEMA_FULL_PATH,
MODEL_OUTPUT_SCHEMA_NESTED_PATH,
ModelInputFormField,
ModelInterface,
ModelOutput,
ModelOutputFormField,
PROCESSOR_CONTEXT,
REQUEST_PREFIX,
REQUEST_PREFIX_WITH_JSONPATH_ROOT_SELECTOR,
SimulateIngestPipelineDoc,
SimulateIngestPipelineResponse,
TRANSFORM_CONTEXT,
WORKFLOW_RESOURCE_TYPE,
WORKFLOW_STEP_TYPE,
Workflow,
WorkflowResource,
BEDROCK_CONFIGS,
COHERE_CONFIGS,
OPENAI_CONFIGS,
customStringify,
NO_TRANSFORMATION,
TRANSFORM_TYPE,
VECTOR_FIELD_PATTERN,
VECTOR_PATTERN,
TEXT_FIELD_PATTERN,
IMAGE_FIELD_PATTERN,
LABEL_FIELD_PATTERN,
MODEL_ID_PATTERN,
WORKFLOW_TYPE,
MIN_SUPPORTED_VERSION,
MINIMUM_FULL_SUPPORTED_VERSION,
} from '../../common';
import {
getCore,
getDataSourceEnabled,
getRouteService,
getSavedObjectsClient,
} from '../services';
import {
Connector,
IngestPipelineErrors,
InputMapEntry,
MapFormValue,
MDSQueryParams,
ModelInputMap,
ModelOutputMap,
OutputMapEntry,
OutputMapFormValue,
QueryParam,
SearchPipelineErrors,
SearchResponseVerbose,
SimulateIngestPipelineResponseVerbose,
} from '../../common/interfaces';
import * as pluginManifest from '../../opensearch_dashboards.json';
import { DataSourceAttributes } from '../../../../src/plugins/data_source/common/data_sources';
import { SavedObject } from '../../../../src/core/public';
// Generate a random ID. Optionally add a prefix. Optionally
// override the default # characters to generate.
export function generateId(prefix?: string, numChars: number = 16): string {
const uniqueChar = () => {
// eslint-disable-next-line no-bitwise
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
const uniqueId = `${uniqueChar()}${uniqueChar()}${uniqueChar()}${uniqueChar()}`;
return `${prefix || ''}_${uniqueId.substring(0, numChars)}`;
}
export function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export function hasProvisionedIngestResources(
workflow: Workflow | undefined
): boolean {
let result = false;
workflow?.resourcesCreated?.some((resource) => {
if (
resource.stepType ===
WORKFLOW_STEP_TYPE.CREATE_INGEST_PIPELINE_STEP_TYPE ||
resource.stepType === WORKFLOW_STEP_TYPE.CREATE_INDEX_STEP_TYPE
) {
result = true;
}
});
return result;
}
export function hasProvisionedSearchResources(
workflow: Workflow | undefined
): boolean {
let result = false;
workflow?.resourcesCreated?.some((resource) => {
if (
resource.stepType === WORKFLOW_STEP_TYPE.CREATE_SEARCH_PIPELINE_STEP_TYPE
) {
result = true;
}
});
return result;
}
// returns a comma-delimited string of all resource IDs that need to be force deleted.
// see https://github.com/opensearch-project/flow-framework/pull/763
export function getResourcesToBeForceDeleted(
workflow: Workflow | undefined
): string | undefined {
const resources = workflow?.resourcesCreated?.filter(
(workflowResource) =>
workflowResource.type === WORKFLOW_RESOURCE_TYPE.INDEX_NAME ||
workflowResource.type === WORKFLOW_RESOURCE_TYPE.PIPELINE_ID
);
if (resources !== undefined && resources.length > 0) {
return resources
.map((resource) => resource.id)
.map(String)
.join(',');
} else {
return undefined;
}
}
export function getObjFromJsonOrYamlString(
fileContents?: string
): object | undefined {
try {
// @ts-ignore
const jsonObj = JSON.parse(fileContents);
return jsonObj;
} catch (e) {}
try {
// @ts-ignore
const yamlObj = yaml.load(fileContents) as object;
return yamlObj;
} catch (e) {}
return undefined;
}
// Based off of https://opensearch.org/docs/latest/automating-configurations/api/create-workflow/#request-fields
// Only "name" field is required
export function isValidWorkflow(workflowObj: any): boolean {
return workflowObj?.name !== undefined;
}
// Determines if a file used for import workflow is compatible with the current data source version.
export async function isCompatibleWorkflow(
workflowObj: any,
dataSourceId?: string | undefined
): Promise<boolean> {
const compatibility = workflowObj?.version?.compatibility;
// Default to true when compatibility cannot be assessed (empty/invalid compatibility array or MDS disabled.)
if (
!Array.isArray(compatibility) ||
compatibility.length === 0 ||
dataSourceId === undefined
) {
return true;
}
const dataSourceVersion =
(await getDataSourceVersion(dataSourceId)) || MIN_SUPPORTED_VERSION;
const [
effectiveMajorVersion,
effectiveMinorVersion,
] = dataSourceVersion.split('.').map(Number);
// Checks if any version in compatibility array matches the current dataSourceVersion (major.minor)
return compatibility.some((compatibleVersion) => {
const [compatibleMajor, compatibleMinor] = compatibleVersion
.split('.')
.map(Number);
return (
effectiveMajorVersion === compatibleMajor &&
effectiveMinorVersion === compatibleMinor
);
});
}
export function isValidUiWorkflow(workflowObj: any): boolean {
return (
isValidWorkflow(workflowObj) &&
workflowObj?.ui_metadata?.config !== undefined &&
workflowObj?.ui_metadata?.type !== undefined &&
Object.values(WORKFLOW_TYPE).includes(workflowObj?.ui_metadata?.type)
);
}
// Docs are expected to be in a certain format to be passed to the simulate ingest pipeline API.
// for details, see https://opensearch.org/docs/latest/ingest-pipelines/simulate-ingest
export function prepareDocsForSimulate(
docs: string,
indexName: string
): SimulateIngestPipelineDoc[] {
const preparedDocs = [] as SimulateIngestPipelineDoc[];
const docObjs = getObjsFromJSONLines(docs);
docObjs?.forEach((doc) => {
preparedDocs.push({
_index: indexName,
_id: generateId(),
_source: doc,
});
});
return preparedDocs;
}
// Utility fn to transform a raw JSON Lines string into an arr of JSON objs
// for easier downstream parsing
export function getObjsFromJSONLines(jsonLines: string | undefined): {}[] {
let objs = [] as {}[];
try {
const lines = jsonLines?.split('\n') as string[];
lines.forEach((line) => objs.push(JSON.parse(line)));
} catch {}
return objs;
}
// Docs are returned in a certain format from the simulate ingest pipeline API. We want
// to format them into a more readable string to display
export function unwrapTransformedDocs(
simulatePipelineResponse: SimulateIngestPipelineResponse
): any[] {
let errorDuringSimulate = undefined as string | undefined;
const transformedDocsSources = simulatePipelineResponse.docs.map(
(transformedDoc) => {
if (transformedDoc.error !== undefined) {
errorDuringSimulate = transformedDoc.error.reason || '';
} else {
return transformedDoc.doc._source;
}
}
);
// there is an edge case where simulate may fail if there is some server-side or OpenSearch issue when
// running ingest (e.g., hitting rate limits on remote model)
// We pull out any returned error from a document and propagate it to the user.
if (errorDuringSimulate !== undefined) {
getCore().notifications.toasts.addDanger(
`Failed to simulate ingest on all documents: ${errorDuringSimulate}`
);
}
return transformedDocsSources;
}
// Extract any processor-level errors from a verbose simulate ingest pipeline API call
export function getIngestPipelineErrors(
simulatePipelineResponse: SimulateIngestPipelineResponseVerbose
): IngestPipelineErrors {
let ingestPipelineErrors = {} as IngestPipelineErrors;
simulatePipelineResponse.docs?.forEach((docResult) => {
docResult.processor_results.forEach((processorResult, idx) => {
if (processorResult.error?.reason !== undefined) {
ingestPipelineErrors[idx] = {
processorType: processorResult.processor_type,
errorMsg: processorResult.error.reason,
};
}
});
});
return ingestPipelineErrors;
}
// Extract any processor-level errors from a verbose search API call
export function getSearchPipelineErrors(
searchResponseVerbose: SearchResponseVerbose
): SearchPipelineErrors {
let searchPipelineErrors = {} as SearchPipelineErrors;
searchResponseVerbose.processor_results?.forEach((processorResult, idx) => {
if (processorResult?.error !== undefined) {
searchPipelineErrors[idx] = {
processorType: processorResult.processor_name,
errorMsg: processorResult.error,
};
}
});
return searchPipelineErrors;
}
// Generate a more UI-friendly layout of a processor error
export function formatProcessorError(processorError: {
processorType: string;
errorMsg: string;
}): ReactNode {
return (
<>
<EuiText size="s">
{`Processor type:`} <b>{capitalize(processorError.processorType)}</b>
</EuiText>
<EuiText size="s">
{`Error:`} <b>{processorError.errorMsg}</b>
</EuiText>
</>
);
}
// ML inference processors will use standard dot notation or JSONPath depending on the input.
// We follow the same logic here to generate consistent results.
export function generateTransform(
input: {} | [],
map: (InputMapEntry | OutputMapEntry)[],
context: PROCESSOR_CONTEXT,
transformContext: TRANSFORM_CONTEXT,
queryContext?: {}
): {} {
let output = {};
map.forEach((mapEntry) => {
try {
const transformedResult = getTransformedResult(
input,
mapEntry.value.value || '',
context,
transformContext,
queryContext
);
output = {
...output,
[mapEntry.key]: transformedResult || '',
};
} catch (e: any) {}
});
return output;
}
// Similar to generateTransform, but collapse the values of the input array into
// a single field value in the transformed output.
// A specialty scenario for when configuring input on search response processors, one-to-one is false,
// and the input is an array.
export function generateArrayTransform(
input: [],
map: (InputMapEntry | OutputMapEntry)[],
context: PROCESSOR_CONTEXT,
transformContext: TRANSFORM_CONTEXT,
queryContext?: {}
): {}[] {
let output = [] as {}[];
map.forEach((mapEntry) => {
try {
// If users define a path using the special query request
// prefix, parse the query context, instead of the other input.
let transformedResult;
if (
(mapEntry.value.value?.startsWith(REQUEST_PREFIX) ||
mapEntry.value.value?.startsWith(
REQUEST_PREFIX_WITH_JSONPATH_ROOT_SELECTOR
)) &&
queryContext !== undefined &&
!isEmpty(queryContext)
) {
transformedResult = getTransformedResult(
{},
mapEntry.value.value,
context,
transformContext,
queryContext
);
} else {
transformedResult = input.map((inputEntry) =>
getTransformedResult(
inputEntry,
mapEntry.value.value || '',
context,
transformContext,
queryContext
)
);
}
output = {
...output,
[mapEntry.key]: transformedResult || '',
};
} catch (e: any) {}
});
return output;
}
function getTransformedResult(
input: {},
path: string,
context: PROCESSOR_CONTEXT,
transformContext: TRANSFORM_CONTEXT,
queryContext?: {}
): any {
// Regular dot notation can only be executed if 1/ the JSONPath selector is not explicitly defined,
// and 2/ it is in the context of ingest, and 3/ it is transforming the input (the source document).
// For all other scenarios, it can only be JSONPath, due to backend parsing limitations.
if (
!path.startsWith(JSONPATH_ROOT_SELECTOR) &&
context === PROCESSOR_CONTEXT.INGEST &&
transformContext === TRANSFORM_CONTEXT.INPUT
) {
// sub-edge case: if the path is ".", it implies returning
// the entire value. This may happen if full_response_path=false
// and the input is the entire result with nothing else to parse out.
// get() does not cover this case, so we override manually.
if (path === '.') {
return input;
} else {
return get(input, path);
}
// If users define a path using the special query request
// prefix, parse the query context, instead of the other input.
} else if (
(path.startsWith(REQUEST_PREFIX) ||
path.startsWith(REQUEST_PREFIX_WITH_JSONPATH_ROOT_SELECTOR)) &&
queryContext !== undefined &&
!isEmpty(queryContext)
) {
const updatedPath = path.startsWith(REQUEST_PREFIX)
? path.replace(REQUEST_PREFIX, '')
: path.replace(REQUEST_PREFIX_WITH_JSONPATH_ROOT_SELECTOR, '');
return executeJsonPath(queryContext, updatedPath);
} else {
return executeJsonPath(input, path);
}
}
// The backend sets a JSONPath setting ALWAYS_RETURN_LIST=false, which
// dynamically returns a list or single value, based on whether
// the path is definite or not. We try to mimic that with a
// custom fn isIndefiniteJsonPath(), since this setting, nor
// knowing if the path is definite or indefinite, is not exposed
// by any known jsonpath JS-based / NPM libraries.
// if found to be definite, we remove the outermost array, which
// will always be returned by default when running query().
function executeJsonPath(input: {}, path: string): any[] {
const isIndefinite = isIndefiniteJsonPath(path);
const res = jsonpath.query(input, path);
if (isIndefinite) {
return res;
} else {
return res[0];
}
}
// Indefinite/definite path defns:
// https://github.com/json-path/JsonPath?tab=readme-ov-file#what-is-returned-when
// Note this may not cover every use case, as the true definition requires low-level
// branch navigation of the path nodes, which is not exposed by this npm library.
// Hence, we do our best to cover the majority of use cases and common patterns.
function isIndefiniteJsonPath(path: string): boolean {
// regex has 3 overall OR checks:
// 1. consecutive '.'s, indicating deep scan - \.{2}
// 2. ?(<anything>), indicating an expression - \?\(.*\)
// 3. multiple array indices - \[\d+,\d+\] | \[.*:.*\] | \[\*\]
// if any are met, then we call the path indefinite.
const indefiniteRegEx = new RegExp(
/\.{2}|\?\(.*\)|\[\d+,\d+\]|\[.*:.*\]|\[\*\]/,
'g'
);
return indefiniteRegEx.test(path);
}
// Derive the collection of model inputs from the model interface JSONSchema into a form-ready list
export function parseModelInputs(
modelInterface: ModelInterface | undefined
): ModelInputFormField[] {
const modelInputsObj = parseModelInputsObj(modelInterface);
return Object.keys(modelInputsObj).map(
(inputName: string) =>
({
label: inputName,
...modelInputsObj[inputName],
} as ModelInputFormField)
);
}
// Derive the collection of model inputs as an obj
export function parseModelInputsObj(
modelInterface: ModelInterface | undefined
): ModelInputMap {
return get(
modelInterface,
// model interface input values will always be nested under a base "parameters" obj.
// we iterate through the obj properties to extract the individual inputs
'input.properties.parameters.properties',
{}
) as ModelInputMap;
}
// Derive the collection of model outputs from the model interface JSONSchema into a form-ready list.
// Expose the full path or nested path depending on fullResponsePath
export function parseModelOutputs(
modelInterface: ModelInterface | undefined,
fullResponsePath: boolean = false
): ModelOutputFormField[] {
const modelOutputsObj = get(
modelInterface,
fullResponsePath
? MODEL_OUTPUT_SCHEMA_FULL_PATH
: MODEL_OUTPUT_SCHEMA_NESTED_PATH,
{}
) as {
[key: string]: ModelOutput;
};
return Object.keys(modelOutputsObj).map(
(outputName: string) =>
({
label: outputName,
...modelOutputsObj[outputName],
} as ModelOutputFormField)
);
}
// Derive the collection of model outputs as an obj.
// Expose the full path or nested path depending on fullResponsePath
export function parseModelOutputsObj(
modelInterface: ModelInterface | undefined,
fullResponsePath: boolean = false
): ModelOutputMap {
return get(
modelInterface,
fullResponsePath
? MODEL_OUTPUT_SCHEMA_FULL_PATH
: MODEL_OUTPUT_SCHEMA_NESTED_PATH,
{}
) as ModelOutputMap;
}
export const getDataSourceFromURL = (location: {
search: string;
}): MDSQueryParams => {
const queryParams = queryString.parse(location.search);
const dataSourceId = queryParams.dataSourceId;
return {
dataSourceId:
typeof dataSourceId === 'string' ? escape(dataSourceId) : undefined,
};
};
export const constructHrefWithDataSourceId = (
basePath: string,
dataSourceId: string = ''
): string => {
const dataSourceEnabled = getDataSourceEnabled().enabled;
const url = new URLSearchParams();
if (dataSourceEnabled && dataSourceId !== undefined) {
url.set('dataSourceId', dataSourceId);
}
return `#${basePath}?${url.toString()}`;
};
export const constructUrlWithParams = (
basePath: string,
workflowId?: string,
dataSourceId?: string
): string => {
const path = workflowId ? `${basePath}/${workflowId}` : basePath;
return `${path}${
dataSourceId !== undefined ? `?dataSourceId=${dataSourceId}` : ''
}`;
};
export const getDataSourceId = () => {
const location = useLocation();
const mdsQueryParams = getDataSourceFromURL(location);
return mdsQueryParams.dataSourceId;
};
export function useDataSourceVersion(
dataSourceId: string | undefined
): string | undefined {
const [dataSourceVersion, setDataSourceVersion] = useState<
string | undefined
>(undefined);
useEffect(() => {
async function getVersion() {
if (dataSourceId !== undefined) {
setDataSourceVersion(await getDataSourceVersion(dataSourceId));
}
}
getVersion();
}, [dataSourceId]);
return dataSourceVersion;
}
export function getIsPreV219(dataSourceVersion: string | undefined): boolean {
return dataSourceVersion !== undefined
? semver.lt(dataSourceVersion, MINIMUM_FULL_SUPPORTED_VERSION)
: false;
}
export const isDataSourceReady = (dataSourceId?: string) => {
const dataSourceEnabled = getDataSourceEnabled().enabled;
return !dataSourceEnabled || dataSourceId !== undefined;
};
// converts camelCase to a space-delimited string with the first word capitalized.
// useful for converting config IDs (in snake_case) to a formatted form title
export function camelCaseToTitleString(snakeCaseString: string): string {
return snakeCaseString
.split('_')
.filter((word) => word.length > 0)
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
export const dataSourceFilterFn = (
dataSource: SavedObject<DataSourceAttributes>
) => {
const dataSourceVersion = dataSource?.attributes?.dataSourceVersion || '';
const installedPlugins = dataSource?.attributes?.installedPlugins || [];
return (
semver.satisfies(
dataSourceVersion,
pluginManifest.supportedOSDataSourceVersions
) &&
pluginManifest.requiredOSDataSourcePlugins.every((plugin) =>
installedPlugins.includes(plugin)
)
);
};
export const extractIdsByStepType = (resources: WorkflowResource[]) => {
const ids = resources.reduce(
(
acc: {
indexIds: string[];
ingestPipelineIds: string[];
searchPipelineIds: string[];
},
item: WorkflowResource
) => {
switch (item.stepType) {
case WORKFLOW_STEP_TYPE.CREATE_INDEX_STEP_TYPE:
acc.indexIds.push(item.id);
break;
case WORKFLOW_STEP_TYPE.CREATE_INGEST_PIPELINE_STEP_TYPE:
acc.ingestPipelineIds.push(item.id);
break;
case WORKFLOW_STEP_TYPE.CREATE_SEARCH_PIPELINE_STEP_TYPE:
acc.searchPipelineIds.push(item.id);
break;
}
return acc;
},
{ indexIds: [], ingestPipelineIds: [], searchPipelineIds: [] }
);
return {
indexIds: ids.indexIds.join(','),
ingestPipelineIds: ids.ingestPipelineIds.join(','),
searchPipelineIds: ids.searchPipelineIds.join(','),
};
};
export const getErrorMessageForStepType = (
stepType: WORKFLOW_STEP_TYPE,
getIndexErrorMessage: string,
getIngestPipelineErrorMessage: string,
getSearchPipelineErrorMessage: string
) => {
switch (stepType) {
case WORKFLOW_STEP_TYPE.CREATE_INDEX_STEP_TYPE:
return getIndexErrorMessage;
case WORKFLOW_STEP_TYPE.CREATE_INGEST_PIPELINE_STEP_TYPE:
return getIngestPipelineErrorMessage;
case WORKFLOW_STEP_TYPE.CREATE_SEARCH_PIPELINE_STEP_TYPE:
return getSearchPipelineErrorMessage;
default:
return '';
}
};
// Sanitize the nested keys in a given JSONPath definition.
// to ensure it works consistently on the frontend & backend. There are several discrepancies
// between the frontend and the backend packages, such that some
// scenarios will succeed on the frontend and fail on the backend,
// or vice versa.
export function sanitizeJSONPath(path: string): string {
return path?.split('.').reduce((prevValue, curValue, idx) => {
// Case 1: accessing array via dot notation. Fails on the backend.
if (!isNaN(parseInt(curValue))) {
return prevValue + `[${curValue}]`;
// Case 2: accessing key with a dash via dot notation. Fails on the frontend.
} else if (curValue.includes('-')) {
return prevValue + `["${curValue}"]`;
} else {
return prevValue + '.' + curValue;
}
});
}
// given a stringified query, extract out all unique placeholder vars
// that follow the pattern {{some-placeholder}}
export function getPlaceholdersFromQuery(queryString: string): string[] {
const regex = /\{\{([^}]+)\}\}/g;
return [
// convert to set to collapse duplicate names
...new Set([...queryString.matchAll(regex)].map((match) => match[1])),
];
}
// simple fn to check if the values in an arr are the same. used for
// checking if the same set of placeholders exists when a new query is selected,
// or an existing query is updated.
export function containsSameValues(arr1: string[], arr2: string[]) {
if (arr1.length !== arr2.length) {
return false;
}
arr1.sort();
arr2.sort();
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
// simple util fn to check for empty/missing query param values
export function containsEmptyValues(params: QueryParam[]): boolean {
let containsEmpty = false;
params.forEach((param) => {
if (isEmpty(param.value)) {
containsEmpty = true;
}
});
return containsEmpty;
}
// simple util fn to inject parameters in the base query string with its associated value
export function injectParameters(
params: QueryParam[],
queryString: string
): string {
let finalQueryString = queryString;
params.forEach((param) => {
finalQueryString = finalQueryString.replace(
new RegExp(`{{${param.name}}}`, 'g'),
param.value
);
});
return finalQueryString;
}
// Fetch embedding dimensions, if the selected model is a known one
export function getEmbeddingModelDimensions(
connector: Connector
): number | undefined {
// some APIs allow specifically setting the dimensions at runtime,
// so we check for that first.
if (connector?.parameters?.dimensions !== undefined) {
return connector.parameters?.dimensions;
} else if (connector?.parameters?.model !== undefined) {
return (
// @ts-ignore
COHERE_CONFIGS[connector.parameters?.model]?.dimension ||
// @ts-ignore
OPENAI_CONFIGS[connector.parameters?.model]?.dimension ||
// @ts-ignore
BEDROCK_CONFIGS[connector.parameters?.model]?.dimension
);
} else {
return undefined;
}
}
// Check if an index is a knn index
export function isKnnIndex(existingSettings: string): boolean {
try {
return get(JSON.parse(existingSettings), 'index.knn', false);
} catch (error) {
console.error('Could not parse index settings: ', error);
return false;
}
}
// Update the index settings based on parameters passed.
// Currently just used for updating the `knn` flag.
export function getUpdatedIndexSettings(
existingSettings: string,
knnBool: boolean
): string {
try {
return customStringify(
set(JSON.parse(existingSettings), 'index.knn', knnBool)
);
} catch {
return existingSettings;
}
}
// Get any embedding fields, if a known embedding model
function getEmbeddingFieldFromConnector(
connector: Connector
): string | undefined {
if (connector?.parameters?.model !== undefined) {
return (
// @ts-ignore
COHERE_CONFIGS[connector?.parameters?.model]?.fieldName ||
// @ts-ignore
OPENAI_CONFIGS[connector?.parameters?.model]?.fieldName ||
// @ts-ignore
BEDROCK_CONFIGS[connector?.parameters?.model]?.fieldName
);
} else {
return undefined;
}
}
// Try to determine the embedding field based on the processor config.
// First check if it is a known model, then make a best guess based on
// the output map configuration, if there is any transformations made
export function getEmbeddingField(
connector: Connector,
processorConfig: any
): string | undefined {
let embeddingField = getEmbeddingFieldFromConnector(connector);
const outputMap = processorConfig?.output_map as OutputMapFormValue;
// legacy text_embedding / text_image_embedding processors store vector fields
// in different configs
const fieldMap = processorConfig?.field_map as MapFormValue; // text embedding processor
const embedding = processorConfig?.embedding; // text/image embedding processor
if (
outputMap !== undefined &&
outputMap[0] !== undefined &&
Array.isArray(outputMap[0]) &&
outputMap[0].length > 0
) {
const relevantOutputMapEntry =
embeddingField !== undefined
? outputMap[0].find(
(outputMapEntry) => outputMapEntry.key === embeddingField
)
: outputMap[0][0];
switch (relevantOutputMapEntry?.value?.transformType) {
case TRANSFORM_TYPE.FIELD: {
embeddingField = relevantOutputMapEntry?.value?.value;
break;
}
case TRANSFORM_TYPE.EXPRESSION: {
embeddingField = get(relevantOutputMapEntry, 'value.nestedVars.0.name');
break;
}
case NO_TRANSFORMATION:
case undefined:
default: {
embeddingField = relevantOutputMapEntry?.key;
break;
}
}
} else if (embedding !== undefined) {
embeddingField = embedding;
} else if (fieldMap !== undefined) {
embeddingField = get(fieldMap, '0.value', embeddingField);
}
return embeddingField;
}
// Update the index mappings based on parameters passed.
// Currently used for updating the knn_vector field configuration, & removing
// any old/existing knn_vector field in the process.
export function getUpdatedIndexMappings(
existingMappings: string,
embeddingFieldName: string,
dimension: number
): string {
try {
const mappingsWithRemovedVectorField = removeVectorFieldFromIndexMappings(
existingMappings
);
return customStringify(
set(
JSON.parse(mappingsWithRemovedVectorField),
`properties.${embeddingFieldName}`,
{
type: 'knn_vector',
dimension,
}
)
);
} catch {
return existingMappings;
}
}
export function removeVectorFieldFromIndexMappings(
existingMappings: string
): string {
try {
let existingMappingsObj = JSON.parse(existingMappings);
const existingEmbeddingField = findKey(
existingMappingsObj?.properties,
(field) => field.type === 'knn_vector'
);
if (existingEmbeddingField !== undefined) {
unset(existingMappingsObj?.properties, existingEmbeddingField);
}
return customStringify(existingMappingsObj);
} catch {
return existingMappings;
}
}
// Parse out any hidden errors within a 2xx ingest response
export function parseErrorsFromIngestResponse(
ingestResponse: any
): string | undefined {
if (get(ingestResponse, 'errors', false)) {
return get(
ingestResponse,
'items.0.index.error.reason',
'Error ingesting documents'
);
}
return;
}
// Update the target query string placeholders into valid placeholder format. Used to disambiguate
// placeholders (${text_field}) vs. dynamic parameters (e.g., "{{query_text}}")
export function injectPlaceholdersInQueryString(query: string): string {
return query
.replace(new RegExp(`"${VECTOR_FIELD_PATTERN}"`, 'g'), `\$\{vector_field\}`)
.replace(new RegExp(`"${VECTOR_PATTERN}"`, 'g'), `\$\{vector\}`)
.replace(new RegExp(`"${TEXT_FIELD_PATTERN}"`, 'g'), `\$\{text_field\}`)
.replace(new RegExp(`"${IMAGE_FIELD_PATTERN}"`, 'g'), `\$\{image_field\}`)
.replace(new RegExp(`"${LABEL_FIELD_PATTERN}"`, 'g'), `\$\{label_field\}`)
.replace(new RegExp(`"${MODEL_ID_PATTERN}"`, 'g'), `\$\{model_id\}`);
}
// Utility fn to parse out a JSON obj and find some value for a given field.
// Primarily used to traverse index mappings and check that values are valid.
export function getFieldValue(jsonObj: {}, fieldName: string): any | undefined {
if (typeof jsonObj !== 'object' || jsonObj === undefined) return undefined;
if (fieldName in jsonObj) {
return get(jsonObj, fieldName) as any;
}
for (const key in jsonObj) {
const result = getFieldValue(get(jsonObj, key), fieldName);
if (result !== undefined) {
return result;
}
}
return undefined;
}
// Get the version from the selected data source, if found
export const getDataSourceVersion = async (
dataSourceId: string | undefined
): Promise<string | undefined> => {
try {
if (dataSourceId === undefined) {
throw new Error();
}
if (dataSourceId === '') {
// Use route service for local cluster case
return await getRouteService().getLocalClusterVersion();
}
const dataSource = await getSavedObjectsClient().get<DataSourceAttributes>(
'data-source',
dataSourceId
);
return dataSource?.attributes?.dataSourceVersion;
} catch (error) {
console.error('Error getting version: ', error);
return undefined;
}
};
export function useMissingDataSourceVersion(
dataSourceId: string | undefined,
dataSourceVersion: string | undefined
): boolean {
const [missingVersion, setMissingVersion] = useState<boolean>(false);
useEffect(() => {
setMissingVersion(
dataSourceId !== undefined && dataSourceVersion === undefined
);
}, [dataSourceId, dataSourceVersion]);
return missingVersion;
}
/**
* Formats version string to show only major.minor numbers
* Example: "3.0.0-alpha1" -> "3.0"
*/
export function formatDisplayVersion(version: string): string {
// Take first two parts of version number (major.minor)
const [major, minor] = version.split('.');
return `${major}.${minor}`;