1 /* 2 * nghttp2 - HTTP/2 C Library 3 * 4 * Copyright (c) 2014 Tatsuhiro Tsujikawa 5 * 6 * Permission is hereby granted, free of charge, to any person obtaining 7 * a copy of this software and associated documentation files (the 8 * "Software"), to deal in the Software without restriction, including 9 * without limitation the rights to use, copy, modify, merge, publish, 10 * distribute, sublicense, and/or sell copies of the Software, and to 11 * permit persons to whom the Software is furnished to do so, subject to 12 * the following conditions: 13 * 14 * The above copyright notice and this permission notice shall be 15 * included in all copies or substantial portions of the Software. 16 * 17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 */ 25 #ifndef SHRPX_CONNECT_BLOCKER_H 26 #define SHRPX_CONNECT_BLOCKER_H 27 28 #include "shrpx.h" 29 30 #include <random> 31 #include <functional> 32 33 #include <ev.h> 34 35 namespace shrpx { 36 37 class ConnectBlocker { 38 public: 39 ConnectBlocker(std::mt19937 &gen, struct ev_loop *loop, 40 std::function<void()> block_func, 41 std::function<void()> unblock_func); 42 ~ConnectBlocker(); 43 44 // Returns true if making connection is not allowed. 45 bool blocked() const; 46 // Call this function if connect operation succeeded. This will 47 // reset sleep_ to minimum value. 48 void on_success(); 49 // Call this function if connect operations failed. This will start 50 // timer and blocks connection establishment with exponential 51 // backoff. 52 void on_failure(); 53 54 size_t get_fail_count() const; 55 56 // Peer is now considered offline. This effectively means that the 57 // connection is blocked until online() is called. 58 void offline(); 59 60 // Peer is now considered online 61 void online(); 62 63 // Returns true if peer is considered offline. 64 bool in_offline() const; 65 66 void call_block_func(); 67 void call_unblock_func(); 68 69 private: 70 std::mt19937 &gen_; 71 // Called when blocking is started 72 std::function<void()> block_func_; 73 // Called when unblocked 74 std::function<void()> unblock_func_; 75 ev_timer timer_; 76 struct ev_loop *loop_; 77 // The number of consecutive connection failure. Reset to 0 on 78 // success. 79 size_t fail_count_; 80 // true if peer is considered offline. 81 bool offline_; 82 }; 83 84 } // namespace shrpx 85 86 #endif // SHRPX_CONNECT_BLOCKER_H 87