1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TalvBansal\ThrottledFailedJobMonitor; |
4
|
|
|
|
5
|
|
|
use Illuminate\Cache\RateLimiter; |
6
|
|
|
use Illuminate\Notifications\RoutesNotifications; |
7
|
|
|
use Illuminate\Support\Facades\Log; |
8
|
|
|
use Illuminate\Support\Str; |
9
|
|
|
use TalvBansal\ThrottledFailedJobMonitor\Event\NotificationLimitReached; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Trait RoutesThrottledNotifications. |
13
|
|
|
*/ |
14
|
|
|
trait RoutesThrottledNotifications |
15
|
|
|
{ |
16
|
|
|
use RoutesNotifications { |
17
|
|
|
RoutesNotifications::notify as parentNotify; |
18
|
|
|
} |
19
|
|
|
|
20
|
5 |
|
public function notify($instance): void |
21
|
|
|
{ |
22
|
5 |
|
if ($instance instanceof ThrottledNotification) { |
23
|
5 |
|
$key = $this->throttleKey($instance); |
24
|
5 |
|
if ($this->limiter()->tooManyAttempts($key, $this->maxAttempts())) { |
25
|
1 |
|
Log::notice("Skipping sending notification with key `$key`. Rate limit reached."); |
26
|
1 |
|
event(new NotificationLimitReached($key)); |
27
|
|
|
|
28
|
1 |
|
return; |
29
|
|
|
} |
30
|
|
|
|
31
|
5 |
|
$this->limiter()->hit($key, ($instance->throttleDecayMinutes() * 60)); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
// Execute the original notify() method. |
35
|
5 |
|
$this->parentNotify($instance); |
|
|
|
|
36
|
5 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Get the rate limiter instance. |
40
|
|
|
*/ |
41
|
5 |
|
protected function limiter(): RateLimiter |
42
|
|
|
{ |
43
|
5 |
|
return app(RateLimiter::class); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Build the notification throttle key from the Notification class name, |
48
|
|
|
* the Notification's throttle key id. |
49
|
|
|
* @param ThrottledNotification $instance |
50
|
|
|
* @return string |
51
|
|
|
*/ |
52
|
5 |
|
protected function throttleKey(ThrottledNotification $instance) |
53
|
|
|
{ |
54
|
5 |
|
return Str::kebab( |
55
|
5 |
|
class_basename($instance).'-'.$instance->throttleKeyId() |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Set the max attempts to 1. |
61
|
|
|
*/ |
62
|
5 |
|
protected function maxAttempts() |
63
|
|
|
{ |
64
|
5 |
|
return 1; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
This check marks calls to methods that do not seem to exist on an object.
This is most likely the result of a method being renamed without all references to it being renamed likewise.