[
  {
    "path": ".editorconfig",
    "content": "# EditorConfig is awesome: https://EditorConfig.org\n\n# top-most EditorConfig file\nroot = true\n\n[*]\nend_of_line = crlf\ninsert_final_newline = true\ncharset = utf-8\n\n[*.py]\nindent_style = space\nindent_size = 4\n\n[*.{yml,yaml}]\nindent_style = space\nindent_size = 2\n"
  },
  {
    "path": ".gitattributes",
    "content": "* text=auto\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ncustom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n  - \"https://donate.aber.sh/\"\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches:\n      - master\n    tags:\n      - \"*\"\n    paths:\n      - \"**.py\"\n      - \"!rpcpy/__version__.py\"\n  pull_request:\n    branches:\n      - master\n    paths:\n      - \"**.py\"\n      - \"!rpcpy/__version__.py\"\n\njobs:\n  Tests:\n    name: \"Python ${{ matrix.python-version }} ${{ matrix.os }}\"\n    runs-on: \"${{ matrix.os }}\"\n    strategy:\n      matrix:\n        python-version: [3.7, 3.8, 3.9, \"3.10\"]\n        os: [windows-latest, ubuntu-latest, macos-latest]\n    env:\n      OS: ${{ matrix.os }}\n      PYTHON: ${{ matrix.python-version }}\n    steps:\n      - uses: actions/checkout@v2\n      - name: Set up Python ${{ matrix.python-version }}\n        uses: actions/setup-python@v2\n        with:\n          python-version: ${{ matrix.python-version }}\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip poetry\n          poetry config virtualenvs.create false --local\n          poetry install -E full\n      - name: Static type and format checking\n        run: |\n          python script/check.py\n      - name: Generate coverage report\n        run: |\n          pytest --cov=./ --cov-report=xml\n      - name: Upload coverage to Codecov\n        uses: codecov/codecov-action@v1\n        with:\n          files: ./coverage.xml\n          directory: ./coverage/reports/\n          flags: unittests\n          env_vars: OS,PYTHON\n          fail_ci_if_error: true\n          path_to_write_report: ./coverage/codecov_report.txt\n          verbose: true\n      - name: Uninstall pydantic\n        run: |\n          pip uninstall -y pydantic\n      - name: Generate coverage report\n        run: |\n          pytest --cov=./ --cov-report=xml\n      - name: Upload coverage to Codecov\n        uses: codecov/codecov-action@v1\n        with:\n          files: ./coverage.xml\n          directory: ./coverage/reports/\n          flags: unittests\n          env_vars: OS,PYTHON\n          fail_ci_if_error: true\n          path_to_write_report: ./coverage/codecov_report.txt\n          verbose: true\n\n  Publish:\n    needs: Tests\n    if: startsWith(github.ref, 'refs/tags/')\n\n    runs-on: \"${{ matrix.os }}\"\n    environment: release\n    permissions:\n      id-token: write\n    strategy:\n      matrix:\n        python-version: [3.7]\n        os: [ubuntu-latest]\n\n    steps:\n      - uses: actions/checkout@v2\n\n      - name: Set up Python ${{ matrix.python-version }}\n        uses: actions/setup-python@v1\n        with:\n          python-version: ${{ matrix.python-version }}\n\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip poetry\n\n      - name: Build\n        run: |\n          poetry build\n\n      - name: Publish package distributions to PyPI\n        uses: pypa/gh-action-pypi-publish@release/v1\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*,cover\n.hypothesis/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# IPython Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# dotenv\n.env\n\n# virtualenv\nvenv/\nENV/\n.venv/\n\n# Spyder project settings\n.spyderproject\n\n# Rope project settings\n.ropeproject\n*.npy\n*.pkl\n\n# mypy\n.mypy_cache/\n\n# VSCode\n.vscode/\n\n# PyCharm\n.idea/\n\n# mkdocs\nsite/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2022 abersheeran\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# rpc.py\n\n[![Codecov](https://img.shields.io/codecov/c/github/abersheeran/rpc.py?style=flat-square)](https://codecov.io/gh/abersheeran/rpc.py)\n\nAn fast and powerful RPC framework based on ASGI/WSGI. Based on WSGI/ASGI, you can deploy the rpc.py server to any server and use http2 to get better performance. And based on httpx's support for multiple http protocols, the client can also use http/1.0, http/1.1 or http2.\n\nYou can freely use ordinary functions and asynchronous functions for one-time response. You can also use generator functions or asynchronous generator functions to stream responses.\n\n## Install\n\nInstall from PyPi:\n\n```bash\npip install rpc.py\n\n# need use client\npip install rpc.py[client]\n\n# need use pydantic type hint or OpenAPI docs\npip install rpc.py[type]\n\n# need use msgpack to serializer\npip install rpc.py[msgpack]\n\n# need use CBOR to serializer\npip install rpc.py[cbor]\n\n# or install all dependencies\npip install rpc.py[full]\n```\n\nInstall from github:\n\n```bash\npip install git+https://github.com/abersheeran/rpc.py@setup.py\n```\n\n## Usage\n\n### Server side:\n\n<details markdown=\"1\">\n<summary>Use <code>ASGI</code> mode to register <code>async def</code>...</summary>\n\n```python\nfrom typing import AsyncGenerator\nfrom typing_extensions import TypedDict\n\nimport uvicorn\nfrom rpcpy import RPC\n\napp = RPC(mode=\"ASGI\")\n\n\n@app.register\nasync def none() -> None:\n    return\n\n\n@app.register\nasync def sayhi(name: str) -> str:\n    return f\"hi {name}\"\n\n\n@app.register\nasync def yield_data(max_num: int) -> AsyncGenerator[int, None]:\n    for i in range(max_num):\n        yield i\n\n\nD = TypedDict(\"D\", {\"key\": str, \"other-key\": str})\n\n\n@app.register\nasync def query_dict(value: str) -> D:\n    return {\"key\": value, \"other-key\": value}\n\n\nif __name__ == \"__main__\":\n    uvicorn.run(app, interface=\"asgi3\", port=65432)\n```\n</details>\n\nOR\n\n<details markdown=\"1\">\n<summary>Use <code>WSGI</code> mode to register <code>def</code>...</summary>\n\n```python\nfrom typing import Generator\nfrom typing_extensions import TypedDict\n\nimport uvicorn\nfrom rpcpy import RPC\n\napp = RPC()\n\n\n@app.register\ndef none() -> None:\n    return\n\n\n@app.register\ndef sayhi(name: str) -> str:\n    return f\"hi {name}\"\n\n\n@app.register\ndef yield_data(max_num: int) -> Generator[int, None, None]:\n    for i in range(max_num):\n        yield i\n\n\nD = TypedDict(\"D\", {\"key\": str, \"other-key\": str})\n\n\n@app.register\ndef query_dict(value: str) -> D:\n    return {\"key\": value, \"other-key\": value}\n\n\nif __name__ == \"__main__\":\n    uvicorn.run(app, interface=\"wsgi\", port=65432)\n```\n</details>\n\n### Client side:\n\nNotice: Regardless of whether the server uses the WSGI mode or the ASGI mode, the client can freely use the asynchronous or synchronous mode.\n\n<details markdown=\"1\">\n<summary>Use <code>httpx.Client()</code> mode to register <code>def</code>...</summary>\n\n```python\nfrom typing import Generator\nfrom typing_extensions import TypedDict\n\nimport httpx\nfrom rpcpy.client import Client\n\napp = Client(httpx.Client(), base_url=\"http://127.0.0.1:65432/\")\n\n\n@app.remote_call\ndef none() -> None:\n    ...\n\n\n@app.remote_call\ndef sayhi(name: str) -> str:\n    ...\n\n\n@app.remote_call\ndef yield_data(max_num: int) -> Generator[int, None, None]:\n    yield\n\n\nD = TypedDict(\"D\", {\"key\": str, \"other-key\": str})\n\n\n@app.remote_call\ndef query_dict(value: str) -> D:\n    ...\n```\n</details>\n\nOR\n\n<details markdown=\"1\">\n<summary>Use <code>httpx.AsyncClient()</code> mode to register <code>async def</code>...</summary>\n\n```python\nfrom typing import AsyncGenerator\nfrom typing_extensions import TypedDict\n\nimport httpx\nfrom rpcpy.client import Client\n\napp = Client(httpx.AsyncClient(), base_url=\"http://127.0.0.1:65432/\")\n\n\n@app.remote_call\nasync def none() -> None:\n    ...\n\n\n@app.remote_call\nasync def sayhi(name: str) -> str:\n    ...\n\n\n@app.remote_call\nasync def yield_data(max_num: int) -> AsyncGenerator[int, None]:\n    yield\n\n\nD = TypedDict(\"D\", {\"key\": str, \"other-key\": str})\n\n\n@app.remote_call\nasync def query_dict(value: str) -> D:\n    ...\n```\n</details>\n\n### Server as client\n\nYou can also write two copies of code in one place. Just make sure that `server.register` is executed before `client.remote_call`.\n\n```python\nimport httpx\nfrom rpcpy import RPC\nfrom rpcpy.client import Client\n\nserver = RPC()\nclient = Client(httpx.Client(), base_url=\"http://127.0.0.1:65432/\")\n\n\n@client.remote_call\n@server.register\ndef sayhi(name: str) -> str:\n    return f\"hi {name}\"\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n\n    uvicorn.run(app, interface=\"wsgi\", port=65432)\n```\n\n### Sub-route\n\nIf you need to deploy the rpc.py server under `example.com/sub-route/*`, you need to set `RPC(prefix=\"/sub-route/\")` and modify the `Client(base_path=https://example.com/sub-route/)`.\n\n### Serialization\n\nCurrently supports three serializers, JSON, Msgpack and CBOR. JSON is used by default. You can override the default `JSONSerializer` with parameters.\n\n```python\nfrom rpcpy.serializers import MsgpackSerializer, CBORSerializer\n\nRPC(\n    ...,\n    response_serializer=MsgpackSerializer(),\n)\n# Or\nClient(\n    ...,\n    request_serializer=CBORSerializer(),\n)\n```\n\n## Type hint and OpenAPI Doc\n\nThanks to the great work of [pydantic](https://pydantic-docs.helpmanual.io/), which makes rpc.py allow you to use type annotation to annotate the types of function parameters and response values, and perform type verification and JSON serialization . At the same time, it is allowed to generate openapi documents for human reading.\n\n### OpenAPI Documents\n\nIf you want to open the OpenAPI document, you need to initialize `RPC` like this `RPC(openapi={\"title\": \"TITLE\", \"description\": \"DESCRIPTION\", \"version\": \"v1\"})`.\n\nThen, visit the `\"{prefix}openapi-docs\"` of RPC and you will be able to see the automatically generated OpenAPI documentation. (If you do not set the `prefix`, the `prefix` is `\"/\"`)\n\n## Limitations\n\nCurrently, file upload is not supported, but you can do this by passing a `bytes` object.\n"
  },
  {
    "path": "examples/async_client.py",
    "content": "from typing import AsyncGenerator\n\nimport httpx\nfrom typing_extensions import TypedDict\n\nfrom rpcpy.client import Client\n\napp = Client(httpx.AsyncClient(), base_url=\"http://127.0.0.1:65432/\")\n\n\n@app.remote_call\nasync def none() -> None:\n    ...\n\n\n@app.remote_call\nasync def sayhi(name: str) -> str:\n    ...\n\n\n@app.remote_call\nasync def yield_data(max_num: int) -> AsyncGenerator[int, None]:\n    yield\n\n\nD = TypedDict(\"D\", {\"key\": str, \"other-key\": str})\n\n\n@app.remote_call\nasync def query_dict(value: str) -> D:\n    ...\n"
  },
  {
    "path": "examples/async_server.py",
    "content": "from typing import AsyncGenerator\n\nimport uvicorn\nfrom typing_extensions import TypedDict\n\nfrom rpcpy import RPC\n\napp = RPC(mode=\"ASGI\")\n\n\n@app.register\nasync def none() -> None:\n    return\n\n\n@app.register\nasync def sayhi(name: str) -> str:\n    return f\"hi {name}\"\n\n\n@app.register\nasync def yield_data(max_num: int) -> AsyncGenerator[int, None]:\n    for i in range(max_num):\n        yield i\n\n\nD = TypedDict(\"D\", {\"key\": str, \"other-key\": str})\n\n\n@app.register\nasync def query_dict(value: str) -> D:\n    return {\"key\": value, \"other-key\": value}\n\n\nif __name__ == \"__main__\":\n    uvicorn.run(app, interface=\"asgi3\", port=65432)\n"
  },
  {
    "path": "examples/sync_client.py",
    "content": "from typing import Generator\n\nimport httpx\nfrom typing_extensions import TypedDict\n\nfrom rpcpy.client import Client\n\napp = Client(httpx.Client(), base_url=\"http://127.0.0.1:65432/\")\n\n\n@app.remote_call\ndef none() -> None:\n    ...\n\n\n@app.remote_call\ndef sayhi(name: str) -> str:\n    ...\n\n\n@app.remote_call\ndef yield_data(max_num: int) -> Generator[int, None, None]:\n    yield\n\n\nD = TypedDict(\"D\", {\"key\": str, \"other-key\": str})\n\n\n@app.remote_call\ndef query_dict(value: str) -> D:\n    ...\n"
  },
  {
    "path": "examples/sync_server.py",
    "content": "from typing import Generator\n\nimport uvicorn\nfrom typing_extensions import TypedDict\n\nfrom rpcpy import RPC\n\napp = RPC()\n\n\n@app.register\ndef none() -> None:\n    return\n\n\n@app.register\ndef sayhi(name: str) -> str:\n    return f\"hi {name}\"\n\n\n@app.register\ndef yield_data(max_num: int) -> Generator[int, None, None]:\n    for i in range(max_num):\n        yield i\n\n\nD = TypedDict(\"D\", {\"key\": str, \"other-key\": str})\n\n\n@app.register\ndef query_dict(value: str) -> D:\n    return {\"key\": value, \"other-key\": value}\n\n\nif __name__ == \"__main__\":\n    uvicorn.run(app, interface=\"wsgi\", port=65432)\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.poetry]\nauthors = [\"abersheeran <me@abersheeran.com>\"]\ndescription = \"An fast and powerful RPC framework based on ASGI/WSGI.\"\nlicense = \"Apache-2.0\"\nname = \"rpc.py\"\nreadme = \"README.md\"\nversion = \"0.6.0\"\n\nhomepage = \"https://github.com/abersheeran/rpc.py\"\nrepository = \"https://github.com/abersheeran/rpc.py\"\n\nclassifiers = [\n  \"Programming Language :: Python :: 3\",\n  \"Typing :: Typed\",\n  \"Programming Language :: Python :: Implementation :: CPython\",\n  \"Programming Language :: Python :: Implementation :: PyPy\",\n  \"Topic :: Internet :: WWW/HTTP\",\n  \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n]\n\npackages = [\n  {include = \"rpcpy\"},\n]\n\n[tool.poetry.dependencies]\npython = \"^3.7\"\n\nbaize = \"*\"\ncbor2 = {version = \"^5.2.0\", optional = true}\nhttpx = {version = \">=0.22,<0.24\", optional = true}# for client and test\nmsgpack = {version = \"^1.0.0\", optional = true}\npydantic = {version = \"^1.9\", optional = true}# for openapi docs\ntyping-extensions = {version = \"*\", python = \"<3.8\"}\n\n[tool.poetry.extras]\ncbor = [\"cbor2\"]\nclient = [\"httpx\"]\nfull = [\"httpx\", \"pydantic\", \"msgpack\", \"cbor2\"]\nmsgpack = [\"msgpack\"]\ntype = [\"pydantic\"]\n\n[tool.poetry.dev-dependencies]\nblack = {version = \"*\", allow-prereleases = true}\nflake8 = \"*\"\nisort = \"*\"\nmypy = \"*\"\npytest = \"*\"\npytest-asyncio = \"*\"\npytest-cov = \"*\"\n\n[tool.black]\nline-length = 91\n\n[tool.isort]\nprofile = \"black\"\n\n[tool.pytest.ini_options]\nasyncio_mode = \"auto\"\n\n[tool.coverage.run]\nomit = [\"*/.venv/*\", \"*/tests/*\"]\n\n[tool.coverage.report]\nexclude_lines = [\n  \"pragma: no cover\",\n  \"raise NotImplementedError\",\n  \"raise RuntimeError\",\n  \"if False:\",\n  \"assert False\",\n  \"if typing.TYPE_CHECKING:\",\n  \"if TYPE_CHECKING:\",\n  \"@typing.overload\",\n]\nshow_missing = true\nskip_covered = true\n\n[build-system]\nbuild-backend = \"poetry.masonry.api\"\nrequires = [\"poetry>=0.12\"]\n"
  },
  {
    "path": "rpcpy/__init__.py",
    "content": "from .application import RPC\n\n__all__ = [\"RPC\"]\n"
  },
  {
    "path": "rpcpy/__version__.py",
    "content": "VERSION = (0, 6, 0)\n\n__version__ = \".\".join(map(str, VERSION))\n"
  },
  {
    "path": "rpcpy/application.py",
    "content": "from __future__ import annotations\n\nimport copy\nimport inspect\nimport json\nimport sys\nimport typing\nfrom base64 import b64encode\nfrom collections.abc import AsyncGenerator, Generator\n\nif sys.version_info[:2] < (3, 8):\n    from typing_extensions import Literal, TypedDict\nelse:\n    from typing import Literal, TypedDict\n\nfrom baize.asgi import PlainTextResponse as AsgiResponse\nfrom baize.asgi import Request as AsgiRequest\nfrom baize.asgi import SendEventResponse as AsgiEventResponse\nfrom baize.typing import (\n    ASGIApp,\n    Environ,\n    Receive,\n    Scope,\n    Send,\n    ServerSentEvent,\n    StartResponse,\n    WSGIApp,\n)\nfrom baize.wsgi import PlainTextResponse as WsgiResponse\nfrom baize.wsgi import Request as WsgiRequest\nfrom baize.wsgi import SendEventResponse as WsgiEventResponse\n\nfrom rpcpy.exceptions import CallbackError, SerializerNotFound\nfrom rpcpy.openapi import TEMPLATE as OPENAPI_TEMPLATE\nfrom rpcpy.openapi import (\n    ValidationError,\n    create_model,\n    is_typed_dict_type,\n    parse_typed_dict,\n    set_type_model,\n)\nfrom rpcpy.serializers import (\n    SERIALIZER_NAMES,\n    SERIALIZER_TYPES,\n    BaseSerializer,\n    JSONSerializer,\n    get_serializer,\n)\n\n__all__ = [\"RPC\", \"WsgiRPC\", \"AsgiRPC\"]\n\nCallable = typing.TypeVar(\"Callable\", bound=typing.Callable)\n\n\nclass RPCMeta(type):\n    def __call__(cls, *args: typing.Any, **kwargs: typing.Any) -> typing.Any:\n        mode = kwargs.get(\"mode\", \"WSGI\")\n        assert mode in (\"WSGI\", \"ASGI\"), \"mode must be in ('WSGI', 'ASGI')\"\n\n        if cls.__name__ == \"RPC\":\n            if mode == \"WSGI\":\n                return WsgiRPC(*args, **kwargs)\n\n            if mode == \"ASGI\":\n                return AsgiRPC(*args, **kwargs)\n\n        return super().__call__(*args, **kwargs)\n\n\nOpenAPI = TypedDict(\"OpenAPI\", {\"title\": str, \"description\": str, \"version\": str})\n\n\nclass RPC(metaclass=RPCMeta):\n    def __init__(\n        self,\n        *,\n        mode: Literal[\"WSGI\", \"ASGI\"] = \"WSGI\",\n        prefix: str = \"/\",\n        response_serializer: BaseSerializer = JSONSerializer(),\n        openapi: typing.Optional[OpenAPI] = None,\n    ) -> None:\n        assert prefix.startswith(\"/\") and prefix.endswith(\"/\")\n        self.callbacks: typing.Dict[str, typing.Callable] = {}\n        self.prefix = prefix\n        self.response_serializer = response_serializer\n        self.openapi = openapi\n\n    def register(self, func: Callable) -> Callable:\n        self.callbacks[func.__name__] = func\n        set_type_model(func)\n        return func\n\n    def get_openapi_docs(self) -> dict:\n        openapi: typing.Dict[str, typing.Any] = {\n            \"openapi\": \"3.0.0\",\n            \"info\": copy.deepcopy(self.openapi) or {},\n            \"paths\": {},\n        }\n        openapi[\"definitions\"] = definitions = {}\n\n        for name, callback in self.callbacks.items():\n            _ = {}\n            # summary and description\n            doc = callback.__doc__\n            if isinstance(doc, str):\n                _.update(\n                    zip(\n                        (\"summary\", \"description\"),\n                        map(lambda i: i.strip(), doc.strip().split(\"\\n\\n\", 1)),\n                    )\n                )\n            _[\"parameters\"] = [\n                {\n                    \"name\": \"content-type\",\n                    \"in\": \"header\",\n                    \"description\": \"At least one of serializer and content-type must be used\"\n                    \" so that the server can know which serializer is used to parse the data.\",\n                    \"required\": True,\n                    \"schema\": {\n                        \"type\": \"string\",\n                        \"enum\": [serializer_type for serializer_type in SERIALIZER_TYPES],\n                    },\n                },\n                {\n                    \"name\": \"serializer\",\n                    \"in\": \"header\",\n                    \"description\": \"At least one of serializer and content-type must be used\"\n                    \" so that the server can know which serializer is used to parse the data.\",\n                    \"required\": True,\n                    \"schema\": {\n                        \"type\": \"string\",\n                        \"enum\": [serializer_name for serializer_name in SERIALIZER_NAMES],\n                    },\n                },\n            ]\n            # request body\n            body_model = getattr(callback, \"__body_model__\", None)\n            if body_model:\n                _schema = copy.deepcopy(body_model.schema())\n                definitions.update(_schema.pop(\"definitions\", {}))\n                del _schema[\"title\"]\n                _[\"requestBody\"] = {\n                    \"required\": True,\n                    \"content\": {\n                        serializer_type: {\"schema\": _schema}\n                        for serializer_type in SERIALIZER_TYPES\n                    },\n                }\n            # response & only 200\n            sig = inspect.signature(callback)\n            if sig.return_annotation != sig.empty:\n                content_type = self.response_serializer.content_type\n                return_annotation = sig.return_annotation\n                if getattr(sig.return_annotation, \"__origin__\", None) in (\n                    Generator,\n                    AsyncGenerator,\n                ):\n                    content_type = \"text/event-stream\"\n                    return_annotation = return_annotation.__args__[0]\n                if is_typed_dict_type(return_annotation):\n                    resp_model = parse_typed_dict(return_annotation)\n                elif return_annotation is None:\n                    resp_model = create_model(callback.__name__ + \"-return\")\n                else:\n                    resp_model = create_model(\n                        callback.__name__ + \"-return\",\n                        __root__=(return_annotation, ...),\n                    )\n                _schema = copy.deepcopy(resp_model.schema())\n                definitions.update(_schema.pop(\"definitions\", {}))\n                del _schema[\"title\"]\n                _[\"responses\"] = {\n                    200: {\n                        \"content\": {content_type: {\"schema\": _schema}},\n                        \"headers\": {\n                            \"serializer\": {\n                                \"schema\": {\n                                    \"type\": \"string\",\n                                    \"enum\": [self.response_serializer.name],\n                                },\n                                \"description\": \"Serializer Name\",\n                            }\n                        },\n                    }\n                }\n            if _:\n                openapi[\"paths\"][f\"{self.prefix}{name}\"] = {\"post\": _}\n        return openapi\n\n    @typing.overload\n    def return_response_class(self, request: WsgiRequest) -> typing.Type[WsgiResponse]:\n        pass\n\n    @typing.overload\n    def return_response_class(self, request: AsgiRequest) -> typing.Type[AsgiResponse]:\n        pass\n\n    def return_response_class(self, request):\n        return AsgiResponse if isinstance(request, AsgiRequest) else WsgiResponse\n\n    @typing.overload\n    def respond_openapi(self, request: WsgiRequest) -> WsgiResponse | None:\n        pass\n\n    @typing.overload\n    def respond_openapi(self, request: AsgiRequest) -> AsgiResponse | None:\n        pass\n\n    def respond_openapi(self, request):\n        response_class = self.return_response_class(request)\n\n        if self.openapi is not None and request.method == \"GET\":\n            if request.url.path[len(self.prefix) :] == \"openapi-docs\":\n                return response_class(OPENAPI_TEMPLATE, media_type=\"text/html\")\n            elif request.url.path[len(self.prefix) :] == \"get-openapi-docs\":\n                return response_class(\n                    json.dumps(self.get_openapi_docs(), ensure_ascii=False),\n                    media_type=\"application/json\",\n                )\n\n        return None\n\n    def preprocess(\n        self, request: WsgiRequest | AsgiRequest\n    ) -> typing.Tuple[BaseSerializer, typing.Callable]:\n        \"\"\"\n        Preprocess request\n        \"\"\"\n        # check request method\n        if request.method != \"POST\":\n            raise CallbackError(content=\"\", status_code=405)\n\n        # check serializer\n        try:\n            serializer = get_serializer(request.headers)\n        except SerializerNotFound as exception:\n            raise CallbackError(content=str(exception), status_code=415)\n\n        # check callback\n        callback = self.callbacks.get(request.url.path[len(self.prefix) :], None)\n        if callback is None:\n            raise CallbackError(content=\"\", status_code=404)\n\n        return serializer, callback\n\n    def preprocess_body(\n        self, serializer: BaseSerializer, callback: typing.Callable, body: bytes\n    ) -> typing.Dict[str, typing.Any]:\n        \"\"\"\n        Preprocess request body\n        \"\"\"\n        if not body:\n            data = {}\n        else:\n            data = serializer.decode(body)\n\n        if hasattr(callback, \"__body_model__\"):\n            try:\n                model = getattr(callback, \"__body_model__\")(**data)\n            except ValidationError as exception:\n                raise CallbackError(\n                    status_code=422,\n                    headers={\"content-type\": \"application/json\"},\n                    content=exception.json(),\n                )\n            data = model.dict()\n\n        return data\n\n    def format_exception(self, exception: Exception) -> bytes:\n        return self.response_serializer.encode(\n            f\"{exception.__class__.__qualname__}: {exception}\"\n        )\n\n\nclass WsgiRPC(RPC):\n    def register(self, func: Callable) -> Callable:\n        if inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func):\n            raise TypeError(\"WSGI mode can only register synchronization functions.\")\n        return super().register(func)\n\n    def create_generator(\n        self, generator: typing.Generator\n    ) -> typing.Generator[ServerSentEvent, None, None]:\n        try:\n            for data in generator:\n                yield {\n                    \"event\": \"yield\",\n                    \"data\": b64encode(self.response_serializer.encode(data)).decode(\n                        \"ascii\"\n                    ),\n                }\n        except Exception as exception:\n            yield {\n                \"event\": \"exception\",\n                \"data\": b64encode(self.format_exception(exception)).decode(\"ascii\"),\n            }\n\n    def on_call(\n        self,\n        callback: typing.Callable[..., typing.Any],\n        data: typing.Dict[str, typing.Any],\n    ) -> WsgiResponse | WsgiEventResponse:\n        response: WsgiResponse | WsgiEventResponse\n        try:\n            result = callback(**data)\n        except Exception as exception:\n            message = self.format_exception(exception)\n            response = WsgiResponse(\n                message,\n                headers={\n                    \"content-type\": self.response_serializer.content_type,\n                    \"callback-status\": \"exception\",\n                },\n            )\n        else:\n            if inspect.isgenerator(result):\n                response = WsgiEventResponse(\n                    self.create_generator(result), headers={\"serializer-base\": \"base64\"}\n                )\n            else:\n                response = WsgiResponse(\n                    self.response_serializer.encode(result),\n                    headers={\"content-type\": self.response_serializer.content_type},\n                )\n\n        return response\n\n    def __call__(\n        self, environ: Environ, start_response: StartResponse\n    ) -> typing.Iterable[bytes]:\n        request = WsgiRequest(environ)\n        response: WSGIApp | None = self.respond_openapi(request)\n        if response is None:\n            try:\n                serializer, callback = self.preprocess(request)\n                data = self.preprocess_body(serializer, callback, request.body)\n            except CallbackError as exception:\n                response = WsgiResponse(\n                    content=exception.content or b\"\",\n                    status_code=exception.status_code,\n                    headers=exception.headers,\n                )\n            else:\n                response = self.on_call(callback, data)\n                response.headers[\"serializer\"] = self.response_serializer.name\n        return response(environ, start_response)\n\n\nclass AsgiRPC(RPC):\n    def register(self, func: Callable) -> Callable:\n        if not (inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)):\n            raise TypeError(\"ASGI mode can only register asynchronous functions.\")\n        return super().register(func)\n\n    async def create_generator(\n        self, generator: typing.AsyncGenerator\n    ) -> typing.AsyncGenerator[ServerSentEvent, None]:\n        try:\n            async for data in generator:\n                yield {\n                    \"event\": \"yield\",\n                    \"data\": b64encode(self.response_serializer.encode(data)).decode(\n                        \"ascii\"\n                    ),\n                }\n        except Exception as exception:\n            yield {\n                \"event\": \"exception\",\n                \"data\": b64encode(self.format_exception(exception)).decode(\"ascii\"),\n            }\n\n    async def on_call(\n        self,\n        callback: typing.Callable[..., typing.Awaitable[typing.Any]],\n        data: typing.Dict[str, typing.Any],\n    ) -> AsgiResponse | AsgiEventResponse:\n        response: AsgiResponse | AsgiEventResponse\n        try:\n            if inspect.isasyncgenfunction(callback):\n                result = callback(**data)\n            else:\n                result = await callback(**data)\n        except Exception as exception:\n            message = self.format_exception(exception)\n            response = AsgiResponse(\n                message,\n                headers={\n                    \"content-type\": self.response_serializer.content_type,\n                    \"callback-status\": \"exception\",\n                },\n            )\n        else:\n            if inspect.isasyncgen(result):\n                response = AsgiEventResponse(\n                    self.create_generator(result), headers={\"serializer-base\": \"base64\"}\n                )\n            else:\n                response = AsgiResponse(\n                    self.response_serializer.encode(result),\n                    headers={\"content-type\": self.response_serializer.content_type},\n                )\n\n        return response\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        request = AsgiRequest(scope, receive, send)\n        response: ASGIApp | None = self.respond_openapi(request)\n        if response is None:\n            try:\n                serializer, callback = self.preprocess(request)\n                data = self.preprocess_body(serializer, callback, await request.body)\n            except CallbackError as exception:\n                response = AsgiResponse(\n                    content=exception.content or b\"\",\n                    status_code=exception.status_code,\n                    headers=exception.headers,\n                )\n            else:\n                response = await self.on_call(callback, data)\n                response.headers[\"serializer\"] = self.response_serializer.name\n        return await response(scope, receive, send)\n"
  },
  {
    "path": "rpcpy/client.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport inspect\nimport typing\nfrom base64 import b64decode\n\nimport httpx\n\nfrom rpcpy.exceptions import RemoteCallError\nfrom rpcpy.openapi import validate_arguments\nfrom rpcpy.serializers import BaseSerializer, JSONSerializer, get_serializer\n\nif typing.TYPE_CHECKING:\n    from baize.typing import ServerSentEvent\n\n__all__ = [\"Client\"]\n\nCallable = typing.TypeVar(\"Callable\", bound=typing.Callable)\n\n\nclass ClientMeta(type):\n    def __call__(cls, *args: typing.Any, **kwargs: typing.Any) -> typing.Any:\n        if cls.__name__ == \"Client\":\n            if isinstance(args[0], httpx.Client):\n                return SyncClient(*args, **kwargs)\n\n            if isinstance(args[0], httpx.AsyncClient):\n                return AsyncClient(*args, **kwargs)\n\n            raise TypeError(\n                \"The parameter `client` must be an httpx.Client or httpx.AsyncClient object.\"\n            )\n\n        return super().__call__(*args, **kwargs)\n\n\nclass Client(metaclass=ClientMeta):\n    def __init__(\n        self,\n        client: typing.Union[httpx.Client, httpx.AsyncClient],\n        *,\n        base_url: str,\n        request_serializer: BaseSerializer = JSONSerializer(),\n    ) -> None:\n        assert base_url.endswith(\"/\"), \"base_url must be end with '/'\"\n        self.base_url = base_url\n        self.client = client\n        self.request_serializer = request_serializer\n\n    def remote_call(self, func: Callable) -> Callable:\n        return func\n\n    def _get_url(self, func: typing.Callable) -> str:\n        return self.base_url + func.__name__\n\n    def _get_content(\n        self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any\n    ) -> bytes:\n        sig = inspect.signature(func)\n        bound_values = sig.bind(*args, **kwargs)\n        parameters = dict(**bound_values.arguments)\n        if parameters:\n            return self.request_serializer.encode(parameters)\n        else:\n            return b\"\"\n\n\nclass AsyncClient(Client):\n    if typing.TYPE_CHECKING:\n        client: httpx.AsyncClient\n\n    def remote_call(self, func: Callable) -> Callable:\n        if not (inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)):\n            raise TypeError(\n                \"Asynchronous Client can only register asynchronous functions.\"\n            )\n\n        func = super().remote_call(func)\n        url = self._get_url(func)\n\n        if not inspect.isasyncgenfunction(func):\n\n            @validate_arguments\n            @functools.wraps(func)\n            async def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:\n                post_content = self._get_content(func, *args, **kwargs)\n                resp = await self.client.post(\n                    url,\n                    content=post_content,\n                    headers={\n                        \"content-type\": self.request_serializer.content_type,\n                        \"serializer\": self.request_serializer.name,\n                    },\n                )\n                resp.raise_for_status()\n                content = get_serializer(resp.headers).decode(resp.content)\n                if resp.headers.get(\"callback-status\") == \"exception\":\n                    raise RemoteCallError(content)\n                else:\n                    return content\n\n        else:\n\n            @validate_arguments\n            @functools.wraps(func)\n            async def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:\n                post_content = self._get_content(func, *args, **kwargs)\n                async with self.client.stream(\n                    \"POST\",\n                    url,\n                    content=post_content,\n                    headers={\n                        \"content-type\": self.request_serializer.content_type,\n                        \"serializer\": self.request_serializer.name,\n                    },\n                ) as resp:\n                    resp.raise_for_status()\n                    sse_parser = ServerSentEventsParser()\n                    serializer = get_serializer(resp.headers)\n                    async for line in resp.aiter_lines():\n                        event = sse_parser.feed(line)\n                        if not event:\n                            continue\n\n                        if event[\"event\"] == \"yield\":\n                            yield serializer.decode(\n                                b64decode(event[\"data\"].encode(\"ascii\"))\n                            )\n                        elif event[\"event\"] == \"exception\":\n                            raise RemoteCallError(\n                                serializer.decode(b64decode(event[\"data\"].encode(\"ascii\")))\n                            )\n                        else:\n                            raise RuntimeError(f\"Unknown event type: {event['event']}\")\n\n        return typing.cast(Callable, wrapper)\n\n\nclass SyncClient(Client):\n    if typing.TYPE_CHECKING:\n        client: httpx.Client\n\n    def remote_call(self, func: Callable) -> Callable:\n        if inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func):\n            raise TypeError(\n                \"Synchronization Client can only register synchronization functions.\"\n            )\n\n        func = super().remote_call(func)\n        url = self._get_url(func)\n\n        if not inspect.isgeneratorfunction(func):\n\n            @validate_arguments\n            @functools.wraps(func)\n            def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:\n                post_content = self._get_content(func, *args, **kwargs)\n                resp = self.client.post(\n                    url,\n                    content=post_content,\n                    headers={\n                        \"content-type\": self.request_serializer.content_type,\n                        \"serializer\": self.request_serializer.name,\n                    },\n                )\n                resp.raise_for_status()\n                content = get_serializer(resp.headers).decode(resp.content)\n                if resp.headers.get(\"callback-status\") == \"exception\":\n                    raise RemoteCallError(content)\n                else:\n                    return content\n\n        else:\n\n            @validate_arguments\n            @functools.wraps(func)\n            def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:\n                post_content = self._get_content(func, *args, **kwargs)\n                with self.client.stream(\n                    \"POST\",\n                    url,\n                    content=post_content,\n                    headers={\n                        \"content-type\": self.request_serializer.content_type,\n                        \"serializer\": self.request_serializer.name,\n                    },\n                ) as resp:\n                    resp.raise_for_status()\n                    sse_parser = ServerSentEventsParser()\n                    serializer = get_serializer(resp.headers)\n                    for line in resp.iter_lines():\n                        event = sse_parser.feed(line)\n                        if not event:\n                            continue\n\n                        if event[\"event\"] == \"yield\":\n                            yield serializer.decode(\n                                b64decode(event[\"data\"].encode(\"ascii\"))\n                            )\n                        elif event[\"event\"] == \"exception\":\n                            raise RemoteCallError(\n                                serializer.decode(b64decode(event[\"data\"].encode(\"ascii\")))\n                            )\n                        else:\n                            raise RuntimeError(f\"Unknown event type: {event['event']}\")\n\n        return typing.cast(Callable, wrapper)\n\n\nclass ServerSentEventsParser:\n    def __init__(self) -> None:\n        self.message: ServerSentEvent = {}\n\n    def feed(self, line: str) -> ServerSentEvent | None:\n        if line == \"\\n\":  # event split line\n            event = self.message\n            self.message = {}\n            return event\n\n        if line[0] == \":\":  # ignore comment\n            return None\n\n        try:\n            key, value = map(str.strip, line.split(\":\", maxsplit=1))\n        except ValueError:\n            key = line.strip()\n            value = \"\"\n\n        if key not in (\"data\", \"event\", \"id\", \"retry\"):  # ignore undefined key\n            return None\n\n        if key == \"data\" and key in self.message:\n            self.message[\"data\"] = f'{self.message[\"data\"]}\\n{value}'\n        elif key == \"retry\":\n            try:\n                self.message[\"retry\"] = int(value)\n            except ValueError:\n                pass  # ignore non-integer retry value\n        else:\n            self.message[key] = value  # type: ignore[literal-required]\n\n        return None\n"
  },
  {
    "path": "rpcpy/exceptions.py",
    "content": "from __future__ import annotations\n\nfrom baize.exceptions import HTTPException\n\n\nclass SerializerNotFound(Exception):\n    \"\"\"\n    Serializer not found\n    \"\"\"\n\n\nclass CallbackError(HTTPException[str]):\n    \"\"\"\n    Callback error\n    \"\"\"\n\n\nclass RemoteCallError(Exception):\n    \"\"\"\n    Remote call error\n    \"\"\"\n"
  },
  {
    "path": "rpcpy/openapi.py",
    "content": "from __future__ import annotations\n\nimport functools\nimport inspect\nimport typing\nimport warnings\n\n__all__ = [\n    \"create_model\",\n    \"validate_arguments\",\n    \"set_type_model\",\n    \"is_typed_dict_type\",\n    \"parse_typed_dict\",\n    \"TEMPLATE\",\n]\n\nCallable = typing.TypeVar(\"Callable\", bound=typing.Callable)\n\ntry:\n    from pydantic import BaseModel, ValidationError, create_model\n    from pydantic import validate_arguments as pydantic_validate_arguments\n\n    # visit this issue\n    # https://github.com/samuelcolvin/pydantic/issues/1205\n    def validate_arguments(function: Callable) -> Callable:\n        function = pydantic_validate_arguments(function)\n\n        @functools.wraps(function)\n        def change_exception(*args, **kwargs):\n            try:\n                return function(*args, **kwargs)\n            except ValidationError as exception:\n                type_error = TypeError(\n                    \"Failed to pass pydantic's type verification, please output\"\n                    \" `.more_info` of this exception to view detailed information.\"\n                )\n                type_error.more_info = exception\n                raise type_error\n\n        return change_exception  # type: ignore\n\nexcept ImportError:\n\n    def create_model(*args, **kwargs):  # type: ignore\n        raise NotImplementedError(\"Need install `pydantic` from pypi.\")\n\n    def validate_arguments(function: Callable) -> Callable:\n        return function\n\n    class ValidationError(Exception):  # type: ignore\n        \"\"\"\n        Just for import\n        \"\"\"\n\n    if typing.TYPE_CHECKING:\n        from pydantic import BaseModel\n\n\ndef set_type_model(func: Callable) -> Callable:\n    \"\"\"\n    try generate request body model from type hint and default value\n    \"\"\"\n    sig = inspect.signature(func)\n    field_definitions: typing.Dict[str, typing.Any] = {}\n    for name, parameter in sig.parameters.items():\n        if parameter.annotation == parameter.empty:\n            # raise ValueError(\n            #     f\"You must specify the type for the parameter {func.__name__}:{name}.\"\n            # )\n            return func  # Maybe the type hint should be mandatory? I'm not sure.\n        if parameter.default == parameter.empty:\n            field_definitions[name] = (parameter.annotation, ...)\n        else:\n            field_definitions[name] = (parameter.annotation, parameter.default)\n    if field_definitions:\n        try:\n            body_model: typing.Type[BaseModel] = create_model(\n                func.__name__, **field_definitions\n            )\n            setattr(func, \"__body_model__\", body_model)\n        except NotImplementedError:\n            message = (\n                \"If you wanna using type hint \"\n                \"to create OpenAPI docs or convert type, \"\n                \"please install `pydantic` from pypi.\"\n            )\n            warnings.warn(message, ImportWarning)\n    return func\n\n\ndef is_typed_dict_type(type_) -> bool:\n    return (\n        isinstance(type_, type)\n        and issubclass(type_, dict)\n        and getattr(type_, \"__annotations__\", False)\n    )\n\n\ndef parse_typed_dict(typed_dict) -> typing.Type[BaseModel]:\n    \"\"\"\n    parse `TypedDict` to generate `pydantic.BaseModel`\n    \"\"\"\n    annotations = {}\n    for name, field in typed_dict.__annotations__.items():\n        if is_typed_dict_type(field):\n            annotations[name] = (parse_typed_dict(field), ...)\n        else:\n            default_value = getattr(typed_dict, name, ...)\n            annotations[name] = (field, default_value)\n\n    return create_model(typed_dict.__name__, **annotations)  # type: ignore\n\n\nTEMPLATE = \"\"\"<!DOCTYPE html>\n<html>\n\n<head>\n    <link type=\"text/css\" rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui.css\">\n    <title>OpenAPI Docs</title>\n</head>\n\n<body>\n    <div id=\"swagger-ui\"></div>\n    <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui-bundle.js\"></script>\n    <script>\n        const ui = SwaggerUIBundle({\n            url: './get-openapi-docs',\n            dom_id: '#swagger-ui',\n            presets: [\n                SwaggerUIBundle.presets.apis,\n                SwaggerUIBundle.SwaggerUIStandalonePreset\n            ],\n            layout: \"BaseLayout\",\n            deepLinking: true,\n            showExtensions: true,\n            showCommonExtensions: true\n        })\n\n    </script>\n</body>\n\n</html>\n\"\"\"\n"
  },
  {
    "path": "rpcpy/serializers.py",
    "content": "import json\nimport pickle\nimport typing\nfrom abc import ABCMeta, abstractmethod\n\ntry:\n    import msgpack\nexcept ImportError:  # pragma: no cover\n    msgpack = None  # type: ignore\n\ntry:\n    import cbor2 as cbor\nexcept ImportError:  # pragma: no cover\n    cbor = None  # type: ignore\n\nfrom rpcpy.exceptions import SerializerNotFound\n\n\nclass BaseSerializer(metaclass=ABCMeta):\n    \"\"\"\n    Base Serializer\n    \"\"\"\n\n    name: str\n    content_type: str\n\n    @abstractmethod\n    def encode(self, data: typing.Any) -> bytes:\n        raise NotImplementedError()\n\n    @abstractmethod\n    def decode(self, raw_data: bytes) -> typing.Any:\n        raise NotImplementedError()\n\n\nclass JSONSerializer(BaseSerializer):\n    name = \"json\"\n    content_type = \"application/json\"\n\n    def __init__(\n        self,\n        default_encode: typing.Callable = None,\n        default_decode: typing.Callable = None,\n    ) -> None:\n        self.default_encode = default_encode\n        self.default_decode = default_decode\n\n    def encode(self, data: typing.Any) -> bytes:\n        return json.dumps(\n            data,\n            ensure_ascii=False,\n            default=self.default_encode,\n        ).encode(\"utf8\")\n\n    def decode(self, data: bytes) -> typing.Any:\n        return json.loads(\n            data.decode(\"utf8\"),\n            object_hook=self.default_decode,\n        )\n\n\nclass PickleSerializer(BaseSerializer):\n    name = \"pickle\"\n    content_type = \"application/x-pickle\"\n\n    def encode(self, data: typing.Any) -> bytes:\n        return pickle.dumps(data)\n\n    def decode(self, data: bytes) -> typing.Any:\n        return pickle.loads(data)\n\n\nclass MsgpackSerializer(BaseSerializer):\n    \"\"\"\n    Msgpack: https://github.com/msgpack/msgpack-python\n    \"\"\"\n\n    name = \"msgpack\"\n    content_type = \"application/x-msgpack\"\n\n    def __init__(\n        self,\n        default_encode: typing.Callable = None,\n        default_decode: typing.Callable = None,\n    ) -> None:\n        self.default_encode = default_encode\n        self.default_decode = default_decode\n\n    def encode(self, data: typing.Any) -> bytes:\n        return msgpack.packb(data, default=self.default_encode)\n\n    def decode(self, data: bytes) -> typing.Any:\n        return msgpack.unpackb(data, object_hook=self.default_decode)\n\n\nclass CBORSerializer(BaseSerializer):\n    \"\"\"\n    CBOR: https://tools.ietf.org/html/rfc7049\n    \"\"\"\n\n    name = \"cbor\"\n    content_type = \"application/x-cbor\"\n\n    def encode(self, data: typing.Any) -> bytes:\n        return cbor.dumps(data)\n\n    def decode(self, data: bytes) -> typing.Any:\n        return cbor.loads(data)\n\n\n# Since the release of pickle to the external network may lead to\n# arbitrary code execution vulnerabilities, this serialization\n# method is not enabled by default. It is recommended to turn it on\n# when there is physical isolation from the outside.\n\nSERIALIZER_NAMES = {\n    JSONSerializer.name: JSONSerializer(),\n    # PickleSerializer.name: PickleSerializer(),\n    MsgpackSerializer.name: MsgpackSerializer(),\n    CBORSerializer.name: CBORSerializer(),\n}\n\nSERIALIZER_TYPES = {\n    JSONSerializer.content_type: JSONSerializer(),\n    # PickleSerializer.content_type: PickleSerializer(),\n    MsgpackSerializer.content_type: MsgpackSerializer(),\n    CBORSerializer.content_type: CBORSerializer(),\n}\n\n\ndef get_serializer(headers: typing.Mapping) -> BaseSerializer:\n    \"\"\"\n    parse header and try find serializer\n    \"\"\"\n    serializer_name = headers.get(\"serializer\", None)\n    if serializer_name:\n        if serializer_name not in SERIALIZER_NAMES:\n            raise SerializerNotFound(f\"Serializer `{serializer_name}` not found\")\n        return SERIALIZER_NAMES[serializer_name]\n\n    serializer_type = headers.get(\"content-type\", None)\n    if serializer_type:\n        if serializer_type not in SERIALIZER_TYPES:\n            raise SerializerNotFound(f\"Serializer for `{serializer_type}` not found\")\n        return SERIALIZER_TYPES[serializer_type]\n\n    raise SerializerNotFound(\n        \"You must set a value for header `serializer` or `content-type`\"\n    )\n"
  },
  {
    "path": "script/check.py",
    "content": "import subprocess\n\nsource_dirs = \"rpcpy tests\"\nsubprocess.check_call(f\"isort --check --diff {source_dirs}\", shell=True)\nsubprocess.check_call(f\"black --check --diff {source_dirs}\", shell=True)\nsubprocess.check_call(f\"flake8 --ignore W503,E203,E501,E731 {source_dirs}\", shell=True)\nsubprocess.check_call(f\"mypy --ignore-missing-imports {source_dirs}\", shell=True)\n"
  },
  {
    "path": "script/upload.py",
    "content": "import os\nimport subprocess\n\nhere = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\npackage_name = \"rpcpy\"\n\n\ndef get_version(package: str = package_name) -> str:\n    \"\"\"\n    Return version.\n    \"\"\"\n    _globals: dict = {}\n    with open(os.path.join(here, package, \"__version__.py\")) as f:\n        exec(f.read(), _globals)\n\n    return _globals[\"__version__\"]\n\n\nos.chdir(here)\nsubprocess.check_call(f\"poetry version {get_version()}\", shell=True)\nsubprocess.check_call(f\"git add {package_name}/__version__.py pyproject.toml\", shell=True)\nsubprocess.check_call(f'git commit -m \"v{get_version()}\"', shell=True)\nsubprocess.check_call(\"git push\", shell=True)\nsubprocess.check_call(\"git tag v{0}\".format(get_version()), shell=True)\nsubprocess.check_call(\"git push --tags\", shell=True)\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/test_application.py",
    "content": "import asyncio\nimport json\nimport sys\nimport time\nfrom typing import AsyncGenerator, Generator\n\nif sys.version_info[:2] < (3, 8):\n    from typing_extensions import TypedDict\nelse:\n    from typing import TypedDict\n\nimport httpx\nimport pytest\n\nfrom rpcpy.application import RPC, AsgiRPC, WsgiRPC\nfrom rpcpy.serializers import SERIALIZER_NAMES, SERIALIZER_TYPES\n\n\ndef test_wsgirpc():\n    rpc = RPC()\n    assert isinstance(rpc, WsgiRPC)\n\n    @rpc.register\n    def sayhi(name: str) -> str:\n        return f\"hi {name}\"\n\n    with pytest.raises(\n        TypeError, match=\"WSGI mode can only register synchronization functions.\"\n    ):\n\n        @rpc.register\n        async def async_sayhi(name: str) -> str:\n            return f\"hi {name}\"\n\n    @rpc.register\n    def sayhi_without_type_hint(name):\n        return f\"hi {name}\"\n\n    with httpx.Client(app=rpc, base_url=\"http://testServer/\") as client:\n        assert client.get(\"/openapi-docs\").status_code == 405\n        assert client.post(\"/sayhi\", data={\"name\": \"Aber\"}).status_code == 415\n        assert client.post(\"/sayhi\", json={\"name\": \"Aber\"}).status_code == 200\n        assert (\n            client.post(\"/sayhi_without_type_hint\", json={\"name\": \"Aber\"})\n        ).status_code == 200\n        assert (\n            client.post(\"/sayhi\", content=json.dumps({\"name\": \"Aber\"})).status_code == 415\n        )\n        assert (\n            client.post(\n                \"/sayhi\",\n                content=json.dumps({\"name\": \"Aber\"}).encode(\"utf8\"),\n                headers={\"serializer\": \"application/json\"},\n            ).status_code\n            == 415\n        )\n        assert (\n            client.post(\n                \"/sayhi\",\n                content=json.dumps({\"name\": \"Aber\"}).encode(\"utf8\"),\n                headers={\"content-type\": \"\", \"serializer\": \"json\"},\n            ).status_code\n            == 200\n        )\n        assert client.post(\"/non-exists\", json={\"name\": \"Aber\"}).status_code == 404\n\n\n@pytest.mark.asyncio\nasync def test_asgirpc():\n    rpc = RPC(mode=\"ASGI\")\n    assert isinstance(rpc, AsgiRPC)\n\n    @rpc.register\n    async def sayhi(name: str) -> str:\n        return f\"hi {name}\"\n\n    @rpc.register\n    async def sayhi_without_type_hint(name):\n        return f\"hi {name}\"\n\n    with pytest.raises(\n        TypeError, match=\"ASGI mode can only register asynchronous functions.\"\n    ):\n\n        @rpc.register\n        def sync_sayhi(name: str) -> str:\n            return f\"hi {name}\"\n\n    async with httpx.AsyncClient(app=rpc, base_url=\"http://testServer/\") as client:\n        assert (await client.get(\"/openapi-docs\")).status_code == 405\n        assert (await client.post(\"/sayhi\", data={\"name\": \"Aber\"})).status_code == 415\n        assert (await client.post(\"/sayhi\", json={\"name\": \"Aber\"})).status_code == 200\n        assert (\n            await client.post(\"/sayhi_without_type_hint\", json={\"name\": \"Aber\"})\n        ).status_code == 200\n        assert (\n            await client.post(\n                \"/sayhi\",\n                content=json.dumps({\"name\": \"Aber\"}).encode(\"utf8\"),\n                headers={\"serializer\": \"application/json\"},\n            )\n        ).status_code == 415\n        assert (\n            await client.post(\n                \"/sayhi\",\n                content=json.dumps({\"name\": \"Aber\"}).encode(\"utf8\"),\n                headers={\"content-type\": \"\", \"serializer\": \"json\"},\n            )\n        ).status_code == 200\n        assert (await client.post(\"/non-exists\", json={\"name\": \"Aber\"})).status_code == 404\n\n\n@pytest.mark.skipif(\"pydantic\" in sys.modules, reason=\"Installed pydantic\")\ndef test_wsgi_openapi_without_pydantic():\n    rpc = RPC(openapi={\"title\": \"Title\", \"description\": \"Description\", \"version\": \"v1\"})\n\n    @rpc.register\n    def sayhi(name: str) -> str:\n        \"\"\"\n        say hi with name\n        \"\"\"\n        return f\"hi {name}\"\n\n    with pytest.raises(NotImplementedError):\n        rpc.get_openapi_docs()\n\n\n@pytest.mark.skipif(\"pydantic\" in sys.modules, reason=\"Installed pydantic\")\n@pytest.mark.asyncio\nasync def test_asgi_openapi_without_pydantic():\n    rpc = RPC(\n        mode=\"ASGI\",\n        openapi={\"title\": \"Title\", \"description\": \"Description\", \"version\": \"v1\"},\n    )\n\n    @rpc.register\n    async def sayhi(name: str) -> str:\n        \"\"\"\n        say hi with name\n        \"\"\"\n        return f\"hi {name}\"\n\n    with pytest.raises(NotImplementedError):\n        rpc.get_openapi_docs()\n\n\n@pytest.mark.skipif(\"pydantic\" not in sys.modules, reason=\"Missing pydantic\")\ndef test_wsgi_openapi():\n    rpc = RPC(openapi={\"title\": \"Title\", \"description\": \"Description\", \"version\": \"v1\"})\n\n    @rpc.register\n    def none() -> None:\n        return None\n\n    @rpc.register\n    def sayhi(name: str) -> str:\n        \"\"\"\n        say hi with name\n        \"\"\"\n        return f\"hi {name}\"\n\n    class DNSRecord(TypedDict):\n        record: str\n        ttl: int\n\n    class DNS(TypedDict):\n        dns_type: str\n        host: str\n        result: DNSRecord\n\n    @rpc.register\n    def query_dns(dns_type: str, host: str) -> DNS:\n        return {\"dns_type\": dns_type, \"host\": host, \"result\": {\"record\": \"\", \"ttl\": 0}}\n\n    @rpc.register\n    def timestamp() -> Generator[int, None, None]:\n        while True:\n            yield int(time.time())\n            time.sleep(1)\n\n    assert rpc.get_openapi_docs() == OPENAPI_DOCS\n\n    with httpx.Client(app=rpc, base_url=\"http://testServer/\") as client:\n        assert client.get(\"/openapi-docs\").status_code == 200\n        assert client.get(\"/get-openapi-docs\").status_code == 200\n\n        assert (\n            client.post(\n                \"/sayhi\",\n                content=json.dumps({\"name0\": \"Aber\"}).encode(\"utf8\"),\n                headers={\"content-type\": \"\", \"serializer\": \"json\"},\n            )\n        ).status_code == 422\n\n\n@pytest.mark.skipif(\"pydantic\" not in sys.modules, reason=\"Missing pydantic\")\n@pytest.mark.asyncio\nasync def test_asgi_openapi():\n    rpc = RPC(\n        mode=\"ASGI\",\n        openapi={\"title\": \"Title\", \"description\": \"Description\", \"version\": \"v1\"},\n    )\n\n    @rpc.register\n    async def none() -> None:\n        return None\n\n    @rpc.register\n    async def sayhi(name: str) -> str:\n        \"\"\"\n        say hi with name\n        \"\"\"\n        return f\"hi {name}\"\n\n    DNSRecord = TypedDict(\"DNSRecord\", {\"record\": str, \"ttl\": int})\n    DNS = TypedDict(\"DNS\", {\"dns_type\": str, \"host\": str, \"result\": DNSRecord})\n\n    @rpc.register\n    async def query_dns(dns_type: str, host: str) -> DNS:\n        return {\"dns_type\": dns_type, \"host\": host, \"result\": {\"record\": \"\", \"ttl\": 0}}\n\n    @rpc.register\n    async def timestamp() -> AsyncGenerator[int, None]:\n        while True:\n            yield int(time.time())\n            await asyncio.sleep(1)\n\n    assert rpc.get_openapi_docs() == OPENAPI_DOCS\n\n    async with httpx.AsyncClient(app=rpc, base_url=\"http://testServer/\") as client:\n        assert (await client.get(\"/openapi-docs\")).status_code == 200\n        assert (await client.get(\"/get-openapi-docs\")).status_code == 200\n\n        assert (\n            await client.post(\n                \"/sayhi\",\n                content=json.dumps({\"name0\": \"Aber\"}).encode(\"utf8\"),\n                headers={\"content-type\": \"\", \"serializer\": \"json\"},\n            )\n        ).status_code == 422\n\n\nDEFAULT_PARAMETERS = [\n    {\n        \"name\": \"content-type\",\n        \"in\": \"header\",\n        \"description\": \"At least one of serializer and content-type must be used\"\n        \" so that the server can know which serializer is used to parse the data.\",\n        \"required\": True,\n        \"schema\": {\n            \"type\": \"string\",\n            \"enum\": [serializer_type for serializer_type in SERIALIZER_TYPES],\n        },\n    },\n    {\n        \"name\": \"serializer\",\n        \"in\": \"header\",\n        \"description\": \"At least one of serializer and content-type must be used\"\n        \" so that the server can know which serializer is used to parse the data.\",\n        \"required\": True,\n        \"schema\": {\n            \"type\": \"string\",\n            \"enum\": [serializer_name for serializer_name in SERIALIZER_NAMES],\n        },\n    },\n]\n\nOPENAPI_DOCS = {\n    \"openapi\": \"3.0.0\",\n    \"info\": {\"title\": \"Title\", \"description\": \"Description\", \"version\": \"v1\"},\n    \"paths\": {\n        \"/none\": {\n            \"post\": {\n                \"parameters\": DEFAULT_PARAMETERS,\n                \"responses\": {\n                    200: {\n                        \"content\": {\n                            \"application/json\": {\n                                \"schema\": {\"type\": \"object\", \"properties\": {}},\n                            }\n                        },\n                        \"headers\": {\n                            \"serializer\": {\n                                \"schema\": {\n                                    \"type\": \"string\",\n                                    \"enum\": [\"json\"],\n                                },\n                                \"description\": \"Serializer Name\",\n                            }\n                        },\n                    }\n                },\n            }\n        },\n        \"/sayhi\": {\n            \"post\": {\n                \"summary\": \"say hi with name\",\n                \"parameters\": DEFAULT_PARAMETERS,\n                \"requestBody\": {\n                    \"required\": True,\n                    \"content\": {\n                        serializer_type: {\n                            \"schema\": {\n                                \"type\": \"object\",\n                                \"properties\": {\n                                    \"name\": {\n                                        \"title\": \"Name\",\n                                        \"type\": \"string\",\n                                    }\n                                },\n                                \"required\": [\"name\"],\n                            }\n                        }\n                        for serializer_type in SERIALIZER_TYPES\n                    },\n                },\n                \"responses\": {\n                    200: {\n                        \"content\": {\"application/json\": {\"schema\": {\"type\": \"string\"}}},\n                        \"headers\": {\n                            \"serializer\": {\n                                \"schema\": {\n                                    \"type\": \"string\",\n                                    \"enum\": [\"json\"],\n                                },\n                                \"description\": \"Serializer Name\",\n                            }\n                        },\n                    }\n                },\n            }\n        },\n        \"/query_dns\": {\n            \"post\": {\n                \"parameters\": DEFAULT_PARAMETERS,\n                \"requestBody\": {\n                    \"required\": True,\n                    \"content\": {\n                        serializer_type: {\n                            \"schema\": {\n                                \"type\": \"object\",\n                                \"properties\": {\n                                    \"dns_type\": {\n                                        \"title\": \"Dns Type\",\n                                        \"type\": \"string\",\n                                    },\n                                    \"host\": {\n                                        \"title\": \"Host\",\n                                        \"type\": \"string\",\n                                    },\n                                },\n                                \"required\": [\"dns_type\", \"host\"],\n                            }\n                        }\n                        for serializer_type in SERIALIZER_TYPES\n                    },\n                },\n                \"responses\": {\n                    200: {\n                        \"content\": {\n                            \"application/json\": {\n                                \"schema\": {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"dns_type\": {\n                                            \"title\": \"Dns Type\",\n                                            \"type\": \"string\",\n                                        },\n                                        \"host\": {\n                                            \"title\": \"Host\",\n                                            \"type\": \"string\",\n                                        },\n                                        \"result\": {\"$ref\": \"#/definitions/DNSRecord\"},\n                                    },\n                                    \"required\": [\"dns_type\", \"host\", \"result\"],\n                                }\n                            }\n                        },\n                        \"headers\": {\n                            \"serializer\": {\n                                \"schema\": {\n                                    \"type\": \"string\",\n                                    \"enum\": [\"json\"],\n                                },\n                                \"description\": \"Serializer Name\",\n                            }\n                        },\n                    }\n                },\n            }\n        },\n        \"/timestamp\": {\n            \"post\": {\n                \"parameters\": DEFAULT_PARAMETERS,\n                \"responses\": {\n                    200: {\n                        \"content\": {\"text/event-stream\": {\"schema\": {\"type\": \"integer\"}}},\n                        \"headers\": {\n                            \"serializer\": {\n                                \"schema\": {\"type\": \"string\", \"enum\": [\"json\"]},\n                                \"description\": \"Serializer Name\",\n                            }\n                        },\n                    }\n                },\n            }\n        },\n    },\n    \"definitions\": {\n        \"DNSRecord\": {\n            \"title\": \"DNSRecord\",\n            \"type\": \"object\",\n            \"properties\": {\n                \"record\": {\"title\": \"Record\", \"type\": \"string\"},\n                \"ttl\": {\"title\": \"Ttl\", \"type\": \"integer\"},\n            },\n            \"required\": [\"record\", \"ttl\"],\n        }\n    },\n}\n"
  },
  {
    "path": "tests/test_client.py",
    "content": "import asyncio\nimport time\nfrom typing import AsyncGenerator, Generator\n\nimport httpx\nimport pytest\n\nfrom rpcpy import RPC\nfrom rpcpy.client import Client, ServerSentEventsParser\nfrom rpcpy.exceptions import RemoteCallError\n\n\n@pytest.fixture\ndef wsgi_app():\n    app = RPC()\n\n    @app.register\n    def none() -> None:\n        return\n\n    @app.register\n    def sayhi(name: str) -> str:\n        return f\"hi {name}\"\n\n    @app.register\n    def yield_data(max_num: int) -> Generator[int, None, None]:\n        for i in range(max_num):\n            time.sleep(1)\n            yield i\n\n    @app.register\n    def exception() -> str:\n        raise ValueError(\"Message\")\n\n    @app.register\n    def exception_in_g() -> Generator[str, None, None]:\n        yield \"Message\"\n        raise TypeError(\"Message\")\n\n    return app\n\n\n@pytest.fixture\ndef asgi_app():\n    app = RPC(mode=\"ASGI\")\n\n    @app.register\n    async def none() -> None:\n        return\n\n    @app.register\n    async def sayhi(name: str) -> str:\n        return f\"hi {name}\"\n\n    @app.register\n    async def yield_data(max_num: int) -> AsyncGenerator[int, None]:\n        for i in range(max_num):\n            await asyncio.sleep(1)\n            yield i\n\n    @app.register\n    async def exception() -> str:\n        raise ValueError(\"Message\")\n\n    @app.register\n    async def exception_in_g() -> AsyncGenerator[str, None]:\n        yield \"Message\"\n        raise TypeError(\"Message\")\n\n    return app\n\n\n@pytest.fixture\ndef sync_client(wsgi_app):\n    httpx_client = httpx.Client(app=wsgi_app)\n    try:\n        yield Client(httpx_client, base_url=\"http://testserver/\")\n    finally:\n        httpx_client.close()\n\n\n@pytest.fixture\ndef async_client(asgi_app):\n    httpx_client = httpx.AsyncClient(app=asgi_app)\n    try:\n        yield Client(httpx_client, base_url=\"http://testserver/\")\n    finally:\n        asyncio.get_event_loop().run_until_complete(httpx_client.aclose())\n\n\ndef test_sync_client(sync_client):\n    @sync_client.remote_call\n    def sayhi(name: str) -> str:\n        ...\n\n    assert sayhi(\"rpc.py\") == \"hi rpc.py\"\n\n    with pytest.raises(\n        TypeError,\n        match=\"Synchronization Client can only register synchronization functions.\",\n    ):\n\n        @sync_client.remote_call\n        async def sayhi(name: str) -> str:\n            ...\n\n    @sync_client.remote_call\n    def yield_data(max_num: int):\n        yield\n\n    index = 0\n    for i in yield_data(5):\n        assert index == i\n        index += 1\n\n    @sync_client.remote_call\n    def exception() -> str:\n        ...\n\n    with pytest.raises(RemoteCallError, match=\"ValueError: Message\"):\n        exception()\n\n    @sync_client.remote_call\n    def exception_in_g() -> Generator[str, None, None]:\n        yield  # type: ignore\n\n    with pytest.raises(RemoteCallError, match=\"TypeError: Message\"):\n        for msg in exception_in_g():\n            assert msg == \"Message\"\n\n\n@pytest.mark.asyncio\nasync def test_async_client(async_client):\n    @async_client.remote_call\n    async def sayhi(name: str) -> str:\n        ...\n\n    assert await sayhi(\"rpc.py\") == \"hi rpc.py\"\n\n    with pytest.raises(\n        TypeError,\n        match=\"Asynchronous Client can only register asynchronous functions.\",\n    ):\n\n        @async_client.remote_call\n        def sayhi(name: str) -> str:\n            ...\n\n    @async_client.remote_call\n    async def yield_data(max_num: int):\n        yield\n\n    index = 0\n    async for i in yield_data(5):\n        assert index == i\n        index += 1\n\n    @async_client.remote_call\n    async def exception() -> str:\n        ...\n\n    with pytest.raises(RemoteCallError, match=\"ValueError: Message\"):\n        await exception()\n\n    @async_client.remote_call\n    async def exception_in_g() -> AsyncGenerator[str, None]:\n        yield  # type: ignore\n\n    with pytest.raises(RemoteCallError, match=\"TypeError: Message\"):\n        async for msg in exception_in_g():\n            assert msg == \"Message\"\n\n\ndef test_none(sync_client):\n    @sync_client.remote_call\n    def none() -> None:\n        ...\n\n    assert none() is None\n\n    with pytest.raises(TypeError):\n        none(\"hi\")\n\n\n@pytest.mark.asyncio\nasync def test_async_none(async_client):\n    @async_client.remote_call\n    async def none() -> None:\n        ...\n\n    assert await none() is None\n\n    with pytest.raises(TypeError):\n        await none(\"hi\")\n\n\ndef test_invalid_client():\n    with pytest.raises(\n        TypeError,\n        match=\"The parameter `client` must be an httpx.Client or httpx.AsyncClient object.\",\n    ):\n        Client(0)\n\n\ndef test_sse_parser():\n    parser = ServerSentEventsParser()\n\n    parser.feed(\"data: hello\\n\")\n    assert parser.feed(\"\\n\") == {\"data\": \"hello\"}\n\n    parser.feed(\"data: hello\\n\")\n    parser.feed(\"data: world\\n\")\n    assert parser.feed(\"\\n\") == {\"data\": \"hello\\nworld\"}\n\n    parser.feed(\": ping\\n\")\n    assert parser.feed(\"\\n\") == {}\n\n    parser.feed(\"retry: 1\\n\")\n    assert parser.feed(\"\\n\") == {\"retry\": 1}\n\n    parser.feed(\"retry: p1\\n\")\n    assert parser.feed(\"\\n\") == {}\n\n    parser.feed(\"undefined\")\n    assert parser.feed(\"\\n\") == {}\n\n    parser.feed(\"event\")\n    assert parser.feed(\"\\n\") == {\"event\": \"\"}\n"
  },
  {
    "path": "tests/test_serializers.py",
    "content": "import pytest\n\nfrom rpcpy.serializers import (\n    CBORSerializer,\n    JSONSerializer,\n    MsgpackSerializer,\n    PickleSerializer,\n)\n\n\n@pytest.mark.parametrize(\n    \"serializer\",\n    [JSONSerializer(), PickleSerializer(), MsgpackSerializer(), CBORSerializer()],\n)\n@pytest.mark.parametrize(\n    \"data\",\n    [\"123\", \"中文\", 1, 0, 1239.123, [\"123\", 1, 123.98], {\"a\": 1}],\n)\ndef test_serializer(serializer, data):\n    _ = serializer.encode(data)\n    assert isinstance(_, bytes)\n    assert serializer.decode(_) == data\n"
  },
  {
    "path": "tests/test_version.py",
    "content": "from rpcpy.__version__ import VERSION, __version__\n\n\ndef test_version():\n    VERSION[0]\n    VERSION[1]\n    VERSION[2]\n\n    assert isinstance(__version__, str)\n"
  }
]