Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/utils/json_stream.py

raw
1 # This code is part of the Ansible collection community.docker, but is an independent component.
2 # This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/)
3 #
4 # Copyright (c) 2016-2022 Docker, Inc.
5 #
6 # It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection)
7 # SPDX-License-Identifier: Apache-2.0
8
9 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
10 # Do not use this from other collections or standalone plugins/modules!
11
12 from __future__ import annotations
13
14 import json
15 import json.decoder
16 import typing as t
17
18 from ..errors import StreamParseError
19
20 if t.TYPE_CHECKING:
21 import re
22 from collections.abc import Callable
23
24 _T = t.TypeVar("_T")
25
26
27 json_decoder = json.JSONDecoder()
28
29
30 def stream_as_text(stream: t.Generator[bytes | str]) -> t.Generator[str]:
31 """
32 Given a stream of bytes or text, if any of the items in the stream
33 are bytes convert them to text.
34 This function can be removed once we return text streams
35 instead of byte streams.
36 """
37 for data in stream:
38 if not isinstance(data, str):
39 data = data.decode("utf-8", "replace")
40 yield data
41
42
43 def json_splitter(buffer: str) -> tuple[t.Any, str] | None:
44 """Attempt to parse a json object from a buffer. If there is at least one
45 object, return it and the rest of the buffer, otherwise return None.
46 """
47 buffer = buffer.strip()
48 try:
49 obj, index = json_decoder.raw_decode(buffer)
50 ws: re.Pattern = json.decoder.WHITESPACE # type: ignore[attr-defined]
51 m = ws.match(buffer, index)
52 rest = buffer[m.end() :] if m else buffer[index:]
53 return obj, rest
54 except ValueError:
55 return None
56
57
58 def json_stream(stream: t.Generator[str | bytes]) -> t.Generator[t.Any]:
59 """Given a stream of text, return a stream of json objects.
60 This handles streams which are inconsistently buffered (some entries may
61 be newline delimited, and others are not).
62 """
63 return split_buffer(stream, json_splitter, json_decoder.decode)
64
65
66 def line_splitter(buffer: str, separator: str = "\n") -> tuple[str, str] | None:
67 index = buffer.find(str(separator))
68 if index == -1:
69 return None
70 return buffer[: index + 1], buffer[index + 1 :]
71
72
73 def split_buffer(
74 stream: t.Generator[str | bytes],
75 splitter: Callable[[str], tuple[_T, str] | None],
76 decoder: Callable[[str], _T],
77 ) -> t.Generator[_T | str]:
78 """Given a generator which yields strings and a splitter function,
79 joins all input, splits on the separator and yields each chunk.
80 Unlike string.split(), each chunk includes the trailing
81 separator, except for the last one if none was found on the end
82 of the input.
83 """
84 buffered = ""
85
86 for data in stream_as_text(stream):
87 buffered += data
88 while True:
89 buffer_split = splitter(buffered)
90 if buffer_split is None:
91 break
92
93 item, buffered = buffer_split
94 yield item
95
96 if buffered:
97 try:
98 yield decoder(buffered)
99 except Exception as e:
100 raise StreamParseError(e) from e