Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion pylsp_jsonrpc/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,12 @@ def write(self, message):
f"{body}"
)

self._wfile.write(response.encode('utf-8'))
remaining = memoryview(response.encode('utf-8'))
while remaining:
written = self._wfile.write(remaining)
if written is None or written <= 0:
raise OSError('Output stream made no progress writing a message')
remaining = remaining[written:]
self._wfile.flush()
except Exception: # pylint: disable=broad-except
log.exception("Failed to write message to output file %s", message)
38 changes: 38 additions & 0 deletions test/test_writer_short_writes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Copyright 2021- Python Language Server Contributors.

from io import BytesIO
from unittest import mock

import pytest

from pylsp_jsonrpc.streams import JsonRpcStreamReader, JsonRpcStreamWriter


@pytest.mark.parametrize('chunk_size', [1, 7])
def test_writer_short_writes(chunk_size):
class ShortWriter(BytesIO):
def write(self, data):
return super().write(data[:chunk_size])

stream = ShortWriter()
stream.flush = mock.Mock()
writer = JsonRpcStreamWriter(stream, ensure_ascii=False)
messages = [{'id': 1, 'result': 'caf\u00e9'}, {'id': 2, 'result': '\u96ea'}]
for message in messages:
writer.write(message)
assert stream.flush.call_count == len(messages)
stream.seek(0)
received = []
JsonRpcStreamReader(stream).listen(received.append)
assert received == messages


@pytest.mark.parametrize('written', [0, None])
def test_writer_short_writes_without_progress(written, caplog):
stream = BytesIO()
stream.write = mock.Mock(return_value=written)
stream.flush = mock.Mock()
JsonRpcStreamWriter(stream).write({'id': 1})
stream.write.assert_called_once()
stream.flush.assert_not_called()
assert 'Output stream made no progress' in caplog.text