Files
swift-nio-imap/Sources/NIOIMAP/Client/IdleStateMachine.swift
David Evans 59a57ee70b New client state machine (#610)
The client state machine has now been fully rewritten, and encapsulates the miniature state machines implemented in previous PRs.

I've extracted the state machine from IMAPClientHandler and moved it into ClientStateMachine, hence all the code deletion.

The state machine receives a command, response, or continuation request from the IMAPClientHandler and returns an array of Chunk/EventLoopPromise pairs that the client handler should then write to the network.

Also we didn't previously queue Append commands like we did for others, however it's now become apparent that all commands types should be queued, so we do that now.

A lot of tests have been added to make sure everything works.

Note that a lot of sendCommand tests have been deleted as we now precondition on user errors instead of throwing.
2021-09-10 13:45:11 +01:00

75 lines
2.3 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOIMAPCore
public struct InvalidIdleState: Error, Hashable {
public init() {}
}
extension ClientStateMachine {
struct Idle: Hashable {
enum State: Hashable {
case waitingForConfirmation
case idling
}
private var state: State = .waitingForConfirmation
mutating func sendCommand(_ command: CommandStreamPart) {
switch self.state {
case .idling:
break
case .waitingForConfirmation:
preconditionFailure("Invalid state: \(self.state)")
}
switch command {
case .idleDone:
break
case .tagged, .append, .continuationResponse:
preconditionFailure("Invalid command for idle state")
}
}
mutating func receiveResponse(_ response: Response) throws {
switch self.state {
case .waitingForConfirmation:
throw UnexpectedResponse(activePromise: nil)
case .idling:
try self.receiveResponse_idlingState(response)
}
}
mutating func receiveContinuationRequest(_: ContinuationRequest) throws {
switch self.state {
case .waitingForConfirmation:
self.state = .idling
case .idling:
throw UnexpectedContinuationRequest()
}
}
private func receiveResponse_idlingState(_ response: Response) throws {
assert(self.state == .idling)
switch response {
case .untagged:
break
case .fetch, .tagged, .fatal, .authenticationChallenge, .idleStarted:
throw UnexpectedResponse(activePromise: nil)
}
}
}
}