Files
swift-nio-imap/Sources/NIOIMAPCore/CommandEncodeBuffer.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

186 lines
8.1 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
//
//===----------------------------------------------------------------------===//
/// Encodes IMAP client commands into wire format ready for transmission to an IMAP server.
///
/// `CommandEncodeBuffer` is the primary interface for encoding commands from the client side.
/// It handles chunking of synchronizing literals (for RFC 3501 Section 4.3 compliance) and
/// respects server capabilities when deciding which literal formats to use.
///
/// ## Usage Example
///
/// ```swift
/// var buffer = CommandEncodeBuffer(
/// options: CommandEncodingOptions(capabilities: [.literalPlus]),
/// loggingMode: false
/// )
/// buffer.writeCommand(TaggedCommand(tag: "A1", command: .login(username: "user", password: "pass")))
/// while let chunk = buffer.nextChunk() {
/// send(chunk.bytes)
/// if chunk.nextStep == .awaitContinuationRequest {
/// // Wait for the server's `+` before sending the next chunk.
/// }
/// }
/// ```
///
/// ## Where the bytes go
///
/// This is the type a client creates; it owns an ``EncoderOutputBuffer``, the sink the encoded bytes
/// are appended to, chosen once with the `sink:` argument and never named again. Leaving it out gives
/// an ``IMAPOutputBuffer``, which is the right answer unless the bytes have to land somewhere
/// specific — see ``EncoderOutputBuffer`` for the choice. The bytes come back out as an
/// ``IMAPBufferList`` from ``nextChunk()``, which converts to a `DispatchData`, to `ByteBuffer`s, or to
/// one contiguous copy.
///
/// - SeeAlso: ``ResponseEncodeBuffer``, ``CommandEncodingOptions``
public struct CommandEncodeBuffer: Hashable {
/// The underlying buffer containing data to be written.
///
/// Provides access to the raw ``EncodeBuffer`` for advanced operations,
/// though most users should interact through the public API of `CommandEncodeBuffer`.
@_spi(NIOIMAPInternal) public var buffer: EncodeBuffer
/// Tracks whether we have encoded at least one catenate element.
internal var encodedAtLeastOneCatenateElement: Bool
/// Creates a new command encoding buffer with explicit options.
///
/// - Parameters:
/// - sink: Where the encoded bytes are appended. Defaults to an ``IMAPOutputBuffer``, which
/// is the right choice unless the bytes have to land somewhere specific.
/// - options: The ``CommandEncodingOptions`` controlling how literals, strings,
/// and other protocol elements are encoded.
/// - encodedAtLeastOneCatenateElement: Internal tracking for CATENATE operations.
/// Typically `false` for new buffers.
/// - loggingMode: When `true`, binary data is replaced with placeholders like
/// `[N bytes]` for safe logging. Defaults to `false`.
public init(
sink: some EncoderOutputBuffer = IMAPOutputBuffer(),
options: CommandEncodingOptions,
encodedAtLeastOneCatenateElement: Bool = false,
loggingMode: Bool
) {
self.buffer = .clientEncodeBuffer(sink: sink, options: options, loggingMode: loggingMode)
self.encodedAtLeastOneCatenateElement = encodedAtLeastOneCatenateElement
}
}
// MARK: - Sendability
/// `CommandEncodeBuffer` is deliberately **not** `Sendable`, because the ``EncoderOutputBuffer`` it
/// writes into is not: see ``EncodeBuffer``. A chunk that has been handed out *is* `Sendable`.
@available(*, unavailable)
extension CommandEncodeBuffer: Sendable {}
extension CommandEncodeBuffer {
/// The encoding options currently in use.
///
/// These options determine how protocol elements are encoded (for example, whether to use
/// quoted strings, which literal formats are supported). You can modify these
/// options at runtime to change encoding behavior for subsequent write operations.
///
/// - Note: Changing this property affects all subsequent encoding operations in
/// this buffer.
public var options: CommandEncodingOptions {
get {
guard case .client(let options) = buffer.mode else {
preconditionFailure("Command encoder mode must be 'client'.")
}
return options
}
set {
buffer.mode = .client(options: newValue)
}
}
/// Creates a new command encoding buffer from server capabilities.
///
/// Converts a list of ``Capability`` values into ``CommandEncodingOptions``,
/// which automatically enables extended literal formats and binary support if the
/// server advertises the corresponding capabilities.
///
/// - Parameters:
/// - sink: Where the encoded bytes are appended. Defaults to an ``IMAPOutputBuffer``.
/// - capabilities: Server capabilities from a `CAPABILITY` response. These are
/// used to configure encoding options automatically.
/// - encodedAtLeastOneCatenateElement: Internal tracking for CATENATE operations.
/// Typically `false` for new buffers.
/// - loggingMode: When `true`, binary data is replaced with placeholders like
/// `[N bytes]` for safe logging. Defaults to `false`.
public init(
sink: some EncoderOutputBuffer = IMAPOutputBuffer(),
capabilities: [Capability],
encodedAtLeastOneCatenateElement: Bool = false,
loggingMode: Bool
) {
self.buffer = .clientEncodeBuffer(sink: sink, capabilities: capabilities, loggingMode: loggingMode)
self.encodedAtLeastOneCatenateElement = encodedAtLeastOneCatenateElement
}
}
extension CommandEncodeBuffer {
/// Call the closure with a buffer, return the result as a String.
///
/// Used for implementing ``CustomDebugStringConvertible`` conformance.
static func makeDescription(loggingMode: Bool = false, _ closure: (inout CommandEncodeBuffer) -> Void) -> String {
var buffer = CommandEncodeBuffer(options: .rfc3501, loggingMode: loggingMode)
closure(&buffer)
var bytes: [UInt8] = []
while let chunk = buffer.nextChunk() {
bytes.append(contentsOf: chunk.bytes.copiedBytes())
}
return String(bestEffortDecodingUTF8Bytes: bytes)
}
}
// MARK: - Chunks
extension CommandEncodeBuffer {
/// Encoded bytes to send as one write, and what the client must do before sending more.
public struct Chunk: Hashable, Sendable {
/// The bytes to send, in order. Large payloads are referenced, not copied.
public var bytes: IMAPBufferList
/// What the client must do after sending `bytes` and before sending the next chunk.
public var nextStep: NextStep
}
/// What a client does after sending a chunk.
public enum NextStep: Hashable, Sendable {
/// Send the next chunk right away.
case proceed
/// The chunk ends with a synchronizing literal header (`{n}`). Wait for the server's
/// continuation request (`+`) before sending the next chunk.
case awaitContinuationRequest
}
/// Removes and returns the next chunk of encoded bytes, ending at the first pending
/// synchronizing literal header; returns `nil` if nothing is pending.
///
/// A chunk may end with the last byte written so far, e.g. after `.append(.beginMessage(…))`:
/// its `nextStep` is still ``NextStep/awaitContinuationRequest``, and the next chunk, once more
/// is written, follows the `+`.
public mutating func nextChunk() -> Chunk? {
guard self.buffer.hasChunks || self.buffer.pendingByteCount > 0 else { return nil }
let (chunk, end) = self.buffer.takeChunk(allowEmptyChunk: true)
switch end {
case .stopPoint:
return Chunk(bytes: chunk.bytes, nextStep: .awaitContinuationRequest)
case .pendingBytes:
return Chunk(bytes: chunk.bytes, nextStep: .proceed)
}
}
}