-
Notifications
You must be signed in to change notification settings - Fork 15
/
GuzzleCcpLogMiddleware.php
227 lines (192 loc) · 7.77 KB
/
GuzzleCcpLogMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
<?php
/**
* Created by PhpStorm.
* User: Exodus 4D
* Date: 01.01.2019
* Time: 22:39
*/
namespace Exodus4D\ESI\Lib\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* ESI endpoints that return warning headers (e.g. "resource_legacy", "resource_deprecated") will get logged
* To prevent big file I/O on these log files, errors get "throttled" and not all of them get logged
* Class GuzzleCcpLogMiddleware
* @package Exodus4D\ESI\Lib\Middleware
*/
class GuzzleCcpLogMiddleware extends AbstractGuzzleMiddleware {
/**
* cache tag for legacy warnings limits
*/
const CACHE_TAG_LEGACY_LIMIT = 'LEGACY_LIMIT';
/**
* cache tag for deprecated warnings limits
*/
const CACHE_TAG_DEPRECATED_LIMIT = 'DEPRECATED_LIMIT';
/**
* default for: global enable this middleware
*/
const DEFAULT_LOG_ENABLED = true;
/**
* default for: Log first "2" errors that occur for an endpoint within "X" seconds
* @see DEFAULT_LOG_LIMIT_COUNT_TTL
*/
const DEFAULT_LOG_COUNT_MAX = 2;
/**
* default for: logging limit
*/
const DEFAULT_LOG_LIMIT_COUNT_TTL = 60;
/**
* default for: callback function that checks a $request
* -> can be used to "exclude" some requests from been logged (e.g. on expected downtime)
*/
const DEFAULT_LOG_LOGGABLE_CALLBACK = null;
/**
* default for: callback function for logging
*/
const DEFAULT_LOG_CALLBACK = null;
/**
* default for: name for log file with endpoints marked as "legacy" in response Headers
*/
const DEFAULT_LOG_FILE_LEGACY = 'esi_resource_legacy';
/**
* default for: name for log file with endpoints marked as "deprecated" in response Headers
*/
const DEFAULT_LOG_FILE_DEPRECATED = 'esi_resource_deprecated';
/**
* error message for legacy endpoints
*/
const ERROR_RESOURCE_LEGACY = 'Resource has been marked as legacy';
/**
* error message for deprecated endpoints
*/
const ERROR_RESOURCE_DEPRECATED = 'Resource has been marked as deprecated';
/**
* default options can go here for middleware
* @var array
*/
private $defaultOptions = [
'ccp_log_enabled' => self::DEFAULT_LOG_ENABLED,
'ccp_log_count_max' => self::DEFAULT_LOG_COUNT_MAX,
'ccp_log_limit_count_ttl' => self::DEFAULT_LOG_LIMIT_COUNT_TTL,
'ccp_log_loggable_callback' => self::DEFAULT_LOG_LOGGABLE_CALLBACK,
'ccp_log_callback' => self::DEFAULT_LOG_CALLBACK,
'ccp_log_file_legacy' => self::DEFAULT_LOG_FILE_LEGACY,
'ccp_log_file_deprecated' => self::DEFAULT_LOG_FILE_DEPRECATED
];
/**
* @var callable
*/
private $nextHandler;
/**
* GuzzleCcpLogMiddleware constructor.
* @param callable $nextHandler
* @param array $defaultOptions
*/
public function __construct(callable $nextHandler, array $defaultOptions = []){
$this->nextHandler = $nextHandler;
$this->defaultOptions = array_replace($this->defaultOptions, $defaultOptions);
}
/**
* log warnings for some ESI specific response headers
* @param RequestInterface $request
* @param array $options
* @return mixed
*/
public function __invoke(RequestInterface $request, array $options){
// Combine options with defaults specified by this middleware
$options = array_replace($this->defaultOptions, $options);
$next = $this->nextHandler;
if(!$options['ccp_log_enabled']){
// middleware disabled -> skip
return $next($request, $options);
}
parent::__invoke($request, $options);
return $next($request, $options)
->then(
$this->onFulfilled($request, $options)
);
}
/**
* No exceptions were thrown during processing
*
* @param RequestInterface $request
* @param array $options
* @return \Closure
*/
protected function onFulfilled(RequestInterface $request, array $options) : \Closure {
return function (ResponseInterface $response) use ($request, $options) {
// check response for "warning" headers
if(!empty($value = $response->getHeaderLine('warning'))){
// check header value for 199 code
if(preg_match('/199/i', $value)){
// "legacy" warning found in response headers
if(is_callable($loggable = $options['ccp_log_loggable_callback']) ? $loggable($request) : (bool)$loggable){
// warning for legacy endpoint -> check log limit (throttle)
if($this->isLoggableRequest($request, self::CACHE_TAG_LEGACY_LIMIT, $options)){
if(is_callable($log = $options['ccp_log_callback'])){
$logData = [
'url' => $request->getUri()->__toString()
];
$log($options['ccp_log_file_legacy'], 'info', $value ? : self::ERROR_RESOURCE_LEGACY, $logData, 'information');
}
}
}
}
// check header value for 299 code
if(preg_match('/299/i', $value)){
// "deprecated" warning found in response headers
if(is_callable($loggable = $options['ccp_log_loggable_callback']) ? $loggable($request) : (bool)$loggable){
// warning for deprecated -> check log limit (throttle)
if($this->isLoggableRequest($request, self::CACHE_TAG_DEPRECATED_LIMIT, $options)){
if(is_callable($log = $options['ccp_log_callback'])){
$logData = [
'url' => $request->getUri()->__toString()
];
$log($options['ccp_log_file_deprecated'], 'warning', $value ? : self::ERROR_RESOURCE_DEPRECATED, $logData, 'warning');
}
}
}
}
}
return $response;
};
}
/**
* checks whether a request should be logged or not
* -> if a request url is already logged with a certain $type,
* it will not get logged the next time until self::DEFAULT_LOG_LIMIT_COUNT_TTL
* expires (this helps to reduce log file I/O)
* @param RequestInterface $request
* @param string $tag
* @param array $options
* @return bool
* @throws \Psr\Cache\InvalidArgumentException
*/
protected function isLoggableRequest(RequestInterface $request, string $tag, array $options) : bool {
$loggable = false;
$cacheKey = $this->cacheKeyFromRequestUrl($request, $tag);
$cacheItem = $this->cache()->getItem($cacheKey);
$legacyLimit = (array)$cacheItem->get();
$count = (int)$legacyLimit['count']++;
if($count < $options['ccp_log_count_max']){
// loggable error count exceeded..
$loggable = true;
if(!$cacheItem->isHit()){
$cacheItem->expiresAfter($options['ccp_log_limit_count_ttl']);
}
$cacheItem->set($legacyLimit);
$this->cache()->save($cacheItem);
}
return $loggable;
}
/**
* @param array $defaultOptions
* @return \Closure
*/
public static function factory(array $defaultOptions = []) : \Closure {
return function(callable $handler) use ($defaultOptions){
return new static($handler, $defaultOptions);
};
}
}