|
| 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 Vapor |
| 16 | +import Redis |
| 17 | + |
| 18 | +final class RateCatcherMiddleware: AsyncMiddleware { |
| 19 | + |
| 20 | + let windowSize: Int // in seconds |
| 21 | + |
| 22 | + public func respond(to request: Request, chainingTo next: AsyncResponder) async throws -> Response { |
| 23 | + guard let cfray = request.headers.first(name: "cf-ray") else { |
| 24 | + return try await next.respond(to: request) |
| 25 | + } |
| 26 | + let seconds: Int = Int(Date().timeIntervalSince1970) |
| 27 | + let combinedKey: RedisKey = "\(cfray):\(seconds)" |
| 28 | + |
| 29 | + let countOverWindow: Int = try await request.redis.increment(combinedKey) |
| 30 | + for i in seconds - windowSize ..< seconds { |
| 31 | + let key: RedisKey = "\(cfray):\(i)" |
| 32 | + countOverWindow += try await request.redis.get(key, as: Int.self) |
| 33 | + } |
| 34 | + |
| 35 | + if countOverWindow > 999 { |
| 36 | + request.logger.log(level: .warning, "RateCatcherMiddleware blocking request with cf-ray \(cfray) due to \(countOverWindow) requests in the last \(windowSize) seconds.") |
| 37 | + throw Abort(.tooManyRequests) |
| 38 | + } else { |
| 39 | + return try await next.respond(to: request) |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + init(windowSize: Int) { |
| 44 | + self.windowSize = windowSize |
| 45 | + } |
| 46 | +} |
0 commit comments