## Rethrow CancellationException in StdioServerTransport, fix ReadBuffer
### Changes
1. StdioServerTransport
- Replace generic `Throwable` catches with specific
`CancellationException` and `Exception` for clarity and correctness.
**breaking change** `Throwable` is not handled any more!
- Refactor launching jobs to separate methods
- Introduce `READ_BUFFER_SIZE` constant to replace inline buffer size
literals.
- Add suppress annotations for clearer intent and constructor
documentation for better usability.
- Extend StdioServerTransportTest
2. ReadBuffer
Previously, readMessage() returned null after consuming an unparseable
line even when more complete lines existed in the buffer. This caused
valid messages following a bad line in the same chunk to be silently
dropped until the next chunk arrived (or forever, in tests).
Fix the loop so null means only "no complete line available", not
"encountered a parse failure". Blank/whitespace-only lines are now
silently skipped via isBlank() rather than forwarded to the deserializer
and logged as errors.
Refactor the method into three focused helpers:
- readMessage() — outer loop over lines
- readLine() — consume the next newline-delimited line from the buffer
- tryRecover() — attempt deserialization from the first '{' onward
3. Add utility method `runIntegrationTest` for integration testing
(`runBlocking` + `withTimeout`). Use it in StdioServerTransportTest
4. Store processing Job reference and `calcelAndJoin()` it on close.
Partially addressing #574
## Motivation and Context
See #575, #564, #242
## How Has This Been Tested?
Unit test added
## Breaking Changes
Semantic change: `Throwable` and CancellationException are not handled
any more!
## Types of changes
- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
## Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply. -->
- [x] I have read the [MCP
Documentation](https://modelcontextprotocol.io)
- [x] My code follows the repository's style guidelines
- [x] New and existing tests pass locally
- [ ] I have added appropriate error handling
- [ ] I have added or updated documentation as needed
## Additional context
<!-- Add any other context, implementation notes, or design decisions
-->
This commit is contained in:
parent
9eabb54cb5
commit
a38818018a
2 changed files with 411 additions and 72 deletions
|
|
@ -20,45 +20,70 @@ public class ReadBuffer {
|
|||
buffer.write(chunk)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and deserializes a JSON-RPC message from the input buffer.
|
||||
*
|
||||
* The method attempts to read lines from the buffer until a valid `JSONRPCMessage` is successfully
|
||||
* deserialized. Blank lines are ignored, and if a deserialization error occurs, the method attempts
|
||||
* to recover and process the message.
|
||||
*
|
||||
* Recovery involves attempting to parse from the first detected JSON object in the line when an
|
||||
* error is encountered during deserialization.
|
||||
*
|
||||
* @return A deserialized `JSONRPCMessage` if successfully processed; otherwise, `null` if the
|
||||
* input buffer is exhausted or no valid message is found.
|
||||
*/
|
||||
public fun readMessage(): JSONRPCMessage? {
|
||||
if (buffer.exhausted()) return null
|
||||
var lfIndex = buffer.indexOf('\n'.code.toByte())
|
||||
val line = when (lfIndex) {
|
||||
-1L -> return null
|
||||
while (true) {
|
||||
val line = readNextLine() ?: return null
|
||||
if (line.isBlank()) continue
|
||||
|
||||
0L -> {
|
||||
buffer.skip(1)
|
||||
return null
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
val message = try {
|
||||
deserializeMessage(line)
|
||||
} catch (e: Exception) {
|
||||
logger.error(e) { "Failed to deserialize message from line: $line\nAttempting to recover..." }
|
||||
tryRecover(line)
|
||||
}
|
||||
|
||||
else -> {
|
||||
var skipBytes = 1
|
||||
if (buffer[lfIndex - 1] == '\r'.code.toByte()) {
|
||||
lfIndex -= 1
|
||||
skipBytes += 1
|
||||
}
|
||||
val string = buffer.readString(lfIndex)
|
||||
buffer.skip(skipBytes.toLong())
|
||||
string
|
||||
}
|
||||
}
|
||||
try {
|
||||
return deserializeMessage(line)
|
||||
} catch (e: Exception) {
|
||||
logger.error(e) { "Failed to deserialize message from line: $line\nAttempting to recover..." }
|
||||
// if there is a non-JSON object prefix, try to parse from the first '{' onward.
|
||||
val braceIndex = line.indexOf('{')
|
||||
if (braceIndex != -1) {
|
||||
val trimmed = line.substring(braceIndex)
|
||||
try {
|
||||
return deserializeMessage(trimmed)
|
||||
} catch (ignored: Exception) {
|
||||
logger.error(ignored) { "Deserialization failed for line: $line\nSkipping..." }
|
||||
}
|
||||
if (message != null) {
|
||||
return message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
private fun readNextLine(): String? {
|
||||
val lfIndex = if (buffer.exhausted()) -1L else buffer.indexOf('\n'.code.toByte())
|
||||
if (lfIndex == -1L) return null
|
||||
|
||||
return if (lfIndex == 0L) {
|
||||
buffer.skip(1)
|
||||
""
|
||||
} else {
|
||||
var skipBytes = 1
|
||||
var messageLength = lfIndex
|
||||
if (buffer[lfIndex - 1] == '\r'.code.toByte()) {
|
||||
messageLength -= 1
|
||||
skipBytes += 1
|
||||
}
|
||||
val string = buffer.readString(messageLength)
|
||||
buffer.skip(skipBytes.toLong())
|
||||
string
|
||||
}
|
||||
}
|
||||
|
||||
private fun tryRecover(line: String): JSONRPCMessage? {
|
||||
// if there is a non-JSON object prefix, try to parse from the first '{' onward.
|
||||
val braceIndex = line.indexOf('{')
|
||||
if (braceIndex == -1) return null
|
||||
|
||||
val trimmed = line.substring(braceIndex)
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
return try {
|
||||
deserializeMessage(trimmed)
|
||||
} catch (ignored: Exception) {
|
||||
logger.error(ignored) { "Deserialization failed for line: $line\nSkipping..." }
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
public fun clear() {
|
||||
|
|
|
|||
|
|
@ -31,6 +31,8 @@ class ReadBufferTest {
|
|||
val messageBytes = json.encodeToString(testMessage).encodeToByteArray()
|
||||
readBuffer.append(messageBytes)
|
||||
assertNull(readBuffer.readMessage())
|
||||
readBuffer.append("\r".encodeToByteArray())
|
||||
assertNull(readBuffer.readMessage())
|
||||
|
||||
// Append a newline and verify message is now available
|
||||
readBuffer.append("\n".encodeToByteArray())
|
||||
|
|
@ -45,6 +47,20 @@ class ReadBufferTest {
|
|||
assertNull(readBuffer.readMessage())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `skip blank line`() {
|
||||
val readBuffer = ReadBuffer()
|
||||
readBuffer.append(" \n".toByteArray())
|
||||
assertNull(readBuffer.readMessage())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `skip invalid json line`() {
|
||||
val readBuffer = ReadBuffer()
|
||||
readBuffer.append(" {ah=oh\n".toByteArray())
|
||||
assertNull(readBuffer.readMessage())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should be reusable after clearing`() {
|
||||
val readBuffer = ReadBuffer()
|
||||
|
|
|
|||
Loading…
Reference in a new issue