|
| 1 | +import NIO |
| 2 | +import NIOConcurrencyHelpers |
| 3 | + |
| 4 | +public final class NIORedisConnection { |
| 5 | + /// The `EventLoop` this connection uses to execute commands on. |
| 6 | + public var eventLoop: EventLoop { return channel.eventLoop } |
| 7 | + |
| 8 | + /// Has the connection been closed? |
| 9 | + public private(set) var isClosed = Atomic<Bool>(value: false) |
| 10 | + |
| 11 | + internal let redisPipeline: RedisMessenger |
| 12 | + |
| 13 | + private let channel: Channel |
| 14 | + |
| 15 | + deinit { assert(!isClosed.load(), "Redis connection was not properly shut down!") } |
| 16 | + |
| 17 | + /// Creates a new connection on the provided channel, using the handler for executing commands. |
| 18 | + /// - Important: Call `close()` before deinitializing to properly cleanup resources! |
| 19 | + init(channel: Channel, handler: RedisMessenger) { |
| 20 | + self.channel = channel |
| 21 | + self.redisPipeline = handler |
| 22 | + } |
| 23 | + |
| 24 | + /// Closes the connection to Redis. |
| 25 | + public func close() { |
| 26 | + guard isClosed.exchange(with: true) else { return } |
| 27 | + |
| 28 | + channel.close(promise: nil) |
| 29 | + } |
| 30 | + |
| 31 | + /// Executes the desired command with the specified arguments. |
| 32 | + /// - Important: All arguments should be in `.bulkString` format. |
| 33 | + public func command(_ command: String, _ arguments: [RedisData] = []) -> EventLoopFuture<RedisData> { |
| 34 | + return send(.array([RedisData(bulk: command)] + arguments)) |
| 35 | + .thenThrowing { response in |
| 36 | + switch response { |
| 37 | + case let .error(error): throw error |
| 38 | + default: return response |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + private func send(_ message: RedisData) -> EventLoopFuture<RedisData> { |
| 44 | + // ensure the connection is still open |
| 45 | + guard !isClosed.load() else { return eventLoop.makeFailedFuture(error: RedisError.connectionClosed) } |
| 46 | + |
| 47 | + // create a new promise to store |
| 48 | + let promise = eventLoop.makePromise(of: RedisData.self) |
| 49 | + |
| 50 | + // cascade this enqueue to the newly created promise |
| 51 | + redisPipeline.enqueue(message).cascade(promise: promise) |
| 52 | + |
| 53 | + return promise.futureResult |
| 54 | + } |
| 55 | +} |
0 commit comments