MediaWiki master
RESTBagOStuff.php
Go to the documentation of this file.
1<?php
2
4
5use InvalidArgumentException;
6use LogicException;
7use Psr\Log\LoggerInterface;
9
96 private const DEFAULT_CONN_TIMEOUT = 1.2;
97
101 private const DEFAULT_REQ_TIMEOUT = 3.0;
102
106 private $client;
107
113 private $url;
114
120 private $httpParams;
121
127 private $serializationType;
128
134 private $hmacKey;
135
139 private $extendedErrorBodyFields;
140
141 public function __construct( $params ) {
142 $params['segmentationSize'] ??= INF;
143 if ( empty( $params['url'] ) ) {
144 throw new InvalidArgumentException( 'URL parameter is required' );
145 }
146
147 if ( empty( $params['client'] ) ) {
148 // Pass through some params to the HTTP client.
149 $clientParams = [
150 'connTimeout' => $params['connTimeout'] ?? self::DEFAULT_CONN_TIMEOUT,
151 'reqTimeout' => $params['reqTimeout'] ?? self::DEFAULT_REQ_TIMEOUT,
152 ];
153 foreach ( [ 'caBundlePath', 'proxy', 'telemetry' ] as $key ) {
154 if ( isset( $params[$key] ) ) {
155 $clientParams[$key] = $params[$key];
156 }
157 }
158 $this->client = new MultiHttpClient( $clientParams );
159 } else {
160 $this->client = $params['client'];
161 }
162
163 $this->httpParams['writeMethod'] = $params['httpParams']['writeMethod'] ?? 'PUT';
164 $this->httpParams['readHeaders'] = $params['httpParams']['readHeaders'] ?? [];
165 $this->httpParams['writeHeaders'] = $params['httpParams']['writeHeaders'] ?? [];
166 $this->httpParams['deleteHeaders'] = $params['httpParams']['deleteHeaders'] ?? [];
167 $this->extendedErrorBodyFields = $params['extendedErrorBodyFields'] ?? [];
168 $this->serializationType = $params['serialization_type'] ?? 'PHP';
169 $this->hmacKey = $params['hmac_key'] ?? '';
170
171 // The parent constructor calls setLogger() which sets the logger in $this->client
172 parent::__construct( $params );
173
174 // Make sure URL ends with /
175 $this->url = rtrim( $params['url'], '/' ) . '/';
176
178 }
179
180 public function setLogger( LoggerInterface $logger ) {
181 parent::setLogger( $logger );
182 $this->client->setLogger( $logger );
183 }
184
185 protected function doGet( $key, $flags = 0, &$casToken = null ) {
186 $getToken = ( $casToken === self::PASS_BY_REF );
187 $casToken = null;
188
189 $req = [
190 'method' => 'GET',
191 'url' => $this->url . rawurlencode( $key ),
192 'headers' => $this->httpParams['readHeaders'],
193 ];
194
195 $value = false;
196 $valueSize = false;
197 [ $rcode, , $rhdrs, $rbody, $rerr ] = $this->client->run( $req );
198 if ( $rcode === 200 && is_string( $rbody ) ) {
199 $value = $this->decodeBody( $rbody );
200 $valueSize = strlen( $rbody );
201 // @FIXME: use some kind of hash or UUID header as CAS token
202 if ( $getToken && $value !== false ) {
203 $casToken = $rbody;
204 }
205 } elseif ( $rcode === 0 || ( $rcode >= 400 && $rcode != 404 ) ) {
206 $this->handleError( 'Failed to fetch {cacheKey}', $rcode, $rerr, $rhdrs, $rbody,
207 [ 'cacheKey' => $key ] );
208 }
209
210 $this->updateOpStats( self::METRIC_OP_GET, [ $key => [ 0, $valueSize ] ] );
211
212 return $value;
213 }
214
215 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
216 $req = [
217 'method' => $this->httpParams['writeMethod'],
218 'url' => $this->url . rawurlencode( $key ),
219 'body' => $this->encodeBody( $value ),
220 'headers' => $this->httpParams['writeHeaders'],
221 ];
222
223 [ $rcode, , $rhdrs, $rbody, $rerr ] = $this->client->run( $req );
224 $res = ( $rcode === 200 || $rcode === 201 || $rcode === 204 );
225 if ( !$res ) {
226 $this->handleError( 'Failed to store {cacheKey}', $rcode, $rerr, $rhdrs, $rbody,
227 [ 'cacheKey' => $key ] );
228 }
229
230 $this->updateOpStats( self::METRIC_OP_SET, [ $key => [ strlen( $rbody ), 0 ] ] );
231
232 return $res;
233 }
234
235 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
236 // NOTE: This is non-atomic
237 if ( $this->get( $key ) === false ) {
238 return $this->set( $key, $value, $exptime, $flags );
239 }
240
241 // key already set
242 return false;
243 }
244
245 protected function doDelete( $key, $flags = 0 ) {
246 $req = [
247 'method' => 'DELETE',
248 'url' => $this->url . rawurlencode( $key ),
249 'headers' => $this->httpParams['deleteHeaders'],
250 ];
251
252 [ $rcode, , $rhdrs, $rbody, $rerr ] = $this->client->run( $req );
253 $res = in_array( $rcode, [ 200, 204, 205, 404, 410 ] );
254 if ( !$res ) {
255 $this->handleError( 'Failed to delete {cacheKey}', $rcode, $rerr, $rhdrs, $rbody,
256 [ 'cacheKey' => $key ] );
257 }
258
259 $this->updateOpStats( self::METRIC_OP_DELETE, [ $key ] );
260
261 return $res;
262 }
263
264 protected function doIncrWithInit( $key, $exptime, $step, $init, $flags ) {
265 // NOTE: This is non-atomic
266 $curValue = $this->doGet( $key );
267 if ( $curValue === false ) {
268 $newValue = $this->doSet( $key, $init, $exptime ) ? $init : false;
269 } elseif ( $this->isInteger( $curValue ) ) {
270 $sum = max( $curValue + $step, 0 );
271 $newValue = $this->doSet( $key, $sum, $exptime ) ? $sum : false;
272 } else {
273 $newValue = false;
274 }
275
276 return $newValue;
277 }
278
286 private function decodeBody( $body ) {
287 $pieces = explode( '.', $body, 3 );
288 if ( count( $pieces ) !== 3 || $pieces[0] !== $this->serializationType ) {
289 return false;
290 }
291 [ , $hmac, $serialized ] = $pieces;
292 if ( $this->hmacKey !== '' ) {
293 $checkHmac = hash_hmac( 'sha256', $serialized, $this->hmacKey, true );
294 if ( !hash_equals( $checkHmac, base64_decode( $hmac ) ) ) {
295 return false;
296 }
297 }
298
299 switch ( $this->serializationType ) {
300 case 'JSON':
301 $value = json_decode( $serialized, true );
302 return ( json_last_error() === JSON_ERROR_NONE ) ? $value : false;
303
304 case 'PHP':
305 return unserialize( $serialized );
306
307 default:
308 throw new \DomainException(
309 "Unknown serialization type: $this->serializationType"
310 );
311 }
312 }
313
322 private function encodeBody( $body ) {
323 switch ( $this->serializationType ) {
324 case 'JSON':
325 $value = json_encode( $body );
326 if ( $value === false ) {
327 throw new InvalidArgumentException( __METHOD__ . ": body could not be encoded." );
328 }
329 break;
330
331 case 'PHP':
332 $value = serialize( $body );
333 break;
334
335 default:
336 throw new \DomainException(
337 "Unknown serialization type: $this->serializationType"
338 );
339 }
340
341 if ( $this->hmacKey !== '' ) {
342 $hmac = base64_encode(
343 hash_hmac( 'sha256', $value, $this->hmacKey, true )
344 );
345 } else {
346 $hmac = '';
347 }
348 return $this->serializationType . '.' . $hmac . '.' . $value;
349 }
350
361 protected function handleError( $msg, $rcode, $rerr, $rhdrs, $rbody, $context = [] ) {
362 $message = "$msg : ({code}) {error}";
363 $context = [
364 'code' => $rcode,
365 'error' => $rerr
366 ] + $context;
367
368 if ( $this->extendedErrorBodyFields !== [] ) {
369 $body = $this->decodeBody( $rbody );
370 if ( $body ) {
371 $extraFields = '';
372 foreach ( $this->extendedErrorBodyFields as $field ) {
373 if ( isset( $body[$field] ) ) {
374 $extraFields .= " : ({$field}) {$body[$field]}";
375 }
376 }
377 if ( $extraFields !== '' ) {
378 $message .= " {extra_fields}";
379 $context['extra_fields'] = $extraFields;
380 }
381 }
382 }
383
384 $this->logger->error( $message, $context );
385 $this->setLastError( $rcode === 0 ? self::ERR_UNREACHABLE : self::ERR_UNEXPECTED );
386 }
387}
388
390class_alias( RESTBagOStuff::class, 'RESTBagOStuff' );
array $params
The job parameters.
Class to handle multiple HTTP requests.
setLastError( $error)
Set the "last error" registry due to a problem encountered during an attempted operation.
Storage medium specific cache for storing items (e.g.
isInteger( $value)
Check if a value is an integer.
const PASS_BY_REF
Idiom for doGet() to return extra information by reference.
Interface to key-value storage behind an HTTP server.
doGet( $key, $flags=0, &$casToken=null)
Get an item.
handleError( $msg, $rcode, $rerr, $rhdrs, $rbody, $context=[])
Handle storage error.
doIncrWithInit( $key, $exptime, $step, $init, $flags)
doDelete( $key, $flags=0)
Delete an item.
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
setLogger(LoggerInterface $logger)
const ATTR_DURABILITY
Durability of writes; see QOS_DURABILITY_* (higher means stronger)
const ERR_UNEXPECTED
Storage medium operation failed due to usage limitations or an I/O error.
const QOS_DURABILITY_DISK
Data is saved to disk and writes do not usually block on fsync()