Skip to content

Commit 9549eb1

Browse files
authored
Merge pull request #967 from balena-io/reduce-constrained-model-memory
Avoid deep cloning relationships when hitting additional permissions for constrained models
2 parents 12f3260 + 87f3eab commit 9549eb1

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

src/sbvr-api/permissions.ts

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -298,30 +298,39 @@ const collapsePermissionFilters = <T>(
298298
return v;
299299
};
300300

301-
const namespaceRelationships = (
302-
relationships: Relationship,
301+
function namespaceRelationships<T extends Relationship>(
302+
relationships: T,
303303
alias: string,
304-
): void => {
304+
): undefined | T {
305+
let ret = relationships;
305306
for (const [key, relationship] of Object.entries(
306307
relationships as RelationshipInternalNode,
307308
)) {
308309
if (key === '$') {
309310
continue;
310311
}
311312

313+
const changedEntry = namespaceRelationships(relationship, alias);
314+
if (changedEntry != null) {
315+
ret = { ...ret };
316+
(ret as RelationshipInternalNode)[key] = changedEntry;
317+
}
318+
312319
let mapping = (relationship as RelationshipLeafNode).$;
313320
if (mapping?.length === 2) {
314321
mapping = _.cloneDeep(mapping);
315-
// we do check the length above, but typescript thinks the second
316-
// element could be undefined
317322
mapping[1]![0] = `${mapping[1]![0]}$${alias}`;
318-
(relationships as RelationshipInternalNode)[`${key}$${alias}`] = {
323+
324+
ret = { ...ret };
325+
(ret as RelationshipInternalNode)[`${key}$${alias}`] = {
319326
$: mapping,
320327
};
321328
}
322-
namespaceRelationships(relationship, alias);
323329
}
324-
};
330+
if (ret !== relationships) {
331+
return ret;
332+
}
333+
}
325334

326335
type PermissionLookup = Dictionary<true | string[]>;
327336

@@ -1198,11 +1207,12 @@ const getBoundConstrainedMemoizer = memoizeWeak(
11981207
return;
11991208
}
12001209
for (const relationship of origRelationships) {
1201-
// TODO: Avoid this cloneDeep when not necessary
1210+
const origRelationship = relationships[relationship];
12021211
relationships[`${relationship}$${alias}`] = relationships[
12031212
relationship
1204-
] = _.cloneDeep(relationships[relationship]);
1205-
namespaceRelationships(relationships[relationship], alias);
1213+
] =
1214+
namespaceRelationships(origRelationship, alias) ??
1215+
origRelationship;
12061216
}
12071217
return relationships[permissionResourceName];
12081218
},

0 commit comments

Comments
 (0)