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