Commit Graph
24 Commits
Author SHA1 Message Date
Daniel Eggert b193b1c18a Add before/after script for IMAPDispatchClient
compare-dispatch-client.sh benchmarks a pinned pre-migration worktree
against this tree. README records the results; Package.swift and
IMAPDispatchClient.swift point to it.
2026-11-24 09:48:37 +09:00
Daniel Eggert 5caa77d7be Add IMAPProfile and a baseline-comparison summarizer
IMAPProfile runs one corpus N times, for tracing under Instruments'
Allocations template; the README says how to read the trace.
summarize-comparison.py condenses `baseline compare` output.
2026-11-24 09:48:37 +09:00
Daniel Eggert 3e59038ff5 Add IMAPParsing and IMAPEncoding thresholds (generated)
Output of `benchmark thresholds update`, measured before a rebase and
not re-measured since. Host-specific; not gated in CI. Apple M5 Max,
macOS 27.3, Swift 6.4.4. From Examples/PerformanceTester, with
six = --metric mallocCountTotal --metric mallocBytesCount
      --metric objectAllocCount --metric retainCount
      --metric releaseCount --metric retainReleaseDelta
two = --metric mallocCountTotal --metric mallocBytesCount:
  swift package --disable-sandbox benchmark thresholds update \
    --target IMAPParsing $six
  swift package --disable-sandbox benchmark thresholds update \
    --target IMAPEncoding --skip 'encode\.dispatch\..*' $six
  swift package --disable-sandbox benchmark thresholds update \
    --target IMAPEncoding --filter 'encode\.dispatch\..*' $two
2026-11-24 09:48:37 +09:00
Daniel Eggert f1a5b029ab Add IMAPEncoding benchmarks
Encoder benchmarks for commands and responses, through contiguous,
NIO-handler and DispatchData drivers. Adds those drivers to
IMAPBenchmarkSupport, plus the response model corpus.

IMAPDispatchClient's no-ARC note now points at encode.dispatch.*'s.
2026-11-24 09:48:37 +09:00
Daniel Eggert 9adb7fbf04 Add IMAPParsing benchmarks
Parser benchmarks for commands and responses, plus IMAPBenchmarkSupport:
the command corpus and the parse drivers. Post-migration only; not
built with IMAP_IMPL=main.
2026-11-24 09:48:35 +09:00
Daniel Eggert e7732411fe Make IMAPBuffer.dispatchDonationThreshold internal
A tuning value nothing outside Core needs. Docs outside it now give
the number instead of the name.
2026-11-24 09:48:20 +09:00
Daniel Eggert ba7308e77b Update IMAPDispatchClient thresholds (generated)
Generated with the two commands in "Add IMAPDispatchClient benchmark
thresholds (generated)", before a rebase; not re-measured since.
"Regenerate benchmark thresholds (generated)" re-measures later.
Apple M5 Max, macOS 27.3, Swift 6.4.4.
2026-11-24 09:48:18 +09:00
Daniel Eggert 854a5256f0 Measure IMAPDispatchClient against either library
The DispatchData client now has two drivers. DispatchClient+Current
uses IMAPInputBuffer (each read appended with append(contentsOf:)),
IMAPBuffer payloads and IMAPOutputBuffer donated via
makeDispatchData(); DispatchClient+Legacy, the ByteBuffer client,
compiles only under IMAP_LEGACY_BUFFERS. IMAP_IMPL=main in Package.swift
points the path dependency at a pre-migration checkout (IMAP_MAIN_PATH)
and defines that flag, so one set of case names yields before/after
numbers.

The encode cases' no-ARC note gains the reasons donation adds: the
queue-dependent retain deltas and the thread the hook race fires on.

Built both ways (IMAP_IMPL=main against f5fa7d36). Thresholds follow
separately.
2026-11-24 09:48:18 +09:00
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
Daniel Eggert a72d61d666 Make payload cases IMAPBuffer
The four raw-payload cases become IMAPBuffer so a large literal can be
handed in and out without a copy: FetchResponse.streamingBytes,
AppendCommand.messageBytes, AppendCommand.CatenateData.bytes,
CommandStreamPart.continuationResponse.

Review focus: writeBytes(IMAPBuffer) keeps payloads by reference
(ZeroCopyWriteTests); the parser's extractBuffer(upTo:) still copies.

Updates IMAPTool and the IMAPCommands append/continuation wrappers.

Public API breaks:
- The four cases above: ByteBuffer -> IMAPBuffer.

Removes the writeBuffer(inout ByteBuffer) shim from "Encode into an
EncoderOutputBuffer sink".
2026-11-24 09:47:34 +09:00
Daniel Eggert 3cd39758d4 Use [UInt8] for small model fields
Small fields (mailbox names, atoms, quoted strings, envelope fields,
base64, URLs, the authentication challenge, catenateURL, ...) become
[UInt8]. The four raw-payload cases stay ByteBuffer until "Make payload
cases IMAPBuffer".

The grammar's string productions return [UInt8]. The parser still runs
on ParseBuffer, so its cursor methods copy out of the ByteBuffer for now.

Review focus: the model files' encoders and ModifiedUTF7 on arrays.

Updates IMAPTool and the IMAPCommands catenate-URL wrapper.

Public API breaks:
- ~38 public declarations ByteBuffer -> [UInt8].
- ModifiedUTF7.EncodingRoundtripError.buffer -> .bytes.
- Response.authenticationChallenge and ContinuationRequest.data are
  [UInt8]; an empty challenge is [].

Internal: writeBufferAsBase64 -> writeBytesAsBase64; the ByteBuffer
writeIMAPString overload is gone.
2026-11-24 09:47:33 +09:00
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
Daniel Eggert e83d3dcb8a Require OS 26 platforms; enable Lifetimes
The new byte types need `Span`-producing stdlib accessors (`Array.span`,
`String.utf8Span`) that are gated at 26. Also adds `DequeModule`.

Public break: raises the deployment floor to 26 on every platform (was
macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2). Examples follow,
since a path dependency cannot have a higher floor than its dependent.
2026-11-24 09:47:31 +09:00
Daniel Eggert ec07823d59 Add IMAPDispatchClient benchmark thresholds (generated)
From Examples/PerformanceTester:
  swift package --disable-sandbox benchmark thresholds update \
    --target IMAPDispatchClient --filter 'dispatch-client\.parse\..*' \
    --metric mallocCountTotal --metric mallocBytesCount \
    --metric objectAllocCount --metric retainCount \
    --metric releaseCount --metric retainReleaseDelta
  swift package --disable-sandbox benchmark thresholds update \
    --target IMAPDispatchClient --filter 'dispatch-client\.encode\..*' \
    --metric mallocCountTotal --metric mallocBytesCount
Apple M5 Max, macOS 27.3, Swift 6.4.4.
2026-11-24 09:47:25 +09:00
Daniel Eggert b7783878e8 Replace PerformanceTester with ordo-one/benchmark suite
IMAPDispatchClient: a DispatchData client (parse + encode), measured
with allocation counters (plus ARC counters for parsing) instead of
Date(). Needs Swift 6.3 (malloc-interposer), so CI builds it in its own
job.

The "Legacy" file name anticipates the migration's
DispatchClient+Current.
2026-11-24 09:47:23 +09:00
Daniel Eggert 4606da62d2 Validate response text, command tags and namespace delimiters (#866)
* Reject invalid response text when writing

`.no(.init(text: "No mailbox x\r\n* BYE pwned"))` was written verbatim,
injecting an untagged response; likewise tagged, BYE, PREAUTH and
continuation responses.

RFC 9051: `text = 1*(TEXT-CHAR / UTF8-2 / UTF8-3 / UTF8-4)`. `writeText`
now asserts no NUL, CR or LF. Empty stays valid. The parser now accepts
UTF-8 text.

* Add Command.Tag for command and response tags

`TaggedCommand(tag: "A1 NOOP\r\nA2 DELETE INBOX\r\nA3", command: .noop)`
was written verbatim, injecting a command; likewise `APPEND` start.
`TaggedResponse(tag: "* BYE x\r\nA1", …)` injected a response.

RFC 3501: `tag = 1*<any ASTRING-CHAR except "+">`. New `Command.Tag`
replaces the `String` in `TaggedCommand`, `TaggedResponse`, `Response`,
`CommandStreamPart`, `AppendCommand`, `BadCommand` and NIOIMAP's state
machine errors; `init?(_:)` validates, literals trap. The parser already
enforces the production. IMAPCommands converts its numeric tags.

* Validate and escape namespace delimiters

`NamespaceDescription(string: "x", char: "\r\n", …)` wrote a raw CRLF
inside `"…"`, injecting a response. `"\""` encoded as `"""`, and `"\\"`
as `"\"` (unterminated); non-ASCII was accepted.

RFC 2342: `DQUOTE QUOTED-CHAR DQUOTE / nil`. `init(string:delimiter:
responseExtensions:)` (was `char:`) throws `InvalidDelimiterError` for
non-ASCII, CR, LF, NUL; the delimiter is stored as a byte, read-only.
Quoted-specials are escaped on write and parsed when escaped.

* Gate a capturing exit test on Swift 6.3
2026-11-04 17:41:52 +00:00
Matt Diephouse f5fa7d3691 Implement OBJECTID+ extension (#840) 2026-10-30 13:47:17 +00:00
Daniel Eggert fbec780de3 Normalize malformed ENVELOPE address groups (#872) 2026-10-27 15:06:24 +01:00
Daniel Eggert 6c8cfaddcc Add a imperative IMAP client and an imap-tool CLI (#841) 2026-09-25 16:16:41 +01:00
Daniel Eggert e536be599e Reject invalid AuthenticationMechanism (#846) 2026-09-01 10:11:11 +02:00
Daniel Eggert c4d4d23e29 Drop pre-Swift 6.2 (#845) 2026-08-29 09:23:34 +02:00
Daniel Eggert 90124af395 Add proxy readme (#839) 2026-07-30 09:57:47 -04:00
Daniel Eggert dcba159054 Modernize the Proxy example (#835) 2026-07-18 21:54:14 +02:00
Daniel Eggert 1057994e93 Move examples into sub-dir (#834) 2026-07-18 12:00:06 +02:00