Skip to content

Commit

Permalink
[7.9] [Security Solution] Add hook for reading/writing resolver query…
Browse files Browse the repository at this point in the history
… params (#70809) (#71905)

* Move resolver query param logic into shared hook

* Store document location in state

* Rename documentLocation to resolverComponentInstanceID

* Use undefined for initial resolverComponentID value

* Update type for initial state of component id
  • Loading branch information
kqualters-elastic authored Jul 15, 2020
1 parent b692b8e commit 47129fc
Show file tree
Hide file tree
Showing 14 changed files with 131 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ interface AppReceivedNewExternalProperties {
* the `_id` of an ES document. This defines the origin of the Resolver graph.
*/
databaseDocumentID?: string;
resolverComponentInstanceID: string;
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import { ResolverAction } from '../actions';
const initialState: DataState = {
relatedEvents: new Map(),
relatedEventsReady: new Map(),
resolverComponentInstanceID: undefined,
};

export const dataReducer: Reducer<DataState, ResolverAction> = (state = initialState, action) => {
if (action.type === 'appReceivedNewExternalProperties') {
const nextState: DataState = {
...state,
databaseDocumentID: action.payload.databaseDocumentID,
resolverComponentInstanceID: action.payload.resolverComponentInstanceID,
};
return nextState;
} else if (action.type === 'appRequestedResolverData') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@ describe('data state', () => {

describe('when there is a databaseDocumentID but no pending request', () => {
const databaseDocumentID = 'databaseDocumentID';
const resolverComponentInstanceID = 'resolverComponentInstanceID';
beforeEach(() => {
actions = [
{
type: 'appReceivedNewExternalProperties',
payload: { databaseDocumentID },
payload: { databaseDocumentID, resolverComponentInstanceID },
},
];
});
Expand Down Expand Up @@ -104,11 +105,12 @@ describe('data state', () => {
});
describe('when there is a pending request for the current databaseDocumentID', () => {
const databaseDocumentID = 'databaseDocumentID';
const resolverComponentInstanceID = 'resolverComponentInstanceID';
beforeEach(() => {
actions = [
{
type: 'appReceivedNewExternalProperties',
payload: { databaseDocumentID },
payload: { databaseDocumentID, resolverComponentInstanceID },
},
{
type: 'appRequestedResolverData',
Expand Down Expand Up @@ -160,12 +162,17 @@ describe('data state', () => {
describe('when there is a pending request for a different databaseDocumentID than the current one', () => {
const firstDatabaseDocumentID = 'first databaseDocumentID';
const secondDatabaseDocumentID = 'second databaseDocumentID';
const resolverComponentInstanceID1 = 'resolverComponentInstanceID1';
const resolverComponentInstanceID2 = 'resolverComponentInstanceID2';
beforeEach(() => {
actions = [
// receive the document ID, this would cause the middleware to starts the request
{
type: 'appReceivedNewExternalProperties',
payload: { databaseDocumentID: firstDatabaseDocumentID },
payload: {
databaseDocumentID: firstDatabaseDocumentID,
resolverComponentInstanceID: resolverComponentInstanceID1,
},
},
// this happens when the middleware starts the request
{
Expand All @@ -175,7 +182,10 @@ describe('data state', () => {
// receive a different databaseDocumentID. this should cause the middleware to abort the existing request and start a new one
{
type: 'appReceivedNewExternalProperties',
payload: { databaseDocumentID: secondDatabaseDocumentID },
payload: {
databaseDocumentID: secondDatabaseDocumentID,
resolverComponentInstanceID: resolverComponentInstanceID2,
},
},
];
});
Expand All @@ -188,6 +198,9 @@ describe('data state', () => {
it('should need to abort the request for the databaseDocumentID', () => {
expect(selectors.databaseDocumentIDToFetch(state())).toBe(secondDatabaseDocumentID);
});
it('should use the correct location for the second resolver', () => {
expect(selectors.resolverComponentInstanceID(state())).toBe(resolverComponentInstanceID2);
});
it('should not have an error, more children, or more ancestors.', () => {
expect(viewAsAString(state())).toMatchInlineSnapshot(`
"is loading: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ export function isLoading(state: DataState): boolean {
return state.pendingRequestDatabaseDocumentID !== undefined;
}

/**
* A string for uniquely identifying the instance of resolver within the app.
*/
export function resolverComponentInstanceID(state: DataState): string {
return state.resolverComponentInstanceID ? state.resolverComponentInstanceID : '';
}

/**
* If a request was made and it threw an error or returned a failure response code.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ export const databaseDocumentIDToAbort = composeSelectors(
dataSelectors.databaseDocumentIDToAbort
);

export const resolverComponentInstanceID = composeSelectors(
dataStateSelector,
dataSelectors.resolverComponentInstanceID
);

export const processAdjacencies = composeSelectors(
dataStateSelector,
dataSelectors.processAdjacencies
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/security_solution/public/resolver/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export interface DataState {
* The id used for the pending request, if there is one.
*/
readonly pendingRequestDatabaseDocumentID?: string;
readonly resolverComponentInstanceID: string | undefined;

/**
* The parameters and response from the last successful request.
Expand Down
12 changes: 11 additions & 1 deletion x-pack/plugins/security_solution/public/resolver/view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useKibana } from '../../../../../../src/plugins/kibana_react/public';
export const Resolver = React.memo(function ({
className,
databaseDocumentID,
resolverComponentInstanceID,
}: {
/**
* Used by `styled-components`.
Expand All @@ -28,6 +29,11 @@ export const Resolver = React.memo(function ({
* Used as the origin of the Resolver graph.
*/
databaseDocumentID?: string;
/**
* A string literal describing where in the app resolver is located,
* used to prevent collisions in things like query params
*/
resolverComponentInstanceID: string;
}) {
const context = useKibana<StartServices>();
const store = useMemo(() => {
Expand All @@ -40,7 +46,11 @@ export const Resolver = React.memo(function ({
*/
return (
<Provider store={store}>
<ResolverMap className={className} databaseDocumentID={databaseDocumentID} />
<ResolverMap
className={className}
databaseDocumentID={databaseDocumentID}
resolverComponentInstanceID={resolverComponentInstanceID}
/>
</Provider>
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { SideEffectContext } from './side_effect_context';
export const ResolverMap = React.memo(function ({
className,
databaseDocumentID,
resolverComponentInstanceID,
}: {
/**
* Used by `styled-components`.
Expand All @@ -39,12 +40,17 @@ export const ResolverMap = React.memo(function ({
* Used as the origin of the Resolver graph.
*/
databaseDocumentID?: string;
/**
* A string literal describing where in the app resolver is located,
* used to prevent collisions in things like query params
*/
resolverComponentInstanceID: string;
}) {
/**
* This is responsible for dispatching actions that include any external data.
* `databaseDocumentID`
*/
useStateSyncingActions({ databaseDocumentID });
useStateSyncingActions({ databaseDocumentID, resolverComponentInstanceID });

const { timestamp } = useContext(SideEffectContext);
const { processNodePositions, connectingEdgeLineSegments } = useSelector(
Expand Down
43 changes: 4 additions & 39 deletions x-pack/plugins/security_solution/public/resolver/view/panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { memo, useCallback, useMemo, useContext, useLayoutEffect, useState } from 'react';
import React, { memo, useMemo, useContext, useLayoutEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
// eslint-disable-next-line import/no-nodejs-modules
import querystring from 'querystring';
import { EuiPanel } from '@elastic/eui';
import * as selectors from '../store/selectors';
import { useResolverDispatch } from './use_resolver_dispatch';
Expand All @@ -20,7 +17,7 @@ import { EventCountsForProcess } from './panels/panel_content_related_counts';
import { ProcessDetails } from './panels/panel_content_process_detail';
import { ProcessListWithCounts } from './panels/panel_content_process_list';
import { RelatedEventDetail } from './panels/panel_content_related_detail';
import { CrumbInfo } from './panels/panel_content_utilities';
import { useResolverQueryParams } from './use_resolver_query_params';

/**
* The team decided to use this table to determine which breadcrumbs/view to display:
Expand All @@ -38,14 +35,11 @@ import { CrumbInfo } from './panels/panel_content_utilities';
* @returns {JSX.Element} The "right" table content to show based on the query params as described above
*/
const PanelContent = memo(function PanelContent() {
const history = useHistory();
const urlSearch = useLocation().search;
const dispatch = useResolverDispatch();

const { timestamp } = useContext(SideEffectContext);
const queryParams: CrumbInfo = useMemo(() => {
return { crumbId: '', crumbEvent: '', ...querystring.parse(urlSearch.slice(1)) };
}, [urlSearch]);

const { pushToQueryParams, queryParams } = useResolverQueryParams();

const graphableProcesses = useSelector(selectors.graphableProcesses);
const graphableProcessEntityIds = useMemo(() => {
Expand Down Expand Up @@ -103,35 +97,6 @@ const PanelContent = memo(function PanelContent() {
}
}, [dispatch, uiSelectedEvent, paramsSelectedEvent, lastUpdatedProcess, timestamp]);

/**
* This updates the breadcrumb nav and the panel view. It's supplied to each
* panel content view to allow them to dispatch transitions to each other.
*/
const pushToQueryParams = useCallback(
(newCrumbs: CrumbInfo) => {
// Construct a new set of params from the current set (minus empty params)
// by assigning the new set of params provided in `newCrumbs`
const crumbsToPass = {
...querystring.parse(urlSearch.slice(1)),
...newCrumbs,
};

// If either was passed in as empty, remove it from the record
if (crumbsToPass.crumbId === '') {
delete crumbsToPass.crumbId;
}
if (crumbsToPass.crumbEvent === '') {
delete crumbsToPass.crumbEvent;
}

const relativeURL = { search: querystring.stringify(crumbsToPass) };
// We probably don't want to nuke the user's history with a huge
// trail of these, thus `.replace` instead of `.push`
return history.replace(relativeURL);
},
[history, urlSearch]
);

const relatedEventStats = useSelector(selectors.relatedEventsStats);
const { crumbId, crumbEvent } = queryParams;
const relatedStatsForIdFromParams: ResolverNodeStats | undefined =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ const BetaHeader = styled(`header`)`
* The two query parameters we read/write on to control which view the table presents:
*/
export interface CrumbInfo {
readonly crumbId: string;
readonly crumbEvent: string;
crumbId: string;
crumbEvent: string;
}

const ThemedBreadcrumbs = styled(EuiBreadcrumbs)<{ background: string; text: string }>`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@
import React, { useCallback, useMemo } from 'react';
import styled from 'styled-components';
import { htmlIdGenerator, EuiButton, EuiI18nNumber, EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import { useHistory } from 'react-router-dom';
// eslint-disable-next-line import/no-nodejs-modules
import querystring from 'querystring';
import { useSelector } from 'react-redux';
import { NodeSubMenu, subMenuAssets } from './submenu';
import { applyMatrix3 } from '../models/vector2';
Expand All @@ -21,7 +18,7 @@ import { ResolverEvent, ResolverNodeStats } from '../../../common/endpoint/types
import { useResolverDispatch } from './use_resolver_dispatch';
import * as eventModel from '../../../common/endpoint/models/event';
import * as selectors from '../store/selectors';
import { CrumbInfo } from './panels/panel_content_utilities';
import { useResolverQueryParams } from './use_resolver_query_params';

interface StyledActionsContainer {
readonly color: string;
Expand Down Expand Up @@ -236,35 +233,7 @@ const UnstyledProcessEventDot = React.memo(
});
}, [dispatch, selfId]);

const history = useHistory();
const urlSearch = history.location.search;

/**
* This updates the breadcrumb nav, the table view
*/
const pushToQueryParams = useCallback(
(newCrumbs: CrumbInfo) => {
// Construct a new set of params from the current set (minus empty params)
// by assigning the new set of params provided in `newCrumbs`
const crumbsToPass = {
...querystring.parse(urlSearch.slice(1)),
...newCrumbs,
};

// If either was passed in as empty, remove it from the record
if (crumbsToPass.crumbId === '') {
delete crumbsToPass.crumbId;
}
if (crumbsToPass.crumbEvent === '') {
delete crumbsToPass.crumbEvent;
}

const relativeURL = { search: querystring.stringify(crumbsToPass) };

return history.replace(relativeURL);
},
[history, urlSearch]
);
const { pushToQueryParams } = useResolverQueryParams();

const handleClick = useCallback(() => {
if (animationTarget.current !== null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* 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, useMemo } from 'react';
// eslint-disable-next-line import/no-nodejs-modules
import querystring from 'querystring';
import { useSelector } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
import * as selectors from '../store/selectors';
import { CrumbInfo } from './panels/panel_content_utilities';

export function useResolverQueryParams() {
/**
* This updates the breadcrumb nav and the panel view. It's supplied to each
* panel content view to allow them to dispatch transitions to each other.
*/
const history = useHistory();
const urlSearch = useLocation().search;
const resolverComponentInstanceID = useSelector(selectors.resolverComponentInstanceID);
const uniqueCrumbIdKey: string = `${resolverComponentInstanceID}CrumbId`;
const uniqueCrumbEventKey: string = `${resolverComponentInstanceID}CrumbEvent`;
const pushToQueryParams = useCallback(
(newCrumbs: CrumbInfo) => {
// Construct a new set of params from the current set (minus empty params)
// by assigning the new set of params provided in `newCrumbs`
const crumbsToPass = {
...querystring.parse(urlSearch.slice(1)),
[uniqueCrumbIdKey]: newCrumbs.crumbId,
[uniqueCrumbEventKey]: newCrumbs.crumbEvent,
};

// If either was passed in as empty, remove it from the record
if (newCrumbs.crumbId === '') {
delete crumbsToPass[uniqueCrumbIdKey];
}
if (newCrumbs.crumbEvent === '') {
delete crumbsToPass[uniqueCrumbEventKey];
}

const relativeURL = { search: querystring.stringify(crumbsToPass) };
// We probably don't want to nuke the user's history with a huge
// trail of these, thus `.replace` instead of `.push`
return history.replace(relativeURL);
},
[history, urlSearch, uniqueCrumbIdKey, uniqueCrumbEventKey]
);
const queryParams: CrumbInfo = useMemo(() => {
const parsed = querystring.parse(urlSearch.slice(1));
const crumbEvent = parsed[uniqueCrumbEventKey];
const crumbId = parsed[uniqueCrumbIdKey];
return {
crumbEvent: Array.isArray(crumbEvent) ? crumbEvent[0] : crumbEvent,
crumbId: Array.isArray(crumbId) ? crumbId[0] : crumbId,
};
}, [urlSearch, uniqueCrumbIdKey, uniqueCrumbEventKey]);

return {
pushToQueryParams,
queryParams,
};
}
Loading

0 comments on commit 47129fc

Please sign in to comment.