Skip to content

Commit 7c0e54f

Browse files
committed
Cache existing Ids
1 parent 86f5f2f commit 7c0e54f

File tree

1 file changed

+21
-16
lines changed
  • src/layers/domain/core/cpm_system_id

1 file changed

+21
-16
lines changed

src/layers/domain/core/cpm_system_id/v1.py

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import re
44
from abc import ABC, abstractmethod
55
from datetime import datetime
6+
from functools import cache
67
from pathlib import Path
78
from uuid import uuid4
89

@@ -30,6 +31,14 @@
3031
)
3132

3233

34+
@cache
35+
def _load_existing_ids():
36+
if os.path.exists(PRODUCT_IDS_GENERATED_FILE):
37+
with open(PRODUCT_IDS_GENERATED_FILE, "r") as file:
38+
return set(json_load(file))
39+
return set()
40+
41+
3342
class CpmSystemId(BaseModel, ABC):
3443
__root__: str = None
3544

@@ -111,28 +120,24 @@ def latest_number(self):
111120
class ProductId(CpmSystemId):
112121
@classmethod
113122
def create(cls):
114-
existing_ids = cls.load_existing_ids()
115-
while True:
116-
"""No current_id needed, key is generated randomly."""
117-
rng = random.Random(datetime.now().timestamp())
118-
product_id = "-".join(
119-
"".join(rng.choices(PRODUCT_ID_VALID_CHARS, k=PRODUCT_ID_PART_LENGTH))
120-
for _ in range(PRODUCT_ID_NUMBER_OF_PARTS)
121-
)
122-
if f"P.{product_id}" not in existing_ids:
123-
return cls(__root__=f"P.{product_id}")
123+
"""No current_id needed, key is generated randomly."""
124+
rng = random.Random(datetime.now().timestamp())
125+
product_id = "-".join(
126+
"".join(rng.choices(PRODUCT_ID_VALID_CHARS, k=PRODUCT_ID_PART_LENGTH))
127+
for _ in range(PRODUCT_ID_NUMBER_OF_PARTS)
128+
)
129+
if f"P.{product_id}" in cls.load_existing_ids():
130+
return cls.create()
131+
return cls(__root__=f"P.{product_id}")
124132

125133
@classmethod
126134
def validate_cpm_system_id(cls, cpm_system_id: str) -> bool:
127135
"""Validate that the ProductId has the correct format."""
128136
return PRODUCT_ID_PATTERN.match(cpm_system_id) is not None
129137

130-
@staticmethod
131-
def load_existing_ids():
132-
if os.path.exists(PRODUCT_IDS_GENERATED_FILE):
133-
with open(PRODUCT_IDS_GENERATED_FILE, "r") as file:
134-
return set(json_load(file))
135-
return set()
138+
@classmethod
139+
def load_existing_ids(cls):
140+
return _load_existing_ids()
136141

137142

138143
class ProductTeamId(CpmSystemId):

0 commit comments

Comments
 (0)