@@ -214,9 +214,8 @@ async def iterate_items(
214214 def _serialize_chunk (cls , items : Sequence [Mapping [str , JsonSerializable ]], offset : int ) -> tuple [str , int ]:
215215 """Serialize items starting at `offset` into one JSON array staying within the payload size limit.
216216
217- The array holds as many consecutive items as fit below `_EFFECTIVE_LIMIT_SIZE`, always at least one.
218- The result is compact JSON - it goes on the wire, so indentation and separator padding would be
219- pure overhead. This is CPU-bound and blocking; call it via `asyncio.to_thread`.
217+ The array holds as many consecutive items as fit within `_EFFECTIVE_LIMIT_SIZE`, always at least one. Output
218+ is compact JSON - it goes straight on the wire. This is CPU-bound and blocking; call it via `asyncio.to_thread`.
220219
221220 Args:
222221 items: The items to serialize.
@@ -228,26 +227,27 @@ def _serialize_chunk(cls, items: Sequence[Mapping[str, JsonSerializable]], offse
228227 Raises:
229228 ValueError: If an item is not JSON serializable or on its own exceeds the size limit.
230229 """
230+ limit = cls ._EFFECTIVE_LIMIT_SIZE .bytes
231231 payloads : list [str ] = []
232- chunk_size = ByteSize ( 2 ) # Add 2 bytes for [] wrapper.
232+ chunk_size = 2 # Add 2 bytes for [] wrapper.
233233
234234 for index in range (offset , len (items )):
235235 try :
236236 payload = json .dumps (items [index ], ensure_ascii = False , separators = (',' , ':' ), default = str )
237237 except Exception as exc :
238238 raise ValueError (f'Data item at index { index } is not serializable to JSON.' ) from exc
239239
240- payload_size = ByteSize ( len (payload .encode ('utf-8' ) ))
241- if payload_size > cls . _EFFECTIVE_LIMIT_SIZE :
240+ payload_size = len (payload .encode ('utf-8' ))
241+ if payload_size > limit :
242242 raise ValueError (
243243 f'Data item at index { index } is too large '
244- f'(size: { payload_size } , limit: { cls ._EFFECTIVE_LIMIT_SIZE } )'
244+ f'(size: { ByteSize ( payload_size ) } , limit: { cls ._EFFECTIVE_LIMIT_SIZE } )'
245245 )
246246
247- if payloads and chunk_size + payload_size > cls . _EFFECTIVE_LIMIT_SIZE :
247+ if payloads and chunk_size + payload_size > limit :
248248 return f'[{ "," .join (payloads )} ]' , index
249249
250250 payloads .append (payload )
251- chunk_size += payload_size + ByteSize ( 1 ) # Add 1 byte for ',' separator.
251+ chunk_size += payload_size + 1 # Add 1 byte for ',' separator.
252252
253253 return f'[{ "," .join (payloads )} ]' , len (items )
0 commit comments