MediaWiki  master
RESTBagOStuff.php
Go to the documentation of this file.
1 <?php
2 
3 use Psr\Log\LoggerInterface;
4 
54  private const DEFAULT_CONN_TIMEOUT = 1.2;
55 
59  private const DEFAULT_REQ_TIMEOUT = 3.0;
60 
64  private $client;
65 
70  private $url;
71 
75  private $httpParams;
76 
82 
87  private $hmacKey;
88 
93 
94  public function __construct( $params ) {
95  $params['segmentationSize'] = $params['segmentationSize'] ?? INF;
96  if ( empty( $params['url'] ) ) {
97  throw new InvalidArgumentException( 'URL parameter is required' );
98  }
99 
100  if ( empty( $params['client'] ) ) {
101  // Pass through some params to the HTTP client.
102  $clientParams = [
103  'connTimeout' => $params['connTimeout'] ?? self::DEFAULT_CONN_TIMEOUT,
104  'reqTimeout' => $params['reqTimeout'] ?? self::DEFAULT_REQ_TIMEOUT,
105  ];
106  foreach ( [ 'caBundlePath', 'proxy' ] as $key ) {
107  if ( isset( $params[$key] ) ) {
108  $clientParams[$key] = $params[$key];
109  }
110  }
111  $this->client = new MultiHttpClient( $clientParams );
112  } else {
113  $this->client = $params['client'];
114  }
115 
116  $this->httpParams['writeMethod'] = $params['httpParams']['writeMethod'] ?? 'PUT';
117  $this->httpParams['readHeaders'] = $params['httpParams']['readHeaders'] ?? [];
118  $this->httpParams['writeHeaders'] = $params['httpParams']['writeHeaders'] ?? [];
119  $this->httpParams['deleteHeaders'] = $params['httpParams']['deleteHeaders'] ?? [];
120  $this->extendedErrorBodyFields = $params['extendedErrorBodyFields'] ?? [];
121  $this->serializationType = $params['serialization_type'] ?? 'PHP';
122  $this->hmacKey = $params['hmac_key'] ?? '';
123 
124  // The parent constructor calls setLogger() which sets the logger in $this->client
125  parent::__construct( $params );
126 
127  // Make sure URL ends with /
128  $this->url = rtrim( $params['url'], '/' ) . '/';
129 
130  // Default config, R+W > N; no locks on reads though; writes go straight to state-machine
131  $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_QC;
132  }
133 
134  public function setLogger( LoggerInterface $logger ) {
135  parent::setLogger( $logger );
136  $this->client->setLogger( $logger );
137  }
138 
139  protected function doGet( $key, $flags = 0, &$casToken = null ) {
140  $getToken = ( $casToken === self::PASS_BY_REF );
141  $casToken = null;
142 
143  $req = [
144  'method' => 'GET',
145  'url' => $this->url . rawurlencode( $key ),
146  'headers' => $this->httpParams['readHeaders'],
147  ];
148 
149  list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
150  if ( $rcode === 200 ) {
151  if ( is_string( $rbody ) ) {
152  $value = $this->decodeBody( $rbody );
154  if ( $getToken && $value !== false ) {
155  $casToken = $rbody;
156  }
157 
158  return $value;
159  }
160  return false;
161  }
162  if ( $rcode === 0 || ( $rcode >= 400 && $rcode != 404 ) ) {
163  return $this->handleError( "Failed to fetch $key", $rcode, $rerr, $rhdrs, $rbody );
164  }
165  return false;
166  }
167 
168  protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
169  // @TODO: respect WRITE_SYNC (e.g. EACH_QUORUM)
170  // @TODO: respect $exptime
171  $req = [
172  'method' => $this->httpParams['writeMethod'],
173  'url' => $this->url . rawurlencode( $key ),
174  'body' => $this->encodeBody( $value ),
175  'headers' => $this->httpParams['writeHeaders'],
176  ];
177 
178  list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
179  if ( $rcode === 200 || $rcode === 201 || $rcode === 204 ) {
180  return true;
181  }
182  return $this->handleError( "Failed to store $key", $rcode, $rerr, $rhdrs, $rbody );
183  }
184 
185  protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
186  // @TODO: make this atomic
187  if ( $this->get( $key ) === false ) {
188  return $this->set( $key, $value, $exptime, $flags );
189  }
190 
191  return false; // key already set
192  }
193 
194  protected function doDelete( $key, $flags = 0 ) {
195  // @TODO: respect WRITE_SYNC (e.g. EACH_QUORUM)
196  $req = [
197  'method' => 'DELETE',
198  'url' => $this->url . rawurlencode( $key ),
199  'headers' => $this->httpParams['deleteHeaders'],
200  ];
201 
202  list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
203  if ( in_array( $rcode, [ 200, 204, 205, 404, 410 ] ) ) {
204  return true;
205  }
206  return $this->handleError( "Failed to delete $key", $rcode, $rerr, $rhdrs, $rbody );
207  }
208 
209  public function incr( $key, $value = 1, $flags = 0 ) {
210  // @TODO: make this atomic
211  $n = $this->get( $key, self::READ_LATEST );
212  if ( $this->isInteger( $n ) ) { // key exists?
213  $n = max( $n + (int)$value, 0 );
214  // @TODO: respect $exptime
215  return $this->set( $key, $n ) ? $n : false;
216  }
217 
218  return false;
219  }
220 
221  public function decr( $key, $value = 1, $flags = 0 ) {
222  return $this->incr( $key, -$value, $flags );
223  }
224 
231  private function decodeBody( $body ) {
232  $pieces = explode( '.', $body, 3 );
233  if ( count( $pieces ) !== 3 || $pieces[0] !== $this->serializationType ) {
234  return false;
235  }
236  list( , $hmac, $serialized ) = $pieces;
237  if ( $this->hmacKey !== '' ) {
238  $checkHmac = hash_hmac( 'sha256', $serialized, $this->hmacKey, true );
239  if ( !hash_equals( $checkHmac, base64_decode( $hmac ) ) ) {
240  return false;
241  }
242  }
243 
244  switch ( $this->serializationType ) {
245  case 'JSON':
246  $value = json_decode( $serialized, true );
247  return ( json_last_error() === JSON_ERROR_NONE ) ? $value : false;
248 
249  case 'PHP':
250  return unserialize( $serialized );
251 
252  default:
253  throw new \DomainException(
254  "Unknown serialization type: $this->serializationType"
255  );
256  }
257  }
258 
266  private function encodeBody( $body ) {
267  switch ( $this->serializationType ) {
268  case 'JSON':
269  $value = json_encode( $body );
270  if ( $value === false ) {
271  throw new InvalidArgumentException( __METHOD__ . ": body could not be encoded." );
272  }
273  break;
274 
275  case 'PHP':
276  $value = serialize( $body );
277  break;
278 
279  default:
280  throw new \DomainException(
281  "Unknown serialization type: $this->serializationType"
282  );
283  }
284 
285  if ( $this->hmacKey !== '' ) {
286  $hmac = base64_encode(
287  hash_hmac( 'sha256', $value, $this->hmacKey, true )
288  );
289  } else {
290  $hmac = '';
291  }
292  return $this->serializationType . '.' . $hmac . '.' . $value;
293  }
294 
304  protected function handleError( $msg, $rcode, $rerr, $rhdrs, $rbody ) {
305  $message = "$msg : ({code}) {error}";
306  $context = [
307  'code' => $rcode,
308  'error' => $rerr
309  ];
310 
311  if ( $this->extendedErrorBodyFields !== [] ) {
312  $body = $this->decodeBody( $rbody );
313  if ( $body ) {
314  $extraFields = '';
315  foreach ( $this->extendedErrorBodyFields as $field ) {
316  if ( isset( $body[$field] ) ) {
317  $extraFields .= " : ({$field}) {$body[$field]}";
318  }
319  }
320  if ( $extraFields !== '' ) {
321  $message .= " {extra_fields}";
322  $context['extra_fields'] = $extraFields;
323  }
324  }
325  }
326 
327  $this->logger->error( $message, $context );
328  $this->setLastError( $rcode === 0 ? self::ERR_UNREACHABLE : self::ERR_UNEXPECTED );
329  return false;
330  }
331 }
MediumSpecificBagOStuff\setLastError
setLastError( $err)
Set the "last error" registry.
Definition: MediumSpecificBagOStuff.php:758
MediumSpecificBagOStuff\isInteger
isInteger( $value)
Check if a value is an integer.
Definition: MediumSpecificBagOStuff.php:881
MultiHttpClient
Class to handle multiple HTTP requests.
Definition: MultiHttpClient.php:55
$serialized
foreach( $res as $row) $serialized
Definition: testCompression.php:88
RESTBagOStuff\doDelete
doDelete( $key, $flags=0)
Delete an item.
Definition: RESTBagOStuff.php:194
RESTBagOStuff\$hmacKey
string $hmacKey
Optional HMAC Key for protecting the serialized blob.
Definition: RESTBagOStuff.php:87
RESTBagOStuff\decr
decr( $key, $value=1, $flags=0)
Decrease stored value of $key by $value while preserving its TTL.
Definition: RESTBagOStuff.php:221
MediumSpecificBagOStuff\serialize
serialize( $value)
Definition: MediumSpecificBagOStuff.php:1048
RESTBagOStuff\decodeBody
decodeBody( $body)
Processes the response body.
Definition: RESTBagOStuff.php:231
RESTBagOStuff
Interface to key-value storage behind an HTTP server.
Definition: RESTBagOStuff.php:48
BagOStuff\$logger
LoggerInterface $logger
Definition: BagOStuff.php:73
RESTBagOStuff\incr
incr( $key, $value=1, $flags=0)
Increase stored value of $key by $value while preserving its TTL.
Definition: RESTBagOStuff.php:209
RESTBagOStuff\__construct
__construct( $params)
Definition: RESTBagOStuff.php:94
BagOStuff\READ_LATEST
const READ_LATEST
Bitfield constants for get()/getMulti(); these are only advisory.
Definition: BagOStuff.php:87
RESTBagOStuff\$serializationType
string $serializationType
Optional serialization type to use.
Definition: RESTBagOStuff.php:81
MediumSpecificBagOStuff
Storage medium specific cache for storing items (e.g.
Definition: MediumSpecificBagOStuff.php:34
RESTBagOStuff\handleError
handleError( $msg, $rcode, $rerr, $rhdrs, $rbody)
Handle storage error.
Definition: RESTBagOStuff.php:304
RESTBagOStuff\DEFAULT_CONN_TIMEOUT
const DEFAULT_CONN_TIMEOUT
Default connection timeout in seconds.
Definition: RESTBagOStuff.php:54
RESTBagOStuff\doSet
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
Definition: RESTBagOStuff.php:168
RESTBagOStuff\$httpParams
array $httpParams
http parameters: readHeaders, writeHeaders, deleteHeaders, writeMethod
Definition: RESTBagOStuff.php:75
RESTBagOStuff\$extendedErrorBodyFields
array $extendedErrorBodyFields
additional body fields to log on error, if possible
Definition: RESTBagOStuff.php:92
RESTBagOStuff\$client
MultiHttpClient $client
Definition: RESTBagOStuff.php:64
RESTBagOStuff\$url
string $url
REST URL to use for storage.
Definition: RESTBagOStuff.php:70
RESTBagOStuff\doAdd
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
Definition: RESTBagOStuff.php:185
RESTBagOStuff\setLogger
setLogger(LoggerInterface $logger)
Definition: RESTBagOStuff.php:134
RESTBagOStuff\DEFAULT_REQ_TIMEOUT
const DEFAULT_REQ_TIMEOUT
Default request timeout.
Definition: RESTBagOStuff.php:59
MediumSpecificBagOStuff\unserialize
unserialize( $value)
Definition: MediumSpecificBagOStuff.php:1057
RESTBagOStuff\doGet
doGet( $key, $flags=0, &$casToken=null)
Definition: RESTBagOStuff.php:139
RESTBagOStuff\encodeBody
encodeBody( $body)
Prepares the request body (the "value" portion of our key/value store) for transmission.
Definition: RESTBagOStuff.php:266