Skip to content

Commit

Permalink
update naming and types
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarezmelissa87 committed Jan 19, 2022
1 parent a52c840 commit e121d67
Show file tree
Hide file tree
Showing 11 changed files with 44 additions and 70 deletions.
1 change: 1 addition & 0 deletions x-pack/plugins/maps/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,5 @@ export type {
TooltipFeature,
VectorLayerDescriptor,
VectorStyleDescriptor,
VectorSourceRequestMeta,
} from './descriptor_types';
9 changes: 1 addition & 8 deletions x-pack/plugins/ml/common/util/job_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,8 @@ export function isMappableJob(job: CombinedJob, detectorIndex: number): boolean

// Returns a boolean indicating whether the specified job is suitable for maps plugin.
export function isJobWithGeoData(job: Job): boolean {
let isMappable = false;
const { detectors } = job.analysis_config;

detectors.forEach((detector) => {
if (detector.function === ML_JOB_AGGREGATION.LAT_LONG) {
isMappable = true;
}
});
return isMappable;
return detectors.some((detector) => detector.function === ML_JOB_AGGREGATION.LAT_LONG);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const jobsApiProvider = (httpService: HttpService) => ({
});
},

jobsWithGeo() {
jobIdsWithGeo() {
return httpService.http<string[]>({
path: `${ML_BASE_PATH}/jobs/jobs_with_geo`,
method: 'GET',
Expand Down
6 changes: 3 additions & 3 deletions x-pack/plugins/ml/public/maps/anomaly_job_selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class AnomalyJobSelector extends Component<Props, State> {
state: State = {};

private async _loadJobs() {
const jobIdList = await this.props.mlJobsService.jobsWithGeo();
const jobIdList = await this.props.mlJobsService.jobIdsWithGeo();
const options = jobIdList.map((jobId) => {
return { label: jobId, value: jobId };
});
Expand All @@ -39,7 +39,7 @@ export class AnomalyJobSelector extends Component<Props, State> {
}
}

componentDidUpdate(prevProps: Readonly<Props>, prevState: Readonly<State>, snapshot?: any): void {
componentDidUpdate(prevProps: Readonly<Props>, prevState: Readonly<State>): void {
this._loadJobs();
}

Expand Down Expand Up @@ -68,7 +68,7 @@ export class AnomalyJobSelector extends Component<Props, State> {
return (
<EuiFormRow
label={i18n.translate('xpack.ml.maps.jobIdLabel', {
defaultMessage: 'JobId',
defaultMessage: 'Job ID',
})}
display="columnCompressed"
>
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/ml/public/maps/anomaly_layer_wizard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { LAYER_WIZARD_CATEGORY } from '../../../maps/common';
import type { LayerWizard } from '../../../maps/public';

export const anomalyLayerWizard: Partial<LayerWizard> = {
categories: [LAYER_WIZARD_CATEGORY.SOLUTIONS],
categories: [LAYER_WIZARD_CATEGORY.SOLUTIONS, LAYER_WIZARD_CATEGORY.ELASTICSEARCH],
description: i18n.translate('xpack.ml.maps.anomalyLayerDescription', {
defaultMessage: 'Create anomalies layers',
}),
Expand Down
28 changes: 15 additions & 13 deletions x-pack/plugins/ml/public/maps/anomaly_layer_wizard_factory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import React from 'react';
import uuid from 'uuid';
import { htmlIdGenerator } from '@elastic/eui';
import type { StartServicesAccessor } from 'kibana/public';
import type { LayerWizard, RenderWizardArguments } from '../../../maps/public';
import { FIELD_ORIGIN, LAYER_TYPE, STYLE_TYPE } from '../../../maps/common';
Expand All @@ -23,6 +23,17 @@ import type { MlPluginStart, MlStartDependencies } from '../plugin';
import type { MlApiServices } from '../application/services/ml_api_service';

export const ML_ANOMALY = 'ML_ANOMALIES';
const CUSTOM_COLOR_RAMP = {
type: STYLE_TYPE.DYNAMIC,
options: {
customColorRamp: SEVERITY_COLOR_RAMP,
field: {
name: 'record_score',
origin: FIELD_ORIGIN.SOURCE,
},
useCustomColorRamp: true,
},
};

export class AnomalyLayerWizardFactory {
public readonly type = ML_ANOMALY;
Expand Down Expand Up @@ -58,7 +69,7 @@ export class AnomalyLayerWizardFactory {
}

const anomalyLayerDescriptor: VectorLayerDescriptor = {
id: uuid(),
id: htmlIdGenerator()(),
type: LAYER_TYPE.GEOJSON_VECTOR,
sourceDescriptor: AnomalySource.createDescriptor({
jobId: sourceConfig.jobId,
Expand All @@ -67,17 +78,8 @@ export class AnomalyLayerWizardFactory {
style: {
type: 'VECTOR',
properties: {
fillColor: {
type: STYLE_TYPE.DYNAMIC,
options: {
customColorRamp: SEVERITY_COLOR_RAMP,
field: {
name: 'record_score',
origin: FIELD_ORIGIN.SOURCE,
},
useCustomColorRamp: true,
},
},
fillColor: CUSTOM_COLOR_RAMP,
lineColor: CUSTOM_COLOR_RAMP,
} as unknown as VectorStylePropertiesDescriptor,
isTimeAware: false,
},
Expand Down
22 changes: 9 additions & 13 deletions x-pack/plugins/ml/public/maps/anomaly_source.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@

import { i18n } from '@kbn/i18n';
import React, { ReactElement } from 'react';
import { FieldFormatter, MAX_ZOOM, MIN_ZOOM, VECTOR_SHAPE_TYPE } from '../../../maps/common';
import {
FieldFormatter,
MAX_ZOOM,
MIN_ZOOM,
VECTOR_SHAPE_TYPE,
VectorSourceRequestMeta,
} from '../../../maps/common';
import { AbstractSourceDescriptor, MapExtent } from '../../../maps/common/descriptor_types';
import { ITooltipProperty } from '../../../maps/public';
import {
Expand All @@ -27,15 +33,6 @@ import { getResultsForJobId, MlAnomalyLayers } from './util';
import { UpdateAnomalySourceEditor } from './update_anomaly_source_editor';
import type { MlApiServices } from '../application/services/ml_api_service';

export type SearchFilters = any & {
applyGlobalQuery: boolean;
applyGlobalTime: boolean;
fieldNames: string[];
geogridPrecision?: number;
sourceQuery?: object;
sourceMeta: object;
};

export interface AnomalySourceDescriptor extends AbstractSourceDescriptor {
jobId: string;
typicalActual: MlAnomalyLayers;
Expand All @@ -46,7 +43,7 @@ export class AnomalySource implements IVectorSource {
static canGetJobs: boolean;

static createDescriptor(descriptor: Partial<AnomalySourceDescriptor>) {
if (!(typeof descriptor.jobId === 'string')) {
if (typeof descriptor.jobId !== 'string') {
throw new Error('Job id is required for anomaly layer creation');
}

Expand All @@ -65,7 +62,7 @@ export class AnomalySource implements IVectorSource {
// TODO: implement query awareness
async getGeoJsonWithMeta(
layerName: string,
searchFilters: SearchFilters,
searchFilters: VectorSourceRequestMeta,
registerCancelCallback: (callback: () => void) => void,
isRequestStillActive: () => boolean
): Promise<GeoJsonWithMeta> {
Expand Down Expand Up @@ -213,7 +210,6 @@ export class AnomalySource implements IVectorSource {
}

async getLicensedFeatures(): Promise<[]> {
// return [{ name: 'layer from ML anomaly job', license: 'enterprise' }];
return [];
}

Expand Down
12 changes: 3 additions & 9 deletions x-pack/plugins/ml/public/maps/anomaly_source_field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

// eslint-disable-next-line max-classes-per-file
import _ from 'lodash';
import { escape } from 'lodash';
import { IField, IVectorSource } from '../../../maps/public';
import { FIELD_ORIGIN } from '../../../maps/common';
import { TileMetaFeature } from '../../../maps/common/descriptor_types';
Expand All @@ -24,13 +24,7 @@ export const ANOMALY_SOURCE_FIELDS: Record<string, Record<string, string>> = {
};

export class AnomalySourceTooltipProperty implements ITooltipProperty {
private readonly _label: string;
private readonly _value: string;

constructor(label: string, value: string) {
this._label = label;
this._value = value;
}
constructor(private readonly _label: string, private readonly _value: string) {}

async getESFilters(): Promise<Filter[]> {
return [];
Expand Down Expand Up @@ -70,7 +64,7 @@ export class AnomalySourceField implements IField {
async createTooltipProperty(value: string | string[] | undefined): Promise<ITooltipProperty> {
return new AnomalySourceTooltipProperty(
await this.getLabel(),
_.escape(Array.isArray(value) ? value.join() : value ? value : '')
escape(Array.isArray(value) ? value.join() : value ? value : '')
);
}

Expand Down
11 changes: 5 additions & 6 deletions x-pack/plugins/ml/public/maps/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@
* 2.0.
*/

import { FeatureCollection, Feature } from 'geojson';
import { FeatureCollection, Feature, Geometry } from 'geojson';
import { ESSearchResponse } from '../../../../../src/core/types/elasticsearch';
import { formatHumanReadableDateTimeSeconds } from '../../common/util/date_utils';
import type { MlApiServices } from '../application/services/ml_api_service';
import { MLAnomalyDoc } from '../../common/types/anomalies';
import type { SearchFilters } from './anomaly_source';
import { VectorSourceRequestMeta } from '../../../maps/common';

export type MlAnomalyLayers = 'typical' | 'actual' | 'connected';

export async function getResultsForJobId(
mlResultsService: MlApiServices['results'],
jobId: string,
locationType: MlAnomalyLayers,
searchFilters: SearchFilters
searchFilters: VectorSourceRequestMeta
): Promise<FeatureCollection> {
const { timeFilters } = searchFilters;
// Query to look for the highest scoring anomaly.
Expand Down Expand Up @@ -98,9 +98,8 @@ export async function getResultsForJobId(
});
}

// @ts-ignore
const features: Feature[] = hits!.map((result) => {
let geometry;
const features: Feature[] = hits.map((result) => {
let geometry: Geometry;
if (locationType === 'typical' || locationType === 'actual') {
geometry = {
type: 'Point',
Expand Down
17 changes: 3 additions & 14 deletions x-pack/plugins/ml/server/models/job_service/jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,20 +272,9 @@ export function jobsProvider(
return jobs;
}

async function getJobsWithGeo(): Promise<string[]> {
async function getJobIdsWithGeo(): Promise<string[]> {
const { body } = await mlClient.getJobs<MlJobsResponse>();

const geoJobs: string[] = [];

if (body.count && body.count > 0) {
body.jobs.forEach((job) => {
if (isJobWithGeoData(job)) {
geoJobs.push(job.job_id);
}
});
}

return geoJobs;
return body.jobs.filter(isJobWithGeoData).map((job) => job.job_id);
}

async function jobsWithTimerange() {
Expand Down Expand Up @@ -678,6 +667,6 @@ export function jobsProvider(
getAllJobAndGroupIds,
getLookBackProgress,
bulkCreate,
getJobsWithGeo,
getJobIdsWithGeo,
};
}
4 changes: 2 additions & 2 deletions x-pack/plugins/ml/server/routes/job_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,13 +306,13 @@ export function jobServiceRoutes({ router, routeGuard }: RouteInitialization) {
},
routeGuard.fullLicenseAPIGuard(async ({ client, mlClient, response, context }) => {
try {
const { getJobsWithGeo } = jobServiceProvider(
const { getJobIdsWithGeo } = jobServiceProvider(
client,
mlClient,
context.alerting?.getRulesClient()
);

const resp = await getJobsWithGeo();
const resp = await getJobIdsWithGeo();

return response.ok({
body: resp,
Expand Down

0 comments on commit e121d67

Please sign in to comment.