|
4 | 4 | from pathlib import Path
|
5 | 5 | from typing import Any, Dict, List, Optional, Type, Union
|
6 | 6 |
|
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 | +) |
8 | 16 |
|
9 | 17 | from pydatalab.models import Person
|
10 | 18 | from pydatalab.models.utils import RandomAlphabeticalRefcodeFactory, RefCodeFactory
|
@@ -86,8 +94,8 @@ class ServerConfig(BaseSettings):
|
86 | 94 | )
|
87 | 95 |
|
88 | 96 | 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`", |
91 | 99 | )
|
92 | 100 |
|
93 | 101 | REFCODE_GENERATOR: Type[RefCodeFactory] = Field(
|
@@ -140,6 +148,49 @@ def validate_cache_ages(cls, values):
|
140 | 148 | )
|
141 | 149 | return values
|
142 | 150 |
|
| 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 | + |
143 | 194 | class Config:
|
144 | 195 | env_prefix = "pydatalab_"
|
145 | 196 | extra = "allow"
|
|
0 commit comments