Skip to content

Commit 7c7b9ef

Browse files
committed
Validate refcode prefixes at config level and warn if unset
1 parent 3d085dd commit 7c7b9ef

File tree

1 file changed

+54
-3
lines changed

1 file changed

+54
-3
lines changed

pydatalab/pydatalab/config.py

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,15 @@
44
from pathlib import Path
55
from typing import Any, Dict, List, Optional, Type, Union
66

7-
from pydantic import AnyUrl, BaseModel, BaseSettings, Field, root_validator, validator
7+
from pydantic import (
8+
AnyUrl,
9+
BaseModel,
10+
BaseSettings,
11+
Field,
12+
ValidationError,
13+
root_validator,
14+
validator,
15+
)
816

917
from pydatalab.models import Person
1018
from pydatalab.models.utils import RandomAlphabeticalRefcodeFactory, RefCodeFactory
@@ -86,8 +94,8 @@ class ServerConfig(BaseSettings):
8694
)
8795

8896
IDENTIFIER_PREFIX: str = Field(
89-
"grey",
90-
description="The prefix to use for identifiers in this deployment, e.g., `grey:AAAAAA`",
97+
None,
98+
description="The prefix to use for identifiers in this deployment, e.g., 'grey' in `grey:AAAAAA`",
9199
)
92100

93101
REFCODE_GENERATOR: Type[RefCodeFactory] = Field(
@@ -140,6 +148,49 @@ def validate_cache_ages(cls, values):
140148
)
141149
return values
142150

151+
@validator("IDENTIFIER_PREFIX", pre=True, always=True)
152+
def validate_identifier_prefix(cls, v, values):
153+
"""Make sure that the identifier prefix is set and is valid, raising clear error messages if not.
154+
155+
If in testing mode, then set the prefix to test too.
156+
157+
"""
158+
159+
if values.get("TESTING"):
160+
return "test"
161+
162+
if v is None:
163+
import warnings
164+
165+
warning_msg = (
166+
"You should configure an identifier prefix for this deployment. "
167+
"You should attempt to make it unique to your deployment or group. "
168+
"In the future these will be optionally globally validated versus all deployments for uniqueness. "
169+
"For now the value of `test` will be used."
170+
)
171+
172+
warnings.warn(warning_msg)
173+
logging.warning(warning_msg)
174+
175+
return "test"
176+
177+
if len(v) > 12:
178+
raise RuntimeError(
179+
"Identifier prefix must be less than 12 characters long, received {v=}"
180+
)
181+
182+
# test a trial refcode
183+
from pydatalab.models.utils import Refcode
184+
185+
try:
186+
Refcode(f"{v}:AAAAAA")
187+
except ValidationError as exc:
188+
raise RuntimeError(
189+
f"Invalid identifier prefix: {v}. Validation with refcode `AAAAAA` returned error: {exc}"
190+
)
191+
192+
return v
193+
143194
class Config:
144195
env_prefix = "pydatalab_"
145196
extra = "allow"

0 commit comments

Comments
 (0)