6
6
use Illuminate \Container \Container ;
7
7
use Throwable ;
8
8
9
- class CircuitBreaker
9
+ class ThrottlesExceptions
10
10
{
11
11
/**
12
- * The maximum number of attempts allowed before the circuit is opened .
12
+ * The maximum number of attempts allowed before rate limiting applies .
13
13
*
14
14
* @var int
15
15
*/
@@ -36,6 +36,13 @@ class CircuitBreaker
36
36
*/
37
37
protected $ key ;
38
38
39
+ /**
40
+ * The callback that determines if rate limiting should apply.
41
+ *
42
+ * @var callable
43
+ */
44
+ protected $ whenCallback ;
45
+
39
46
/**
40
47
* The prefix of the rate limiter key.
41
48
*
@@ -86,34 +93,40 @@ public function handle($job, $next)
86
93
87
94
$ this ->limiter ->clear ($ jobKey );
88
95
} catch (Throwable $ throwable ) {
96
+ if ($ this ->whenCallback && ! call_user_func ($ this ->whenCallback , $ throwable )) {
97
+ throw $ throwable ;
98
+ }
99
+
89
100
$ this ->limiter ->hit ($ jobKey , $ this ->decayMinutes * 60 );
90
101
91
102
return $ job ->release ($ this ->retryAfterMinutes * 60 );
92
103
}
93
104
}
94
105
95
106
/**
96
- * Set the prefix of the rate limiter key .
107
+ * Specify a callback that should determine if rate limiting behavior should apply .
97
108
*
98
- * @param string $prefix
109
+ * @param callable $callback
99
110
* @return $this
100
111
*/
101
- public function withPrefix ( string $ prefix )
112
+ public function when ( callable $ callback )
102
113
{
103
- $ this ->prefix = $ prefix ;
114
+ $ this ->whenCallback = $ callback ;
104
115
105
116
return $ this ;
106
117
}
107
118
108
119
/**
109
- * Get the number of seconds that should elapse before the job is retried .
120
+ * Set the prefix of the rate limiter key .
110
121
*
111
- * @param string $key
112
- * @return int
122
+ * @param string $prefix
123
+ * @return $this
113
124
*/
114
- protected function getTimeUntilNextRetry ( $ key )
125
+ public function withPrefix ( string $ prefix )
115
126
{
116
- return $ this ->limiter ->availableIn ($ key ) + 3 ;
127
+ $ this ->prefix = $ prefix ;
128
+
129
+ return $ this ;
117
130
}
118
131
119
132
/**
@@ -124,6 +137,17 @@ protected function getTimeUntilNextRetry($key)
124
137
*/
125
138
protected function getKey ($ job )
126
139
{
127
- return md5 ($ this ->prefix .(empty ($ this ->key ) ? get_class ($ job ) : $ this ->key ));
140
+ return $ this ->prefix .md5 (empty ($ this ->key ) ? get_class ($ job ) : $ this ->key );
141
+ }
142
+
143
+ /**
144
+ * Get the number of seconds that should elapse before the job is retried.
145
+ *
146
+ * @param string $key
147
+ * @return int
148
+ */
149
+ protected function getTimeUntilNextRetry ($ key )
150
+ {
151
+ return $ this ->limiter ->availableIn ($ key ) + 3 ;
128
152
}
129
153
}
0 commit comments