|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +from typing import Any, Union, Tuple, Dict, Optional, overload |
| 4 | +from contextlib import asynccontextmanager |
| 5 | +from .communication import PaperMuncherRequest |
| 6 | +from .default import DefaultEnvironment |
| 7 | +from .exceptions import PaperMuncherError |
| 8 | +from .utils import locate_executable |
| 9 | +from .options import PMOptions |
| 10 | +from .handlers import handle_get_request, handle_put_request |
| 11 | +from ._internal import SyncStreamWrapper |
| 12 | + |
| 13 | + |
| 14 | +_logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | +@overload |
| 17 | +def paper_muncher( |
| 18 | + doc : Optional[Any] = None, |
| 19 | + auto : bool = True, |
| 20 | + environment : Optional[Any] = None, |
| 21 | + as_stream : bool = True, |
| 22 | + **rendering_options : Dict[str, str], |
| 23 | +) -> SyncStreamWrapper: |
| 24 | + ... |
| 25 | +@overload |
| 26 | +def paper_muncher( |
| 27 | + doc : Optional[Any] = None, |
| 28 | + auto : bool = True, |
| 29 | + environment : Optional[Any] = None, |
| 30 | + as_stream : bool = False, |
| 31 | + **rendering_options : Dict[str, str], |
| 32 | +) -> bytes: |
| 33 | + ... |
| 34 | +@overload |
| 35 | +def paper_muncher( |
| 36 | + doc : Optional[Any] = None, |
| 37 | + auto : bool = False, |
| 38 | + environment : Optional[Any] = None, |
| 39 | + as_stream : bool = True or False, |
| 40 | + **rendering_options : Dict[str, str], |
| 41 | +) -> Tuple[asyncio.subprocess.PIPE, asyncio.subprocess.PIPE, asyncio.subprocess.PIPE]: |
| 42 | + ... |
| 43 | + |
| 44 | + |
| 45 | +@asynccontextmanager |
| 46 | +async def paper_muncher( |
| 47 | + doc : Optional[Any] = None, |
| 48 | + environment : Optional[Any] = None, |
| 49 | + auto : bool = True, |
| 50 | + as_stream : bool = True, |
| 51 | + **rendering_options : Dict[str, str], |
| 52 | +) -> Union[ |
| 53 | + SyncStreamWrapper, |
| 54 | + bytes, |
| 55 | + Tuple[asyncio.subprocess.PIPE, asyncio.subprocess.PIPE, asyncio.subprocess.PIPE], |
| 56 | +]: |
| 57 | + """ |
| 58 | + Asynchronous context manager for rendering documents using Paper Muncher. |
| 59 | + This function handles the rendering process and provides an interface |
| 60 | + for interacting with the rendering options. |
| 61 | + Args: |
| 62 | + doc (Any): The document to be rendered. |
| 63 | + auto (bool): Flag to indicate automatic rendering. |
| 64 | + environment (Optional[Any]): An optional environment object for |
| 65 | + handling URLs and assets. |
| 66 | + as_stream (bool): Flag to indicate if the output should be a stream. |
| 67 | + **rendering_options (dict[str, str]): Additional rendering options. |
| 68 | + Yields: |
| 69 | + Union[ |
| 70 | + SyncStreamWrapper, |
| 71 | + bytes, |
| 72 | + Tuple[asyncio.subprocess.PIPE, asyncio.subprocess.PIPE, asyncio.subprocess.PIPE] |
| 73 | + ]: - the set of pipes to interact with the process if auto is False |
| 74 | + If the document should be rendered in pipe: |
| 75 | + - the rendered document as bytes if auto is True and as_stream is False |
| 76 | + - a stream wrapper if auto is True and as_stream is True |
| 77 | + If at url or file path: |
| 78 | + - The path/url of the file if auto is True and as_stream is False |
| 79 | + - a stream wrapper if auto is True and as_stream is True |
| 80 | + """ |
| 81 | + |
| 82 | + pm_options = PMOptions(**rendering_options, auto=auto) |
| 83 | + pm_process = await asyncio.subprocess.create_subprocess_exec( |
| 84 | + locate_executable(), |
| 85 | + *pm_options.args, |
| 86 | + stdin=asyncio.subprocess.PIPE, |
| 87 | + stdout=asyncio.subprocess.PIPE, |
| 88 | + stderr=asyncio.subprocess.PIPE, |
| 89 | + ) |
| 90 | + |
| 91 | + try: |
| 92 | + stdin, stdout, stderr = pm_process.stdin, pm_process.stdout, pm_process.stderr |
| 93 | + if not auto: |
| 94 | + yield stdin, stdout, stderr |
| 95 | + else: |
| 96 | + if pm_options.is_piped and environment is None: |
| 97 | + if doc is None: |
| 98 | + raise ValueError("Document cannot be None when auto is True") |
| 99 | + if environment is None: |
| 100 | + _logger.warning("No environment provided, assets will not be loaded") |
| 101 | + environment = DefaultEnvironment(from_doc=doc) |
| 102 | + while True: |
| 103 | + request = PaperMuncherRequest() |
| 104 | + await request.read_header(stdout) |
| 105 | + if request is None: |
| 106 | + break |
| 107 | + if request.method == "GET": |
| 108 | + await handle_get_request(request, stdin, environment) |
| 109 | + elif request.method == "PUT": |
| 110 | + await handle_put_request(stdin) |
| 111 | + if as_stream: |
| 112 | + yield SyncStreamWrapper(stdout) |
| 113 | + else: |
| 114 | + yield await stdout.read() |
| 115 | + break |
| 116 | + else: |
| 117 | + _logger.error("Unsupported method: %s", request.method) |
| 118 | + break |
| 119 | + except asyncio.CancelledError: |
| 120 | + _logger.warning("Paper Muncher process cancelled") |
| 121 | + raise |
| 122 | + except Exception as e: |
| 123 | + raise PaperMuncherError(f"Error in Paper Muncher: {e}") from e |
| 124 | + finally: |
| 125 | + pm_process.terminate() |
| 126 | + await pm_process.wait() |
| 127 | + if pm_process.returncode: |
| 128 | + _logger.error("Paper Muncher exited with code %s", pm_process.returncode) |
0 commit comments