|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the swift-memcache-gsoc open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2023 Apple Inc. and the swift-memcache-gsoc project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of swift-memcache-gsoc project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +import NIOCore |
| 16 | +import NIOPosix |
| 17 | + |
| 18 | +/// Responses look like: |
| 19 | +/// |
| 20 | +/// <RC> <datalen*> <flag1> <flag2> <...>\r\n |
| 21 | +/// |
| 22 | +/// Where <RC> is a 2 character return code. The number of flags returned are |
| 23 | +/// based off of the flags supplied. |
| 24 | +/// |
| 25 | +/// <datalen> is only for responses with payloads, with the return code 'VA'. |
| 26 | +/// |
| 27 | +/// Flags are single character codes, ie 'q' or 'k' or 'I', which adjust the |
| 28 | +/// behavior of the command. If a flag requests a response flag (ie 't' for TTL |
| 29 | +/// remaining), it is returned in the same order as they were in the original |
| 30 | +/// command, though this is not strict. |
| 31 | +/// |
| 32 | +/// Flags are single character codes, ie 'q' or 'k' or 'O', which adjust the |
| 33 | +/// behavior of a command. Flags may contain token arguments, which come after the |
| 34 | +/// flag and before the next space or newline, ie 'Oopaque' or 'Kuserkey'. Flags |
| 35 | +/// can return new data or reflect information, in the same order they were |
| 36 | +/// supplied in the request. Sending an 't' flag with a get for an item with 20 |
| 37 | +/// seconds of TTL remaining, would return 't20' in the response. |
| 38 | +/// |
| 39 | +/// All commands accept a tokens 'P' and 'L' which are completely ignored. The |
| 40 | +/// arguments to 'P' and 'L' can be used as hints or path specifications to a |
| 41 | +/// proxy or router inbetween a client and a memcached daemon. For example, a |
| 42 | +/// client may prepend a "path" in the key itself: "mg /path/foo v" or in a proxy |
| 43 | +/// token: "mg foo Lpath/ v" - the proxy may then optionally remove or forward the |
| 44 | +/// token to a memcached daemon, which will ignore them. |
| 45 | +/// |
| 46 | +/// Syntax errors are handled the same as noted under 'Error strings' section |
| 47 | +/// below. |
| 48 | +/// |
| 49 | +/// For usage examples beyond basic syntax, please see the wiki: |
| 50 | +/// https://github.com/memcached/memcached/wiki/MetaCommands |
| 51 | +struct MemcachedResponseDecoder: NIOSingleStepByteToMessageDecoder { |
| 52 | + typealias InboundOut = MemcachedResponse |
| 53 | + |
| 54 | + /// Describes the errors that can occur during the decoding process. |
| 55 | + enum MemcachedDecoderError: Error { |
| 56 | + /// This error is thrown when EOF is encountered but there are still |
| 57 | + /// readable bytes in the buffer, which can indicate a bad message. |
| 58 | + case unexpectedEOF |
| 59 | + |
| 60 | + /// This error is thrown when EOF is encountered but there is still an expected next step |
| 61 | + /// in the decoder's state machine. This error suggests that the message ended prematurely, |
| 62 | + /// possibly indicating a bad message. |
| 63 | + case unexpectedNextStep(NextStep) |
| 64 | + |
| 65 | + /// This error is thrown when an unexpected character is encountered in the buffer |
| 66 | + /// during the decoding process. |
| 67 | + case unexpectedCharacter(UInt8) |
| 68 | + } |
| 69 | + |
| 70 | + /// The next step that the decoder will take. The value of this enum determines how the decoder |
| 71 | + /// processes the current state of the ByteBuffer. |
| 72 | + enum NextStep: Hashable { |
| 73 | + /// The initial step. |
| 74 | + case returnCode |
| 75 | + /// Decode the data length, flags or check if we are the end |
| 76 | + case dataLengthOrFlag(MemcachedResponse.ReturnCode) |
| 77 | + /// Decode the next flag |
| 78 | + case decodeNextFlag(MemcachedResponse.ReturnCode, UInt64?) |
| 79 | + // TODO: Add a next step for decoding the response data if the return code is VA |
| 80 | + } |
| 81 | + |
| 82 | + /// The action that the decoder will take in response to the current state of the ByteBuffer and the `NextStep`. |
| 83 | + enum NextDecodeAction { |
| 84 | + /// We need more bytes to decode the next step. |
| 85 | + case waitForMoreBytes |
| 86 | + /// We can continue decoding. |
| 87 | + case continueDecodeLoop |
| 88 | + /// We have decoded the next response and need to return it. |
| 89 | + case returnDecodedResponse(MemcachedResponse) |
| 90 | + } |
| 91 | + |
| 92 | + /// The next step in decoding. |
| 93 | + var nextStep: NextStep = .returnCode |
| 94 | + |
| 95 | + mutating func decode(buffer: inout ByteBuffer) throws -> InboundOut? { |
| 96 | + while true { |
| 97 | + switch try self.next(buffer: &buffer) { |
| 98 | + case .returnDecodedResponse(let response): |
| 99 | + return response |
| 100 | + |
| 101 | + case .waitForMoreBytes: |
| 102 | + return nil |
| 103 | + |
| 104 | + case .continueDecodeLoop: |
| 105 | + () |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + mutating func next(buffer: inout ByteBuffer) throws -> NextDecodeAction { |
| 111 | + switch self.nextStep { |
| 112 | + case .returnCode: |
| 113 | + guard let bytes = buffer.readInteger(as: UInt16.self) else { |
| 114 | + return .waitForMoreBytes |
| 115 | + } |
| 116 | + |
| 117 | + let returnCode = MemcachedResponse.ReturnCode(bytes) |
| 118 | + self.nextStep = .dataLengthOrFlag(returnCode) |
| 119 | + return .continueDecodeLoop |
| 120 | + |
| 121 | + case .dataLengthOrFlag(let returnCode): |
| 122 | + if returnCode == .VA { |
| 123 | + // TODO: Implement decoding of data length |
| 124 | + fatalError("Decoding for VA return code is not yet implemented") |
| 125 | + } |
| 126 | + |
| 127 | + guard let nextByte = buffer.readInteger(as: UInt8.self) else { |
| 128 | + return .waitForMoreBytes |
| 129 | + } |
| 130 | + |
| 131 | + if nextByte == UInt8.whitespace { |
| 132 | + self.nextStep = .decodeNextFlag(returnCode, nil) |
| 133 | + return .continueDecodeLoop |
| 134 | + } else if nextByte == UInt8.carriageReturn { |
| 135 | + guard let nextNextByte = buffer.readInteger(as: UInt8.self), nextNextByte == UInt8.newline else { |
| 136 | + return .waitForMoreBytes |
| 137 | + } |
| 138 | + let response = MemcachedResponse(returnCode: returnCode, dataLength: nil) |
| 139 | + self.nextStep = .returnCode |
| 140 | + return .returnDecodedResponse(response) |
| 141 | + } else { |
| 142 | + throw MemcachedDecoderError.unexpectedCharacter(nextByte) |
| 143 | + } |
| 144 | + |
| 145 | + case .decodeNextFlag(let returnCode, let dataLength): |
| 146 | + while let nextByte = buffer.readInteger(as: UInt8.self), nextByte != UInt8.whitespace { |
| 147 | + // for now consume the byte and do nothing with it. |
| 148 | + // TODO: Implement decoding of flags |
| 149 | + } |
| 150 | + |
| 151 | + let response = MemcachedResponse(returnCode: returnCode, dataLength: dataLength) |
| 152 | + self.nextStep = .returnCode |
| 153 | + return .returnDecodedResponse(response) |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + mutating func decodeLast(buffer: inout ByteBuffer, seenEOF: Bool) throws -> MemcachedResponse? { |
| 158 | + // Try to decode what is left in the buffer. |
| 159 | + if let output = try self.decode(buffer: &buffer) { |
| 160 | + return output |
| 161 | + } |
| 162 | + |
| 163 | + guard buffer.readableBytes == 0 || seenEOF else { |
| 164 | + // If there are still readable bytes left and we haven't seen an EOF |
| 165 | + // then something is wrong with the message or how we called the decoder. |
| 166 | + throw MemcachedDecoderError.unexpectedEOF |
| 167 | + } |
| 168 | + |
| 169 | + switch self.nextStep { |
| 170 | + case .returnCode: |
| 171 | + return nil |
| 172 | + default: |
| 173 | + throw MemcachedDecoderError.unexpectedNextStep(self.nextStep) |
| 174 | + } |
| 175 | + } |
| 176 | +} |
0 commit comments