|
| 1 | +// Copyright Dave Verwer, Sven A. Schmidt, and other contributors. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import NIOCore |
| 16 | +@preconcurrency import RediStack |
| 17 | + |
| 18 | + |
| 19 | +actor Redis { |
| 20 | + var client: RedisClient |
| 21 | + static private var task: Task<Redis?, Never>? |
| 22 | + |
| 23 | + static var shared: Redis? { |
| 24 | + get async { |
| 25 | + if let task { |
| 26 | + return await task.value |
| 27 | + } |
| 28 | + let task = Task<Redis?, Never> { |
| 29 | + var attemptsLeft = maxConnectionAttempts |
| 30 | + while attemptsLeft > 0 { |
| 31 | + do { |
| 32 | + return try await Redis() |
| 33 | + } catch { |
| 34 | + attemptsLeft -= 1 |
| 35 | + Current.logger().warning("Redis connection failed, \(attemptsLeft) attempts left. Error: \(error)") |
| 36 | + try? await Task.sleep(for: .milliseconds(500)) |
| 37 | + } |
| 38 | + } |
| 39 | + return nil |
| 40 | + } |
| 41 | + self.task = task |
| 42 | + return await task.value |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private init() async throws { |
| 47 | + let connection = RedisConnection.make( |
| 48 | + configuration: try .init(hostname: Redis.hostname), |
| 49 | + boundEventLoop: NIOSingletons.posixEventLoopGroup.any() |
| 50 | + ) |
| 51 | + self.client = try await connection.get() |
| 52 | + } |
| 53 | + |
| 54 | + static let expirationInSeconds = 5*60 |
| 55 | + static let hostname = "redis" |
| 56 | + static let maxConnectionAttempts = 3 |
| 57 | + |
| 58 | + func set(owner: String, repository: String, reference: String?) async -> Void { |
| 59 | + let key = "\(owner)/\(repository)".lowercased() |
| 60 | + if let reference { |
| 61 | + let buffer = ByteBuffer(string: reference) |
| 62 | + try? await client.setex(.init(key), |
| 63 | + to: RESPValue.bulkString(buffer), |
| 64 | + expirationInSeconds: Self.expirationInSeconds).get() |
| 65 | + } else { |
| 66 | + _ = try? await client.delete([.init(key)]).get() |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + func get(owner: String, repository: String) async -> String? { |
| 71 | + let key = "\(owner)/\(repository)".lowercased() |
| 72 | + return try? await client.get(.init(key)).map(\.string).get() |
| 73 | + } |
| 74 | +} |
| 75 | + |
0 commit comments