Skip to content

Commit

Permalink
Cache existing Ids
Browse files Browse the repository at this point in the history
  • Loading branch information
jameslinnell committed Dec 5, 2024
1 parent 86f5f2f commit 7c0e54f
Showing 1 changed file with 21 additions and 16 deletions.
37 changes: 21 additions & 16 deletions src/layers/domain/core/cpm_system_id/v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import re
from abc import ABC, abstractmethod
from datetime import datetime
from functools import cache
from pathlib import Path
from uuid import uuid4

Expand Down Expand Up @@ -30,6 +31,14 @@
)


@cache
def _load_existing_ids():
if os.path.exists(PRODUCT_IDS_GENERATED_FILE):
with open(PRODUCT_IDS_GENERATED_FILE, "r") as file:
return set(json_load(file))
return set()


class CpmSystemId(BaseModel, ABC):
__root__: str = None

Expand Down Expand Up @@ -111,28 +120,24 @@ def latest_number(self):
class ProductId(CpmSystemId):
@classmethod
def create(cls):
existing_ids = cls.load_existing_ids()
while True:
"""No current_id needed, key is generated randomly."""
rng = random.Random(datetime.now().timestamp())
product_id = "-".join(
"".join(rng.choices(PRODUCT_ID_VALID_CHARS, k=PRODUCT_ID_PART_LENGTH))
for _ in range(PRODUCT_ID_NUMBER_OF_PARTS)
)
if f"P.{product_id}" not in existing_ids:
return cls(__root__=f"P.{product_id}")
"""No current_id needed, key is generated randomly."""
rng = random.Random(datetime.now().timestamp())
product_id = "-".join(
"".join(rng.choices(PRODUCT_ID_VALID_CHARS, k=PRODUCT_ID_PART_LENGTH))
for _ in range(PRODUCT_ID_NUMBER_OF_PARTS)
)
if f"P.{product_id}" in cls.load_existing_ids():
return cls.create()
return cls(__root__=f"P.{product_id}")

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

@staticmethod
def load_existing_ids():
if os.path.exists(PRODUCT_IDS_GENERATED_FILE):
with open(PRODUCT_IDS_GENERATED_FILE, "r") as file:
return set(json_load(file))
return set()
@classmethod
def load_existing_ids(cls):
return _load_existing_ids()


class ProductTeamId(CpmSystemId):
Expand Down

0 comments on commit 7c0e54f

Please sign in to comment.