diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index decb206648ba..1289b62606d2 100644 --- a/sdk/core/azure-core/CHANGELOG.md +++ b/sdk/core/azure-core/CHANGELOG.md @@ -6,6 +6,7 @@ Azure-core is supported on Python 3.7 or later. For more details, please read ou ### Features Added +- Added Pyodide-compatible transport. - Added `CaseInsensitiveDict` implementation in `azure.core.utils` removing dependency on `requests` and `aiohttp` ### Breaking Changes diff --git a/sdk/core/azure-core/azure/core/pipeline/transport/pyodide.py b/sdk/core/azure-core/azure/core/pipeline/transport/pyodide.py new file mode 100644 index 000000000000..b721fe7e296e --- /dev/null +++ b/sdk/core/azure-core/azure/core/pipeline/transport/pyodide.py @@ -0,0 +1,160 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +from collections.abc import AsyncIterator +from io import BytesIO + +import js # pylint: disable=import-error +from pyodide import JsException # pylint: disable=import-error +from pyodide.http import pyfetch # pylint: disable=import-error + +from azure.core.exceptions import HttpResponseError +from azure.core.pipeline import Pipeline +from azure.core.utils import CaseInsensitiveDict + +from ...rest._http_response_impl_async import AsyncHttpResponseImpl +from . import HttpRequest +from ._requests_asyncio import AsyncioRequestsTransport + + +class PyodideTransportResponse(AsyncHttpResponseImpl): + """Async response object for the `PyodideTransport`.""" + + def __init__(self, **kwargs): + super(PyodideTransportResponse, self).__init__(**kwargs) + # clone to avoid reading from the same `FetchResponse` a second time in `load_body`. + self._js_stream = self.internal_response.clone().js_response.body + self._js_reader = None + + async def close(self) -> None: + """We don't actually have control over closing connections in the browser, so we just pretend + to close. + """ + self._is_closed = True + + async def load_body(self) -> None: + """Load the body of the response.""" + if self._content is None: + self._content = await self._internal_response.bytes() + + def body(self) -> bytes: + """The body is just the content.""" + return self.content + +class PyodideStreamDownloadGenerator(AsyncIterator): + """Simple stream download generator that returns the contents of + a request. + """ + + # pylint: disable=unused-argument + def __init__(self, pipeline: Pipeline, response: PyodideTransportResponse, *_, **kwargs): + self._block_size = response._block_size + self.response = response + # use this to efficiently store bytes. + if kwargs.pop("decompress", False): + self._js_reader = response._js_stream.pipeThrough(js.DecompressionStream.new("gzip")).getReader() + else: + self._js_reader = response._js_stream.getReader() + self._stream = BytesIO() + + self._closed = False + # We cannot control how many bytes we get from `response.reader`. `self.buffer_left` + # indicates how many unread bytes there are in `self.stream` + self.buffer_left = 0 + self.done = False + + async def __anext__(self) -> bytes: + """Get the next block of bytes.""" + if self._closed: + raise StopAsyncIteration() + + # remember the initial stream position + start_pos = self._stream.tell() + # move stream position to the end + self._stream.read() + # read from reader until there is no more data or we have `self._block_size` unread bytes. + while self.buffer_left < self._block_size: + read = await self._js_reader.read() + if read.done: + self._closed = True + break + self.buffer_left += self._stream.write(bytes(read.value)) + + # move the stream position back to where we started + self._stream.seek(start_pos) + self.buffer_left -= self._block_size + return self._stream.read(self._block_size) + +class PyodideTransport(AsyncioRequestsTransport): + """Implements a basic HTTP sender using the Pyodide Javascript Fetch API. + + WARNING: Pyodide is still an alpha technology. As such, this transport + is highly experimental and subject to breaking changes. This transport was + built around Pyodide version 0.20.0. + """ + + async def send(self, request: HttpRequest, **kwargs) -> PyodideTransportResponse: + """Send request object according to configuration. + + :param request: The request object to be sent. + :type request: ~azure.core.pipeline.transport.HttpRequest + :return: An HTTPResponse object. + :rtype: PyodideResponseTransport + """ + stream_response = kwargs.pop("stream_response", False) + endpoint = request.url + request_headers = dict(request.headers) + init = { + "method": request.method, + "headers": request_headers, + "body": request.data, + "files": request.files, + "verify": kwargs.pop("connection_verify", self.connection_config.verify), + "cert": kwargs.pop("connection_cert", self.connection_config.cert), + "allow_redirects": False, + **kwargs, + } + + try: + response = await pyfetch(endpoint, **init) + except JsException as error: + raise HttpResponseError(error, error=error) + + headers = CaseInsensitiveDict(response.js_response.headers) + transport_response = PyodideTransportResponse( + request=request, + internal_response=response, + block_size=self.connection_config.data_block_size, + status_code=response.status, + reason=response.status_text, + content_type=headers.get("content-type"), + headers=headers, + stream_download_generator=PyodideStreamDownloadGenerator, + ) + if not stream_response: + await transport_response.load_body() + + return transport_response diff --git a/sdk/core/azure-core/samples/test_pyodide_integration/async_testing.py b/sdk/core/azure-core/samples/test_pyodide_integration/async_testing.py new file mode 100644 index 000000000000..1e3eff2f9901 --- /dev/null +++ b/sdk/core/azure-core/samples/test_pyodide_integration/async_testing.py @@ -0,0 +1,27 @@ +import traceback +import sys + + +class AsyncTestSuite: + """Async test cases + Test must be asynchronous and follow the pattern `test*`. + """ + + async def run(self): + """Run the tests an print the results.""" + print("".join(("-" * 8, type(self).__name__, "-" * 8))) + for method_name in dir(self): + if not method_name.startswith("test"): + continue + print(method_name, end="... ") + try: + await getattr(self, method_name)() + except AssertionError: + print("FAIL") + traceback.print_exception(*sys.exc_info()) + except Exception: # pylint: disable=broad-except + print("ERROR") + traceback.print_exception(*sys.exc_info()) + else: + print("PASS") + print() diff --git a/sdk/core/azure-core/samples/test_pyodide_integration/browser_test.py b/sdk/core/azure-core/samples/test_pyodide_integration/browser_test.py new file mode 100644 index 000000000000..6f47d4698899 --- /dev/null +++ b/sdk/core/azure-core/samples/test_pyodide_integration/browser_test.py @@ -0,0 +1,95 @@ +from unittest.mock import _patch_dict, patch +from uuid import uuid4 + +from azure.ai.textanalytics.aio import TextAnalyticsClient +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline.transport import HttpRequest +from azure.core.pipeline.transport.pyodide import PyodideTransport +from azure.storage.blob.aio import BlobClient, BlobServiceClient + +# pylint: disable=import-error +from async_testing import AsyncTestSuite + + +class PyodideTransportIntegrationTestSuite(AsyncTestSuite): + """Integration tests for the Pyodide transport.""" + + text_analytics_client: TextAnalyticsClient + blob_service_client: BlobServiceClient + + def __init__( + self, + text_analytics_key: str, + text_analytics_endpoint: str, + blob_service_key: str, + blob_service_endpoint: str, + ): + self.text_analytics_client = TextAnalyticsClient( + endpoint=text_analytics_endpoint, + credential=AzureKeyCredential(text_analytics_key), + transport=PyodideTransport(), + ) + self.blob_service_client = BlobServiceClient( + blob_service_endpoint, blob_service_key, transport=PyodideTransport() + ) + + async def test_decompress_generator(self): + """Test that we can decompress streams properly.""" + url = "data/hello-world.gz" + request = HttpRequest(method="GET", url=url) + transport = PyodideTransport() + response = await transport.send(request, stream_response=True) + data = b"".join([x async for x in response.iter_bytes()]) + assert data == b"hello world\n" + + response = await transport.send(request, stream_response=True) + data = b"".join([x async for x in response.iter_raw()]) + assert data != b"hello world\n" + + + async def test_sentiment_analysis(self): + """Test that sentiment analysis works.""" + results = await self.text_analytics_client.analyze_sentiment( + ["good great amazing"] + ) + assert len(results) == 1 + result = results[0] + assert result.sentiment == "positive" + assert result.confidence_scores.positive > 0.98 + assert result.confidence_scores.neutral < 0.02 + assert result.confidence_scores.negative < 0.02 + + async def test_storage(self): + """Test that we can upload and download from blob storage""" + account_name = uuid4().hex + container_client = await self.blob_service_client.create_container(account_name) + blob_name = uuid4().hex + blob_data = b"012345" + try: + assert await container_client.exists() + blob_client = container_client.get_blob_client(blob_name) + await blob_client.upload_blob(blob_data) + + # make a new client so we don't have cached data + blob_client = BlobClient( + account_url=self.blob_service_client.url, + container_name=container_client.container_name, + blob_name=blob_name, + credential=container_client.credential, + max_single_get_size=1, + max_chunk_get_size=1, + transport=PyodideTransport(), + ) + assert await blob_client.exists() + downloader = await blob_client.download_blob() + i = 0 + async for chunk in downloader.chunks(): + assert chunk == bytes(str(i), "utf-8") + i += 1 + assert i == len(blob_data) + + except Exception: + await container_client.delete_container() + raise + else: + await container_client.delete_container() diff --git a/sdk/core/azure-core/samples/test_pyodide_integration/data/hello-world.gz b/sdk/core/azure-core/samples/test_pyodide_integration/data/hello-world.gz new file mode 100644 index 000000000000..34336ab5dd95 Binary files /dev/null and b/sdk/core/azure-core/samples/test_pyodide_integration/data/hello-world.gz differ diff --git a/sdk/core/azure-core/samples/test_pyodide_integration/example-env b/sdk/core/azure-core/samples/test_pyodide_integration/example-env new file mode 100644 index 000000000000..57f925f76d42 --- /dev/null +++ b/sdk/core/azure-core/samples/test_pyodide_integration/example-env @@ -0,0 +1,4 @@ +TEXT_ANALYTICS_KEY= +TEXT_ANALYTICS_ENDPOINT= +BLOB_SERVICE_KEY= +BLOB_SERVICE_ENDPOINT=https://.blob.core.windows.net diff --git a/sdk/core/azure-core/samples/test_pyodide_integration/index.html b/sdk/core/azure-core/samples/test_pyodide_integration/index.html new file mode 100644 index 000000000000..34a921b498d8 --- /dev/null +++ b/sdk/core/azure-core/samples/test_pyodide_integration/index.html @@ -0,0 +1,89 @@ + + + + + + + + + + diff --git a/sdk/core/azure-core/samples/test_pyodide_integration/readme.md b/sdk/core/azure-core/samples/test_pyodide_integration/readme.md new file mode 100644 index 000000000000..b77429080bd1 --- /dev/null +++ b/sdk/core/azure-core/samples/test_pyodide_integration/readme.md @@ -0,0 +1,37 @@ +# Integration Testing + +## Running + +Once you have set up your Azure Resources and your `.env` file, from this directory, run + +```python +python -h http.server 8000 +``` + +(You can use any other port). Then, from a Chromium-based browser such as Edge, go to [`http://localhost:8000/`](http://localhost:8000/) and the tests will be run in the browser. Dev tip: keep your browser's devtools open. + +## Adding tests + +Add tests in `browser_test.py`. I couldn't get `pytest` or `unittest` to cooperate with me, so I made my own little async testing framework (`async_test.py`). If you are creating new files to test or new packages, update the `TEST_FILES` and `PACKAGES` variables in `index.html`, import the test case, and run it. + +## Sensitive values + +To run the tests, you need a `.env` folder in this directory with your sensitive values. +see `example-env`. You can then access the values as environment variables using `os.getenv`. You will +need to have your `textanalytics` key and endpoint as well as your Blob Storage key and url. + +## Dependencies + +All all packages listed in `requirements.txt` will be available in the testing environment. + +## Azure Resources + +You need your own Text Analytics and Blob Storage accounts to run these tests. Blob storage requirest some additional configuration to work. To set up Blob Storage, navigate to your storage client homepage and go to the `Resource Sharing (CORS)` tab. Create a rule with the following values + +| Allowed origins | Allowed methods | Allowed headers | Exposed headers | Max age | +|-----------------|-----------------|-----------------|-----------------|---------| +| `*` | All | `*` | See below | `3600` | + +For exposed headers, put + +> Server,Content-Range,ETag,Last-Modified,Accept-Ranges,x-ms-* diff --git a/sdk/core/azure-core/samples/test_pyodide_integration/requirements.txt b/sdk/core/azure-core/samples/test_pyodide_integration/requirements.txt new file mode 100644 index 000000000000..3e0a7d91664b --- /dev/null +++ b/sdk/core/azure-core/samples/test_pyodide_integration/requirements.txt @@ -0,0 +1,6 @@ +python-dotenv +# todo: delete the following line +https://tsjinxuanstorage2.blob.core.windows.net/pyodide/azure_core-1.25.0-py3-none-any.whl +azure-ai-textanalytics +azure-storage-blob +azure-ai-formrecognizer diff --git a/sdk/core/azure-core/tests/test_pyodide_transport.py b/sdk/core/azure-core/tests/test_pyodide_transport.py new file mode 100644 index 000000000000..53f5c14defda --- /dev/null +++ b/sdk/core/azure-core/tests/test_pyodide_transport.py @@ -0,0 +1,194 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# -------------------------------------------------------------------------- +"""Tests that mock the browser layer.""" +import asyncio +import sys +from typing import NamedTuple +from unittest import mock + +import pytest +from azure.core.exceptions import HttpResponseError +from azure.core.pipeline._base_async import AsyncPipeline +from azure.core.pipeline.policies._retry_async import AsyncRetryPolicy +from azure.core.rest import HttpRequest + +PLACEHOLDER_ENDPOINT = "https://my-resource-group.cognitiveservices.azure.com/" + + +class TestPyodideTransportClass: + """Unittest for the Pyodide transport.""" + + @pytest.fixture() + def mock_pyodide_module(self): + """Create a mock for the Pyodide module.""" + mock_pyodide_module = mock.Mock() + mock_pyodide_module.http.pyfetch = mock.Mock() + mock_pyodide_module.JsException = type("JsException", (Exception,), {}) + return mock_pyodide_module + + @pytest.fixture() + def mock_js_module(self): + """Mock the `js` module""" + return mock.Mock() + + @pytest.fixture() + def transport(self, mock_pyodide_module, mock_js_module): + """Add the mock Pyodide module to `sys.modules` and import our transport.""" + # Use patch so we don't clutter up the `sys.modules` namespace. + patch_dict = ( + ("pyodide", mock_pyodide_module), + ("pyodide.http", mock_pyodide_module.http), + ("js", mock_js_module), + ) + with mock.patch.dict(sys.modules, patch_dict): + import azure.core.pipeline.transport.pyodide + + yield azure.core.pipeline.transport.pyodide + + @pytest.fixture() + def pipeline(self, transport): + """Create a pipeline to test.""" + return AsyncPipeline(transport.PyodideTransport(), [AsyncRetryPolicy()]) + + @pytest.fixture() + def mock_pyfetch(self, mock_pyodide_module): + """Utility fixture for less typing.""" + return mock_pyodide_module.http.pyfetch + + def create_mock_response( + self, body: bytes, headers: dict, status: int, status_text: str + ) -> mock.Mock: + """Create a mock response object that mimics `pyodide.http.FetchResponse`""" + mock_response = mock.Mock() + mock_response.body = body + mock_response.js_response.headers = headers + mock_response.status = status + mock_response.status_text = status_text + bytes_promise = asyncio.Future() + bytes_promise.set_result(body) + mock_response.bytes = mock.Mock() + mock_response.bytes.return_value = bytes_promise + + response_promise = asyncio.Future() + response_promise.set_result(mock_response) + return response_promise + + @pytest.mark.asyncio + async def test_successful_send(self, mock_pyfetch, mock_pyodide_module, pipeline): + """Test that a successful send returns the correct values.""" + # setup data + mock_pyfetch.reset_mock() + method = "POST" + headers = {"key": "value"} + data = b"data" + request = HttpRequest( + method=method, url=PLACEHOLDER_ENDPOINT, headers=headers, data=data + ) + response_body = b"0123" + response_headers = {"header": "value"} + response_status = 200 + response_text = "OK" + mock_response = self.create_mock_response( + body=response_body, + headers=response_headers, + status=response_status, + status_text=response_text, + ) + mock_pyodide_module.http.pyfetch.return_value = mock_response + response = (await pipeline.run(request=request)).http_response + # Check that the pipeline processed the data correctly. + assert response.body() == response_body + assert response.status_code == response_status + assert response.headers == response_headers + assert response.reason == response_text + + assert not response._is_closed + await response.close() + assert response._is_closed + + # Check that the call had the correct arguments. + mock_pyfetch.assert_called_once() + args = mock_pyfetch.call_args[0] + kwargs = mock_pyfetch.call_args[1] + assert len(args) == 1 + assert args[0] == PLACEHOLDER_ENDPOINT + assert kwargs["method"] == method + assert kwargs["body"] == data + assert not kwargs["allow_redirects"] + assert kwargs["headers"]["key"] == "value" + assert kwargs["headers"]["Content-Length"] == str(len(data)) + assert kwargs["verify"] + assert kwargs["cert"] is None + assert not kwargs["files"] + + @pytest.mark.asyncio + async def test_unsuccessful_send(self, mock_pyfetch, mock_pyodide_module, pipeline): + """Test that the pipeline is failing correctly.""" + mock_pyfetch.reset_mock() + mock_pyfetch.side_effect = mock_pyodide_module.JsException + retry_total = 3 + request = HttpRequest(method="GET", url=PLACEHOLDER_ENDPOINT) + with pytest.raises(HttpResponseError): + await pipeline.run(request) + # 3 retries plus the original request. + assert mock_pyfetch.call_count == retry_total + 1 + + @pytest.mark.asyncio + async def test_download_generator(self, transport): + """Test that the download generator is working correctly.""" + class ReaderReturn(NamedTuple): + value: bytes + done: bool + + response_mock = mock.Mock() + response_mock._block_size = 5 + response_mock._js_reader.read = mock.Mock() + read_promise = asyncio.Future() + read_promise.set_result(ReaderReturn(value=b"01", done=False)) + reader = mock.Mock() + reader.read.return_value = read_promise + response_mock._js_stream.getReader.return_value = reader + generator = transport.PyodideStreamDownloadGenerator(pipeline=None, response=response_mock) + + assert len(await generator.__anext__()) == response_mock._block_size + assert reader.read.call_count == 3 + assert len(await generator.__anext__()) == response_mock._block_size + # 5 because there is a leftover byte from the previous `__anext__` call. + assert reader.read.call_count == 5 + + read_promise = asyncio.Future() + read_promise.set_result(ReaderReturn(value=None, done=True)) + reader.read.return_value = read_promise + await generator.__anext__() + with pytest.raises(StopAsyncIteration): + await generator.__anext__() + + @pytest.mark.asyncio + async def test_download_generator_compress(self, transport, mock_js_module): + """Test that we are attempting to decompress data when passing the `decompress`.""" + transport.PyodideStreamDownloadGenerator(pipeline=None, response=mock.Mock(), decompress=True) + mock_js_module.DecompressionStream.new.assert_called_once_with("gzip") + \ No newline at end of file