Skip to content

Commit

Permalink
[Security][Lists] Add API functions and react hooks for value list AP…
Browse files Browse the repository at this point in the history
…Is (elastic#69603)

* Add pure API functions and react hooks for value list APIs

This also adds a generic hook, useAsyncTask, that wraps an async
function to provide basic utilities:
  * loading state
  * error state
  * abort/cancel function

* Fix type errors in hook tests

These were not caught locally as I was accidentally running typescript
without the full project.

* Document current limitations of useAsyncTask

* Defines a new validation function that returns an Either instead of a tuple

This allows callers to further leverage fp-ts functions as needed.

* Remove duplicated copyright comment

* WIP: Perform request/response validations in the FP style

* leverages new validateEither fn which returns an Either
* constructs a pipeline that:
  * validates the payload
  * performs the API call
  * validates the response
and short-circuits if any of those produce a Left value.

It then converts the Either into a promise that either rejects with the
Left or resolves with the Right.

* Adds helper function to convert a TaskEither back to a Promise

This cleans up our validation pipeline considerably.

* Adds request/response validations to findLists

* refactors private API functions to accept the encoded request schema
(i.e. snake cased)
* refactors validateEither to use `schema.validate` instead of
`schema.decode` since we don't actually want the decoded value, we just
want to verify that it'll be able to be decoded on the backend.

* Refactor our API types

* Add request/response validation to import/export functions

* Fix type errors

* Continue to export decoded types without a qualifier
* pull types used by hooks from their new location
* Fix errors with usage of act()

* Attempting to reduce plugin bundle size

By pulling from the module directly instead of an index, we can
hopefully narrow down our dependencies until tree-shaking does this for
us.

* useAsyncFn's initiator does not return a promise

Rather than returning a promise and requiring the caller to handle a
rejection, we instead return nothing and require the user to watch the
hook's state.

* success can be handled with a useEffect on state.result
* errors can be handled with a useEffect on state.error

* Fix failing test

Assertion count wasn't updated following interface changes; we've now
got two inline expectations so this isn't needed.

Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
2 people authored and Bamieh committed Jul 1, 2020
1 parent e34d342 commit 325fdd2
Show file tree
Hide file tree
Showing 25 changed files with 1,040 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export const deleteListSchema = t.exact(
);

export type DeleteListSchema = t.TypeOf<typeof deleteListSchema>;
export type DeleteListSchemaEncoded = t.OutputOf<typeof deleteListSchema>;
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ export const exportListItemQuerySchema = t.exact(
);

export type ExportListItemQuerySchema = t.TypeOf<typeof exportListItemQuerySchema>;
export type ExportListItemQuerySchemaEncoded = t.OutputOf<typeof exportListItemQuerySchema>;
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import * as t from 'io-ts';

import { cursor, filter, sort_field, sort_order } from '../common/schemas';
import { RequiredKeepUndefined } from '../../types';
import { StringToPositiveNumber } from '../types/string_to_positive_number';

export const findListSchema = t.exact(
Expand All @@ -23,6 +22,5 @@ export const findListSchema = t.exact(
})
);

export type FindListSchemaPartial = t.TypeOf<typeof findListSchema>;

export type FindListSchema = RequiredKeepUndefined<t.TypeOf<typeof findListSchema>>;
export type FindListSchema = t.TypeOf<typeof findListSchema>;
export type FindListSchemaEncoded = t.OutputOf<typeof findListSchema>;
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
import * as t from 'io-ts';

import { list_id, type } from '../common/schemas';
import { Identity, RequiredKeepUndefined } from '../../types';
import { Identity } from '../../types';

export const importListItemQuerySchema = t.exact(t.partial({ list_id, type }));

export type ImportListItemQuerySchemaPartial = Identity<t.TypeOf<typeof importListItemQuerySchema>>;
export type ImportListItemQuerySchema = RequiredKeepUndefined<
t.TypeOf<typeof importListItemQuerySchema>
>;

export type ImportListItemQuerySchema = t.TypeOf<typeof importListItemQuerySchema>;
export type ImportListItemQuerySchemaEncoded = t.OutputOf<typeof importListItemQuerySchema>;
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export const importListItemSchema = t.exact(
);

export type ImportListItemSchema = t.TypeOf<typeof importListItemSchema>;
export type ImportListItemSchemaEncoded = t.OutputOf<typeof importListItemSchema>;
2 changes: 1 addition & 1 deletion x-pack/plugins/lists/common/siem_common_deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ export { DefaultUuid } from '../../security_solution/common/detection_engine/sch
export { DefaultStringArray } from '../../security_solution/common/detection_engine/schemas/types/default_string_array';
export { exactCheck } from '../../security_solution/common/exact_check';
export { getPaths, foldLeftRight } from '../../security_solution/common/test_utils';
export { validate } from '../../security_solution/common/validate';
export { validate, validateEither } from '../../security_solution/common/validate';
export { formatErrors } from '../../security_solution/common/format_errors';
23 changes: 23 additions & 0 deletions x-pack/plugins/lists/public/common/fp_utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { tryCatch } from 'fp-ts/lib/TaskEither';

import { toPromise } from './fp_utils';

describe('toPromise', () => {
it('rejects with left if TaskEither is left', async () => {
const task = tryCatch(() => Promise.reject(new Error('whoops')), String);

await expect(toPromise(task)).rejects.toEqual('Error: whoops');
});

it('resolves with right if TaskEither is right', async () => {
const task = tryCatch(() => Promise.resolve('success'), String);

await expect(toPromise(task)).resolves.toEqual('success');
});
});
18 changes: 18 additions & 0 deletions x-pack/plugins/lists/public/common/fp_utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { pipe } from 'fp-ts/lib/pipeable';
import { TaskEither } from 'fp-ts/lib/TaskEither';
import { fold } from 'fp-ts/lib/Either';

export const toPromise = async <E, A>(taskEither: TaskEither<E, A>): Promise<A> =>
pipe(
await taskEither(),
fold(
(e) => Promise.reject(e),
(a) => Promise.resolve(a)
)
);
93 changes: 93 additions & 0 deletions x-pack/plugins/lists/public/common/hooks/use_async_task.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { act, renderHook } from '@testing-library/react-hooks';

import { useAsyncTask } from './use_async_task';

describe('useAsyncTask', () => {
let task: jest.Mock;

beforeEach(() => {
task = jest.fn().mockResolvedValue('resolved value');
});

it('does not invoke task if start was not called', () => {
renderHook(() => useAsyncTask(task));
expect(task).not.toHaveBeenCalled();
});

it('invokes the task when start is called', async () => {
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({});
});
await waitForNextUpdate();

expect(task).toHaveBeenCalled();
});

it('invokes the task with a signal and start args', async () => {
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({
arg1: 'value1',
arg2: 'value2',
});
});
await waitForNextUpdate();

expect(task).toHaveBeenCalledWith(expect.any(AbortController), {
arg1: 'value1',
arg2: 'value2',
});
});

it('populates result with the resolved value of the task', async () => {
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({});
});
await waitForNextUpdate();

expect(result.current.result).toEqual('resolved value');
expect(result.current.error).toBeUndefined();
});

it('populates error if task rejects', async () => {
task.mockRejectedValue(new Error('whoops'));
const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({});
});
await waitForNextUpdate();

expect(result.current.result).toBeUndefined();
expect(result.current.error).toEqual(new Error('whoops'));
});

it('populates the loading state while the task is pending', async () => {
let resolve: () => void;
task.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve)));

const { result, waitForNextUpdate } = renderHook(() => useAsyncTask(task));

act(() => {
result.current.start({});
});

expect(result.current.loading).toBe(true);

act(() => resolve());
await waitForNextUpdate();

expect(result.current.loading).toBe(false);
});
});
48 changes: 48 additions & 0 deletions x-pack/plugins/lists/public/common/hooks/use_async_task.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { useCallback, useRef } from 'react';
import useAsyncFn from 'react-use/lib/useAsyncFn';

// Params can be generalized to a ...rest parameter extending unknown[] once https://github.com/microsoft/TypeScript/pull/39094 is available.
// for now, the task must still receive unknown as a second argument, and an argument must be passed to start()
export type UseAsyncTask = <Result, Params extends unknown>(
task: (...args: [AbortController, Params]) => Promise<Result>
) => AsyncTask<Result, Params>;

export interface AsyncTask<Result, Params extends unknown> {
start: (params: Params) => void;
abort: () => void;
loading: boolean;
error: Error | undefined;
result: Result | undefined;
}

/**
*
* @param task Async function receiving an AbortController and optional arguments
*
* @returns An {@link AsyncTask} containing the underlying task's state along with start/abort helpers
*/
export const useAsyncTask: UseAsyncTask = (task) => {
const ctrl = useRef(new AbortController());
const abort = useCallback((): void => {
ctrl.current.abort();
}, []);

// @ts-ignore typings are incorrect, see: https://github.com/streamich/react-use/pull/589
const [state, initiator] = useAsyncFn(task, [task]);

const start = useCallback(
(args) => {
ctrl.current = new AbortController();
initiator(ctrl.current, args);
},
[initiator]
);

return { abort, error: state.error, loading: state.loading, result: state.value, start };
};
5 changes: 5 additions & 0 deletions x-pack/plugins/lists/public/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

// Exports to be shared with plugins
export { useApi } from './exceptions/hooks/use_api';
export { usePersistExceptionItem } from './exceptions/hooks/persist_exception_item';
export { usePersistExceptionList } from './exceptions/hooks/persist_exception_list';
export { useExceptionList } from './exceptions/hooks/use_exception_list';
export { useFindLists } from './lists/hooks/use_find_lists';
export { useImportList } from './lists/hooks/use_import_list';
export { useDeleteList } from './lists/hooks/use_delete_list';
export { useExportList } from './lists/hooks/use_export_list';
export {
ExceptionList,
ExceptionIdentifiers,
Expand Down
Loading

0 comments on commit 325fdd2

Please sign in to comment.