Skip to content

Commit 95f706f

Browse files
committed
Check if IDs exist in generated product IDS
1 parent a2606e4 commit 95f706f

File tree

1 file changed

+23
-7
lines changed
  • src/layers/domain/core/cpm_system_id

1 file changed

+23
-7
lines changed

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

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
1+
import os
12
import random
23
import re
34
from abc import ABC, abstractmethod
45
from datetime import datetime
6+
from pathlib import Path
57
from uuid import uuid4
68

79
from domain.core.base import BaseModel
810
from domain.core.device_key import validate_key
911
from domain.core.error import InvalidKeyPattern
1012
from domain.core.product_key import ProductKeyType
13+
from event.json import json_load
1114
from pydantic import validator
1215

1316
FIRST_ASID = 200000099999
@@ -19,6 +22,9 @@
1922
PRODUCT_ID_PATTERN = re.compile(
2023
rf"^P\.[{PRODUCT_ID_VALID_CHARS}]{{{PRODUCT_ID_PART_LENGTH}}}-[{PRODUCT_ID_VALID_CHARS}]{{{PRODUCT_ID_PART_LENGTH}}}$"
2124
)
25+
26+
PATH_TO_CPM_SYSTEM_IDS = Path(__file__).parent
27+
PRODUCT_IDS_GENERATED_FILE = f"{PATH_TO_CPM_SYSTEM_IDS}/generated_ids/product_ids.json"
2228
PRODUCT_TEAM_ID_PATTERN = re.compile(
2329
r"^[a-zA-Z0-9]+\.([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$"
2430
)
@@ -105,19 +111,29 @@ def latest_number(self):
105111
class ProductId(CpmSystemId):
106112
@classmethod
107113
def create(cls):
108-
"""No current_id needed, key is generated randomly."""
109-
rng = random.Random(datetime.now().timestamp())
110-
product_id = "-".join(
111-
"".join(rng.choices(PRODUCT_ID_VALID_CHARS, k=PRODUCT_ID_PART_LENGTH))
112-
for _ in range(PRODUCT_ID_NUMBER_OF_PARTS)
113-
)
114-
return cls(__root__=f"P.{product_id}")
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}")
115124

116125
@classmethod
117126
def validate_cpm_system_id(cls, cpm_system_id: str) -> bool:
118127
"""Validate that the ProductId has the correct format."""
119128
return PRODUCT_ID_PATTERN.match(cpm_system_id) is not None
120129

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()
136+
121137

122138
class ProductTeamId(CpmSystemId):
123139
@classmethod

0 commit comments

Comments
 (0)