serialize.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import base64
  2. import io
  3. import json
  4. import zlib
  5. from pip._vendor.requests.structures import CaseInsensitiveDict
  6. from .compat import HTTPResponse, pickle
  7. def _b64_encode_bytes(b):
  8. return base64.b64encode(b).decode("ascii")
  9. def _b64_encode_str(s):
  10. return _b64_encode_bytes(s.encode("utf8"))
  11. def _b64_decode_bytes(b):
  12. return base64.b64decode(b.encode("ascii"))
  13. def _b64_decode_str(s):
  14. return _b64_decode_bytes(s).decode("utf8")
  15. class Serializer(object):
  16. def dumps(self, request, response, body=None):
  17. response_headers = CaseInsensitiveDict(response.headers)
  18. if body is None:
  19. body = response.read(decode_content=False)
  20. # NOTE: 99% sure this is dead code. I'm only leaving it
  21. # here b/c I don't have a test yet to prove
  22. # it. Basically, before using
  23. # `cachecontrol.filewrapper.CallbackFileWrapper`,
  24. # this made an effort to reset the file handle. The
  25. # `CallbackFileWrapper` short circuits this code by
  26. # setting the body as the content is consumed, the
  27. # result being a `body` argument is *always* passed
  28. # into cache_response, and in turn,
  29. # `Serializer.dump`.
  30. response._fp = io.BytesIO(body)
  31. data = {
  32. "response": {
  33. "body": _b64_encode_bytes(body),
  34. "headers": dict(
  35. (_b64_encode_str(k), _b64_encode_str(v))
  36. for k, v in response.headers.items()
  37. ),
  38. "status": response.status,
  39. "version": response.version,
  40. "reason": _b64_encode_str(response.reason),
  41. "strict": response.strict,
  42. "decode_content": response.decode_content,
  43. },
  44. }
  45. # Construct our vary headers
  46. data["vary"] = {}
  47. if "vary" in response_headers:
  48. varied_headers = response_headers['vary'].split(',')
  49. for header in varied_headers:
  50. header = header.strip()
  51. data["vary"][header] = request.headers.get(header, None)
  52. # Encode our Vary headers to ensure they can be serialized as JSON
  53. data["vary"] = dict(
  54. (_b64_encode_str(k), _b64_encode_str(v) if v is not None else v)
  55. for k, v in data["vary"].items()
  56. )
  57. return b",".join([
  58. b"cc=2",
  59. zlib.compress(
  60. json.dumps(
  61. data, separators=(",", ":"), sort_keys=True,
  62. ).encode("utf8"),
  63. ),
  64. ])
  65. def loads(self, request, data):
  66. # Short circuit if we've been given an empty set of data
  67. if not data:
  68. return
  69. # Determine what version of the serializer the data was serialized
  70. # with
  71. try:
  72. ver, data = data.split(b",", 1)
  73. except ValueError:
  74. ver = b"cc=0"
  75. # Make sure that our "ver" is actually a version and isn't a false
  76. # positive from a , being in the data stream.
  77. if ver[:3] != b"cc=":
  78. data = ver + data
  79. ver = b"cc=0"
  80. # Get the version number out of the cc=N
  81. ver = ver.split(b"=", 1)[-1].decode("ascii")
  82. # Dispatch to the actual load method for the given version
  83. try:
  84. return getattr(self, "_loads_v{0}".format(ver))(request, data)
  85. except AttributeError:
  86. # This is a version we don't have a loads function for, so we'll
  87. # just treat it as a miss and return None
  88. return
  89. def prepare_response(self, request, cached):
  90. """Verify our vary headers match and construct a real urllib3
  91. HTTPResponse object.
  92. """
  93. # Special case the '*' Vary value as it means we cannot actually
  94. # determine if the cached response is suitable for this request.
  95. if "*" in cached.get("vary", {}):
  96. return
  97. # Ensure that the Vary headers for the cached response match our
  98. # request
  99. for header, value in cached.get("vary", {}).items():
  100. if request.headers.get(header, None) != value:
  101. return
  102. body_raw = cached["response"].pop("body")
  103. try:
  104. body = io.BytesIO(body_raw)
  105. except TypeError:
  106. # This can happen if cachecontrol serialized to v1 format (pickle)
  107. # using Python 2. A Python 2 str(byte string) will be unpickled as
  108. # a Python 3 str (unicode string), which will cause the above to
  109. # fail with:
  110. #
  111. # TypeError: 'str' does not support the buffer interface
  112. body = io.BytesIO(body_raw.encode('utf8'))
  113. return HTTPResponse(
  114. body=body,
  115. preload_content=False,
  116. **cached["response"]
  117. )
  118. def _loads_v0(self, request, data):
  119. # The original legacy cache data. This doesn't contain enough
  120. # information to construct everything we need, so we'll treat this as
  121. # a miss.
  122. return
  123. def _loads_v1(self, request, data):
  124. try:
  125. cached = pickle.loads(data)
  126. except ValueError:
  127. return
  128. return self.prepare_response(request, cached)
  129. def _loads_v2(self, request, data):
  130. try:
  131. cached = json.loads(zlib.decompress(data).decode("utf8"))
  132. except ValueError:
  133. return
  134. # We need to decode the items that we've base64 encoded
  135. cached["response"]["body"] = _b64_decode_bytes(
  136. cached["response"]["body"]
  137. )
  138. cached["response"]["headers"] = dict(
  139. (_b64_decode_str(k), _b64_decode_str(v))
  140. for k, v in cached["response"]["headers"].items()
  141. )
  142. cached["response"]["reason"] = _b64_decode_str(
  143. cached["response"]["reason"],
  144. )
  145. cached["vary"] = dict(
  146. (_b64_decode_str(k), _b64_decode_str(v) if v is not None else v)
  147. for k, v in cached["vary"].items()
  148. )
  149. return self.prepare_response(request, cached)