Skip to content

Conversation

@RaoulSchaffranek
Copy link
Member

This PR extends the JsonRpcServer with support for streaming.
JsonRpcMethods can now return a stream of bytes (Iterator[bytes]) instead of a JSON-serializable value.
The method must ensure that the produced stream is already JSON-encoded, as no extra validation is performed.
This allows us to transfer large responses without buffering the entire response in memory.

This is needed by the kontrol-node, when transferring large execution traces.

def encode(self) -> bytes:
return json.dumps(self.to_json()).encode('ascii')
def encode(self) -> Iterator[bytes]:
yield json.dumps(self.wrap_response()).encode('utf-8')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This yields the whole bytes value, if you want to yield each byte, you can do

data = json.dumps(self.wrap_response()).encode('utf-8')
yield from (bytes([b]) for b in data)

id: str | int | None

def to_json(self) -> dict[str, Any]:
def wrap_response(self) -> dict[str, Any]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR description states

This PR extends the JsonRpcServer with support for streaming.

but it introduces what look like breaking changes. Are there other clients to this library other than kontrol-node?

version_encoded = json.dumps(JsonRpcServer.JSONRPC_VERSION)
yield f'{{"jsonrpc": {version_encoded}, "id": {id_encoded}, "result": '.encode()
if isinstance(self.payload, Iterator):
yield from self.payload
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is self.payload a bytes now? If so, the type hint can be strengthened.

if isinstance(self.payload, Iterator):
yield from self.payload
else:
yield json.dumps(self.payload).encode('utf-8')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also yields the whole bytes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants