perf: Policy evaluation (#10863)

* perf: Several O(n) improvements in policy calculation

* perf: Simplify to single loop in can method

* perf: refactor ability lookups
This commit is contained in:
Tom Moor authored and GitHub committed 2025-12-11 20:51:22 -05:00
1 parent 8cb07889ce
commit 2e471f88be
4 files changed
+132 -55

No files matched your search

+98 -43
View File
@@ -1,6 +1,4 @@
import flattenDeep from "lodash/flattenDeep";
import isObject from "lodash/isPlainObject";
import uniq from "lodash/uniq";
import { Model } from "sequelize-typescript";
import { AuthorizationError } from "@server/errors";
@@ -26,8 +24,6 @@ type Ability = {
* This is originally adapted from https://www.npmjs.com/package/cancan
*/
export class CanCan {
public abilities: Ability[] = [];
/**
* Define an authorized ability for a model, action, and target.
*
@@ -58,7 +54,17 @@ export class CanCan {
(this.toArray(actions) as string[]).forEach((action) => {
(this.toArray(targets) as T[]).forEach((target) => {
this.abilities.push({ model, action, target, condition } as Ability);
const ability = { model, action, target, condition } as Ability;
// Add to index
if (!this.abilities.has(model)) {
this.abilities.set(model, new Map());
}
const actionMap = this.abilities.get(model)!;
if (!actionMap.has(action)) {
actionMap.set(action, []);
}
actionMap.get(action)!.push(ability);
});
});
};
@@ -85,25 +91,31 @@ export class CanCan {
);
// Check conditions only for matching abilities
const conditions = uniq(
flattenDeep(
matchingAbilities.map((ability) => {
if (!ability.condition) {
return false;
}
return ability.condition(performer, target, options || {});
})
)
);
const seenConditions = new Set<boolean | string>();
const membershipIds: string[] = [];
let hasNonMembershipMatch = false;
const matchingConditions = conditions.filter(Boolean);
const matchingMembershipIds = matchingConditions.filter(
(m) => typeof m === "string"
) as string[];
for (const ability of matchingAbilities) {
if (!ability.condition) {
continue;
}
return matchingMembershipIds.length > 0
? matchingMembershipIds
: matchingConditions.length > 0;
const result = ability.condition(performer, target, options);
if (!result || seenConditions.has(result)) {
continue;
}
seenConditions.add(result);
if (typeof result === "string") {
membershipIds.push(result);
} else {
hasNonMembershipMatch = true;
}
}
return membershipIds.length > 0 ? membershipIds : hasNonMembershipMatch;
};
/*
@@ -113,22 +125,31 @@ export class CanCan {
*/
public serialize = (performer: Model, target: Model | null): Policy => {
const output: Record<string, boolean | string[]> = {};
abilities.forEach((ability) => {
if (
performer instanceof ability.model &&
target instanceof (ability.target as any)
) {
let response: boolean | string[] = true;
try {
response = this.can(performer, ability.action, target);
} catch (_err) {
response = false;
// Get all unique actions to check from the index
const actionsToCheck = new Set<string>();
for (const [model, actionMap] of this.abilities.entries()) {
if (performer instanceof model) {
for (const [action, abilities] of actionMap.entries()) {
for (const ability of abilities) {
if (target instanceof (ability.target as any)) {
actionsToCheck.add(action);
break;
}
}
}
}
}
output[ability.action] = response;
// Check each unique action once
actionsToCheck.forEach((action) => {
try {
output[action] = this.can(performer, action, target);
} catch (_err) {
output[action] = false;
}
});
return output;
};
@@ -174,15 +195,49 @@ export class CanCan {
performer: Model,
action: string,
target: Model | null | undefined
) =>
this.abilities.filter(
(ability) =>
performer instanceof ability.model &&
(ability.target === "all" ||
target === ability.target ||
target instanceof (ability.target as any)) &&
(ability.action === "manage" || action === ability.action)
);
) => {
const matchingAbilities: Ability[] = [];
// Use index to find abilities by model and action
for (const [model, actionMap] of this.abilities.entries()) {
if (!(performer instanceof model)) {
continue;
}
// Check for specific action
const specificAbilities = actionMap.get(action);
if (specificAbilities) {
for (const ability of specificAbilities) {
if (
ability.target === "all" ||
target === ability.target ||
target instanceof (ability.target as any)
) {
matchingAbilities.push(ability);
}
}
}
// Check for "manage" action (applies to all actions)
const manageAbilities = actionMap.get("manage");
if (manageAbilities) {
for (const ability of manageAbilities) {
if (
ability.target === "all" ||
target === ability.target ||
target instanceof (ability.target as any)
) {
matchingAbilities.push(ability);
}
}
}
}
return matchingAbilities;
};
// Index for fast lookups: Map<model, Map<action, Ability[]>>
private abilities: Map<Constructor, Map<string, Ability[]>> = new Map();
private get = <T extends object>(obj: T, key: keyof T) =>
"get" in obj && typeof obj.get === "function" ? obj.get(key) : obj[key];
@@ -219,7 +274,7 @@ export class CanCan {
const cancan = new CanCan();
export const { allow, can, cannot, abilities, serialize } = cancan;
export const { allow, can, cannot, serialize } = cancan;
// This is exported separately as a workaround for the following issue:
// https://github.com/microsoft/TypeScript/issues/36931
+14 -5
View File
@@ -1,5 +1,4 @@
import invariant from "invariant";
import filter from "lodash/filter";
import { CollectionPermission } from "@shared/types";
import { Collection, User, Team } from "@server/models";
import { allow } from "./cancan";
@@ -194,10 +193,20 @@ function includesMembership(
"Development: collection groupMemberships not preloaded, did you forget `withMembership` scope?"
);
const membershipIds = filter(
[...collection.memberships, ...collection.groupMemberships],
(m) => permissions.includes(m.permission as CollectionPermission)
).map((m) => m.id);
const permissionSet = new Set(permissions);
const membershipIds: string[] = [];
for (const membership of collection.memberships) {
if (permissionSet.has(membership.permission as CollectionPermission)) {
membershipIds.push(membership.id);
}
}
for (const membership of collection.groupMemberships) {
if (permissionSet.has(membership.permission as CollectionPermission)) {
membershipIds.push(membership.id);
}
}
return membershipIds.length > 0 ? membershipIds : false;
}
+14 -5
View File
@@ -1,5 +1,4 @@
import invariant from "invariant";
import filter from "lodash/filter";
import { DocumentPermission, TeamPreference } from "@shared/types";
import { Document, Revision, User, Team } from "@server/models";
import { allow, cannot, can } from "./cancan";
@@ -322,10 +321,20 @@ function includesMembership(
"Development: document groupMemberships should be preloaded, did you forget withMembership scope?"
);
const membershipIds = filter(
[...document.memberships, ...document.groupMemberships],
(m) => permissions.includes(m.permission as DocumentPermission)
).map((m) => m.id);
const permissionSet = new Set(permissions);
const membershipIds: string[] = [];
for (const membership of document.memberships) {
if (permissionSet.has(membership.permission as DocumentPermission)) {
membershipIds.push(membership.id);
}
}
for (const membership of document.groupMemberships) {
if (permissionSet.has(membership.permission as DocumentPermission)) {
membershipIds.push(membership.id);
}
}
return membershipIds.length > 0 ? membershipIds : false;
}
+6 -2
View File
@@ -7,8 +7,12 @@ import invariant from "invariant";
type Args = boolean | string | Args[];
export function and(...args: Args[]) {
const filtered = args.filter(Boolean);
return filtered.length === args.length ? filtered : false;
for (const arg of args) {
if (!arg) {
return false;
}
}
return args;
}
export function or(...args: Args[]) {