-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add publisher gateway client #240
Open
lengau
wants to merge
5
commits into
main
Choose a base branch
from
work/charmcraft-1901
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1eb2088
feat: add publisher gateway client
lengau 502584b
Merge branch 'main' into work/charmcraft-1901
lengau 83764a9
fix: pr suggestion about unifying httpx auth tokens
lengau 771e63c
fix: pr suggestions
lengau 05c109e
fix: pr suggestions
lengau File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- | ||
# | ||
# Copyright 2024 Canonical Ltd. | ||
# | ||
# This program is free software; you can redistribute it and/or | ||
# modify it under the terms of the GNU Lesser General Public | ||
# License version 3 as published by the Free Software Foundation. | ||
# | ||
# This program is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
# Lesser General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Lesser General Public License | ||
# along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
"""Package containing the Publisher Gateway client and relevant metadata.""" | ||
|
||
from ._request import ( | ||
CreateTrackRequest, | ||
) | ||
|
||
from ._response import ( | ||
PackageMetadata, | ||
PublisherMetadata, | ||
TrackMetadata, | ||
) | ||
from ._publishergw import PublisherGateway | ||
|
||
__all__ = [ | ||
"CreateTrackRequest", | ||
"PackageMetadata", | ||
"PublisherMetadata", | ||
"TrackMetadata", | ||
"PublisherGateway", | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- | ||
# | ||
# Copyright 2024 Canonical Ltd. | ||
# | ||
# This program is free software; you can redistribute it and/or | ||
# modify it under the terms of the GNU Lesser General Public | ||
# License version 3 as published by the Free Software Foundation. | ||
# | ||
# This program is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
# Lesser General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Lesser General Public License | ||
# along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
"""Client for the publisher gateway.""" | ||
from __future__ import annotations | ||
|
||
from json import JSONDecodeError | ||
from typing import cast | ||
|
||
import httpx | ||
|
||
from craft_store import errors | ||
from craft_store._httpx_auth import CandidAuth | ||
from craft_store.auth import Auth | ||
|
||
from . import _request, _response | ||
|
||
|
||
class PublisherGateway: | ||
"""Client for the publisher gateway. | ||
|
||
This class is a client wrapper for the Canonical Publisher Gateway. | ||
The latest version of the server API can be seen at: https://api.charmhub.io/docs/ | ||
|
||
Each instance is only valid for one particular namespace. | ||
""" | ||
|
||
def __init__(self, base_url: str, namespace: str, auth: Auth) -> None: | ||
self._namespace = namespace | ||
self._client = httpx.Client( | ||
base_url=base_url, | ||
auth=CandidAuth(auth=auth, auth_type="macaroon"), | ||
) | ||
|
||
@staticmethod | ||
def _check_error(response: httpx.Response) -> None: | ||
if response.is_success: | ||
return | ||
try: | ||
error_response = response.json() | ||
except JSONDecodeError as exc: | ||
raise errors.CraftStoreError( | ||
f"Invalid response from server ({response.status_code})", | ||
details=response.text, | ||
) from exc | ||
error_list = error_response.get("error-list", []) | ||
if response.status_code >= 500: | ||
brief = f"Store had an error ({response.status_code})" | ||
else: | ||
brief = f"Error {response.status_code} returned from store" | ||
if len(error_list) == 1: | ||
brief = f"{brief}: {error_list[0].get('message')}" | ||
else: | ||
fancy_error_list = errors.StoreErrorList(error_list) | ||
brief = f"{brief}.\n{fancy_error_list}" | ||
raise errors.CraftStoreError( | ||
brief, store_errors=errors.StoreErrorList(error_list) | ||
) | ||
|
||
def get_package_metadata(self, name: str) -> _response.PackageMetadata: | ||
"""Get general metadata for a package. | ||
|
||
:param name: The name of the package to query. | ||
:returns: A dictionary matching the result from the publisher gateway. | ||
|
||
API docs: https://api.charmhub.io/docs/default.html#package_metadata | ||
""" | ||
response = self._client.get( | ||
url=f"/v1/{self._namespace}/{name}", | ||
) | ||
self._check_error(response) | ||
return cast(_response.PackageMetadata, response.json()["metadata"]) | ||
|
||
def create_tracks(self, name: str, *tracks: _request.CreateTrackRequest) -> int: | ||
"""Create one or more tracks in the store. | ||
|
||
:param name: The store name (i.e. the specific charm, snap or other package) | ||
to which this track will be attached. | ||
:param tracks: Each track is a dictionary mapping query values. | ||
:returns: The number of tracks created by the store. | ||
:returns: InvalidRequestError if the name field of any passed track is invalid. | ||
|
||
API docs: https://api.charmhub.io/docs/default.html#create_tracks | ||
""" | ||
bad_track_names = { | ||
track["name"] | ||
for track in tracks | ||
if not _request.TRACK_NAME_REGEX.match(track["name"]) | ||
or len(track["name"]) > 28 | ||
} | ||
if bad_track_names: | ||
bad_tracks = ", ".join(sorted(bad_track_names)) | ||
raise errors.InvalidRequestError( | ||
f"The following track names are invalid: {bad_tracks}", | ||
resolution="Ensure all tracks have valid names.", | ||
) | ||
|
||
response = self._client.post( | ||
f"/v1/{self._namespace}/{name}/tracks", json=tracks | ||
) | ||
self._check_error(response) | ||
|
||
return int(response.json()["num-tracks-created"]) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
how does this affect exporting credentials and our existing wire protocol for it?