Files
swift-nio-imap/Sources/NIOIMAP/Coders/IMAPClientHandler.swift
T
Daniel Eggert cbbce83ab6 Encode into an EncoderOutputBuffer sink
EncodeBuffer appends to `any EncoderOutputBuffer` (IMAPOutputBuffer by
default) instead of holding a ByteBuffer. Chunks come out as
IMAPBufferList; the handlers write one buffer per payload via
makeOutboundBuffers(). CommandEncoder is deleted: it kept only the first
chunk of a synchronizing literal and had no users but its own test.
nextChunk() caps a chunk at 64 regions, coalescing the tail, whatever
the sink returned, so no sink (a caller's own included) has to.

EncodeBuffer stages writes under 256 bytes inline and appends them to
the sink in one call: one existential call per ~256 bytes, not per
write. It flushes before every hand-out and before any direct sink
append (writeBytes(IMAPBuffer), larger writes), so payloads still reach
the sink by reference and in order. Conformers see batched appends;
byteCount may lag until a hand-out (documented on EncoderOutputBuffer).
Per-write cost therefore no longer separates the two sinks, so the
docs choosing IMAPOutputBuffer over ByteBufferOutput (ByteBufferOutput's,
EncoderOutputBuffer's, IMAPOutputBuffer's, the handlers') rest on the
hand-out instead.

Review focus: totalWritten / handedOut and absolute stop points in
nextChunk() (an off-by-one deadlocks the protocol, see
EncodeBufferSinkTests), the staging flush points, and
IMAPClientHandler.writeChunk's promise handling across several writes.

The CLI example's round-trip handler compares all chunks via the public
nextChunk() (it compared only the first) and drops its SPI import.

Public API breaks:
- CommandEncodeBuffer / ResponseEncodeBuffer: `init(buffer:…)` ->
  `init(sink: = IMAPOutputBuffer(), …)`; no longer Sendable.
- EncodeBuffer.Chunk.bytes and ResponseEncodeBuffer.readBytes() are
  IMAPBufferList.
- EncodeBuffer.writeBytes takes a Collection; writeBytes(IMAPBuffer) added;
  writeBuffer(inout ByteBuffer) removed.
- EncodeBuffer (SPI) is no longer Sendable; == / hash compare the pending
  bytes.

Public API addition: CommandEncodeBuffer.nextChunk() -> Chunk?, with
Chunk { bytes, nextStep } and NextStep { proceed,
awaitContinuationRequest }, so a client with its own transport needs no
SPI. nextStep awaits whenever a chunk ends at a synchronizing literal
header, also at the last byte written (APPEND .beginMessage,
.catenateData(.begin)), where the SPI Chunk.waitForContinuation says no
wait. ClientStateMachine uses it and imports no NIOIMAPCore SPI.

Behavior change: an APPEND part that ends in a literal the APPEND flow
doesn't expect (zero-length, e.g. an empty mailbox with quoted strings
off) waits for `+` before the next part instead of running ahead; its
write promise completes after the `+`.

Examples/PerformanceTester (IMAPDispatchClient) does not build from here
until "Measure IMAPDispatchClient against either library".

Temporary: EncodeBuffer+ByteBufferShim.swift keeps an internal
writeBuffer(inout ByteBuffer) for the model types that still hold one.
2026-11-24 09:47:33 +09:00

230 lines
9.0 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
import OrderedCollections
/// To be used by a IMAP client implementation.
public final class IMAPClientHandler: ChannelDuplexHandler {
/// Should receive a raw buffer in, after any TLS.
public typealias InboundIn = ByteBuffer
/// Converts a `ByteBuffer` into a `Response` by sending data through a parser.
public typealias InboundOut = Response
/// Either `CommandStreamPart` or options.
public typealias OutboundIn = Message
/// After encoding the bytes may be sent further through the channel to, for example, a TLS handler.
public typealias OutboundOut = ByteBuffer
/// We can receive either `CommandStreamPart` or `EncodingOptions`.
public enum Message: Hashable, Sendable {
case part(CommandStreamPart)
case setEncodingOptions(EncodingOptions)
}
private let decoder: NIOSingleStepByteToMessageProcessor<ResponseDecoder>
private var state: ClientStateMachine
public init(
encodingOptions: EncodingOptions = .automatic,
parserOptions: ResponseParser.Options = ResponseParser.Options(),
maximumBufferSize: Int = IMAPDefaults.lineLengthLimit
) {
self.state = .init(encodingOptions: encodingOptions)
self.decoder = NIOSingleStepByteToMessageProcessor(
ResponseDecoder(
options: parserOptions
),
maximumBufferSize: maximumBufferSize
)
}
public func channelInactive(context: ChannelHandlerContext) {
let pendingWritePromises = self.state.channelInactive()
pendingWritePromises.forEach { $0.fail(ChannelError.ioOnClosedChannel) }
context.fireChannelInactive()
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let data = self.unwrapInboundIn(data)
do {
try self.decoder.process(buffer: data) { response in
try self.handleResponseOrContinuationRequest(response, context: context)
}
} catch let error as UnexpectedResponse {
error.activePromise?.fail(error)
context.fireErrorCaught(error)
} catch {
context.fireErrorCaught(error)
}
}
public func handlerAdded(context: ChannelHandlerContext) {
self.state.handlerAdded(context.channel.allocator)
context.fireChannelActive()
}
private func handleResponseOrContinuationRequest(
_ response: ResponseOrContinuationRequest,
context: ChannelHandlerContext
) throws {
switch response {
case .continuationRequest(let continuationRequest):
let action = try self.state.receiveContinuationRequest(continuationRequest)
self.handleContinuationRequestAction(action, request: continuationRequest, context: context)
case .response(let response):
let actions = try self.state.receiveResponse(response)
// Write what the response released before succeeding promises and forwarding the
// response, so that anything written in reaction to those goes out after it.
self.writeChunks(actions.compactMap(\.chunk), context: context)
for case .succeed(let promise) in actions {
promise?.succeed()
}
context.fireChannelRead(self.wrapInboundOut(response))
self.state.encodingOptions.updateAutomaticOptions(response: response)
}
}
private func handleContinuationRequestAction(
_ action: ClientStateMachine.ContinuationRequestAction,
request: ContinuationRequest,
context: ChannelHandlerContext
) {
switch action {
case .sendChunks(let chunks):
self.writeChunks(chunks, context: context)
context.fireUserInboundEventTriggered(request)
case .fireIdleStarted(let chunks):
// Before forwarding `.idleStarted`, so that anything written in reaction to it goes
// out after a DONE that was held back for the confirmation.
self.writeChunks(chunks, context: context)
context.fireChannelRead(self.wrapInboundOut(.idleStarted))
context.fireUserInboundEventTriggered(request)
case .fireAuthenticationChallenge:
switch request {
case .responseText:
// No valid base64, so forward on an empty BB
context.fireChannelRead(
self.wrapInboundOut(.authenticationChallenge(context.channel.allocator.buffer(capacity: 0)))
)
case .data(let byteBuffer):
context.fireChannelRead(self.wrapInboundOut(.authenticationChallenge(byteBuffer)))
}
}
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
switch self.unwrapOutboundIn(data) {
case .part(let command):
do {
switch try self.state.sendCommand(command, promise: promise) {
case .write(let chunk):
self.writeChunk(chunk, context: context)
case .succeed(let promise):
promise?.succeed()
case nil:
break
}
} catch {
context.fireErrorCaught(error)
promise?.fail(error)
}
case .setEncodingOptions(let options):
state.encodingOptions.userOptions = options
promise?.succeed()
}
}
private func writeChunks(_ chunks: [OutgoingChunk], context: ChannelHandlerContext) {
guard chunks.count > 0 else { return }
chunks.forEach { chunk in
self.writeChunk(chunk, context: context)
}
context.flush() // we wouldn't reach this point if we hadn't already flushed
}
private func writeChunk(_ chunk: OutgoingChunk, context: ChannelHandlerContext) {
// A chunk usually becomes one write. It becomes several when it carries a payload the encoder
// kept by reference — an `APPEND` message — because writing that payload on its own is what
// keeps it from being copied, and NIO gathers the writes into one `writev` anyway. See
// `IMAPBufferList.makeOutboundBuffers()` for why this is not simply one write per region.
//
// A chunk with no bytes still has to reach the channel: an empty write is how the end of an
// `APPEND` message is signalled, and the promise has to be resolved either way.
switch chunk.bytes.regionCount {
case 0:
self.write(ByteBuffer(), of: chunk, position: .last, context: context)
case 1:
self.write(chunk.bytes.regions[0].byteBuffer, of: chunk, position: .last, context: context)
default:
let buffers = chunk.bytes.makeOutboundBuffers()
for (index, buffer) in buffers.enumerated() {
let position: BufferPosition = index == buffers.count - 1 ? .last : .notLast
self.write(buffer, of: chunk, position: position, context: context)
}
}
}
/// Where a buffer sits among the writes of one chunk.
private enum BufferPosition {
case notLast
/// The chunk's final write; it may resolve the chunk's promise.
case last
}
/// Writes one of a chunk's buffers, resolving the chunk's promise on the last of them.
private func write(
_ bytes: ByteBuffer,
of chunk: OutgoingChunk,
position: BufferPosition,
context: ChannelHandlerContext
) {
let outbound = self.wrapOutboundOut(bytes)
if position == .last, chunk.shouldSucceedPromise {
context.write(outbound, promise: chunk.promise)
} else {
// Not the last buffer, or a chunk that will only be finished by a later one: the promise
// must not succeed yet, but a failure anywhere has to reach it.
context.write(outbound).cascadeFailure(to: chunk.promise)
}
}
public func flush(context: ChannelHandlerContext) {
do {
for chunk in try self.state.flush() {
self.writeChunk(chunk, context: context)
}
} catch {
context.fireErrorCaught(error)
}
context.flush()
}
}
extension IMAPClientHandler {
public enum EncodingOptions: Hashable, Sendable {
case automatic
case fixed(CommandEncodingOptions)
}
}
// `IMAPClientHandler` holds per-connection mutable state and is confined to a
// single `EventLoop`, so it is deliberately non-`Sendable`.
@available(*, unavailable)
extension IMAPClientHandler: Sendable {}