Files
swift-nio-imap/Sources/NIOIMAP/Coders/CommandDecoder.swift
T
Daniel Eggert 5d1358d09c Deliver received literals zero-copy via IMAPInputProcessor
The handlers stage reads in an IMAPInputBuffer (IMAPInputProcessor)
instead of NIOSingleStepByteToMessageProcessor's coalesced ByteBuffer,
so a FETCH/APPEND literal piece of at least 1 KiB within one read of
at least 1 KiB is delivered as a reference to the received bytes.
Shorter pieces are copied; bytes from smaller reads are copied twice,
into a tail on arrival and out of it on delivery. The decoders keep
their ByteBuffer entry point for ByteToMessageHandler and the decoder
verifier; that path copies.

A decoder error or PayloadTooLargeError is final: the buffer is dropped
and later reads rethrow it without decoding (ByteToMessageHandler also
stops decoding, but fires dataReceivedInErrorState). Keeping the
unparsed bytes would make every later read append, fail on the same
bytes and copy all of them into IMAPDecoderError.buffer: unbounded
memory and quadratic copying, past the maximumBufferSize check. Errors
thrown by the message receiver (e.g. UnexpectedResponse) pass through
and are not final.

Reads under 1 KiB are copied into IMAPInputBuffer's tails, so 1-byte
reads cost a region per KiB and pin no receive buffers. A larger read
still pins its whole receive buffer, which maximumBufferSize does not
count.

Review focus: IMAPInputProcessor.

Behavior changes:
- A stream whose input failed to parse stays failed.
- IMAPDecoderError.buffer holds the bytes waiting to be parsed when the
  error was thrown.
- Leftover literal bytes followed by a read that starts a new region
  reach the handler's consumer as two .streamingBytes events, not
  one. Every read of at least 1 KiB starts a region; a smaller one
  does when the last region is a retained read, or a tail it does not
  fit or that is not uniquely referenced.
  ParseInput.extractBuffer(upTo:) takes bytes from the current region
  only, where the old code took min(remaining, readable) across the
  whole buffer. Legal, but observable. A caller passing a multi-region
  buffer to the stream parsers directly sees this from the previous
  commit on.
2026-11-24 09:48:18 +09:00

60 lines
2.2 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
import NIOIMAPCore
/// Thrown if an error occurs when decoding IMAP data.
public struct IMAPDecoderError: Error {
/// The error that was thrown by the IMAP parser.
public var parserError: Error
/// The bytes that were waiting to be parsed when the error was thrown.
public var buffer: ByteBuffer
}
struct CommandDecoder: NIOSingleStepByteToMessageDecoder, IMAPMessageDecoder {
typealias InboundOut = SynchronizedCommand
private var parser: CommandParser
init(literalSizeLimit: Int = IMAPDefaults.literalSizeLimit) {
self.parser = CommandParser(literalSizeLimit: literalSizeLimit)
}
/// Parses out of the library's own input buffer — the path the handler takes.
mutating func decode(input: inout IMAPInputBuffer) throws -> SynchronizedCommand? {
do {
return try self.parser.parseCommandStream(buffer: &input)
} catch {
throw IMAPDecoderError(parserError: error, buffer: input.coalescedByteBuffer())
}
}
/// Parses out of a `ByteBuffer`, for `ByteToMessageHandler` and the decoder verifier.
///
/// The parser reads only an ``IMAPInputBuffer``, so `buffer` is appended to a fresh one — kept by
/// reference if large, copied if small — and its reader index moved past what was consumed.
mutating func decode(buffer: inout ByteBuffer) throws -> SynchronizedCommand? {
var input = IMAPInputBuffer()
input.append(buffer)
defer { buffer.moveReaderIndex(forwardBy: buffer.readableBytes - input.count) }
return try self.decode(input: &input)
}
mutating func decodeLast(buffer: inout ByteBuffer, seenEOF: Bool) throws -> SynchronizedCommand? {
try self.decode(buffer: &buffer)
}
}