Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,7 @@ import type { IndexSourceDefinition } from '@kbn/wci-common';
export interface GenerateConfigurationResponse {
definition: IndexSourceDefinition;
}

export interface SearchIndicesResponse {
indexNames: string[];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import useDebounce from 'react-use/lib/useDebounce';
import type { CoreStart } from '@kbn/core/public';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import type { SearchIndicesResponse } from '../../common/http_api/configuration';

export const useIndexNameAutocomplete = ({ query }: { query: string }) => {
const {
services: { http, notifications },
} = useKibana<CoreStart>();

const [debouncedQuery, setDebounceQuery] = useState<string>(query);

useDebounce(
() => {
setDebounceQuery(query);
},
250,
[query]
);

const { isLoading, data } = useQuery({
queryKey: ['index-name-autocomplete', debouncedQuery],
queryFn: async () => {
if (query.length < 3) {
return [];
}
const response = await http.get<SearchIndicesResponse>(
`/internal/wci-index-source/indices-autocomplete`,
{
query: {
index: query,
},
}
);
return response.indexNames;
},
initialData: [],
onError: (err: any) => {
notifications.toasts.addError(err, { title: 'Error fetching indices' });
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are surfacing the error in a toast, we should wrap the error string with the i18n logic

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've copied it over from another WorkChat component - none of components are using i18n, so it should be fine to not do it here? Or should I change this everywhere in the code within the PR?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think it should be fine to not worry about i18n at this stage

},
});

return {
isLoading,
data,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
* 2.0.
*/

import React, { useCallback } from 'react';
import React, { useCallback, useState } from 'react';
import { useFieldArray, Controller } from 'react-hook-form';
import {
EuiTextArea,
EuiComboBox,
EuiFormRow,
EuiDescribedFormGroup,
EuiFieldText,
Expand All @@ -21,11 +22,13 @@ import {
EuiFlexItem,
EuiCallOut,
EuiButtonEmpty,
EuiComboBoxOptionOption,
} from '@elastic/eui';
import type { IndexSourceDefinition } from '@kbn/wci-common';
import { IntegrationConfigurationFormProps } from '@kbn/wci-browser';
import type { WCIIndexSourceFilterField, WCIIndexSourceContextField } from '../../common/types';
import { useGenerateSchema } from '../hooks/use_generate_schema';
import { useIndexNameAutocomplete } from '../hooks/use_index_name_autocomplete';

export const IndexSourceConfigurationForm: React.FC<IntegrationConfigurationFormProps> = ({
form,
Expand All @@ -35,6 +38,7 @@ export const IndexSourceConfigurationForm: React.FC<IntegrationConfigurationForm
control,
name: 'configuration.fields.filterFields',
});
const [query, setQuery] = useState('');

const contextFieldsArray = useFieldArray({
control,
Expand All @@ -50,6 +54,16 @@ export const IndexSourceConfigurationForm: React.FC<IntegrationConfigurationForm
];

const { generateSchema } = useGenerateSchema();
const { isLoading, data } = useIndexNameAutocomplete({ query });
const [selectedOptions, setSelected] = useState<EuiComboBoxOptionOption[]>([]);

const onIndexNameChange = (onChangeSelectedOptions: EuiComboBoxOptionOption[]) => {
setSelected(onChangeSelectedOptions);
};

const onSearchChange = (searchValue: string) => {
setQuery(searchValue);
};

const onSchemaGenerated = useCallback(
(definition: IndexSourceDefinition) => {
Expand Down Expand Up @@ -116,16 +130,28 @@ export const IndexSourceConfigurationForm: React.FC<IntegrationConfigurationForm
name="configuration.index"
control={control}
render={({ field }) => (
<EuiFieldText
<EuiComboBox
data-test-subj="workchatAppIntegrationEditViewIndex"
placeholder="Enter index name"
{...field}
placeholder="Select an index"
isLoading={isLoading}
selectedOptions={selectedOptions}
singleSelection={{ asPlainText: true }}
options={data.map((option) => ({ label: option, key: option }))}
onChange={onIndexNameChange}
fullWidth={true}
onSearchChange={onSearchChange}
append={
<EuiButtonEmpty
size="xs"
iconType="gear"
onClick={() => {
generateSchema({ indexName: field.value }, { onSuccess: onSchemaGenerated });
if (selectedOptions.length === 0) return;
if (!selectedOptions[0].key) return;

generateSchema(
{ indexName: selectedOptions[0].key },
{ onSuccess: onSchemaGenerated }
);
}}
>
Generate configuration
Expand Down Expand Up @@ -180,7 +206,7 @@ export const IndexSourceConfigurationForm: React.FC<IntegrationConfigurationForm
</EuiFormRow>
) : (
filterFieldsArray.fields.map((filterField, index) => (
<EuiPanel paddingSize="s" key={filterField.id} style={{ marginBottom: '8px' }}>
<EuiPanel paddingSize="s" key={filterField.id} css={{ marginBottom: '8px' }}>
<EuiFlexGroup alignItems="center">
<EuiFlexItem>
<EuiFormRow label="Field name">
Expand Down Expand Up @@ -275,7 +301,7 @@ export const IndexSourceConfigurationForm: React.FC<IntegrationConfigurationForm
</EuiFormRow>
) : (
contextFieldsArray.fields.map((contextField, index) => (
<EuiPanel paddingSize="s" key={contextField.id} style={{ marginBottom: '8px' }}>
<EuiPanel paddingSize="s" key={contextField.id} css={{ marginBottom: '8px' }}>
<EuiFlexGroup alignItems="center">
<EuiFlexItem>
<EuiFormRow label="Field name">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import { schema } from '@kbn/config-schema';
import { apiCapabilities } from '@kbn/workchat-app/common/features';
import { buildSchema } from '@kbn/wc-index-schema-builder';
import { getConnectorList, getDefaultConnector } from '@kbn/wc-genai-utils';
import type { GenerateConfigurationResponse } from '../../common/http_api/configuration';
import type {
GenerateConfigurationResponse,
SearchIndicesResponse,
} from '../../common/http_api/configuration';
import type { RouteDependencies } from './types';

export const registerConfigurationRoutes = ({ router, core, logger }: RouteDependencies) => {
Expand Down Expand Up @@ -61,4 +64,57 @@ export const registerConfigurationRoutes = ({ router, core, logger }: RouteDepen
}
}
);

router.get(
{
path: '/internal/wci-index-source/indices-autocomplete',
security: {
authz: {
requiredPrivileges: [apiCapabilities.manageWorkchat],
},
},
validate: {
query: schema.object({
index: schema.maybe(schema.string()),
}),
},
},
async (ctx, request, res) => {
const { elasticsearch } = await ctx.core;
let pattern = request.query.index || '';

if (pattern.length >= 3) {
pattern = `${pattern}*`;
}

const esClient = elasticsearch.client.asCurrentUser;

try {
const response = await esClient.cat.indices({
index: [pattern],
h: 'index',
expand_wildcards: 'open',
format: 'json',
});

return res.ok<SearchIndicesResponse>({
body: {
indexNames: response
.map((indexRecord) => indexRecord.index)
.filter((index) => !!index) as string[],
},
});
} catch (e) {
// TODO: sigh, is there a better way?
if (e?.meta?.body?.error?.type === 'index_not_found_exception') {
return res.ok<SearchIndicesResponse>({
body: {
indexNames: [],
},
});
}
throw e;
}
}
);
};