tahoe-lafs/src/allmydata/storage/http_client.py

61 lines
1.7 KiB
Python
Raw Normal View History

2021-11-12 12:51:52 -05:00
"""
HTTP client that talks to the HTTP storage server.
"""
2021-11-16 10:56:21 -05:00
import base64
2021-11-12 13:13:19 -05:00
# TODO Make sure to import Python version?
from cbor2 import loads, dumps
2021-11-12 12:51:52 -05:00
2021-11-16 10:56:21 -05:00
from twisted.web.http_headers import Headers
2021-11-12 13:13:19 -05:00
from twisted.internet.defer import inlineCallbacks, returnValue, fail
2021-11-12 12:51:52 -05:00
from hyperlink import DecodedURL
import treq
2021-11-12 13:13:19 -05:00
class ClientException(Exception):
"""An unexpected error."""
2021-11-12 12:51:52 -05:00
def _decode_cbor(response):
"""Given HTTP response, return decoded CBOR body."""
2021-11-12 13:13:19 -05:00
if response.code > 199 and response.code < 300:
return treq.content(response).addCallback(loads)
return fail(ClientException(response.code, response.phrase))
2021-11-12 12:51:52 -05:00
2021-11-16 11:09:08 -05:00
def swissnum_auth_header(swissnum): # type: (bytes) -> bytes
2021-11-16 10:56:21 -05:00
"""Return value for ``Authentication`` header."""
return b"Tahoe-LAFS " + base64.encodestring(swissnum).strip()
2021-11-12 12:51:52 -05:00
class StorageClient(object):
"""
HTTP client that talks to the HTTP storage server.
"""
def __init__(self, url: DecodedURL, swissnum, treq=treq):
self._base_url = url
self._swissnum = swissnum
self._treq = treq
2021-11-16 11:09:08 -05:00
def _get_headers(self): # type: () -> Headers
2021-11-16 10:56:21 -05:00
"""Return the basic headers to be used by default."""
headers = Headers()
headers.addRawHeader(
"Authorization",
swissnum_auth_header(self._swissnum),
)
return headers
2021-11-12 12:51:52 -05:00
@inlineCallbacks
def get_version(self):
"""
Return the version metadata for the server.
"""
2021-11-16 10:56:21 -05:00
url = self._base_url.click("/v1/version")
response = yield self._treq.get(url, headers=self._get_headers())
2021-11-12 13:13:19 -05:00
decoded_response = yield _decode_cbor(response)
returnValue(decoded_response)