|
| 1 | +import contextlib |
| 2 | +import http.client |
| 3 | +import io |
| 4 | +import json |
| 5 | +import os |
| 6 | +import pathlib |
| 7 | +import runpy |
| 8 | +import ssl |
| 9 | +import subprocess |
| 10 | +import tempfile |
| 11 | +import unittest |
| 12 | +import urllib.error |
| 13 | +from unittest import mock |
| 14 | + |
| 15 | + |
| 16 | +SCRIPT = pathlib.Path(__file__).with_name("git_lfs_probe.py") |
| 17 | +ENDPOINT = "https://lfs.example.test/repo/info/lfs" |
| 18 | +BACKUP = "https://backup.example.test/repo/info/lfs" |
| 19 | +OID = "a" * 64 |
| 20 | +DOWNLOAD = "https://downloads.example.test/content?signature=test-signature" |
| 21 | + |
| 22 | + |
| 23 | +def response(): |
| 24 | + return io.BytesIO(json.dumps({ |
| 25 | + "objects": [{"oid": OID, "actions": {"download": {"href": DOWNLOAD}}}], |
| 26 | + }).encode()) |
| 27 | + |
| 28 | + |
| 29 | +def http_error(code, retry_after=None): |
| 30 | + headers = {} if retry_after is None else {"Retry-After": retry_after} |
| 31 | + return urllib.error.HTTPError( |
| 32 | + ENDPOINT + "/objects/batch", code, "test-secret", headers, io.BytesIO() |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +class BatchRequestTest(unittest.TestCase): |
| 37 | + def setUp(self): |
| 38 | + self.stack = contextlib.ExitStack() |
| 39 | + self.addCleanup(self.stack.close) |
| 40 | + root = pathlib.Path(self.stack.enter_context(tempfile.TemporaryDirectory())) |
| 41 | + pointer = root / "pointer" |
| 42 | + pointer.write_text( |
| 43 | + "version https://git-lfs.github.com/spec/v1\n" |
| 44 | + f"oid sha256:{OID}\nsize 42\n" |
| 45 | + ) |
| 46 | + local = root / "local" |
| 47 | + local.write_text("not an LFS pointer\n") |
| 48 | + self.stack.enter_context(mock.patch("sys.argv", [str(SCRIPT), str(local), str(pointer)])) |
| 49 | + self.stack.enter_context(mock.patch.dict(os.environ, {"GITHUB_TOKEN": ""})) |
| 50 | + self.stack.enter_context(mock.patch( |
| 51 | + "subprocess.check_output", |
| 52 | + side_effect=[ |
| 53 | + str(root), |
| 54 | + f"Endpoint={ENDPOINT} (auth=none)\nEndpoint (backup)={BACKUP} (auth=none)\n", |
| 55 | + ], |
| 56 | + )) |
| 57 | + self.stack.enter_context(mock.patch( |
| 58 | + "subprocess.run", |
| 59 | + return_value=subprocess.CompletedProcess( |
| 60 | + [], 0, stdout="Authorization: Basic test-secret" |
| 61 | + ), |
| 62 | + )) |
| 63 | + self.urlopen = self.stack.enter_context(mock.patch("urllib.request.urlopen")) |
| 64 | + self.sleep = self.stack.enter_context(mock.patch("time.sleep")) |
| 65 | + self.stack.enter_context(mock.patch("time.time", return_value=1445412480)) |
| 66 | + self.stdout = self.stack.enter_context(contextlib.redirect_stdout(io.StringIO())) |
| 67 | + self.stderr = self.stack.enter_context(contextlib.redirect_stderr(io.StringIO())) |
| 68 | + |
| 69 | + def run_probe(self, outcomes): |
| 70 | + self.urlopen.side_effect = outcomes |
| 71 | + runpy.run_path(str(SCRIPT), run_name="__main__") |
| 72 | + |
| 73 | + def assert_requests(self, endpoints): |
| 74 | + self.assertEqual(self.urlopen.call_count, len(endpoints)) |
| 75 | + for call, endpoint in zip(self.urlopen.call_args_list, endpoints): |
| 76 | + request = call.args[0] |
| 77 | + self.assertEqual(request.full_url, endpoint + "/objects/batch") |
| 78 | + self.assertEqual(request.get_method(), "POST") |
| 79 | + self.assertEqual(request.get_header("Authorization"), "Basic test-secret") |
| 80 | + self.assertEqual(request.get_header("Content-type"), "application/vnd.git-lfs+json") |
| 81 | + self.assertEqual(json.loads(request.data), { |
| 82 | + "operation": "download", |
| 83 | + "transfers": ["basic"], |
| 84 | + "objects": [{"oid": OID, "size": 42}], |
| 85 | + "hash_algo": "sha256", |
| 86 | + }) |
| 87 | + self.assertEqual(call.kwargs, {"timeout": 20}) |
| 88 | + self.assertNotIn("test-secret", self.stderr.getvalue()) |
| 89 | + self.assertNotIn("test-signature", self.stderr.getvalue()) |
| 90 | + |
| 91 | + def test_disconnect_and_read_timeout_retry_same_request(self): |
| 92 | + partial_response = mock.MagicMock() |
| 93 | + partial_response.__enter__.return_value = partial_response |
| 94 | + partial_response.read.side_effect = TimeoutError("test-secret") |
| 95 | + self.run_probe([ |
| 96 | + http.client.RemoteDisconnected("test-secret"), |
| 97 | + partial_response, |
| 98 | + response(), |
| 99 | + ]) |
| 100 | + self.assert_requests([ENDPOINT] * 3) |
| 101 | + self.assertEqual(self.sleep.call_args_list, [mock.call(1), mock.call(2)]) |
| 102 | + partial_response.__exit__.assert_called_once() |
| 103 | + self.assertEqual(self.stdout.getvalue(), f"local\n{OID} {DOWNLOAD}\n") |
| 104 | + |
| 105 | + def test_wrapped_timeout_retries_before_fallback(self): |
| 106 | + self.run_probe([ |
| 107 | + urllib.error.URLError(TimeoutError("test-secret")), |
| 108 | + response(), |
| 109 | + ]) |
| 110 | + self.assert_requests([ENDPOINT] * 2) |
| 111 | + self.sleep.assert_called_once_with(1) |
| 112 | + |
| 113 | + def test_rate_limit_retry_after(self): |
| 114 | + cases = [ |
| 115 | + ("7", 7), |
| 116 | + (" 7 ", 7), |
| 117 | + ("30", 30), |
| 118 | + ("Wed, 21 Oct 2015 07:28:09 GMT", 9), |
| 119 | + ("Wed, 21 Oct 2015 07:27:00 GMT", 1), |
| 120 | + ("0", 1), |
| 121 | + ("-1", 1), |
| 122 | + ("invalid", 1), |
| 123 | + (None, 1), |
| 124 | + ] |
| 125 | + for header, delay in cases: |
| 126 | + with self.subTest(header=header): |
| 127 | + self.urlopen.reset_mock() |
| 128 | + self.sleep.reset_mock() |
| 129 | + with mock.patch("subprocess.check_output", side_effect=[ |
| 130 | + str(SCRIPT.parent), |
| 131 | + f"Endpoint={ENDPOINT} (auth=none)\n", |
| 132 | + ]): |
| 133 | + error = http_error(429, header) |
| 134 | + body = error.fp |
| 135 | + self.run_probe([error, response()]) |
| 136 | + self.assert_requests([ENDPOINT] * 2) |
| 137 | + self.sleep.assert_called_once_with(delay) |
| 138 | + self.assertTrue(body.closed) |
| 139 | + |
| 140 | + def test_long_retry_after_skips_endpoint_without_sleeping(self): |
| 141 | + self.run_probe([http_error(429, "31"), response()]) |
| 142 | + self.assert_requests([ENDPOINT, BACKUP]) |
| 143 | + self.sleep.assert_not_called() |
| 144 | + self.assertIn("429", self.stderr.getvalue()) |
| 145 | + |
| 146 | + def test_transient_http_errors_exhaust_then_fall_back(self): |
| 147 | + self.run_probe([http_error(503), http_error(502), http_error(504), response()]) |
| 148 | + self.assert_requests([ENDPOINT] * 3 + [BACKUP]) |
| 149 | + self.assertEqual(self.sleep.call_args_list, [mock.call(1), mock.call(2)]) |
| 150 | + |
| 151 | + def test_all_endpoints_exhausted_reports_failure(self): |
| 152 | + with self.assertRaises(SystemExit) as raised: |
| 153 | + self.run_probe([TimeoutError("test-secret") for _ in range(6)]) |
| 154 | + self.assertEqual(raised.exception.code, 1) |
| 155 | + self.assert_requests([ENDPOINT] * 3 + [BACKUP] * 3) |
| 156 | + self.assertEqual( |
| 157 | + self.sleep.call_args_list, |
| 158 | + [mock.call(1), mock.call(2), mock.call(1), mock.call(2)], |
| 159 | + ) |
| 160 | + self.assertIn("ERROR: no valid endpoints found", self.stderr.getvalue()) |
| 161 | + self.assertEqual(self.stdout.getvalue(), "") |
| 162 | + |
| 163 | + def test_permanent_errors_are_not_retried(self): |
| 164 | + with self.assertRaises(SystemExit) as raised: |
| 165 | + self.run_probe([ |
| 166 | + http_error(403), |
| 167 | + urllib.error.URLError(ssl.SSLCertVerificationError("test-secret")), |
| 168 | + ]) |
| 169 | + self.assertEqual(raised.exception.code, 1) |
| 170 | + self.assert_requests([ENDPOINT, BACKUP]) |
| 171 | + self.sleep.assert_not_called() |
| 172 | + self.assertIn("403", self.stderr.getvalue()) |
| 173 | + self.assertIn("SSLCertVerificationError", self.stderr.getvalue()) |
| 174 | + |
| 175 | + def test_malformed_response_fallback_preserves_batch_payload(self): |
| 176 | + malformed = io.BytesIO(json.dumps({ |
| 177 | + "objects": [{"oid": OID, "actions": {"upload": {"href": DOWNLOAD}}}], |
| 178 | + }).encode()) |
| 179 | + self.run_probe([malformed, response()]) |
| 180 | + self.assert_requests([ENDPOINT, BACKUP]) |
| 181 | + self.sleep.assert_not_called() |
| 182 | + self.assertEqual(self.stdout.getvalue(), f"local\n{OID} {DOWNLOAD}\n") |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + unittest.main() |
0 commit comments