Skip to content

Commit

Permalink
[APM] Lint rule for explicit return types (#124771) (#125619)
Browse files Browse the repository at this point in the history
(cherry picked from commit 0202164)
  • Loading branch information
dgieselaar authored Feb 15, 2022
1 parent fe9f171 commit e6f5618
Show file tree
Hide file tree
Showing 9 changed files with 160 additions and 80 deletions.
12 changes: 12 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -885,6 +885,18 @@ module.exports = {
],
},
},
{
// require explicit return types in route handlers for performance reasons
files: ['x-pack/plugins/apm/server/**/route.ts'],
rules: {
'@typescript-eslint/explicit-function-return-type': [
'error',
{
allowTypedFunctionExpressions: false,
},
],
},
},

/**
* Fleet overrides
Expand Down
33 changes: 21 additions & 12 deletions x-pack/plugins/apm/server/routes/backends/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { getTopBackends } from './get_top_backends';
import { getUpstreamServicesForBackend } from './get_upstream_services_for_backend';
import { getThroughputChartsForBackend } from './get_throughput_charts_for_backend';
import { getErrorRateChartsForBackend } from './get_error_rate_charts_for_backend';
import { ConnectionStatsItemWithImpact } from './../../../common/connections';

const topBackendsRoute = createApmServerRoute({
endpoint: 'GET /internal/apm/backends/top_backends',
Expand Down Expand Up @@ -105,10 +106,11 @@ const topBackendsRoute = createApmServerRoute({
]);

return {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
backends: currentBackends.map((backend) => {
const { stats, ...rest } = backend;
const prev = previousBackends.find(
(item) => item.location.id === backend.location.id
(item): boolean => item.location.id === backend.location.id
);
return {
...rest,
Expand Down Expand Up @@ -221,17 +223,24 @@ const upstreamServicesForBackendRoute = createApmServerRoute({
]);

return {
services: currentServices.map((service) => {
const { stats, ...rest } = service;
const prev = previousServices.find(
(item) => item.location.id === service.location.id
);
return {
...rest,
currentStats: stats,
previousStats: prev?.stats ?? null,
};
}),
services: currentServices.map(
(
service
): Omit<ConnectionStatsItemWithImpact, 'stats'> & {
currentStats: ConnectionStatsItemWithImpact['stats'];
previousStats: ConnectionStatsItemWithImpact['stats'] | null;
} => {
const { stats, ...rest } = service;
const prev = previousServices.find(
(item): boolean => item.location.id === service.location.id
);
return {
...rest,
currentStats: stats,
previousStats: prev?.stats ?? null,
};
}
),
};
},
});
Expand Down
26 changes: 20 additions & 6 deletions x-pack/plugins/apm/server/routes/correlations/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ import { withApmSpan } from '../../utils/with_apm_span';

import { createApmServerRoute } from '../apm_routes/create_apm_server_route';
import { environmentRt, kueryRt, rangeRt } from '../default_api_types';
import { LatencyCorrelation } from './../../../common/correlations/latency_correlations/types';
import {
FieldStats,
TopValuesStats,
} from './../../../common/correlations/field_stats_types';
import { FieldValuePair } from './../../../common/correlations/types';
import { FailedTransactionsCorrelation } from './../../../common/correlations/failed_transactions_correlations/types';

const INVALID_LICENSE = i18n.translate('xpack.apm.correlations.license.text', {
defaultMessage:
Expand Down Expand Up @@ -59,7 +66,7 @@ const fieldCandidatesRoute = createApmServerRoute({

return withApmSpan(
'get_correlations_field_candidates',
async () =>
async (): Promise<{ fieldCandidates: string[] }> =>
await fetchTransactionDurationFieldCandidates(esClient, {
...resources.params.query,
index: indices.transaction,
Expand Down Expand Up @@ -106,7 +113,7 @@ const fieldStatsRoute = createApmServerRoute({

return withApmSpan(
'get_correlations_field_stats',
async () =>
async (): Promise<{ stats: FieldStats[]; errors: any[] }> =>
await fetchFieldsStats(
esClient,
{
Expand Down Expand Up @@ -155,7 +162,7 @@ const fieldValueStatsRoute = createApmServerRoute({

return withApmSpan(
'get_correlations_field_value_stats',
async () =>
async (): Promise<TopValuesStats> =>
await fetchFieldValueFieldStats(
esClient,
{
Expand Down Expand Up @@ -206,7 +213,7 @@ const fieldValuePairsRoute = createApmServerRoute({

return withApmSpan(
'get_correlations_field_value_pairs',
async () =>
async (): Promise<{ errors: any[]; fieldValuePairs: FieldValuePair[] }> =>
await fetchTransactionDurationFieldValuePairs(
esClient,
{
Expand Down Expand Up @@ -268,7 +275,11 @@ const significantCorrelationsRoute = createApmServerRoute({

return withApmSpan(
'get_significant_correlations',
async () =>
async (): Promise<{
latencyCorrelations: LatencyCorrelation[];
ccsWarning: boolean;
totalDocCount: number;
}> =>
await fetchSignificantCorrelations(
esClient,
paramsWithIndex,
Expand Down Expand Up @@ -321,7 +332,10 @@ const pValuesRoute = createApmServerRoute({

return withApmSpan(
'get_p_values',
async () => await fetchPValues(esClient, paramsWithIndex, fieldCandidates)
async (): Promise<{
failedTransactionsCorrelations: FailedTransactionsCorrelation[];
ccsWarning: boolean;
}> => await fetchPValues(esClient, paramsWithIndex, fieldCandidates)
);
},
});
Expand Down
6 changes: 5 additions & 1 deletion x-pack/plugins/apm/server/routes/data_view/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { createStaticDataView } from './create_static_data_view';
import { setupRequest } from '../../lib/helpers/setup_request';
import { getDynamicDataView } from './get_dynamic_data_view';
import { createApmServerRoute } from '../apm_routes/create_apm_server_route';
import { ISavedObjectsRepository } from '../../../../../../src/core/server';

const staticDataViewRoute = createApmServerRoute({
endpoint: 'POST /internal/apm/data_view/static',
Expand All @@ -24,7 +25,10 @@ const staticDataViewRoute = createApmServerRoute({
const setupPromise = setupRequest(resources);
const clientPromise = core
.start()
.then((coreStart) => coreStart.savedObjects.createInternalRepository());
.then(
(coreStart): ISavedObjectsRepository =>
coreStart.savedObjects.createInternalRepository()
);

const setup = await setupPromise;
const savedObjectsClient = await clientPromise;
Expand Down
29 changes: 19 additions & 10 deletions x-pack/plugins/apm/server/routes/fleet/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,25 @@ const fleetAgentsRoute = createApmServerRoute({
return {
cloudStandaloneSetup,
isFleetEnabled: true,
fleetAgents: fleetAgents.map((agent) => {
const packagePolicy = policiesGroupedById[agent.id];
const packagePolicyVars = packagePolicy.inputs[0]?.vars;
return {
id: agent.id,
name: agent.name,
apmServerUrl: packagePolicyVars?.url?.value,
secretToken: packagePolicyVars?.secret_token?.value,
};
}),
fleetAgents: fleetAgents.map(
(
agent
): {
id: string;
name: string;
apmServerUrl: string | undefined;
secretToken: string | undefined;
} => {
const packagePolicy = policiesGroupedById[agent.id];
const packagePolicyVars = packagePolicy.inputs[0]?.vars;
return {
id: agent.id,
name: agent.name,
apmServerUrl: packagePolicyVars?.url?.value,
secretToken: packagePolicyVars?.secret_token?.value,
};
}
),
};
},
});
Expand Down
49 changes: 30 additions & 19 deletions x-pack/plugins/apm/server/routes/observability_overview/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,25 +58,36 @@ const observabilityOverviewRoute = createApmServerRoute({
kuery: '',
});

return withApmSpan('observability_overview', async () => {
const [serviceCount, transactionPerMinute] = await Promise.all([
getServiceCount({
setup,
searchAggregatedTransactions,
start,
end,
}),
getTransactionsPerMinute({
setup,
bucketSize,
searchAggregatedTransactions,
start,
end,
intervalString,
}),
]);
return { serviceCount, transactionPerMinute };
});
return withApmSpan(
'observability_overview',
async (): Promise<{
serviceCount: number;
transactionPerMinute:
| { value: undefined; timeseries: never[] }
| {
value: number;
timeseries: Array<{ x: number; y: number | null }>;
};
}> => {
const [serviceCount, transactionPerMinute] = await Promise.all([
getServiceCount({
setup,
searchAggregatedTransactions,
start,
end,
}),
getTransactionsPerMinute({
setup,
bucketSize,
searchAggregatedTransactions,
start,
end,
intervalString,
}),
]);
return { serviceCount, transactionPerMinute };
}
);
},
});

Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/apm/server/routes/rum_client/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@ function decodeUiFilters(
}
}

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
async function setupUXRequest<TParams extends SetupUXRequestParams>(
resources: APMRouteHandlerResources & { params: TParams }
) {
Expand Down
76 changes: 46 additions & 30 deletions x-pack/plugins/apm/server/routes/services/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ import {
} from '../../../../ml/server';
import { getServiceInstancesDetailedStatisticsPeriods } from './get_service_instances/detailed_statistics';
import { ML_ERRORS } from '../../../common/anomaly_detection';
import { ScopedAnnotationsClient } from '../../../../observability/server';
import { Annotation } from './../../../../observability/common/annotations';
import { ConnectionStatsItemWithImpact } from './../../../common/connections';

const servicesRoute = createApmServerRoute({
endpoint: 'GET /internal/apm/services',
Expand Down Expand Up @@ -373,8 +376,10 @@ const serviceAnnotationsRoute = createApmServerRoute({
const [annotationsClient, searchAggregatedTransactions] = await Promise.all(
[
observability
? withApmSpan('get_scoped_annotations_client', () =>
observability.setup.getScopedAnnotationsClient(context, request)
? withApmSpan(
'get_scoped_annotations_client',
(): Promise<undefined | ScopedAnnotationsClient> =>
observability.setup.getScopedAnnotationsClient(context, request)
)
: undefined,
getSearchAggregatedTransactions({
Expand Down Expand Up @@ -443,8 +448,10 @@ const serviceAnnotationsCreateRoute = createApmServerRoute({
} = resources;

const annotationsClient = observability
? await withApmSpan('get_scoped_annotations_client', () =>
observability.setup.getScopedAnnotationsClient(context, request)
? await withApmSpan(
'get_scoped_annotations_client',
(): Promise<undefined | ScopedAnnotationsClient> =>
observability.setup.getScopedAnnotationsClient(context, request)
)
: undefined;

Expand All @@ -454,20 +461,22 @@ const serviceAnnotationsCreateRoute = createApmServerRoute({

const { body, path } = params;

return withApmSpan('create_annotation', () =>
annotationsClient.create({
message: body.service.version,
...body,
'@timestamp': new Date(body['@timestamp']).toISOString(),
annotation: {
type: 'deployment',
},
service: {
...body.service,
name: path.serviceName,
},
tags: uniq(['apm'].concat(body.tags ?? [])),
})
return withApmSpan(
'create_annotation',
(): Promise<{ _id: string; _index: string; _source: Annotation }> =>
annotationsClient.create({
message: body.service.version,
...body,
'@timestamp': new Date(body['@timestamp']).toISOString(),
annotation: {
type: 'deployment',
},
service: {
...body.service,
name: path.serviceName,
},
tags: uniq(['apm'].concat(body.tags ?? [])),
})
);
},
});
Expand Down Expand Up @@ -925,18 +934,25 @@ export const serviceDependenciesRoute = createApmServerRoute({
]);

return {
serviceDependencies: currentPeriod.map((item) => {
const { stats, ...rest } = item;
const previousPeriodItem = previousPeriod.find(
(prevItem) => item.location.id === prevItem.location.id
);

return {
...rest,
currentStats: stats,
previousStats: previousPeriodItem?.stats || null,
};
}),
serviceDependencies: currentPeriod.map(
(
item
): Omit<ConnectionStatsItemWithImpact, 'stats'> & {
currentStats: ConnectionStatsItemWithImpact['stats'];
previousStats: ConnectionStatsItemWithImpact['stats'] | null;
} => {
const { stats, ...rest } = item;
const previousPeriodItem = previousPeriod.find(
(prevItem): boolean => item.location.id === prevItem.location.id
);

return {
...rest,
currentStats: stats,
previousStats: previousPeriodItem?.stats || null,
};
}
),
};
},
});
Expand Down
Loading

0 comments on commit e6f5618

Please sign in to comment.