Skip to content

Commit

Permalink
Minor reduce perf optimizations (#170922)
Browse files Browse the repository at this point in the history
## Summary

Cherry picked from #168812 the
changes from `core` packages and the `security` and `spaces` plugins

---------

Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
pgayvallet and kibanamachine authored Nov 10, 2023
1 parent c43e699 commit 2b60d3a
Show file tree
Hide file tree
Showing 15 changed files with 83 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,14 @@ const validateAggregationContainer = (
) => {
return Object.entries(container).reduce<estypes.AggregationsAggregationContainer>(
(memo, [aggName, aggregation]) => {
if (aggregationKeys.includes(aggName)) {
return memo;
if (!aggregationKeys.includes(aggName)) {
(memo as Record<string, unknown>)[aggName] = validateAggregationType(
aggName,
aggregation,
childContext(context, aggName)
);
}
return {
...memo,
[aggName]: validateAggregationType(aggName, aggregation, childContext(context, aggName)),
};
return memo;
},
{}
);
Expand Down
5 changes: 1 addition & 4 deletions packages/kbn-config-schema/src/types/object_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,7 @@ export class ObjectType<P extends Props = any> extends Type<ObjectResultType<P>>
...newProps,
}).reduce((memo, [key, value]) => {
if (value !== null && value !== undefined) {
return {
...memo,
[key]: value,
};
(memo as Record<string, unknown>)[key] = value;
}
return memo;
}, {} as ExtendedProps<P, NP>);
Expand Down
15 changes: 5 additions & 10 deletions packages/kbn-i18n/src/core/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,12 @@ export const unique = <T>(arr: T[] = []): T[] => [...new Set(arr)];
const merge = (a: any, b: any): { [k: string]: any } =>
unique([...Object.keys(a), ...Object.keys(b)]).reduce((acc, key) => {
if (isObject(a[key]) && isObject(b[key]) && !Array.isArray(a[key]) && !Array.isArray(b[key])) {
return {
...acc,
[key]: merge(a[key], b[key]),
};
acc[key] = merge(a[key], b[key]);
} else {
acc[key] = b[key] === undefined ? a[key] : b[key];
}

return {
...acc,
[key]: b[key] === undefined ? a[key] : b[key],
};
}, {});
return acc;
}, {} as { [k: string]: any });

export const mergeAll = (...sources: any[]) =>
sources.filter(isObject).reduce((acc, source) => merge(acc, source));
11 changes: 4 additions & 7 deletions packages/kbn-i18n/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,10 @@ export async function getAllTranslations(): Promise<{ [key: string]: Translation
const locales = getRegisteredLocales();
const translations = await Promise.all(locales.map(getTranslationsByLocale));

return locales.reduce(
(acc, locale, index) => ({
...acc,
[locale]: translations[index],
}),
{}
);
return locales.reduce((acc, locale, index) => {
acc[locale] = translations[index];
return acc;
}, {} as { [key: string]: Translation });
}

/**
Expand Down
5 changes: 4 additions & 1 deletion packages/kbn-std/src/iteration/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,8 @@ export async function asyncMapWithLimit<T1, T2>(

return results
.sort(([a], [b]) => a - b)
.reduce((acc: T2[], [, result]) => acc.concat(result), []);
.reduce((acc: T2[], [, result]) => {
acc.push(...result);
return acc;
}, []);
}
5 changes: 4 additions & 1 deletion packages/kbn-telemetry-tools/src/tools/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,10 @@ export function getDescriptor(node: ts.Node, program: ts.Program): Descriptor |
const constraints = getConstraints(constraint, program);
const constraintsArray = Array.isArray(constraints) ? constraints : [constraints];
if (typeof constraintsArray[0] === 'string') {
return constraintsArray.reduce((acc, c) => ({ ...acc, [c]: descriptor }), {});
return constraintsArray.reduce((acc, c) => {
(acc as Record<string, unknown>)[c] = descriptor;
return acc;
}, {});
}
}
return { '@@INDEX@@': descriptor };
Expand Down
12 changes: 5 additions & 7 deletions x-pack/plugins/security/server/authorization/check_privileges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,13 +144,11 @@ export function checkPrivilegesFactory(
const indexPrivileges = Object.entries(hasPrivilegesResponse.index ?? {}).reduce<
CheckPrivilegesResponse['privileges']['elasticsearch']['index']
>((acc, [index, indexResponse]) => {
return {
...acc,
[index]: Object.entries(indexResponse).map(([privilege, authorized]) => ({
privilege,
authorized,
})),
};
acc[index] = Object.entries(indexResponse).map(([privilege, authorized]) => ({
privilege,
authorized,
}));
return acc;
}, {});

// we need to filter out the non requested privileges from the response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,8 @@ export function disableUICapabilitiesFactory(
const elasticsearchFeatureMap = elasticsearchFeatures.reduce<
Record<string, RecursiveReadonlyArray<FeatureElasticsearchPrivileges>>
>((acc, esFeature) => {
return {
...acc,
[esFeature.id]: esFeature.privileges,
};
acc[esFeature.id] = esFeature.privileges;
return acc;
}, {});

const allRequiredClusterPrivileges = Array.from(
Expand All @@ -59,11 +57,9 @@ export function disableUICapabilitiesFactory(
return {
...acc,
...Object.entries(p.requiredIndexPrivileges!).reduce((acc2, [indexName, privileges]) => {
return {
...acc2,
[indexName]: [...(acc[indexName] ?? []), ...privileges],
};
}, {}),
acc2[indexName] = [...(acc[indexName] ?? []), ...privileges];
return acc2;
}, {} as Record<string, string[]>),
};
}, {});

Expand Down Expand Up @@ -157,14 +153,16 @@ export function disableUICapabilitiesFactory(
}

const uiActions = Object.entries(uiCapabilities).reduce<string[]>(
(acc, [featureId, featureUICapabilities]) => [
...acc,
...flatten(
Object.entries(featureUICapabilities).map(([uiCapability, value]) => {
return getActionsForFeatureCapability(featureId, uiCapability, value);
})
),
],
(acc, [featureId, featureUICapabilities]) => {
acc.push(
...flatten(
Object.entries(featureUICapabilities).map(([uiCapability, value]) => {
return getActionsForFeatureCapability(featureId, uiCapability, value);
})
)
);
return acc;
},
[]
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ export class FeaturePrivilegeManagementBuilder extends BaseFeaturePrivilegeBuild
}

return Object.entries(managementSections).reduce((acc, [sectionId, items]) => {
return [...acc, ...items.map((item) => this.actions.ui.get('management', sectionId, item))];
acc.push(...items.map((item) => this.actions.ui.get('management', sectionId, item)));
return acc;
}, [] as string[]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ export function privilegesFactory(
(feature) => !feature.excludeFromBasePrivileges
);

let allActions: string[] = [];
let readActions: string[] = [];
const allActionsSet = new Set<string>();
const readActionsSet = new Set<string>();

basePrivilegeFeatures.forEach((feature) => {
for (const { privilegeId, privilege } of featuresService.featurePrivilegeIterator(feature, {
Expand All @@ -47,15 +47,17 @@ export function privilegesFactory(
predicate: (pId, featurePrivilege) => !featurePrivilege.excludeFromBasePrivileges,
})) {
const privilegeActions = featurePrivilegeBuilder.getActions(privilege, feature);
allActions = [...allActions, ...privilegeActions];
if (privilegeId === 'read') {
readActions = [...readActions, ...privilegeActions];
}
privilegeActions.forEach((action) => {
allActionsSet.add(action);
if (privilegeId === 'read') {
readActionsSet.add(action);
}
});
}
});

allActions = uniq(allActions);
readActions = uniq(readActions);
const allActions = [...allActionsSet];
const readActions = [...readActionsSet];

const featurePrivileges: Record<string, Record<string, string[]>> = {};
for (const feature of features) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,10 @@ export function defineGetPrivilegesRoutes({ router, authz }: RouteDefinitionPara
space: Object.keys(privileges.space),
features: Object.entries(privileges.features).reduce(
(acc, [featureId, featurePrivileges]) => {
return {
...acc,
[featureId]: Object.keys(featurePrivileges),
};
acc[featureId] = Object.keys(featurePrivileges);
return acc;
},
{}
{} as Record<string, string[]>
),
reserved: Object.keys(privileges.reserved),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ export async function ensureAuthorized<T extends string>(

// Neither fully nor partially authorized. Bail with error.
const uniqueUnauthorizedPrivileges = [...missingPrivileges.entries()].reduce(
(acc, [, privilegeSet]) => new Set([...acc, ...privilegeSet]),
(acc, [, privilegeSet]) => {
privilegeSet.forEach((entry) => acc.add(entry));
return acc;
},
new Set<string>()
);
const targetTypesAndActions = [...uniqueUnauthorizedPrivileges]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,13 @@ export class SecureSpacesClientWrapper implements ISpacesClient {

// Collect all privileges which need to be checked
const allPrivileges = Object.entries(PURPOSE_PRIVILEGE_MAP).reduce(
(acc, [getSpacesPurpose, privilegeFactory]) =>
!includeAuthorizedPurposes && getSpacesPurpose !== purpose
? acc
: { ...acc, [getSpacesPurpose]: privilegeFactory(this.authorization) },
(acc, [getSpacesPurpose, privilegeFactory]) => {
if (!includeAuthorizedPurposes && getSpacesPurpose !== purpose) {
return acc;
}
acc[getSpacesPurpose as GetAllSpacesPurpose] = privilegeFactory(this.authorization);
return acc;
},
{} as Record<GetAllSpacesPurpose, string[]>
);

Expand Down Expand Up @@ -117,7 +120,8 @@ export class SecureSpacesClientWrapper implements ISpacesClient {
const requiredActions = privilegeFactory(this.authorization);
const hasAllRequired = checkHasAllRequired(space, requiredActions);
hasAnyAuthorization = hasAnyAuthorization || hasAllRequired;
return { ...acc, [purposeKey]: hasAllRequired };
acc[purposeKey as GetAllSpacesPurpose] = hasAllRequired;
return acc;
},
{} as Record<GetAllSpacesPurpose, boolean>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,12 +160,7 @@ export function registerSecurityUsageCollector({ usageCollection, config, licens
const loginSelectorEnabled = config.authc.selector.enabled;
const authProviderCount = config.authc.sortedProviders.length;
const enabledAuthProviders = [
...new Set(
config.authc.sortedProviders.reduce(
(acc, provider) => [...acc, provider.type],
[] as string[]
)
),
...new Set(config.authc.sortedProviders.map((provider) => provider.type)),
];
const accessAgreementEnabled =
allowAccessAgreement &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,19 @@ function toggleDisabledFeatures(
) {
const disabledFeatureKeys = activeSpace.disabledFeatures;

const [enabledFeatures, disabledFeatures] = features.reduce(
const { enabledFeatures, disabledFeatures } = features.reduce(
(acc, feature) => {
if (disabledFeatureKeys.includes(feature.id)) {
return [acc[0], [...acc[1], feature]];
acc.disabledFeatures.push(feature);
} else {
acc.enabledFeatures.push(feature);
}
return [[...acc[0], feature], acc[1]];
return acc;
},
[[], []] as [KibanaFeature[], KibanaFeature[]]
{ enabledFeatures: [], disabledFeatures: [] } as {
enabledFeatures: KibanaFeature[];
disabledFeatures: KibanaFeature[];
}
);

const navLinks = capabilities.navLinks;
Expand Down

0 comments on commit 2b60d3a

Please sign in to comment.