Skip to content

Commit 9dcedfc

Browse files
committed
fix(backend): use LRU cache to store SDK schemas
Signed-off-by: Fatih Acar <[email protected]>
1 parent d5feee1 commit 9dcedfc

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

backend/infrahub/core/schema/manager.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from typing import TYPE_CHECKING, Any
44

5+
from cachetools import LRUCache
56
from infrahub_sdk.schema import BranchSchema as SDKBranchSchema
67

78
from infrahub import lock
@@ -42,7 +43,8 @@ class SchemaManager(NodeManager):
4243
def __init__(self) -> None:
4344
self._cache: dict[int, Any] = {}
4445
self._branches: dict[str, SchemaBranch] = {}
45-
self._sdk_branches: dict[str, SDKBranchSchema] = {}
46+
self._branch_hash_by_name: dict[str, str] = {}
47+
self._sdk_branches: LRUCache[str, SDKBranchSchema] = LRUCache(maxsize=10)
4648

4749
def _get_from_cache(self, key: int) -> Any:
4850
return self._cache[key]
@@ -147,12 +149,19 @@ def get_schema_branch(self, name: str) -> SchemaBranch:
147149
return self._branches[name]
148150

149151
def get_sdk_schema_branch(self, name: str) -> SDKBranchSchema:
150-
return self._sdk_branches[name]
152+
schema_hash = self._branch_hash_by_name[name]
153+
branch_schema = self._sdk_branches.get(schema_hash)
154+
if not branch_schema:
155+
self._sdk_branches[schema_hash] = SDKBranchSchema.from_api_response(
156+
data=self._branches[name].to_dict_api_schema_object()
157+
)
158+
159+
return self._sdk_branches[schema_hash]
151160

152161
def set_schema_branch(self, name: str, schema: SchemaBranch) -> None:
153162
schema.name = name
154163
self._branches[name] = schema
155-
self._sdk_branches[name] = SDKBranchSchema.from_api_response(data=schema.to_dict_api_schema_object())
164+
self._branch_hash_by_name[name] = schema.get_hash()
156165

157166
def process_schema_branch(self, name: str) -> None:
158167
schema_branch = self.get_schema_branch(name=name)
@@ -771,8 +780,8 @@ def purge_inactive_branches(self, active_branches: list[str]) -> list[str]:
771780
for branch_name in list(self._branches.keys()):
772781
if branch_name not in active_branches:
773782
del self._branches[branch_name]
774-
if branch_name in self._sdk_branches:
775-
del self._sdk_branches[branch_name]
783+
if branch_name in self._branch_hash_by_name:
784+
del self._branch_hash_by_name[branch_name]
776785
removed_branches.append(branch_name)
777786

778787
for hash_key in list(self._cache.keys()):

0 commit comments

Comments
 (0)