You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by "RustToMetal (via GitHub)" <gi...@apache.org> on 2026/10/25 08:14:37 UTC

[PR] feat(swift): add the consumer [iggy]

RustToMetal opened a new pull request, #4641:
URL: https://github.com/apache/iggy/pull/4641

   ## Which issue does this PR address?
   
   Relates to #4001
   
   ## Rationale
   
   The Swift client can poll messages and store offsets (#4553) and produce with `IggyProducer` (#4577), but an application that reads a topic steadily needs what the Rust `IggyConsumer` gives it: tracking each partition's position, committing it at the right moment, and coming back after an outage or a rebalance. This is the next step of #4001: the consumer.
   
   ## What changed?
   
   `IggyConsumer` is a port of the current Rust consumer, as an actor that is also an `AsyncSequence`. `client.consumer(name:streamID:topicID:partitionID:)` builds a standalone consumer of one partition and `client.consumerGroup(name:streamID:topicID:)` a group member that joins its group, creating it when allowed, and reads the server's assignment. `initialize()` looks the stream and topic up with the configured retries. `next()` hands messages over one at a time from a buffer that a poll refills; each poll of a partition continues after the last message handed over, under the partition context that delivered it, and a message already handed over from the same partition history is skipped unless `allowReplay` is set. A failed poll is thrown after the retry interval and leaves the consumer usable; a member that lost its membership joins again before the next poll.
   
   The auto-commit modes follow Rust: with the poll, on an interval, while messages are handed over (each, every nth offset, end of batch), and after a handler of `consumeMessages(_:)` returned. Queued commits collapse to the latest per partition, a position the last store already covers is not sent again, and `shutdown()` drains the commit tasks, stores the reading position of every partition read unless auto-commit is disabled, and leaves the group. Concurrent `initialize()` and `shutdown()` calls share one run, a dropped consumer ends its tasks, and options out of range are refused when the consumer is built. The client gains an internal `canRecover`, which `consumeMessages(_:)` uses to stop once the client cannot come back without the caller.
   
   The Swift client has no encryptor and no operation lanes yet, so the consumer does not decrypt and does not resolve a group create or join whose reply was lost; the docs and README say so.
   
   Of the 1,588 added lines, 664 are tests.
   
   ## Local Execution
   
   - Passed
   - Pre-commit hooks ran
   
   Run on macOS (Swift 6.4) on the final commit: `swift format lint --strict`, `swift build -Xswiftc -warnings-as-errors` (sources and tests), `swift build -c release`, `swift test` (395 tests, three runs), the golden lane (regenerate, no diff), and `prek run` over the commit. Before the rebase onto current master the same build and tests passed in Docker on Linux with Swift 6.4 and with Swift 6.1, the toolchain of the macOS lane.
   
   The end-to-end suite (50 tests, 2 of them for the consumer) passed against `iggy-server` built from current master, started the way the CI lane starts it: plain, with TLS using the certificates in `core/certs`, and as a two-node cluster.
   
   ## AI Usage
   
   1. Claude Code.
   2. Implementation and tests were written with it, as a port of `core/sdk/src/clients/consumer.rs`, `consumer_builder.rs`, and `consumer_ext/consumer_message_ext.rs`, applying the patterns from the review rounds on the earlier Swift PRs.
   3. The local runs listed above, plus mutation checks: the replay filter, the continuation, dropping a refused continuation, the covered-position skip, the shared shutdown and initialization, the weak task captures, the rejoin after a revoked membership, the end of `consumeMessages` for a client that cannot come back, and the after-handler triggers were each broken on purpose and a test failed or hung for each.
   4. Yes.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(swift): add the consumer [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio merged PR #4641:
URL: https://github.com/apache/iggy/pull/4641


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(swift): add the consumer [iggy]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on code in PR #4641:
URL: https://github.com/apache/iggy/pull/4641#discussion_r4377150148


##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {

Review Comment:
   warning: `start()` joins the group before it checks `isShutDown`, so a shutdown during `initialize()` leaves the group joined after `drain()` passed its leave check. Check `isShutDown` after every join and leave the group, including the join in `poll()`.



##########
foreign/swift/Sources/Iggy/Client/ClientCore.swift:
##########
@@ -383,6 +383,19 @@ actor ClientCore {
         try VSRFrame.encodeRequest(session: &session, code: code, payload: payload, partitionContext: context)
     }
 
+    /// Whether the client comes back on its own: it is signed in, or a
+    /// request or the heartbeat reconnects and signs it in again. A client
+    /// that is shut down, that the caller disconnected, or that has no
+    /// reconnection or no credentials only comes back when the caller acts.
+    var canRecover: Bool {

Review Comment:
   warning: `canRecover` reports a signed-out client as self-recovering whenever reconnection is enabled and credentials exist, even when `heartbeatInterval` is zero and no heartbeat runs. The consumer then parks without sending the request that would reconnect it. Make `canRecover` false when the heartbeat is off, so the poll runs the request.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()
+        }
+        guard !isShutDown else {
+            // A shutdown came in meanwhile and already stopped what it found.
+            eventsTask?.cancel()
+            eventsTask = nil
+            return
+        }
+        if let interval = configuration.autoCommit.interval {
+            intervalTask = Task { [weak self] in
+                while (try? await Task.sleep(for: interval)) != nil {
+                    guard let self, await self.storeOnTick() else {
+                        return
+                    }
+                }
+            }
+        }
+        commitTask = Task { [weak self, commitWakeups] in
+            for await _ in commitWakeups {
+                guard let self, await self.sendPendingCommits() else {
+                    return
+                }
+            }
+        }
+        isInitialized = true
+        logger.info("The consumer has been initialized", metadata: metadata)
+    }
+
+    /// Stops reading, sends the queued commits, stores the reading position
+    /// of every partition read unless auto-commit is disabled, and leaves the
+    /// group. Every caller waits for the same shutdown. Failures are logged:
+    /// nothing is left for the caller to undo.
+    public func shutdown() async {
+        if let shutdownTask {
+            await shutdownTask.value
+            return
+        }
+        isShutDown = true
+        let task = Task { await self.drain() }
+        shutdownTask = task
+        await task.value
+    }
+
+    private func drain() async {
+        logger.info("Shutting down the consumer", metadata: metadata)
+        let timeout = configuration.offsetDrainTimeout
+        if let intervalTask {
+            // A tick sleeping gets cancelled; one storing finishes first.
+            if intervalIsStoring {
+                await Self.wait(for: intervalTask, upTo: timeout)
+            }
+            intervalTask.cancel()
+        }
+        if let commitTask {
+            commitWakeup.yield()
+            await Self.wait(for: commitTask, upTo: timeout)
+            commitTask.cancel()
+        }
+        if configuration.autoCommit != .disabled {
+            let positions = Array(lastConsumed.values)
+            // One deadline for every final store, as in the Rust SDK.
+            _ = try? await withDeadline(.now + client.configuration.requestTimeout) {
+                await self.storeFinalPositions(positions)
+            }
+        }
+        if isConsumerGroup, joinedGroup {
+            joinedGroup = false
+            do {
+                try await client.leaveConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+            } catch {
+                // Expected after an explicit leave or a deleted group.
+                logger.debug("Failed to leave the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            }
+        }
+        eventsTask?.cancel()
+        eventsTask = nil
+        logger.info("The consumer has been shut down", metadata: metadata)
+    }
+
+    // MARK: Reading
+
+    /// The next message: from the buffer, or from a poll once it is empty.
+    /// Throws what a poll or join ran into, after the retry interval, and can
+    /// be called again after it threw. Nil once the consumer is shut down.
+    public func next() async throws -> ReceivedMessage? {
+        try await reading.lock()
+        defer { reading.unlock() }
+        if isShutDown {
+            return nil
+        }
+        if bufferIndex < buffer.count {
+            return handOverBuffered()
+        }
+        while !isShutDown {
+            try Task.checkCancellation()
+            let polled = try await poll()
+            if !polled.messages.isEmpty, !isShutDown {
+                return handOverPolled(polled)
+            }
+        }
+        return nil
+    }
+
+    /// Hands every message to `handler` until the consumer shuts down, the
+    /// task is cancelled, or an error ends the reading: a client that is shut
+    /// down or cannot come back without the caller, or an invalid address.
+    /// Other errors are logged and reading goes on, and a handler that throws
+    /// is logged too. The ``AutoCommitAfter`` triggers fire here, after the
+    /// handler returned or threw.
+    public func consumeMessages(_ handler: @Sendable (ReceivedMessage) async throws -> Void) async throws {
+        let after = configuration.autoCommit.afterTrigger
+        while true {
+            let received: ReceivedMessage
+            do {
+                guard let next = try await next() else {
+                    return
+                }
+                received = next
+            } catch let error as IggyError {
+                let ends = Self.endsConsumption(error) ? true : !(await client.canRecover)
+                if ends {
+                    logger.error("Reading stopped", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                    throw error
+                }
+                logger.error("Failed to read a message", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                continue
+            }
+            do {
+                try await handler(received)
+            } catch {
+                logger.error(
+                    "The handler failed", metadata: metadata.merging(["offset": "\(received.message.offset)", "error": "\(error)"]) { $1 })
+            }
+            switch after {
+            case .consumingEachMessage?:
+                queueCommit(received.position)
+            case .consumingEveryNthMessage(let n)?:
+                if received.message.offset % UInt64(n) == 0 {
+                    queueCommit(received.position)
+                }
+            case .consumingAllMessages?:
+                if received.message.offset == received.currentOffset {
+                    queueCommit(received.position)
+                }
+            case nil:
+                break
+            }
+        }
+    }
+
+    // MARK: Offsets
+
+    /// Stores `offset` for a partition, the current one when nil, under the
+    /// context of the last message handed over from it. Before any was, it
+    /// is stored without a context.
+    public func storeOffset(_ offset: UInt64, partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        if let last = lastConsumed[partition] {
+            try await storePosition(ConsumerPosition(partitionID: partition, offset: offset, context: last.context))
+            return
+        }
+        try await client.storeConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition, offset: offset)
+        lastStored[partition] = ConsumerPosition(partitionID: partition, offset: offset, context: .empty)
+    }
+
+    /// Stores the exact position delivered, as
+    /// ``ReceivedMessage/position`` gives it, even after later polls. Without
+    /// ``ConsumerConfiguration/allowReplay`` a position at or below the one
+    /// already stored in the same partition history is not sent.
+    public func storePosition(_ position: ConsumerPosition) async throws {
+        try await store(position, allowReplay: configuration.allowReplay)
+    }
+
+    /// Deletes the stored offset of a partition, the current one when nil.
+    /// Unlike the Rust consumer, a group member's nil is not left to the
+    /// server, since the Swift client routes the request by its partition.
+    public func deleteOffset(partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        // A cancelled delete can still have committed, so a later store must
+        // not be skipped as covered.
+        lastStored[partition] = nil
+        try await client.deleteConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition)
+    }
+
+    /// The offset of the last message handed over from the partition.
+    public func lastConsumedOffset(partitionID: UInt32) -> UInt64? {
+        lastConsumed[partitionID]?.offset
+    }
+
+    /// The offset this consumer last stored for the partition.
+    public func lastStoredOffset(partitionID: UInt32) -> UInt64? {
+        lastStored[partitionID]?.offset
+    }
+
+    // MARK: Internals
+
+    private var metadata: Logger.Metadata {
+        ["consumer": "\(name)", "stream": "\(streamID)", "topic": "\(topicID)"]
+    }
+
+    private func waitForStreamAndTopic() async throws {
+        let retries = configuration.initRetries ?? 0
+        var ticker = RetryTicker(interval: configuration.initRetryInterval)
+        try await ticker.tick()
+        var streamExists = try await client.getStream(streamID) != nil
+        var topicExists = false
+        if streamExists {
+            topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+        }
+        var attempt: UInt32 = 0
+        // A stream or topic may still be being created by someone else.
+        while !(streamExists && topicExists), attempt < retries {
+            attempt += 1
+            logger.warning(
+                "The stream or topic does not exist yet, retrying",
+                metadata: metadata.merging(["retry": "\(attempt)/\(retries)", "stream_exists": "\(streamExists)"]) { $1 })
+            try await ticker.tick()
+            if !streamExists {
+                streamExists = try await client.getStream(streamID) != nil
+            }
+            if streamExists {
+                topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+            }
+        }
+        guard streamExists else {
+            throw streamID.name.map { IggyError(.streamNameNotFound, context: "stream \($0) was not found") }
+                ?? IggyError(.streamIdNotFound, context: "stream \(streamID) was not found")
+        }
+        guard topicExists else {
+            throw topicID.name.map { IggyError(.topicNameNotFound, context: "topic \($0) was not found in stream \(streamID)") }
+                ?? IggyError(.topicIdNotFound, context: "topic \(topicID) was not found in stream \(streamID)")
+        }
+    }
+
+    private func joinGroup() async throws {
+        if joinedGroup {
+            return
+        }
+        if try await client.getConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id) == nil {
+            guard configuration.createConsumerGroupIfNotExists else {
+                throw IggyError(.consumerGroupNameNotFound, context: "consumer group \(name) does not exist and auto-creation is disabled")
+            }
+            logger.info("Creating the consumer group", metadata: metadata)
+            do {
+                _ = try await client.createConsumerGroup(streamID: streamID, topicID: topicID, name: name)
+            } catch let error as IggyError where error.code == .consumerGroupNameAlreadyExists {
+                // Another member created it first.
+            }
+        }
+        logger.info("Joining the consumer group", metadata: metadata)
+        try await client.joinConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+        joinedGroup = true
+    }
+
+    /// Returns false once the client shut down, which ends the subscription.
+    private func observe(_ event: DiagnosticEvent) async -> Bool {
+        switch event {
+        case .shutdown:
+            logger.warning("The client has been shut down", metadata: metadata)
+            joinedGroup = false
+            canPoll = false
+            return false
+        case .connected, .disconnected, .signedOut:
+            joinedGroup = false
+        case .signedIn:
+            break
+        }
+        // Events can arrive after one that reports a later state, so the
+        // state of the client decides.
+        canPoll = await client.state == .authenticated
+        return true
+    }
+
+    /// One poll, as the Rust consumer's poll future: the interval wait, the
+    /// sign-in wait, a join when the membership was lost, and the request.
+    /// An empty result is not an error.
+    private func poll() async throws -> PolledMessages {
+        if let pollInterval = configuration.pollInterval, let lastPolledAt {
+            try await Task.sleep(until: lastPolledAt + pollInterval, clock: .continuous)
+        }
+        let retryInterval = configuration.pollingRetryInterval
+        // A client that only the caller brings back never recovers, so the
+        // poll goes on and fails with the reason instead of waiting for good.
+        while !canPoll, await client.canRecover {

Review Comment:
   critical: `poll()` waits while `canPoll` is false and never checks `isShutDown`. `shutdown()` cancels the events task that writes `canPoll`, so a pending `next()` can wait forever instead of returning nil. When `isShutDown` is set, return an empty poll so `next()` returns nil.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()
+        }
+        guard !isShutDown else {
+            // A shutdown came in meanwhile and already stopped what it found.
+            eventsTask?.cancel()
+            eventsTask = nil
+            return
+        }
+        if let interval = configuration.autoCommit.interval {
+            intervalTask = Task { [weak self] in
+                while (try? await Task.sleep(for: interval)) != nil {
+                    guard let self, await self.storeOnTick() else {
+                        return
+                    }
+                }
+            }
+        }
+        commitTask = Task { [weak self, commitWakeups] in
+            for await _ in commitWakeups {
+                guard let self, await self.sendPendingCommits() else {
+                    return
+                }
+            }
+        }
+        isInitialized = true
+        logger.info("The consumer has been initialized", metadata: metadata)
+    }
+
+    /// Stops reading, sends the queued commits, stores the reading position
+    /// of every partition read unless auto-commit is disabled, and leaves the
+    /// group. Every caller waits for the same shutdown. Failures are logged:
+    /// nothing is left for the caller to undo.
+    public func shutdown() async {
+        if let shutdownTask {
+            await shutdownTask.value
+            return
+        }
+        isShutDown = true
+        let task = Task { await self.drain() }
+        shutdownTask = task
+        await task.value
+    }
+
+    private func drain() async {
+        logger.info("Shutting down the consumer", metadata: metadata)
+        let timeout = configuration.offsetDrainTimeout
+        if let intervalTask {
+            // A tick sleeping gets cancelled; one storing finishes first.
+            if intervalIsStoring {
+                await Self.wait(for: intervalTask, upTo: timeout)

Review Comment:
   warning: `drain()` waits for the interval task to end, but a tick that just stored sleeps a full interval before it checks the shutdown. `shutdown()` can then block past `offsetDrainTimeout`. Return `!isShutDown` from `storeOnTick` so the loop ends right after the store.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()
+        }
+        guard !isShutDown else {
+            // A shutdown came in meanwhile and already stopped what it found.
+            eventsTask?.cancel()
+            eventsTask = nil
+            return
+        }
+        if let interval = configuration.autoCommit.interval {
+            intervalTask = Task { [weak self] in
+                while (try? await Task.sleep(for: interval)) != nil {
+                    guard let self, await self.storeOnTick() else {
+                        return
+                    }
+                }
+            }
+        }
+        commitTask = Task { [weak self, commitWakeups] in
+            for await _ in commitWakeups {
+                guard let self, await self.sendPendingCommits() else {
+                    return
+                }
+            }
+        }
+        isInitialized = true
+        logger.info("The consumer has been initialized", metadata: metadata)
+    }
+
+    /// Stops reading, sends the queued commits, stores the reading position
+    /// of every partition read unless auto-commit is disabled, and leaves the
+    /// group. Every caller waits for the same shutdown. Failures are logged:
+    /// nothing is left for the caller to undo.
+    public func shutdown() async {
+        if let shutdownTask {
+            await shutdownTask.value
+            return
+        }
+        isShutDown = true
+        let task = Task { await self.drain() }
+        shutdownTask = task
+        await task.value
+    }
+
+    private func drain() async {
+        logger.info("Shutting down the consumer", metadata: metadata)
+        let timeout = configuration.offsetDrainTimeout
+        if let intervalTask {
+            // A tick sleeping gets cancelled; one storing finishes first.
+            if intervalIsStoring {
+                await Self.wait(for: intervalTask, upTo: timeout)
+            }
+            intervalTask.cancel()
+        }
+        if let commitTask {
+            commitWakeup.yield()
+            await Self.wait(for: commitTask, upTo: timeout)
+            commitTask.cancel()
+        }
+        if configuration.autoCommit != .disabled {
+            let positions = Array(lastConsumed.values)
+            // One deadline for every final store, as in the Rust SDK.
+            _ = try? await withDeadline(.now + client.configuration.requestTimeout) {
+                await self.storeFinalPositions(positions)
+            }
+        }
+        if isConsumerGroup, joinedGroup {
+            joinedGroup = false
+            do {
+                try await client.leaveConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+            } catch {
+                // Expected after an explicit leave or a deleted group.
+                logger.debug("Failed to leave the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            }
+        }
+        eventsTask?.cancel()
+        eventsTask = nil
+        logger.info("The consumer has been shut down", metadata: metadata)
+    }
+
+    // MARK: Reading
+
+    /// The next message: from the buffer, or from a poll once it is empty.
+    /// Throws what a poll or join ran into, after the retry interval, and can
+    /// be called again after it threw. Nil once the consumer is shut down.
+    public func next() async throws -> ReceivedMessage? {
+        try await reading.lock()

Review Comment:
   simplification: `next()` takes the reading mutex for every buffered message, though the buffer path has no await and actor isolation already serializes it. Check the buffer before locking so buffered handovers skip the mutex.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()
+        }
+        guard !isShutDown else {
+            // A shutdown came in meanwhile and already stopped what it found.
+            eventsTask?.cancel()
+            eventsTask = nil
+            return
+        }
+        if let interval = configuration.autoCommit.interval {
+            intervalTask = Task { [weak self] in
+                while (try? await Task.sleep(for: interval)) != nil {
+                    guard let self, await self.storeOnTick() else {
+                        return
+                    }
+                }
+            }
+        }
+        commitTask = Task { [weak self, commitWakeups] in
+            for await _ in commitWakeups {
+                guard let self, await self.sendPendingCommits() else {
+                    return
+                }
+            }
+        }
+        isInitialized = true
+        logger.info("The consumer has been initialized", metadata: metadata)
+    }
+
+    /// Stops reading, sends the queued commits, stores the reading position
+    /// of every partition read unless auto-commit is disabled, and leaves the
+    /// group. Every caller waits for the same shutdown. Failures are logged:
+    /// nothing is left for the caller to undo.
+    public func shutdown() async {
+        if let shutdownTask {
+            await shutdownTask.value
+            return
+        }
+        isShutDown = true
+        let task = Task { await self.drain() }
+        shutdownTask = task
+        await task.value
+    }
+
+    private func drain() async {
+        logger.info("Shutting down the consumer", metadata: metadata)
+        let timeout = configuration.offsetDrainTimeout
+        if let intervalTask {
+            // A tick sleeping gets cancelled; one storing finishes first.
+            if intervalIsStoring {
+                await Self.wait(for: intervalTask, upTo: timeout)
+            }
+            intervalTask.cancel()
+        }
+        if let commitTask {
+            commitWakeup.yield()
+            await Self.wait(for: commitTask, upTo: timeout)
+            commitTask.cancel()
+        }
+        if configuration.autoCommit != .disabled {
+            let positions = Array(lastConsumed.values)
+            // One deadline for every final store, as in the Rust SDK.
+            _ = try? await withDeadline(.now + client.configuration.requestTimeout) {
+                await self.storeFinalPositions(positions)
+            }
+        }
+        if isConsumerGroup, joinedGroup {
+            joinedGroup = false
+            do {
+                try await client.leaveConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+            } catch {
+                // Expected after an explicit leave or a deleted group.
+                logger.debug("Failed to leave the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            }
+        }
+        eventsTask?.cancel()
+        eventsTask = nil
+        logger.info("The consumer has been shut down", metadata: metadata)
+    }
+
+    // MARK: Reading
+
+    /// The next message: from the buffer, or from a poll once it is empty.
+    /// Throws what a poll or join ran into, after the retry interval, and can
+    /// be called again after it threw. Nil once the consumer is shut down.
+    public func next() async throws -> ReceivedMessage? {
+        try await reading.lock()
+        defer { reading.unlock() }
+        if isShutDown {
+            return nil
+        }
+        if bufferIndex < buffer.count {
+            return handOverBuffered()
+        }
+        while !isShutDown {
+            try Task.checkCancellation()
+            let polled = try await poll()
+            if !polled.messages.isEmpty, !isShutDown {
+                return handOverPolled(polled)
+            }
+        }
+        return nil
+    }
+
+    /// Hands every message to `handler` until the consumer shuts down, the
+    /// task is cancelled, or an error ends the reading: a client that is shut
+    /// down or cannot come back without the caller, or an invalid address.
+    /// Other errors are logged and reading goes on, and a handler that throws
+    /// is logged too. The ``AutoCommitAfter`` triggers fire here, after the
+    /// handler returned or threw.
+    public func consumeMessages(_ handler: @Sendable (ReceivedMessage) async throws -> Void) async throws {
+        let after = configuration.autoCommit.afterTrigger
+        while true {
+            let received: ReceivedMessage
+            do {
+                guard let next = try await next() else {
+                    return
+                }
+                received = next
+            } catch let error as IggyError {
+                let ends = Self.endsConsumption(error) ? true : !(await client.canRecover)
+                if ends {
+                    logger.error("Reading stopped", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                    throw error
+                }
+                logger.error("Failed to read a message", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                continue
+            }
+            do {
+                try await handler(received)
+            } catch {
+                logger.error(
+                    "The handler failed", metadata: metadata.merging(["offset": "\(received.message.offset)", "error": "\(error)"]) { $1 })
+            }
+            switch after {
+            case .consumingEachMessage?:
+                queueCommit(received.position)
+            case .consumingEveryNthMessage(let n)?:
+                if received.message.offset % UInt64(n) == 0 {
+                    queueCommit(received.position)
+                }
+            case .consumingAllMessages?:
+                if received.message.offset == received.currentOffset {
+                    queueCommit(received.position)
+                }
+            case nil:
+                break
+            }
+        }
+    }
+
+    // MARK: Offsets
+
+    /// Stores `offset` for a partition, the current one when nil, under the
+    /// context of the last message handed over from it. Before any was, it
+    /// is stored without a context.
+    public func storeOffset(_ offset: UInt64, partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        if let last = lastConsumed[partition] {
+            try await storePosition(ConsumerPosition(partitionID: partition, offset: offset, context: last.context))
+            return
+        }
+        try await client.storeConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition, offset: offset)
+        lastStored[partition] = ConsumerPosition(partitionID: partition, offset: offset, context: .empty)
+    }
+
+    /// Stores the exact position delivered, as
+    /// ``ReceivedMessage/position`` gives it, even after later polls. Without
+    /// ``ConsumerConfiguration/allowReplay`` a position at or below the one
+    /// already stored in the same partition history is not sent.
+    public func storePosition(_ position: ConsumerPosition) async throws {
+        try await store(position, allowReplay: configuration.allowReplay)
+    }
+
+    /// Deletes the stored offset of a partition, the current one when nil.
+    /// Unlike the Rust consumer, a group member's nil is not left to the
+    /// server, since the Swift client routes the request by its partition.
+    public func deleteOffset(partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        // A cancelled delete can still have committed, so a later store must
+        // not be skipped as covered.
+        lastStored[partition] = nil
+        try await client.deleteConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition)
+    }
+
+    /// The offset of the last message handed over from the partition.
+    public func lastConsumedOffset(partitionID: UInt32) -> UInt64? {
+        lastConsumed[partitionID]?.offset
+    }
+
+    /// The offset this consumer last stored for the partition.
+    public func lastStoredOffset(partitionID: UInt32) -> UInt64? {
+        lastStored[partitionID]?.offset
+    }
+
+    // MARK: Internals
+
+    private var metadata: Logger.Metadata {
+        ["consumer": "\(name)", "stream": "\(streamID)", "topic": "\(topicID)"]
+    }
+
+    private func waitForStreamAndTopic() async throws {
+        let retries = configuration.initRetries ?? 0
+        var ticker = RetryTicker(interval: configuration.initRetryInterval)
+        try await ticker.tick()
+        var streamExists = try await client.getStream(streamID) != nil
+        var topicExists = false
+        if streamExists {
+            topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+        }
+        var attempt: UInt32 = 0
+        // A stream or topic may still be being created by someone else.
+        while !(streamExists && topicExists), attempt < retries {
+            attempt += 1
+            logger.warning(
+                "The stream or topic does not exist yet, retrying",
+                metadata: metadata.merging(["retry": "\(attempt)/\(retries)", "stream_exists": "\(streamExists)"]) { $1 })
+            try await ticker.tick()
+            if !streamExists {
+                streamExists = try await client.getStream(streamID) != nil
+            }
+            if streamExists {
+                topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+            }
+        }
+        guard streamExists else {
+            throw streamID.name.map { IggyError(.streamNameNotFound, context: "stream \($0) was not found") }
+                ?? IggyError(.streamIdNotFound, context: "stream \(streamID) was not found")
+        }
+        guard topicExists else {
+            throw topicID.name.map { IggyError(.topicNameNotFound, context: "topic \($0) was not found in stream \(streamID)") }
+                ?? IggyError(.topicIdNotFound, context: "topic \(topicID) was not found in stream \(streamID)")
+        }
+    }
+
+    private func joinGroup() async throws {
+        if joinedGroup {
+            return
+        }
+        if try await client.getConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id) == nil {
+            guard configuration.createConsumerGroupIfNotExists else {
+                throw IggyError(.consumerGroupNameNotFound, context: "consumer group \(name) does not exist and auto-creation is disabled")
+            }
+            logger.info("Creating the consumer group", metadata: metadata)
+            do {
+                _ = try await client.createConsumerGroup(streamID: streamID, topicID: topicID, name: name)
+            } catch let error as IggyError where error.code == .consumerGroupNameAlreadyExists {
+                // Another member created it first.
+            }
+        }
+        logger.info("Joining the consumer group", metadata: metadata)
+        try await client.joinConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+        joinedGroup = true
+    }
+
+    /// Returns false once the client shut down, which ends the subscription.
+    private func observe(_ event: DiagnosticEvent) async -> Bool {
+        switch event {
+        case .shutdown:
+            logger.warning("The client has been shut down", metadata: metadata)
+            joinedGroup = false
+            canPoll = false
+            return false
+        case .connected, .disconnected, .signedOut:
+            joinedGroup = false
+        case .signedIn:
+            break
+        }
+        // Events can arrive after one that reports a later state, so the
+        // state of the client decides.
+        canPoll = await client.state == .authenticated
+        return true
+    }
+
+    /// One poll, as the Rust consumer's poll future: the interval wait, the
+    /// sign-in wait, a join when the membership was lost, and the request.
+    /// An empty result is not an error.
+    private func poll() async throws -> PolledMessages {
+        if let pollInterval = configuration.pollInterval, let lastPolledAt {
+            try await Task.sleep(until: lastPolledAt + pollInterval, clock: .continuous)
+        }
+        let retryInterval = configuration.pollingRetryInterval
+        // A client that only the caller brings back never recovers, so the
+        // poll goes on and fails with the reason instead of waiting for good.
+        while !canPoll, await client.canRecover {
+            try await Task.sleep(for: retryInterval)
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup, !joinedGroup {
+            do {
+                try await joinGroup()
+            } catch {
+                logger.error("Failed to join the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                try await Task.sleep(for: retryInterval)
+                throw error
+            }
+        }
+        lastPolledAt = .now
+        let continuations = nextPositions
+        let strategy = configuration.pollingStrategy
+        // A refusal does not name its partition, and it answers the last one
+        // the strategy was asked for.
+        let polledPartition = NIOLockedValueBox(PolledMessages.noAssignedPartition)
+        do {
+            var polled = try await client.pollMessages(
+                streamID: streamID, topicID: topicID, partitionID: partitionID, consumer: consumer, count: configuration.batchLength,
+                autoCommit: configuration.autoCommit.whenTrigger == .pollingMessages
+            ) { partition in
+                polledPartition.withLockedValue { $0 = partition }
+                return continuations[partition].map { .offset($0.offset, context: $0.context) } ?? strategy
+            }
+            if polled.partitionID == PolledMessages.noAssignedPartition {
+                nextPositions.removeAll()
+                try await Task.sleep(for: retryInterval)
+                return polled
+            }
+            if !configuration.allowReplay, let consumed = lastConsumed[polled.partitionID], Self.sameHistory(consumed.context, polled.context) {
+                polled.messages.removeAll { $0.offset <= consumed.offset }
+                polled.count = UInt32(polled.messages.count)
+            }
+            return polled
+        } catch let error as IggyError {
+            if error.code == .historyUnavailable || error.code == .consumerGroupPartitionNotOwned {
+                nextPositions[polledPartition.withLockedValue { $0 }] = nil
+            }
+            logger.error("Failed to poll messages", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            if isConsumerGroup, configuration.autoJoinConsumerGroup, error.code == .consumerGroupMemberNotFound {
+                // The membership was revoked; the next poll joins again.
+                joinedGroup = false
+                return PolledMessages(partitionID: PolledMessages.noAssignedPartition, currentOffset: 0, count: 0, messages: [])
+            }
+            if isConsumerGroup, [.disconnected, .unauthenticated, .staleClient].contains(error.code) {
+                joinedGroup = false
+            }
+            try await Task.sleep(for: retryInterval)
+            throw error
+        }
+    }
+
+    private func handOverPolled(_ polled: PolledMessages) -> ReceivedMessage {
+        let partition = polled.partitionID
+        currentPartitionID = partition
+        buffer = polled.messages
+        bufferIndex = 0
+        bufferedContext = polled.context
+        bufferedCurrentOffset = polled.currentOffset
+        return handOverBuffered()
+    }
+
+    private func handOverBuffered() -> ReceivedMessage {
+        let partition = currentPartitionID
+        let message = buffer[bufferIndex]
+        bufferIndex += 1
+        let position = ConsumerPosition(partitionID: partition, offset: message.offset, context: bufferedContext)
+        lastConsumed[partition] = position
+        let drained = bufferIndex == buffer.count
+        // The strategy only says where a partition starts; the next poll of
+        // it continues after the last message handed over.
+        if configuration.pollingStrategy.kind != .next {

Review Comment:
   simplification: `handOverBuffered` writes `nextPositions` for every message in a batch, while the Rust consumer writes it once when the batch drains. Move the write into the drained branch with the last offset plus one.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {

Review Comment:
   nit: Two `for try await` loops over one consumer split the messages between them. The reading lock serializes calls but does not give the stream to one reader. Document that one reader consumes a consumer, as the Rust SDK does.



##########
foreign/swift/README.md:
##########
@@ -322,6 +323,37 @@ written in order. A topic addressed by name and by numeric id counts as two, and
 failed request does not hold back the ones after it, so a resend from `errorHandler`
 lands behind them.
 
+### Consumer
+
+`IggyConsumer` reads one topic and hands its messages over one at a time. A standalone
+consumer reads one partition; a member of a consumer group reads the partitions the
+server assigns, joining the group in `initialize()`:
+
+```swift
+let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+try await consumer.initialize()
+for try await received in consumer {
+    print(received.partitionID, received.message.offset, received.message.payloadString)
+}
+```
+
+A poll refills the buffer once it runs empty, and each poll of a partition continues

Review Comment:
   nit: The README says each poll continues after the last message handed over. Under the default `.next` strategy the client sends no continuation, and the server's stored offset decides. Name the `.next` exception here, as `ConsumerConfiguration` does.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(swift): add the consumer [iggy]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #4641:
URL: https://github.com/apache/iggy/pull/4641#issuecomment-6395283406

   <!-- iggy-pr-triage-welcome -->
   Thanks for the PR. It is labeled `S-waiting-on-review` and queued for review.
   
   If AI was used to create this PR, you must run the [`team-review` skill](https://github.com/apache/iggy/blob/master/.claude/skills/team-review/SKILL.md) before opening it.
   
   Slash commands (own line, regular comment) move it around the queue:
   
   - `/ready` - back to `S-waiting-on-review` after addressing feedback
   - `/author` - flip to `S-waiting-on-author` while you finish changes
   - `/request-review @user-or-team` - request a reviewer
   - `/pin` - exempt the PR from the stale bot, `/unpin` to undo
   
   See [CONTRIBUTING.md](https://github.com/apache/iggy/blob/master/CONTRIBUTING.md#pr-triage-commands) for details.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(swift): add the consumer [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4641:
URL: https://github.com/apache/iggy/pull/4641#discussion_r4376606649


##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()
+        }
+        guard !isShutDown else {
+            // A shutdown came in meanwhile and already stopped what it found.
+            eventsTask?.cancel()
+            eventsTask = nil
+            return
+        }
+        if let interval = configuration.autoCommit.interval {
+            intervalTask = Task { [weak self] in
+                while (try? await Task.sleep(for: interval)) != nil {
+                    guard let self, await self.storeOnTick() else {
+                        return
+                    }
+                }
+            }
+        }
+        commitTask = Task { [weak self, commitWakeups] in
+            for await _ in commitWakeups {
+                guard let self, await self.sendPendingCommits() else {
+                    return
+                }
+            }
+        }
+        isInitialized = true
+        logger.info("The consumer has been initialized", metadata: metadata)
+    }
+
+    /// Stops reading, sends the queued commits, stores the reading position
+    /// of every partition read unless auto-commit is disabled, and leaves the
+    /// group. Every caller waits for the same shutdown. Failures are logged:
+    /// nothing is left for the caller to undo.
+    public func shutdown() async {
+        if let shutdownTask {
+            await shutdownTask.value
+            return
+        }
+        isShutDown = true
+        let task = Task { await self.drain() }
+        shutdownTask = task
+        await task.value
+    }
+
+    private func drain() async {
+        logger.info("Shutting down the consumer", metadata: metadata)
+        let timeout = configuration.offsetDrainTimeout
+        if let intervalTask {
+            // A tick sleeping gets cancelled; one storing finishes first.
+            if intervalIsStoring {
+                await Self.wait(for: intervalTask, upTo: timeout)
+            }
+            intervalTask.cancel()
+        }
+        if let commitTask {
+            commitWakeup.yield()
+            await Self.wait(for: commitTask, upTo: timeout)
+            commitTask.cancel()
+        }
+        if configuration.autoCommit != .disabled {
+            let positions = Array(lastConsumed.values)
+            // One deadline for every final store, as in the Rust SDK.
+            _ = try? await withDeadline(.now + client.configuration.requestTimeout) {
+                await self.storeFinalPositions(positions)
+            }
+        }
+        if isConsumerGroup, joinedGroup {
+            joinedGroup = false
+            do {
+                try await client.leaveConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+            } catch {
+                // Expected after an explicit leave or a deleted group.
+                logger.debug("Failed to leave the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            }
+        }
+        eventsTask?.cancel()
+        eventsTask = nil
+        logger.info("The consumer has been shut down", metadata: metadata)
+    }
+
+    // MARK: Reading
+
+    /// The next message: from the buffer, or from a poll once it is empty.
+    /// Throws what a poll or join ran into, after the retry interval, and can
+    /// be called again after it threw. Nil once the consumer is shut down.
+    public func next() async throws -> ReceivedMessage? {
+        try await reading.lock()
+        defer { reading.unlock() }
+        if isShutDown {
+            return nil
+        }
+        if bufferIndex < buffer.count {
+            return handOverBuffered()
+        }
+        while !isShutDown {
+            try Task.checkCancellation()
+            let polled = try await poll()
+            if !polled.messages.isEmpty, !isShutDown {
+                return handOverPolled(polled)
+            }
+        }
+        return nil
+    }
+
+    /// Hands every message to `handler` until the consumer shuts down, the
+    /// task is cancelled, or an error ends the reading: a client that is shut
+    /// down or cannot come back without the caller, or an invalid address.
+    /// Other errors are logged and reading goes on, and a handler that throws
+    /// is logged too. The ``AutoCommitAfter`` triggers fire here, after the
+    /// handler returned or threw.
+    public func consumeMessages(_ handler: @Sendable (ReceivedMessage) async throws -> Void) async throws {
+        let after = configuration.autoCommit.afterTrigger
+        while true {
+            let received: ReceivedMessage
+            do {
+                guard let next = try await next() else {
+                    return
+                }
+                received = next
+            } catch let error as IggyError {
+                let ends = Self.endsConsumption(error) ? true : !(await client.canRecover)
+                if ends {
+                    logger.error("Reading stopped", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                    throw error
+                }
+                logger.error("Failed to read a message", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                continue
+            }
+            do {
+                try await handler(received)
+            } catch {
+                logger.error(
+                    "The handler failed", metadata: metadata.merging(["offset": "\(received.message.offset)", "error": "\(error)"]) { $1 })
+            }
+            switch after {
+            case .consumingEachMessage?:
+                queueCommit(received.position)
+            case .consumingEveryNthMessage(let n)?:
+                if received.message.offset % UInt64(n) == 0 {
+                    queueCommit(received.position)
+                }
+            case .consumingAllMessages?:
+                if received.message.offset == received.currentOffset {
+                    queueCommit(received.position)
+                }
+            case nil:
+                break
+            }
+        }
+    }
+
+    // MARK: Offsets
+
+    /// Stores `offset` for a partition, the current one when nil, under the
+    /// context of the last message handed over from it. Before any was, it
+    /// is stored without a context.
+    public func storeOffset(_ offset: UInt64, partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        if let last = lastConsumed[partition] {
+            try await storePosition(ConsumerPosition(partitionID: partition, offset: offset, context: last.context))
+            return
+        }
+        try await client.storeConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition, offset: offset)
+        lastStored[partition] = ConsumerPosition(partitionID: partition, offset: offset, context: .empty)
+    }
+
+    /// Stores the exact position delivered, as
+    /// ``ReceivedMessage/position`` gives it, even after later polls. Without
+    /// ``ConsumerConfiguration/allowReplay`` a position at or below the one
+    /// already stored in the same partition history is not sent.
+    public func storePosition(_ position: ConsumerPosition) async throws {
+        try await store(position, allowReplay: configuration.allowReplay)
+    }
+
+    /// Deletes the stored offset of a partition, the current one when nil.
+    /// Unlike the Rust consumer, a group member's nil is not left to the
+    /// server, since the Swift client routes the request by its partition.
+    public func deleteOffset(partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        // A cancelled delete can still have committed, so a later store must
+        // not be skipped as covered.
+        lastStored[partition] = nil
+        try await client.deleteConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition)
+    }
+
+    /// The offset of the last message handed over from the partition.
+    public func lastConsumedOffset(partitionID: UInt32) -> UInt64? {
+        lastConsumed[partitionID]?.offset
+    }
+
+    /// The offset this consumer last stored for the partition.
+    public func lastStoredOffset(partitionID: UInt32) -> UInt64? {
+        lastStored[partitionID]?.offset
+    }
+
+    // MARK: Internals
+
+    private var metadata: Logger.Metadata {
+        ["consumer": "\(name)", "stream": "\(streamID)", "topic": "\(topicID)"]
+    }
+
+    private func waitForStreamAndTopic() async throws {
+        let retries = configuration.initRetries ?? 0
+        var ticker = RetryTicker(interval: configuration.initRetryInterval)
+        try await ticker.tick()
+        var streamExists = try await client.getStream(streamID) != nil
+        var topicExists = false
+        if streamExists {
+            topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+        }
+        var attempt: UInt32 = 0
+        // A stream or topic may still be being created by someone else.
+        while !(streamExists && topicExists), attempt < retries {
+            attempt += 1
+            logger.warning(
+                "The stream or topic does not exist yet, retrying",
+                metadata: metadata.merging(["retry": "\(attempt)/\(retries)", "stream_exists": "\(streamExists)"]) { $1 })
+            try await ticker.tick()
+            if !streamExists {
+                streamExists = try await client.getStream(streamID) != nil
+            }
+            if streamExists {
+                topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+            }
+        }
+        guard streamExists else {
+            throw streamID.name.map { IggyError(.streamNameNotFound, context: "stream \($0) was not found") }
+                ?? IggyError(.streamIdNotFound, context: "stream \(streamID) was not found")
+        }
+        guard topicExists else {
+            throw topicID.name.map { IggyError(.topicNameNotFound, context: "topic \($0) was not found in stream \(streamID)") }
+                ?? IggyError(.topicIdNotFound, context: "topic \(topicID) was not found in stream \(streamID)")
+        }
+    }
+
+    private func joinGroup() async throws {
+        if joinedGroup {
+            return
+        }
+        if try await client.getConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id) == nil {
+            guard configuration.createConsumerGroupIfNotExists else {
+                throw IggyError(.consumerGroupNameNotFound, context: "consumer group \(name) does not exist and auto-creation is disabled")
+            }
+            logger.info("Creating the consumer group", metadata: metadata)
+            do {
+                _ = try await client.createConsumerGroup(streamID: streamID, topicID: topicID, name: name)
+            } catch let error as IggyError where error.code == .consumerGroupNameAlreadyExists {
+                // Another member created it first.
+            }
+        }
+        logger.info("Joining the consumer group", metadata: metadata)
+        try await client.joinConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+        joinedGroup = true
+    }
+
+    /// Returns false once the client shut down, which ends the subscription.
+    private func observe(_ event: DiagnosticEvent) async -> Bool {
+        switch event {
+        case .shutdown:
+            logger.warning("The client has been shut down", metadata: metadata)
+            joinedGroup = false
+            canPoll = false
+            return false
+        case .connected, .disconnected, .signedOut:
+            joinedGroup = false
+        case .signedIn:
+            break
+        }
+        // Events can arrive after one that reports a later state, so the
+        // state of the client decides.
+        canPoll = await client.state == .authenticated
+        return true
+    }
+
+    /// One poll, as the Rust consumer's poll future: the interval wait, the
+    /// sign-in wait, a join when the membership was lost, and the request.
+    /// An empty result is not an error.
+    private func poll() async throws -> PolledMessages {
+        if let pollInterval = configuration.pollInterval, let lastPolledAt {
+            try await Task.sleep(until: lastPolledAt + pollInterval, clock: .continuous)
+        }
+        let retryInterval = configuration.pollingRetryInterval
+        // A client that only the caller brings back never recovers, so the
+        // poll goes on and fails with the reason instead of waiting for good.
+        while !canPoll, await client.canRecover {

Review Comment:
   critical: with heartbeats and auto-commit disabled, a lost poll can leave this loop waiting forever without triggering reconnection. call `client.requireAuthenticated()` during recovery and exit when the consumer shuts down.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()
+        }
+        guard !isShutDown else {
+            // A shutdown came in meanwhile and already stopped what it found.
+            eventsTask?.cancel()
+            eventsTask = nil
+            return
+        }
+        if let interval = configuration.autoCommit.interval {
+            intervalTask = Task { [weak self] in
+                while (try? await Task.sleep(for: interval)) != nil {
+                    guard let self, await self.storeOnTick() else {
+                        return
+                    }
+                }
+            }
+        }
+        commitTask = Task { [weak self, commitWakeups] in
+            for await _ in commitWakeups {
+                guard let self, await self.sendPendingCommits() else {
+                    return
+                }
+            }
+        }
+        isInitialized = true
+        logger.info("The consumer has been initialized", metadata: metadata)
+    }
+
+    /// Stops reading, sends the queued commits, stores the reading position
+    /// of every partition read unless auto-commit is disabled, and leaves the
+    /// group. Every caller waits for the same shutdown. Failures are logged:
+    /// nothing is left for the caller to undo.
+    public func shutdown() async {
+        if let shutdownTask {
+            await shutdownTask.value
+            return
+        }
+        isShutDown = true
+        let task = Task { await self.drain() }
+        shutdownTask = task
+        await task.value
+    }
+
+    private func drain() async {
+        logger.info("Shutting down the consumer", metadata: metadata)
+        let timeout = configuration.offsetDrainTimeout
+        if let intervalTask {
+            // A tick sleeping gets cancelled; one storing finishes first.
+            if intervalIsStoring {
+                await Self.wait(for: intervalTask, upTo: timeout)
+            }
+            intervalTask.cancel()
+        }
+        if let commitTask {
+            commitWakeup.yield()
+            await Self.wait(for: commitTask, upTo: timeout)
+            commitTask.cancel()
+        }
+        if configuration.autoCommit != .disabled {
+            let positions = Array(lastConsumed.values)
+            // One deadline for every final store, as in the Rust SDK.
+            _ = try? await withDeadline(.now + client.configuration.requestTimeout) {
+                await self.storeFinalPositions(positions)
+            }
+        }
+        if isConsumerGroup, joinedGroup {
+            joinedGroup = false
+            do {
+                try await client.leaveConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+            } catch {
+                // Expected after an explicit leave or a deleted group.
+                logger.debug("Failed to leave the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            }
+        }
+        eventsTask?.cancel()
+        eventsTask = nil
+        logger.info("The consumer has been shut down", metadata: metadata)
+    }
+
+    // MARK: Reading
+
+    /// The next message: from the buffer, or from a poll once it is empty.
+    /// Throws what a poll or join ran into, after the retry interval, and can
+    /// be called again after it threw. Nil once the consumer is shut down.
+    public func next() async throws -> ReceivedMessage? {
+        try await reading.lock()
+        defer { reading.unlock() }
+        if isShutDown {
+            return nil
+        }
+        if bufferIndex < buffer.count {
+            return handOverBuffered()
+        }
+        while !isShutDown {
+            try Task.checkCancellation()
+            let polled = try await poll()
+            if !polled.messages.isEmpty, !isShutDown {
+                return handOverPolled(polled)
+            }
+        }
+        return nil
+    }
+
+    /// Hands every message to `handler` until the consumer shuts down, the
+    /// task is cancelled, or an error ends the reading: a client that is shut
+    /// down or cannot come back without the caller, or an invalid address.
+    /// Other errors are logged and reading goes on, and a handler that throws
+    /// is logged too. The ``AutoCommitAfter`` triggers fire here, after the
+    /// handler returned or threw.
+    public func consumeMessages(_ handler: @Sendable (ReceivedMessage) async throws -> Void) async throws {
+        let after = configuration.autoCommit.afterTrigger
+        while true {
+            let received: ReceivedMessage
+            do {
+                guard let next = try await next() else {
+                    return
+                }
+                received = next
+            } catch let error as IggyError {
+                let ends = Self.endsConsumption(error) ? true : !(await client.canRecover)
+                if ends {
+                    logger.error("Reading stopped", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                    throw error
+                }
+                logger.error("Failed to read a message", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                continue
+            }
+            do {
+                try await handler(received)
+            } catch {
+                logger.error(
+                    "The handler failed", metadata: metadata.merging(["offset": "\(received.message.offset)", "error": "\(error)"]) { $1 })
+            }
+            switch after {
+            case .consumingEachMessage?:
+                queueCommit(received.position)
+            case .consumingEveryNthMessage(let n)?:
+                if received.message.offset % UInt64(n) == 0 {
+                    queueCommit(received.position)
+                }
+            case .consumingAllMessages?:
+                if received.message.offset == received.currentOffset {
+                    queueCommit(received.position)
+                }
+            case nil:
+                break
+            }
+        }
+    }
+
+    // MARK: Offsets
+
+    /// Stores `offset` for a partition, the current one when nil, under the
+    /// context of the last message handed over from it. Before any was, it
+    /// is stored without a context.
+    public func storeOffset(_ offset: UInt64, partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        if let last = lastConsumed[partition] {
+            try await storePosition(ConsumerPosition(partitionID: partition, offset: offset, context: last.context))
+            return
+        }
+        try await client.storeConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition, offset: offset)
+        lastStored[partition] = ConsumerPosition(partitionID: partition, offset: offset, context: .empty)
+    }
+
+    /// Stores the exact position delivered, as
+    /// ``ReceivedMessage/position`` gives it, even after later polls. Without
+    /// ``ConsumerConfiguration/allowReplay`` a position at or below the one
+    /// already stored in the same partition history is not sent.
+    public func storePosition(_ position: ConsumerPosition) async throws {
+        try await store(position, allowReplay: configuration.allowReplay)
+    }
+
+    /// Deletes the stored offset of a partition, the current one when nil.
+    /// Unlike the Rust consumer, a group member's nil is not left to the
+    /// server, since the Swift client routes the request by its partition.
+    public func deleteOffset(partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        // A cancelled delete can still have committed, so a later store must
+        // not be skipped as covered.
+        lastStored[partition] = nil
+        try await client.deleteConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition)
+    }
+
+    /// The offset of the last message handed over from the partition.
+    public func lastConsumedOffset(partitionID: UInt32) -> UInt64? {
+        lastConsumed[partitionID]?.offset
+    }
+
+    /// The offset this consumer last stored for the partition.
+    public func lastStoredOffset(partitionID: UInt32) -> UInt64? {
+        lastStored[partitionID]?.offset
+    }
+
+    // MARK: Internals
+
+    private var metadata: Logger.Metadata {
+        ["consumer": "\(name)", "stream": "\(streamID)", "topic": "\(topicID)"]
+    }
+
+    private func waitForStreamAndTopic() async throws {
+        let retries = configuration.initRetries ?? 0
+        var ticker = RetryTicker(interval: configuration.initRetryInterval)
+        try await ticker.tick()
+        var streamExists = try await client.getStream(streamID) != nil
+        var topicExists = false
+        if streamExists {
+            topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+        }
+        var attempt: UInt32 = 0
+        // A stream or topic may still be being created by someone else.
+        while !(streamExists && topicExists), attempt < retries {
+            attempt += 1
+            logger.warning(
+                "The stream or topic does not exist yet, retrying",
+                metadata: metadata.merging(["retry": "\(attempt)/\(retries)", "stream_exists": "\(streamExists)"]) { $1 })
+            try await ticker.tick()
+            if !streamExists {
+                streamExists = try await client.getStream(streamID) != nil
+            }
+            if streamExists {
+                topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+            }
+        }
+        guard streamExists else {
+            throw streamID.name.map { IggyError(.streamNameNotFound, context: "stream \($0) was not found") }
+                ?? IggyError(.streamIdNotFound, context: "stream \(streamID) was not found")
+        }
+        guard topicExists else {
+            throw topicID.name.map { IggyError(.topicNameNotFound, context: "topic \($0) was not found in stream \(streamID)") }
+                ?? IggyError(.topicIdNotFound, context: "topic \(topicID) was not found in stream \(streamID)")
+        }
+    }
+
+    private func joinGroup() async throws {
+        if joinedGroup {
+            return
+        }
+        if try await client.getConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id) == nil {
+            guard configuration.createConsumerGroupIfNotExists else {
+                throw IggyError(.consumerGroupNameNotFound, context: "consumer group \(name) does not exist and auto-creation is disabled")
+            }
+            logger.info("Creating the consumer group", metadata: metadata)
+            do {
+                _ = try await client.createConsumerGroup(streamID: streamID, topicID: topicID, name: name)
+            } catch let error as IggyError where error.code == .consumerGroupNameAlreadyExists {
+                // Another member created it first.
+            }
+        }
+        logger.info("Joining the consumer group", metadata: metadata)
+        try await client.joinConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+        joinedGroup = true
+    }
+
+    /// Returns false once the client shut down, which ends the subscription.
+    private func observe(_ event: DiagnosticEvent) async -> Bool {
+        switch event {
+        case .shutdown:
+            logger.warning("The client has been shut down", metadata: metadata)
+            joinedGroup = false
+            canPoll = false
+            return false
+        case .connected, .disconnected, .signedOut:
+            joinedGroup = false
+        case .signedIn:
+            break
+        }
+        // Events can arrive after one that reports a later state, so the
+        // state of the client decides.
+        canPoll = await client.state == .authenticated
+        return true
+    }
+
+    /// One poll, as the Rust consumer's poll future: the interval wait, the
+    /// sign-in wait, a join when the membership was lost, and the request.
+    /// An empty result is not an error.
+    private func poll() async throws -> PolledMessages {
+        if let pollInterval = configuration.pollInterval, let lastPolledAt {
+            try await Task.sleep(until: lastPolledAt + pollInterval, clock: .continuous)
+        }
+        let retryInterval = configuration.pollingRetryInterval
+        // A client that only the caller brings back never recovers, so the
+        // poll goes on and fails with the reason instead of waiting for good.
+        while !canPoll, await client.canRecover {
+            try await Task.sleep(for: retryInterval)
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup, !joinedGroup {
+            do {
+                try await joinGroup()
+            } catch {
+                logger.error("Failed to join the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                try await Task.sleep(for: retryInterval)
+                throw error
+            }
+        }
+        lastPolledAt = .now
+        let continuations = nextPositions
+        let strategy = configuration.pollingStrategy
+        // A refusal does not name its partition, and it answers the last one
+        // the strategy was asked for.
+        let polledPartition = NIOLockedValueBox(PolledMessages.noAssignedPartition)
+        do {
+            var polled = try await client.pollMessages(
+                streamID: streamID, topicID: topicID, partitionID: partitionID, consumer: consumer, count: configuration.batchLength,
+                autoCommit: configuration.autoCommit.whenTrigger == .pollingMessages
+            ) { partition in
+                polledPartition.withLockedValue { $0 = partition }
+                return continuations[partition].map { .offset($0.offset, context: $0.context) } ?? strategy
+            }
+            if polled.partitionID == PolledMessages.noAssignedPartition {
+                nextPositions.removeAll()
+                try await Task.sleep(for: retryInterval)
+                return polled
+            }
+            if !configuration.allowReplay, let consumed = lastConsumed[polled.partitionID], Self.sameHistory(consumed.context, polled.context) {
+                polled.messages.removeAll { $0.offset <= consumed.offset }
+                polled.count = UInt32(polled.messages.count)
+            }
+            return polled
+        } catch let error as IggyError {
+            if error.code == .historyUnavailable || error.code == .consumerGroupPartitionNotOwned {
+                nextPositions[polledPartition.withLockedValue { $0 }] = nil
+            }
+            logger.error("Failed to poll messages", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            if isConsumerGroup, configuration.autoJoinConsumerGroup, error.code == .consumerGroupMemberNotFound {
+                // The membership was revoked; the next poll joins again.
+                joinedGroup = false
+                return PolledMessages(partitionID: PolledMessages.noAssignedPartition, currentOffset: 0, count: 0, messages: [])
+            }
+            if isConsumerGroup, [.disconnected, .unauthenticated, .staleClient].contains(error.code) {
+                joinedGroup = false
+            }
+            try await Task.sleep(for: retryInterval)
+            throw error
+        }
+    }
+
+    private func handOverPolled(_ polled: PolledMessages) -> ReceivedMessage {
+        let partition = polled.partitionID
+        currentPartitionID = partition
+        buffer = polled.messages
+        bufferIndex = 0
+        bufferedContext = polled.context
+        bufferedCurrentOffset = polled.currentOffset
+        return handOverBuffered()
+    }
+
+    private func handOverBuffered() -> ReceivedMessage {
+        let partition = currentPartitionID
+        let message = buffer[bufferIndex]
+        bufferIndex += 1
+        let position = ConsumerPosition(partitionID: partition, offset: message.offset, context: bufferedContext)
+        lastConsumed[partition] = position
+        let drained = bufferIndex == buffer.count
+        // The strategy only says where a partition starts; the next poll of
+        // it continues after the last message handed over.
+        if configuration.pollingStrategy.kind != .next {
+            nextPositions[partition] = ConsumerPosition(partitionID: partition, offset: message.offset + 1, context: bufferedContext)
+        }
+        switch configuration.autoCommit.whenTrigger {
+        case .consumingEachMessage?:
+            queueCommit(position)
+        case .consumingEveryNthMessage(let n)?:
+            if message.offset % UInt64(n) == 0 {
+                queueCommit(position)
+            }
+        case .consumingAllMessages?:
+            if drained {
+                queueCommit(position)
+            }
+        case .pollingMessages?, nil:
+            break
+        }
+        let received = ReceivedMessage(message: message, currentOffset: bufferedCurrentOffset, partitionID: partition, context: bufferedContext)
+        if drained {
+            buffer.removeAll(keepingCapacity: true)
+            bufferIndex = 0
+        }
+        return received
+    }
+
+    /// Queues a commit for the commit task. A later one for the same
+    /// partition replaces a queued one not sent yet.
+    private func queueCommit(_ position: ConsumerPosition) {
+        guard isInitialized, !isShutDown else {
+            logger.error("The commit was not queued because the consumer is not running", metadata: metadata)
+            return
+        }
+        pendingCommits[position.partitionID] = position
+        commitWakeup.yield()
+    }
+
+    /// Sends the queued commits. Returns false once the consumer is shut
+    /// down and nothing is left, which ends the commit task.
+    private func sendPendingCommits() async -> Bool {
+        while let partition = pendingCommits.keys.first, let position = pendingCommits.removeValue(forKey: partition) {
+            await storeInBackground(position)
+        }
+        return !isShutDown
+    }
+
+    /// Returns false once the consumer is shut down, which ends the interval
+    /// task before it stores anything more.
+    private func storeOnTick() async -> Bool {
+        guard !isShutDown else {
+            return false
+        }
+        intervalIsStoring = true
+        defer { intervalIsStoring = false }
+        for position in lastConsumed.values {
+            await storeInBackground(position)
+        }
+        return true
+    }
+
+    private func storeFinalPositions(_ positions: [ConsumerPosition]) async {
+        for position in positions {
+            do {
+                try await store(position, allowReplay: false)
+            } catch {
+                logger.warning(
+                    "The final checkpoint was not acknowledged",
+                    metadata: metadata.merging(["partition": "\(position.partitionID)", "offset": "\(position.offset)", "error": "\(error)"]) { $1 })
+            }
+        }
+    }
+
+    /// Background commits have no caller to report to, so a failure is
+    /// logged. They never move a stored offset back: replay governs reading.
+    private func storeInBackground(_ position: ConsumerPosition) async {
+        do {
+            try await store(position, allowReplay: false)
+        } catch {
+            logger.error(
+                "Failed to store the offset",
+                metadata: metadata.merging(["partition": "\(position.partitionID)", "offset": "\(position.offset)", "error": "\(error)"]) { $1 })
+        }
+    }
+
+    private func store(_ position: ConsumerPosition, allowReplay: Bool) async throws {
+        if !allowReplay, storedPositionCovers(position) {
+            return
+        }
+        try await client.storeConsumerPosition(consumer: consumer, streamID: streamID, topicID: topicID, position: position)
+        lastStored[position.partitionID] = position
+    }
+
+    /// A store without a context proves nothing about a partition history.
+    private func storedPositionCovers(_ position: ConsumerPosition) -> Bool {
+        guard let stored = lastStored[position.partitionID], stored.context.incarnation != 0, position.context.incarnation != 0 else {
+            return false
+        }
+        return Self.sameHistory(stored.context, position.context) && position.offset <= stored.offset
+    }
+
+    /// Offsets compare only within one incarnation and owner. The metadata
+    /// frontier is left out: another group's change can move it between two
+    /// polls of the same partition.
+    static func sameHistory(_ left: PartitionContext, _ right: PartitionContext) -> Bool {
+        left.incarnation == right.incarnation && left.ownerGeneration == right.ownerGeneration
+    }
+
+    static func endsConsumption(_ error: IggyError) -> Bool {
+        switch error.code {
+        case .invalidServerAddress, .invalidClientAddress, .clientShutdown: true
+        default: false
+        }
+    }
+
+    private static func wait(for task: Task<Void, Never>, upTo timeout: Duration) async {

Review Comment:
   critical: canceling the `task.value` waiter does not cancel the original task, so shutdown can outlast `offsetDrainTimeout` by a full commit interval. cancel the original task at the deadline, then await it.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {

Review Comment:
   warning: this iterator can return messages after throwing an error, which violates the `AsyncIteratorProtocol` contract. mark each iterator finished after its first error or `nil`, and return `nil` on subsequent calls.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()

Review Comment:
   critical: initialization can join the group after `shutdown()` returns, leaving partitions assigned to a closed consumer. coordinate initialization with shutdown so every successful join completes before the final leave.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()
+        }
+        guard !isShutDown else {
+            // A shutdown came in meanwhile and already stopped what it found.
+            eventsTask?.cancel()
+            eventsTask = nil
+            return
+        }
+        if let interval = configuration.autoCommit.interval {
+            intervalTask = Task { [weak self] in
+                while (try? await Task.sleep(for: interval)) != nil {
+                    guard let self, await self.storeOnTick() else {
+                        return
+                    }
+                }
+            }
+        }
+        commitTask = Task { [weak self, commitWakeups] in
+            for await _ in commitWakeups {
+                guard let self, await self.sendPendingCommits() else {
+                    return
+                }
+            }
+        }
+        isInitialized = true
+        logger.info("The consumer has been initialized", metadata: metadata)
+    }
+
+    /// Stops reading, sends the queued commits, stores the reading position
+    /// of every partition read unless auto-commit is disabled, and leaves the
+    /// group. Every caller waits for the same shutdown. Failures are logged:
+    /// nothing is left for the caller to undo.
+    public func shutdown() async {
+        if let shutdownTask {
+            await shutdownTask.value
+            return
+        }
+        isShutDown = true
+        let task = Task { await self.drain() }
+        shutdownTask = task
+        await task.value
+    }
+
+    private func drain() async {
+        logger.info("Shutting down the consumer", metadata: metadata)
+        let timeout = configuration.offsetDrainTimeout
+        if let intervalTask {
+            // A tick sleeping gets cancelled; one storing finishes first.
+            if intervalIsStoring {
+                await Self.wait(for: intervalTask, upTo: timeout)
+            }
+            intervalTask.cancel()
+        }
+        if let commitTask {
+            commitWakeup.yield()
+            await Self.wait(for: commitTask, upTo: timeout)
+            commitTask.cancel()
+        }
+        if configuration.autoCommit != .disabled {
+            let positions = Array(lastConsumed.values)
+            // One deadline for every final store, as in the Rust SDK.
+            _ = try? await withDeadline(.now + client.configuration.requestTimeout) {
+                await self.storeFinalPositions(positions)
+            }
+        }
+        if isConsumerGroup, joinedGroup {
+            joinedGroup = false
+            do {
+                try await client.leaveConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+            } catch {
+                // Expected after an explicit leave or a deleted group.
+                logger.debug("Failed to leave the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            }
+        }
+        eventsTask?.cancel()
+        eventsTask = nil
+        logger.info("The consumer has been shut down", metadata: metadata)
+    }
+
+    // MARK: Reading
+
+    /// The next message: from the buffer, or from a poll once it is empty.
+    /// Throws what a poll or join ran into, after the retry interval, and can
+    /// be called again after it threw. Nil once the consumer is shut down.
+    public func next() async throws -> ReceivedMessage? {
+        try await reading.lock()
+        defer { reading.unlock() }
+        if isShutDown {
+            return nil
+        }
+        if bufferIndex < buffer.count {
+            return handOverBuffered()
+        }
+        while !isShutDown {
+            try Task.checkCancellation()
+            let polled = try await poll()
+            if !polled.messages.isEmpty, !isShutDown {
+                return handOverPolled(polled)
+            }
+        }
+        return nil
+    }
+
+    /// Hands every message to `handler` until the consumer shuts down, the
+    /// task is cancelled, or an error ends the reading: a client that is shut
+    /// down or cannot come back without the caller, or an invalid address.
+    /// Other errors are logged and reading goes on, and a handler that throws
+    /// is logged too. The ``AutoCommitAfter`` triggers fire here, after the
+    /// handler returned or threw.
+    public func consumeMessages(_ handler: @Sendable (ReceivedMessage) async throws -> Void) async throws {
+        let after = configuration.autoCommit.afterTrigger
+        while true {
+            let received: ReceivedMessage
+            do {
+                guard let next = try await next() else {
+                    return
+                }
+                received = next
+            } catch let error as IggyError {
+                let ends = Self.endsConsumption(error) ? true : !(await client.canRecover)
+                if ends {
+                    logger.error("Reading stopped", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                    throw error
+                }
+                logger.error("Failed to read a message", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                continue
+            }
+            do {
+                try await handler(received)
+            } catch {
+                logger.error(
+                    "The handler failed", metadata: metadata.merging(["offset": "\(received.message.offset)", "error": "\(error)"]) { $1 })
+            }
+            switch after {
+            case .consumingEachMessage?:
+                queueCommit(received.position)
+            case .consumingEveryNthMessage(let n)?:
+                if received.message.offset % UInt64(n) == 0 {
+                    queueCommit(received.position)
+                }
+            case .consumingAllMessages?:
+                if received.message.offset == received.currentOffset {
+                    queueCommit(received.position)
+                }
+            case nil:
+                break
+            }
+        }
+    }
+
+    // MARK: Offsets
+
+    /// Stores `offset` for a partition, the current one when nil, under the
+    /// context of the last message handed over from it. Before any was, it
+    /// is stored without a context.
+    public func storeOffset(_ offset: UInt64, partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        if let last = lastConsumed[partition] {
+            try await storePosition(ConsumerPosition(partitionID: partition, offset: offset, context: last.context))
+            return
+        }
+        try await client.storeConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition, offset: offset)
+        lastStored[partition] = ConsumerPosition(partitionID: partition, offset: offset, context: .empty)
+    }
+
+    /// Stores the exact position delivered, as
+    /// ``ReceivedMessage/position`` gives it, even after later polls. Without
+    /// ``ConsumerConfiguration/allowReplay`` a position at or below the one
+    /// already stored in the same partition history is not sent.
+    public func storePosition(_ position: ConsumerPosition) async throws {
+        try await store(position, allowReplay: configuration.allowReplay)
+    }
+
+    /// Deletes the stored offset of a partition, the current one when nil.
+    /// Unlike the Rust consumer, a group member's nil is not left to the
+    /// server, since the Swift client routes the request by its partition.
+    public func deleteOffset(partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        // A cancelled delete can still have committed, so a later store must
+        // not be skipped as covered.
+        lastStored[partition] = nil
+        try await client.deleteConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition)
+    }
+
+    /// The offset of the last message handed over from the partition.
+    public func lastConsumedOffset(partitionID: UInt32) -> UInt64? {
+        lastConsumed[partitionID]?.offset
+    }
+
+    /// The offset this consumer last stored for the partition.
+    public func lastStoredOffset(partitionID: UInt32) -> UInt64? {
+        lastStored[partitionID]?.offset
+    }
+
+    // MARK: Internals
+
+    private var metadata: Logger.Metadata {
+        ["consumer": "\(name)", "stream": "\(streamID)", "topic": "\(topicID)"]
+    }
+
+    private func waitForStreamAndTopic() async throws {
+        let retries = configuration.initRetries ?? 0
+        var ticker = RetryTicker(interval: configuration.initRetryInterval)
+        try await ticker.tick()
+        var streamExists = try await client.getStream(streamID) != nil
+        var topicExists = false
+        if streamExists {
+            topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+        }
+        var attempt: UInt32 = 0
+        // A stream or topic may still be being created by someone else.
+        while !(streamExists && topicExists), attempt < retries {
+            attempt += 1
+            logger.warning(
+                "The stream or topic does not exist yet, retrying",
+                metadata: metadata.merging(["retry": "\(attempt)/\(retries)", "stream_exists": "\(streamExists)"]) { $1 })
+            try await ticker.tick()
+            if !streamExists {
+                streamExists = try await client.getStream(streamID) != nil
+            }
+            if streamExists {
+                topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+            }
+        }
+        guard streamExists else {
+            throw streamID.name.map { IggyError(.streamNameNotFound, context: "stream \($0) was not found") }
+                ?? IggyError(.streamIdNotFound, context: "stream \(streamID) was not found")
+        }
+        guard topicExists else {
+            throw topicID.name.map { IggyError(.topicNameNotFound, context: "topic \($0) was not found in stream \(streamID)") }
+                ?? IggyError(.topicIdNotFound, context: "topic \(topicID) was not found in stream \(streamID)")
+        }
+    }
+
+    private func joinGroup() async throws {
+        if joinedGroup {
+            return
+        }
+        if try await client.getConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id) == nil {
+            guard configuration.createConsumerGroupIfNotExists else {
+                throw IggyError(.consumerGroupNameNotFound, context: "consumer group \(name) does not exist and auto-creation is disabled")
+            }
+            logger.info("Creating the consumer group", metadata: metadata)
+            do {
+                _ = try await client.createConsumerGroup(streamID: streamID, topicID: topicID, name: name)
+            } catch let error as IggyError where error.code == .consumerGroupNameAlreadyExists {
+                // Another member created it first.
+            }
+        }
+        logger.info("Joining the consumer group", metadata: metadata)
+        try await client.joinConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+        joinedGroup = true
+    }
+
+    /// Returns false once the client shut down, which ends the subscription.
+    private func observe(_ event: DiagnosticEvent) async -> Bool {
+        switch event {
+        case .shutdown:
+            logger.warning("The client has been shut down", metadata: metadata)
+            joinedGroup = false
+            canPoll = false
+            return false
+        case .connected, .disconnected, .signedOut:
+            joinedGroup = false
+        case .signedIn:
+            break
+        }
+        // Events can arrive after one that reports a later state, so the
+        // state of the client decides.
+        canPoll = await client.state == .authenticated
+        return true
+    }
+
+    /// One poll, as the Rust consumer's poll future: the interval wait, the
+    /// sign-in wait, a join when the membership was lost, and the request.
+    /// An empty result is not an error.
+    private func poll() async throws -> PolledMessages {
+        if let pollInterval = configuration.pollInterval, let lastPolledAt {
+            try await Task.sleep(until: lastPolledAt + pollInterval, clock: .continuous)
+        }
+        let retryInterval = configuration.pollingRetryInterval
+        // A client that only the caller brings back never recovers, so the
+        // poll goes on and fails with the reason instead of waiting for good.
+        while !canPoll, await client.canRecover {
+            try await Task.sleep(for: retryInterval)
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup, !joinedGroup {
+            do {
+                try await joinGroup()
+            } catch {
+                logger.error("Failed to join the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                try await Task.sleep(for: retryInterval)
+                throw error
+            }
+        }
+        lastPolledAt = .now
+        let continuations = nextPositions
+        let strategy = configuration.pollingStrategy
+        // A refusal does not name its partition, and it answers the last one
+        // the strategy was asked for.
+        let polledPartition = NIOLockedValueBox(PolledMessages.noAssignedPartition)
+        do {
+            var polled = try await client.pollMessages(
+                streamID: streamID, topicID: topicID, partitionID: partitionID, consumer: consumer, count: configuration.batchLength,
+                autoCommit: configuration.autoCommit.whenTrigger == .pollingMessages
+            ) { partition in
+                polledPartition.withLockedValue { $0 = partition }
+                return continuations[partition].map { .offset($0.offset, context: $0.context) } ?? strategy
+            }
+            if polled.partitionID == PolledMessages.noAssignedPartition {
+                nextPositions.removeAll()
+                try await Task.sleep(for: retryInterval)
+                return polled
+            }
+            if !configuration.allowReplay, let consumed = lastConsumed[polled.partitionID], Self.sameHistory(consumed.context, polled.context) {
+                polled.messages.removeAll { $0.offset <= consumed.offset }
+                polled.count = UInt32(polled.messages.count)
+            }
+            return polled
+        } catch let error as IggyError {
+            if error.code == .historyUnavailable || error.code == .consumerGroupPartitionNotOwned {
+                nextPositions[polledPartition.withLockedValue { $0 }] = nil
+            }
+            logger.error("Failed to poll messages", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            if isConsumerGroup, configuration.autoJoinConsumerGroup, error.code == .consumerGroupMemberNotFound {
+                // The membership was revoked; the next poll joins again.
+                joinedGroup = false
+                return PolledMessages(partitionID: PolledMessages.noAssignedPartition, currentOffset: 0, count: 0, messages: [])
+            }
+            if isConsumerGroup, [.disconnected, .unauthenticated, .staleClient].contains(error.code) {
+                joinedGroup = false
+            }
+            try await Task.sleep(for: retryInterval)
+            throw error
+        }
+    }
+
+    private func handOverPolled(_ polled: PolledMessages) -> ReceivedMessage {
+        let partition = polled.partitionID
+        currentPartitionID = partition
+        buffer = polled.messages
+        bufferIndex = 0
+        bufferedContext = polled.context
+        bufferedCurrentOffset = polled.currentOffset
+        return handOverBuffered()
+    }
+
+    private func handOverBuffered() -> ReceivedMessage {
+        let partition = currentPartitionID
+        let message = buffer[bufferIndex]
+        bufferIndex += 1
+        let position = ConsumerPosition(partitionID: partition, offset: message.offset, context: bufferedContext)
+        lastConsumed[partition] = position
+        let drained = bufferIndex == buffer.count
+        // The strategy only says where a partition starts; the next poll of
+        // it continues after the last message handed over.
+        if configuration.pollingStrategy.kind != .next {
+            nextPositions[partition] = ConsumerPosition(partitionID: partition, offset: message.offset + 1, context: bufferedContext)
+        }
+        switch configuration.autoCommit.whenTrigger {
+        case .consumingEachMessage?:
+            queueCommit(position)
+        case .consumingEveryNthMessage(let n)?:
+            if message.offset % UInt64(n) == 0 {
+                queueCommit(position)
+            }
+        case .consumingAllMessages?:
+            if drained {
+                queueCommit(position)
+            }
+        case .pollingMessages?, nil:
+            break
+        }
+        let received = ReceivedMessage(message: message, currentOffset: bufferedCurrentOffset, partitionID: partition, context: bufferedContext)
+        if drained {
+            buffer.removeAll(keepingCapacity: true)
+            bufferIndex = 0
+        }
+        return received
+    }
+
+    /// Queues a commit for the commit task. A later one for the same
+    /// partition replaces a queued one not sent yet.
+    private func queueCommit(_ position: ConsumerPosition) {
+        guard isInitialized, !isShutDown else {
+            logger.error("The commit was not queued because the consumer is not running", metadata: metadata)
+            return
+        }
+        pendingCommits[position.partitionID] = position
+        commitWakeup.yield()
+    }
+
+    /// Sends the queued commits. Returns false once the consumer is shut
+    /// down and nothing is left, which ends the commit task.
+    private func sendPendingCommits() async -> Bool {
+        while let partition = pendingCommits.keys.first, let position = pendingCommits.removeValue(forKey: partition) {
+            await storeInBackground(position)
+        }
+        return !isShutDown
+    }
+
+    /// Returns false once the consumer is shut down, which ends the interval
+    /// task before it stores anything more.
+    private func storeOnTick() async -> Bool {
+        guard !isShutDown else {
+            return false
+        }
+        intervalIsStoring = true
+        defer { intervalIsStoring = false }
+        for position in lastConsumed.values {
+            await storeInBackground(position)
+        }
+        return true
+    }
+
+    private func storeFinalPositions(_ positions: [ConsumerPosition]) async {
+        for position in positions {
+            do {
+                try await store(position, allowReplay: false)
+            } catch {
+                logger.warning(
+                    "The final checkpoint was not acknowledged",
+                    metadata: metadata.merging(["partition": "\(position.partitionID)", "offset": "\(position.offset)", "error": "\(error)"]) { $1 })
+            }
+        }
+    }
+
+    /// Background commits have no caller to report to, so a failure is
+    /// logged. They never move a stored offset back: replay governs reading.
+    private func storeInBackground(_ position: ConsumerPosition) async {
+        do {
+            try await store(position, allowReplay: false)
+        } catch {
+            logger.error(
+                "Failed to store the offset",
+                metadata: metadata.merging(["partition": "\(position.partitionID)", "offset": "\(position.offset)", "error": "\(error)"]) { $1 })
+        }
+    }
+
+    private func store(_ position: ConsumerPosition, allowReplay: Bool) async throws {
+        if !allowReplay, storedPositionCovers(position) {
+            return
+        }
+        try await client.storeConsumerPosition(consumer: consumer, streamID: streamID, topicID: topicID, position: position)

Review Comment:
   warning: concurrent `storePosition()` calls can overwrite a newer offset with an older one despite `allowReplay: false`. serialize the coverage check, request, and cache update with all offset stores and deletes.



##########
foreign/swift/Sources/Iggy/Consumer/IggyConsumer.swift:
##########
@@ -0,0 +1,672 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import Logging
+import NIOConcurrencyHelpers
+
+/// Reads the partitions of one topic and hands their messages over one at a
+/// time, a port of `IggyConsumer` in the Rust SDK.
+///
+/// Build a standalone consumer of one partition with
+/// ``IggyClient/consumer(name:streamID:topicID:partitionID:configuration:)``,
+/// or a member of a consumer group with
+/// ``IggyClient/consumerGroup(name:streamID:topicID:configuration:)``, whose
+/// partitions the server assigns. Call ``initialize()`` once, then read with
+/// ``next()``, `for try await`, or ``consumeMessages(_:)``:
+///
+/// ```swift
+/// let consumer = try client.consumerGroup(name: "billing", streamID: "orders", topicID: "created")
+/// try await consumer.initialize()
+/// for try await received in consumer {
+///     print(received.partitionID, received.message.offset)
+/// }
+/// ```
+///
+/// Messages come from a buffer that a poll refills once it runs empty. A
+/// failed poll is thrown after ``ConsumerConfiguration/pollingRetryInterval``
+/// and leaves the consumer usable, so a caller of ``next()`` can call it again;
+/// a `for try await` loop ends at the first error instead. ``next()`` returns
+/// nil only after ``shutdown()``.
+///
+/// The consumer remembers the last message handed over from each partition.
+/// Without ``ConsumerConfiguration/allowReplay`` a message at or below it is
+/// not handed over again, and ``ConsumerConfiguration/autoCommit`` decides
+/// when the reading position is stored on the server.
+///
+/// Unlike the Rust consumer, this one has no encryptor, since the Swift
+/// client has none, and does not resolve a group create or join whose outcome
+/// was lost: the Swift client has no operation lanes to resolve them through.
+public actor IggyConsumer: AsyncSequence {
+    public typealias Element = ReceivedMessage
+
+    public nonisolated let name: String
+    public nonisolated let streamID: Identifier
+    public nonisolated let topicID: Identifier
+    public nonisolated let consumer: Consumer
+    /// The partition a standalone consumer reads; nil for a group member.
+    public nonisolated let partitionID: UInt32?
+    /// The partition of the last batch handed over. Before the first one it
+    /// is the partition of a standalone consumer and zero for a group member.
+    public private(set) var currentPartitionID: UInt32
+
+    private let client: IggyClient
+    private let configuration: ConsumerConfiguration
+    private let logger: Logger
+    private let isConsumerGroup: Bool
+    /// One reader at a time, as the Rust consumer's `&mut self` ensures.
+    private let reading = AsyncMutex()
+    private let commitWakeups: AsyncStream<Void>
+    private let commitWakeup: AsyncStream<Void>.Continuation
+
+    private var isInitialized = false
+    /// Shared by concurrent calls of ``initialize()``.
+    private var initialization: Task<Void, any Error>?
+    private var isShutDown = false
+    private var shutdownTask: Task<Void, Never>?
+    /// Follows the client's events: polling waits while the client is signed
+    /// out and can come back on its own.
+    private var canPoll = true
+    private var joinedGroup = false
+    private var buffer: [IggyMessage] = []
+    private var bufferIndex = 0
+    private var bufferedContext = PartitionContext.empty
+    private var bufferedCurrentOffset: UInt64 = 0
+    private var lastPolledAt: ContinuousClock.Instant?
+    /// Where each partition continues after its last message handed over,
+    /// unless the strategy is `next`, which leaves that to the server.
+    private var nextPositions: [UInt32: ConsumerPosition] = [:]
+    private var lastConsumed: [UInt32: ConsumerPosition] = [:]
+    private var lastStored: [UInt32: ConsumerPosition] = [:]
+    /// Commits queued by the message triggers, the latest per partition.
+    private var pendingCommits: [UInt32: ConsumerPosition] = [:]
+    private var eventsTask: Task<Void, Never>?
+    private var intervalTask: Task<Void, Never>?
+    private var intervalIsStoring = false
+    private var commitTask: Task<Void, Never>?
+
+    init(
+        client: IggyClient, name: String, consumer: Consumer, streamID: Identifier, topicID: Identifier, partitionID: UInt32?,
+        configuration: ConsumerConfiguration
+    ) throws {
+        try configuration.validate()
+        self.client = client
+        self.name = name
+        self.consumer = consumer
+        self.streamID = streamID
+        self.topicID = topicID
+        self.partitionID = partitionID
+        currentPartitionID = partitionID ?? 0
+        self.configuration = configuration
+        logger = client.logger
+        isConsumerGroup = consumer.kind == .consumerGroup
+        (commitWakeups, commitWakeup) = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
+    }
+
+    deinit {
+        eventsTask?.cancel()
+        intervalTask?.cancel()
+        commitTask?.cancel()
+        commitWakeup.finish()
+    }
+
+    public nonisolated func makeAsyncIterator() -> AsyncIterator {
+        AsyncIterator(consumer: self)
+    }
+
+    public struct AsyncIterator: AsyncIteratorProtocol {
+        let consumer: IggyConsumer
+
+        public mutating func next() async throws -> ReceivedMessage? {
+            try await consumer.next()
+        }
+    }
+
+    // MARK: Lifecycle
+
+    /// Looks the stream and topic up, retrying a missing one as
+    /// ``ConsumerConfiguration/initRetries`` says, joins the group of a member
+    /// that joins on its own, and starts the commit tasks. Concurrent calls
+    /// share one run, and calling it again after it succeeded, or after
+    /// ``shutdown()``, does nothing.
+    public func initialize() async throws {
+        if isInitialized || isShutDown {
+            return
+        }
+        if let initialization {
+            return try await initialization.value
+        }
+        let task = Task { try await self.start() }
+        initialization = task
+        defer { initialization = nil }
+        try await task.value
+    }
+
+    private func start() async throws {
+        logger.info("Initializing the consumer", metadata: metadata)
+        try await waitForStreamAndTopic()
+        let events = await client.events
+        // A retried initialize after a failed join replaces the subscription
+        // with nothing suspending in between, so none is left behind.
+        eventsTask?.cancel()
+        eventsTask = Task { [weak self] in
+            for await event in events {
+                guard let self, await self.observe(event) else {
+                    return
+                }
+            }
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup {
+            try await joinGroup()
+        }
+        guard !isShutDown else {
+            // A shutdown came in meanwhile and already stopped what it found.
+            eventsTask?.cancel()
+            eventsTask = nil
+            return
+        }
+        if let interval = configuration.autoCommit.interval {
+            intervalTask = Task { [weak self] in
+                while (try? await Task.sleep(for: interval)) != nil {
+                    guard let self, await self.storeOnTick() else {
+                        return
+                    }
+                }
+            }
+        }
+        commitTask = Task { [weak self, commitWakeups] in
+            for await _ in commitWakeups {
+                guard let self, await self.sendPendingCommits() else {
+                    return
+                }
+            }
+        }
+        isInitialized = true
+        logger.info("The consumer has been initialized", metadata: metadata)
+    }
+
+    /// Stops reading, sends the queued commits, stores the reading position
+    /// of every partition read unless auto-commit is disabled, and leaves the
+    /// group. Every caller waits for the same shutdown. Failures are logged:
+    /// nothing is left for the caller to undo.
+    public func shutdown() async {
+        if let shutdownTask {
+            await shutdownTask.value
+            return
+        }
+        isShutDown = true
+        let task = Task { await self.drain() }
+        shutdownTask = task
+        await task.value
+    }
+
+    private func drain() async {
+        logger.info("Shutting down the consumer", metadata: metadata)
+        let timeout = configuration.offsetDrainTimeout
+        if let intervalTask {
+            // A tick sleeping gets cancelled; one storing finishes first.
+            if intervalIsStoring {
+                await Self.wait(for: intervalTask, upTo: timeout)
+            }
+            intervalTask.cancel()
+        }
+        if let commitTask {
+            commitWakeup.yield()
+            await Self.wait(for: commitTask, upTo: timeout)
+            commitTask.cancel()
+        }
+        if configuration.autoCommit != .disabled {
+            let positions = Array(lastConsumed.values)
+            // One deadline for every final store, as in the Rust SDK.
+            _ = try? await withDeadline(.now + client.configuration.requestTimeout) {
+                await self.storeFinalPositions(positions)
+            }
+        }
+        if isConsumerGroup, joinedGroup {
+            joinedGroup = false
+            do {
+                try await client.leaveConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+            } catch {
+                // Expected after an explicit leave or a deleted group.
+                logger.debug("Failed to leave the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            }
+        }
+        eventsTask?.cancel()
+        eventsTask = nil
+        logger.info("The consumer has been shut down", metadata: metadata)
+    }
+
+    // MARK: Reading
+
+    /// The next message: from the buffer, or from a poll once it is empty.
+    /// Throws what a poll or join ran into, after the retry interval, and can
+    /// be called again after it threw. Nil once the consumer is shut down.
+    public func next() async throws -> ReceivedMessage? {
+        try await reading.lock()
+        defer { reading.unlock() }
+        if isShutDown {
+            return nil
+        }
+        if bufferIndex < buffer.count {
+            return handOverBuffered()
+        }
+        while !isShutDown {
+            try Task.checkCancellation()
+            let polled = try await poll()
+            if !polled.messages.isEmpty, !isShutDown {
+                return handOverPolled(polled)
+            }
+        }
+        return nil
+    }
+
+    /// Hands every message to `handler` until the consumer shuts down, the
+    /// task is cancelled, or an error ends the reading: a client that is shut
+    /// down or cannot come back without the caller, or an invalid address.
+    /// Other errors are logged and reading goes on, and a handler that throws
+    /// is logged too. The ``AutoCommitAfter`` triggers fire here, after the
+    /// handler returned or threw.
+    public func consumeMessages(_ handler: @Sendable (ReceivedMessage) async throws -> Void) async throws {
+        let after = configuration.autoCommit.afterTrigger
+        while true {
+            let received: ReceivedMessage
+            do {
+                guard let next = try await next() else {
+                    return
+                }
+                received = next
+            } catch let error as IggyError {
+                let ends = Self.endsConsumption(error) ? true : !(await client.canRecover)
+                if ends {
+                    logger.error("Reading stopped", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                    throw error
+                }
+                logger.error("Failed to read a message", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                continue
+            }
+            do {
+                try await handler(received)
+            } catch {
+                logger.error(
+                    "The handler failed", metadata: metadata.merging(["offset": "\(received.message.offset)", "error": "\(error)"]) { $1 })
+            }
+            switch after {
+            case .consumingEachMessage?:
+                queueCommit(received.position)
+            case .consumingEveryNthMessage(let n)?:
+                if received.message.offset % UInt64(n) == 0 {
+                    queueCommit(received.position)
+                }
+            case .consumingAllMessages?:
+                if received.message.offset == received.currentOffset {
+                    queueCommit(received.position)
+                }
+            case nil:
+                break
+            }
+        }
+    }
+
+    // MARK: Offsets
+
+    /// Stores `offset` for a partition, the current one when nil, under the
+    /// context of the last message handed over from it. Before any was, it
+    /// is stored without a context.
+    public func storeOffset(_ offset: UInt64, partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        if let last = lastConsumed[partition] {
+            try await storePosition(ConsumerPosition(partitionID: partition, offset: offset, context: last.context))
+            return
+        }
+        try await client.storeConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition, offset: offset)
+        lastStored[partition] = ConsumerPosition(partitionID: partition, offset: offset, context: .empty)
+    }
+
+    /// Stores the exact position delivered, as
+    /// ``ReceivedMessage/position`` gives it, even after later polls. Without
+    /// ``ConsumerConfiguration/allowReplay`` a position at or below the one
+    /// already stored in the same partition history is not sent.
+    public func storePosition(_ position: ConsumerPosition) async throws {
+        try await store(position, allowReplay: configuration.allowReplay)
+    }
+
+    /// Deletes the stored offset of a partition, the current one when nil.
+    /// Unlike the Rust consumer, a group member's nil is not left to the
+    /// server, since the Swift client routes the request by its partition.
+    public func deleteOffset(partitionID: UInt32? = nil) async throws {
+        let partition = partitionID ?? currentPartitionID
+        // A cancelled delete can still have committed, so a later store must
+        // not be skipped as covered.
+        lastStored[partition] = nil
+        try await client.deleteConsumerOffset(consumer: consumer, streamID: streamID, topicID: topicID, partitionID: partition)
+    }
+
+    /// The offset of the last message handed over from the partition.
+    public func lastConsumedOffset(partitionID: UInt32) -> UInt64? {
+        lastConsumed[partitionID]?.offset
+    }
+
+    /// The offset this consumer last stored for the partition.
+    public func lastStoredOffset(partitionID: UInt32) -> UInt64? {
+        lastStored[partitionID]?.offset
+    }
+
+    // MARK: Internals
+
+    private var metadata: Logger.Metadata {
+        ["consumer": "\(name)", "stream": "\(streamID)", "topic": "\(topicID)"]
+    }
+
+    private func waitForStreamAndTopic() async throws {
+        let retries = configuration.initRetries ?? 0
+        var ticker = RetryTicker(interval: configuration.initRetryInterval)
+        try await ticker.tick()
+        var streamExists = try await client.getStream(streamID) != nil
+        var topicExists = false
+        if streamExists {
+            topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+        }
+        var attempt: UInt32 = 0
+        // A stream or topic may still be being created by someone else.
+        while !(streamExists && topicExists), attempt < retries {
+            attempt += 1
+            logger.warning(
+                "The stream or topic does not exist yet, retrying",
+                metadata: metadata.merging(["retry": "\(attempt)/\(retries)", "stream_exists": "\(streamExists)"]) { $1 })
+            try await ticker.tick()
+            if !streamExists {
+                streamExists = try await client.getStream(streamID) != nil
+            }
+            if streamExists {
+                topicExists = try await client.getTopic(streamID: streamID, topicID: topicID) != nil
+            }
+        }
+        guard streamExists else {
+            throw streamID.name.map { IggyError(.streamNameNotFound, context: "stream \($0) was not found") }
+                ?? IggyError(.streamIdNotFound, context: "stream \(streamID) was not found")
+        }
+        guard topicExists else {
+            throw topicID.name.map { IggyError(.topicNameNotFound, context: "topic \($0) was not found in stream \(streamID)") }
+                ?? IggyError(.topicIdNotFound, context: "topic \(topicID) was not found in stream \(streamID)")
+        }
+    }
+
+    private func joinGroup() async throws {
+        if joinedGroup {
+            return
+        }
+        if try await client.getConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id) == nil {
+            guard configuration.createConsumerGroupIfNotExists else {
+                throw IggyError(.consumerGroupNameNotFound, context: "consumer group \(name) does not exist and auto-creation is disabled")
+            }
+            logger.info("Creating the consumer group", metadata: metadata)
+            do {
+                _ = try await client.createConsumerGroup(streamID: streamID, topicID: topicID, name: name)
+            } catch let error as IggyError where error.code == .consumerGroupNameAlreadyExists {
+                // Another member created it first.
+            }
+        }
+        logger.info("Joining the consumer group", metadata: metadata)
+        try await client.joinConsumerGroup(streamID: streamID, topicID: topicID, groupID: consumer.id)
+        joinedGroup = true
+    }
+
+    /// Returns false once the client shut down, which ends the subscription.
+    private func observe(_ event: DiagnosticEvent) async -> Bool {
+        switch event {
+        case .shutdown:
+            logger.warning("The client has been shut down", metadata: metadata)
+            joinedGroup = false
+            canPoll = false
+            return false
+        case .connected, .disconnected, .signedOut:
+            joinedGroup = false
+        case .signedIn:
+            break
+        }
+        // Events can arrive after one that reports a later state, so the
+        // state of the client decides.
+        canPoll = await client.state == .authenticated
+        return true
+    }
+
+    /// One poll, as the Rust consumer's poll future: the interval wait, the
+    /// sign-in wait, a join when the membership was lost, and the request.
+    /// An empty result is not an error.
+    private func poll() async throws -> PolledMessages {
+        if let pollInterval = configuration.pollInterval, let lastPolledAt {
+            try await Task.sleep(until: lastPolledAt + pollInterval, clock: .continuous)
+        }
+        let retryInterval = configuration.pollingRetryInterval
+        // A client that only the caller brings back never recovers, so the
+        // poll goes on and fails with the reason instead of waiting for good.
+        while !canPoll, await client.canRecover {
+            try await Task.sleep(for: retryInterval)
+        }
+        if isConsumerGroup, configuration.autoJoinConsumerGroup, !joinedGroup {
+            do {
+                try await joinGroup()
+            } catch {
+                logger.error("Failed to join the consumer group", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+                try await Task.sleep(for: retryInterval)
+                throw error
+            }
+        }
+        lastPolledAt = .now
+        let continuations = nextPositions
+        let strategy = configuration.pollingStrategy
+        // A refusal does not name its partition, and it answers the last one
+        // the strategy was asked for.
+        let polledPartition = NIOLockedValueBox(PolledMessages.noAssignedPartition)
+        do {
+            var polled = try await client.pollMessages(
+                streamID: streamID, topicID: topicID, partitionID: partitionID, consumer: consumer, count: configuration.batchLength,
+                autoCommit: configuration.autoCommit.whenTrigger == .pollingMessages
+            ) { partition in
+                polledPartition.withLockedValue { $0 = partition }
+                return continuations[partition].map { .offset($0.offset, context: $0.context) } ?? strategy
+            }
+            if polled.partitionID == PolledMessages.noAssignedPartition {
+                nextPositions.removeAll()
+                try await Task.sleep(for: retryInterval)
+                return polled
+            }
+            if !configuration.allowReplay, let consumed = lastConsumed[polled.partitionID], Self.sameHistory(consumed.context, polled.context) {
+                polled.messages.removeAll { $0.offset <= consumed.offset }
+                polled.count = UInt32(polled.messages.count)
+            }
+            return polled
+        } catch let error as IggyError {
+            if error.code == .historyUnavailable || error.code == .consumerGroupPartitionNotOwned {
+                nextPositions[polledPartition.withLockedValue { $0 }] = nil
+            }
+            logger.error("Failed to poll messages", metadata: metadata.merging(["error": "\(error)"]) { $1 })
+            if isConsumerGroup, configuration.autoJoinConsumerGroup, error.code == .consumerGroupMemberNotFound {
+                // The membership was revoked; the next poll joins again.
+                joinedGroup = false
+                return PolledMessages(partitionID: PolledMessages.noAssignedPartition, currentOffset: 0, count: 0, messages: [])
+            }
+            if isConsumerGroup, [.disconnected, .unauthenticated, .staleClient].contains(error.code) {
+                joinedGroup = false
+            }
+            try await Task.sleep(for: retryInterval)
+            throw error
+        }
+    }
+
+    private func handOverPolled(_ polled: PolledMessages) -> ReceivedMessage {
+        let partition = polled.partitionID
+        currentPartitionID = partition
+        buffer = polled.messages
+        bufferIndex = 0
+        bufferedContext = polled.context
+        bufferedCurrentOffset = polled.currentOffset
+        return handOverBuffered()
+    }
+
+    private func handOverBuffered() -> ReceivedMessage {
+        let partition = currentPartitionID
+        let message = buffer[bufferIndex]
+        bufferIndex += 1
+        let position = ConsumerPosition(partitionID: partition, offset: message.offset, context: bufferedContext)
+        lastConsumed[partition] = position
+        let drained = bufferIndex == buffer.count
+        // The strategy only says where a partition starts; the next poll of
+        // it continues after the last message handed over.
+        if configuration.pollingStrategy.kind != .next {

Review Comment:
   warning: `.next` with `batchLength: 1` and `.when(.consumingEveryNthMessage(2))` stalls at offset 1 because polls repeat that uncommitted offset. keep a local continuation so consumption can reach the next commit threshold.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(swift): add the consumer [iggy]

Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on PR #4641:
URL: https://github.com/apache/iggy/pull/4641#issuecomment-6413598660

   /skill team-review


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org