Skip to content

Commit c6d6bf7

Browse files
aKlimauclaude
andcommitted
Add more Pulp Exceptions.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 0873f64 commit c6d6bf7

11 files changed

Lines changed: 241 additions & 48 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add more Pulp Exceptions.

pulp_python/app/exceptions.py

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
from gettext import gettext as _
2+
3+
from pulpcore.plugin.exceptions import PulpException
4+
5+
6+
class ProvenanceVerificationError(PulpException):
7+
"""
8+
Raised when provenance verification fails.
9+
"""
10+
11+
error_code = "PYT0001"
12+
13+
def __init__(self, message):
14+
"""
15+
:param message: Description of the provenance verification error
16+
:type message: str
17+
"""
18+
self.message = message
19+
20+
def __str__(self):
21+
return f"[{self.error_code}] " + _("Provenance verification failed: {message}").format(
22+
message=self.message
23+
)
24+
25+
26+
class AttestationVerificationError(PulpException):
27+
"""
28+
Raised when attestation verification fails.
29+
"""
30+
31+
error_code = "PYT0002"
32+
33+
def __init__(self, message):
34+
"""
35+
:param message: Description of the attestation verification error
36+
:type message: str
37+
"""
38+
self.message = message
39+
40+
def __str__(self):
41+
return f"[{self.error_code}] " + _("Attestation verification failed: {message}").format(
42+
message=self.message
43+
)
44+
45+
46+
class PackageSubstitutionError(PulpException):
47+
"""
48+
Raised when packages with the same filename but different checksums are being added.
49+
"""
50+
51+
error_code = "PYT0003"
52+
53+
def __init__(self, duplicates):
54+
"""
55+
:param duplicates: Description of duplicate packages
56+
:type duplicates: str
57+
"""
58+
self.duplicates = duplicates
59+
60+
def __str__(self):
61+
return f"[{self.error_code}] " + _(
62+
"Found duplicate packages being added with the same filename but different "
63+
"checksums. To allow this, set 'allow_package_substitution' to True on the "
64+
"repository. Conflicting packages: {duplicates}"
65+
).format(duplicates=self.duplicates)
66+
67+
68+
class UnsupportedProtocolError(PulpException):
69+
"""
70+
Raised when an unsupported protocol is used for syncing.
71+
"""
72+
73+
error_code = "PYT0004"
74+
75+
def __init__(self, protocol):
76+
"""
77+
:param protocol: The unsupported protocol
78+
:type protocol: str
79+
"""
80+
self.protocol = protocol
81+
82+
def __str__(self):
83+
return f"[{self.error_code}] " + _(
84+
"Only HTTP(S) is supported for python syncing, got: {protocol}"
85+
).format(protocol=self.protocol)
86+
87+
88+
class MissingRelativePathError(PulpException):
89+
"""
90+
Raised when relative_path field is missing during package upload.
91+
"""
92+
93+
error_code = "PYT0005"
94+
95+
def __str__(self):
96+
return f"[{self.error_code}] " + _("This field is required: relative_path")
97+
98+
99+
class InvalidPythonExtensionError(PulpException):
100+
"""
101+
Raised when a file has an invalid Python package extension.
102+
"""
103+
104+
error_code = "PYT0006"
105+
106+
def __init__(self, filename):
107+
"""
108+
:param filename: The filename with invalid extension
109+
:type filename: str
110+
"""
111+
self.filename = filename
112+
113+
def __str__(self):
114+
return f"[{self.error_code}] " + _(
115+
"Extension on {filename} is not a valid python extension "
116+
"(.whl, .exe, .egg, .tar.gz, .tar.bz2, .zip)"
117+
).format(filename=self.filename)
118+
119+
120+
class InvalidProvenanceError(PulpException):
121+
"""
122+
Raised when uploaded provenance data is invalid.
123+
"""
124+
125+
error_code = "PYT0007"
126+
127+
def __init__(self, message):
128+
"""
129+
:param message: Description of the provenance validation error
130+
:type message: str
131+
"""
132+
self.message = message
133+
134+
def __str__(self):
135+
return f"[{self.error_code}] " + _(
136+
"The uploaded provenance is not valid: {message}"
137+
).format(message=self.message)
138+
139+
140+
class RemoteFetchError(PulpException):
141+
"""
142+
Raised when fetching metadata from all remotes fails.
143+
"""
144+
145+
error_code = "PYT0008"
146+
147+
def __init__(self, url):
148+
self.url = url
149+
150+
def __str__(self):
151+
return f"[{self.error_code}] " + _("Failed to fetch {url} from any remote.").format(
152+
url=self.url
153+
)
154+
155+
156+
class InvalidAttestationsError(PulpException):
157+
"""
158+
Raised when attestation data cannot be validated.
159+
"""
160+
161+
error_code = "PYT0009"
162+
163+
def __init__(self, message):
164+
self.message = message
165+
166+
def __str__(self):
167+
return f"[{self.error_code}] " + _("Invalid attestations: {message}").format(
168+
message=self.message
169+
)
170+
171+
172+
class BlocklistedPackageError(PulpException):
173+
"""
174+
Raised when packages matching a blocklist entry are added to a repository.
175+
"""
176+
177+
error_code = "PYT0010"
178+
179+
def __init__(self, blocked):
180+
self.blocked = blocked
181+
182+
def __str__(self):
183+
return f"[{self.error_code}] " + _(
184+
"Blocklisted packages cannot be added to this repository: {blocked}"
185+
).format(blocked=", ".join(self.blocked))

pulp_python/app/models.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
BEFORE_SAVE,
1212
hook,
1313
)
14-
from rest_framework.serializers import ValidationError
1514
from pulpcore.plugin.models import (
1615
AutoAddObjPermsMixin,
1716
BaseModel,
@@ -24,6 +23,7 @@
2423
from pulpcore.plugin.responses import ArtifactResponse
2524

2625
from pathlib import PurePath
26+
from .exceptions import BlocklistedPackageError, PackageSubstitutionError
2727
from .provenance import Provenance
2828
from .utils import (
2929
artifact_to_python_content_data,
@@ -411,17 +411,13 @@ def finalize_new_version(self, new_version):
411411

412412
def _check_for_package_substitution(self, new_version):
413413
"""
414-
Raise a ValidationError if newly added packages would replace existing packages that have
415-
the same filename but a different sha256 checksum.
414+
Raise a PackageSubstitutionError if newly added packages would replace existing packages
415+
that have the same filename but a different sha256 checksum.
416416
"""
417417
qs = PythonPackageContent.objects.filter(pk__in=new_version.content)
418418
duplicates = collect_duplicates(qs, ("filename",))
419419
if duplicates:
420-
raise ValidationError(
421-
"Found duplicate packages being added with the same filename but different checksums. " # noqa: E501
422-
"To allow this, set 'allow_package_substitution' to True on the repository. "
423-
f"Conflicting packages: {duplicates}"
424-
)
420+
raise PackageSubstitutionError(duplicates)
425421

426422
def _check_blocklist(self, new_version):
427423
"""
@@ -452,10 +448,7 @@ def check_blocklist_for_packages(self, packages):
452448
blocked.append(pkg.filename)
453449
break
454450
if blocked:
455-
raise ValidationError(
456-
"Blocklisted packages cannot be added to this repository: "
457-
"{}".format(", ".join(blocked))
458-
)
451+
raise BlocklistedPackageError(blocked)
459452

460453

461454
class PythonBlocklistEntry(BaseModel):

pulp_python/app/serializers.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,22 @@
99
from packaging.version import Version, InvalidVersion
1010
from rest_framework import serializers
1111
from pypi_attestations import AttestationError
12-
from pydantic import TypeAdapter, ValidationError
12+
from pydantic import TypeAdapter, ValidationError as PydanticValidationError
1313
from urllib.parse import urljoin
1414

15+
from pulpcore.plugin.exceptions import DigestValidationError
1516
from pulpcore.plugin import models as core_models
1617
from pulpcore.plugin import serializers as core_serializers
1718
from pulpcore.plugin.util import get_domain, get_prn, get_current_authenticated_user, reverse
1819

1920
from pulp_python.app import models as python_models
21+
from pulp_python.app.exceptions import (
22+
AttestationVerificationError,
23+
InvalidProvenanceError,
24+
InvalidPythonExtensionError,
25+
MissingRelativePathError,
26+
ProvenanceVerificationError,
27+
)
2028
from pulp_python.app.utils import canonicalize_name
2129
from pulp_python.app.provenance import (
2230
Attestation,
@@ -386,7 +394,7 @@ def validate_attestations(self, value):
386394
attestations = TypeAdapter(list[Attestation]).validate_json(value)
387395
else:
388396
attestations = TypeAdapter(list[Attestation]).validate_python(value)
389-
except ValidationError as e:
397+
except PydanticValidationError as e:
390398
raise serializers.ValidationError(_("Invalid attestations: {}".format(e)))
391399
return attestations
392400

@@ -399,9 +407,7 @@ def handle_attestations(self, filename, sha256, attestations, offline=True):
399407
try:
400408
verify_provenance(filename, sha256, provenance, offline=offline)
401409
except AttestationError as e:
402-
raise serializers.ValidationError(
403-
{"attestations": _("Attestations failed verification: {}".format(e))}
404-
)
410+
raise AttestationVerificationError(str(e))
405411
return provenance.model_dump(mode="json")
406412

407413
def deferred_validate(self, data):
@@ -420,26 +426,18 @@ def deferred_validate(self, data):
420426
try:
421427
filename = data["relative_path"]
422428
except KeyError:
423-
raise serializers.ValidationError(detail={"relative_path": _("This field is required")})
429+
raise MissingRelativePathError()
424430

425431
artifact = data["artifact"]
426432
try:
427433
_data = artifact_to_python_content_data(filename, artifact, domain=get_domain())
428434
except ValueError:
429-
raise serializers.ValidationError(
430-
_(
431-
"Extension on {} is not a valid python extension "
432-
"(.whl, .exe, .egg, .tar.gz, .tar.bz2, .zip)"
433-
).format(filename)
434-
)
435+
raise InvalidPythonExtensionError(filename)
435436

436437
if data.get("sha256") and data["sha256"] != artifact.sha256:
437-
raise serializers.ValidationError(
438-
detail={
439-
"sha256": _(
440-
"The uploaded artifact's sha256 checksum does not match the one provided"
441-
)
442-
}
438+
raise DigestValidationError(
439+
actual=artifact.sha256,
440+
expected=data["sha256"],
443441
)
444442

445443
data.update(_data)
@@ -653,15 +651,13 @@ def deferred_validate(self, data):
653651
try:
654652
provenance = Provenance.model_validate_json(data["file"].read())
655653
data["provenance"] = provenance.model_dump(mode="json")
656-
except ValidationError as e:
657-
raise serializers.ValidationError(
658-
_("The uploaded provenance is not valid: {}".format(e))
659-
)
654+
except PydanticValidationError as e:
655+
raise InvalidProvenanceError(str(e))
660656
if data.pop("verify"):
661657
try:
662658
verify_provenance(data["package"].filename, data["package"].sha256, provenance)
663659
except AttestationError as e:
664-
raise serializers.ValidationError(_("Provenance verification failed: {}".format(e)))
660+
raise ProvenanceVerificationError(str(e))
665661
return data
666662

667663
def retrieve(self, validated_data):

pulp_python/app/tasks/sync.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,9 @@
33

44
from aiohttp import ClientResponseError, ClientError
55
from lxml.etree import LxmlError
6-
from gettext import gettext as _
76
from functools import partial
87

9-
from rest_framework import serializers
10-
8+
from pulpcore.plugin.exceptions import SyncError
119
from pulpcore.plugin.download import HttpDownloader
1210
from pulpcore.plugin.models import Artifact, ProgressReport, Remote, Repository
1311
from pulpcore.plugin.stages import (
@@ -17,6 +15,7 @@
1715
Stage,
1816
)
1917

18+
from pulp_python.app.exceptions import UnsupportedProtocolError
2019
from pulp_python.app.models import (
2120
PythonPackageContent,
2221
PythonRemote,
@@ -54,7 +53,7 @@ def sync(remote_pk, repository_pk, mirror):
5453
repository = Repository.objects.get(pk=repository_pk)
5554

5655
if not remote.url:
57-
raise serializers.ValidationError(detail=_("A remote must have a url attribute to sync."))
56+
raise SyncError("A remote must have a url attribute to sync.")
5857

5958
first_stage = PythonBanderStage(remote)
6059
DeclarativeVersion(first_stage, repository, mirror).create()
@@ -117,7 +116,8 @@ async def run(self):
117116
url = self.remote.url.rstrip("/")
118117
downloader = self.remote.get_downloader(url=url)
119118
if not isinstance(downloader, HttpDownloader):
120-
raise ValueError("Only HTTP(S) is supported for python syncing")
119+
protocol = type(downloader).__name__
120+
raise UnsupportedProtocolError(protocol)
121121

122122
async with Master(url, allow_non_https=True) as master:
123123
# Replace the session with the remote's downloader session

0 commit comments

Comments
 (0)