3 namespace Wikimedia\ObjectCache
;
5 use InvalidArgumentException
;
6 use Psr\Log\LoggerInterface
;
7 use Wikimedia\Http\MultiHttpClient
;
10 * Store key-value data via an HTTP service.
12 * ### Important caveats
14 * This interface is currently an incomplete BagOStuff implementation,
15 * supported only for use with MediaWiki features that accept a dedicated
16 * cache type to use for a narrow set of cache keys that share the same
17 * key expiry and replication requirements, and where the key-value server
18 * in question is statically configured with domain knowledge of said
19 * key expiry and replication requirements.
21 * Specifically, RESTBagOStuff has the following limitations:
23 * - The expiry parameter is ignored in methods like `set()`.
25 * There is not currently an agreed protocol for sending this to a
26 * server. This class is written for use with MediaWiki\Session\SessionManager
27 * and Kask/Cassanda at WMF, which does not expose a customizable expiry.
29 * As such, it is not recommended to use RESTBagOStuff to back a general
30 * purpose cache type (such as MediaWiki's main cache, or main stash).
31 * Instead, it is only supported toMediaWiki features where a cache type can
32 * be pointed for a narrow set of keys that naturally share the same TTL
33 * anyway, or where the feature behaves correctly even if the logical expiry
34 * is longer than specified (e.g. immutable keys, or value verification)
36 * - Most methods are non-atomic.
38 * The class should only be used for get, set, and delete operations.
39 * Advanced methods like `incr()`, `add()` and `lock()` do exist but
40 * inherit a native and best-effort implementation based on get+set.
41 * These should not be relied upon.
43 * ### Backend requirements
45 * The HTTP server will receive requests for URLs like `{baseURL}/{KEY}`. It
46 * must implement the GET, PUT and DELETE methods.
48 * E.g., when the base URL is `/sessions/v1`, then `set()` will:
50 * `PUT /sessions/v1/mykeyhere`
52 * and `get()` would do:
54 * `GET /sessions/v1/mykeyhere`
56 * and `delete()` would do:
58 * `DELETE /sessions/v1/mykeyhere`
60 * ### Example configuration
62 * Minimal generic configuration:
65 * $wgObjectCaches['sessions'] = array(
66 * 'class' => 'RESTBagOStuff',
67 * 'url' => 'http://localhost:7231/example/'
72 * Configuration for [Kask](https://www.mediawiki.org/wiki/Kask) session store:
74 * $wgObjectCaches['sessions'] = array(
75 * 'class' => 'RESTBagOStuff',
76 * 'url' => 'https://kaskhost:1234/sessions/v1/',
78 * 'readHeaders' => [],
79 * 'writeHeaders' => [ 'content-type' => 'application/octet-stream' ],
80 * 'deleteHeaders' => [],
81 * 'writeMethod' => 'POST',
83 * 'serialization_type' => 'JSON',
84 * 'extendedErrorBodyFields' => [ 'type', 'title', 'detail', 'instance' ]
86 * $wgSessionCacheType = 'sessions';
89 class RESTBagOStuff
extends MediumSpecificBagOStuff
{
91 * Default connection timeout in seconds. The kernel retransmits the SYN
92 * packet after 1 second, so 1.2 seconds allows for 1 retransmit without
95 private const DEFAULT_CONN_TIMEOUT
= 1.2;
98 * Default request timeout
100 private const DEFAULT_REQ_TIMEOUT
= 3.0;
103 * @var MultiHttpClient
108 * REST URL to use for storage.
115 * HTTP parameters: readHeaders, writeHeaders, deleteHeaders, writeMethod.
122 * Optional serialization type to use. Allowed values: "PHP", "JSON".
126 private $serializationType;
129 * Optional HMAC Key for protecting the serialized blob. If omitted no protection is done
136 * @var array additional body fields to log on error, if possible
138 private $extendedErrorBodyFields;
140 public function __construct( $params ) {
141 $params['segmentationSize'] ??
= INF
;
142 if ( empty( $params['url'] ) ) {
143 throw new InvalidArgumentException( 'URL parameter is required' );
146 if ( empty( $params['client'] ) ) {
147 // Pass through some params to the HTTP client.
149 'connTimeout' => $params['connTimeout'] ?? self
::DEFAULT_CONN_TIMEOUT
,
150 'reqTimeout' => $params['reqTimeout'] ?? self
::DEFAULT_REQ_TIMEOUT
,
152 foreach ( [ 'caBundlePath', 'proxy', 'telemetry' ] as $key ) {
153 if ( isset( $params[$key] ) ) {
154 $clientParams[$key] = $params[$key];
157 $this->client
= new MultiHttpClient( $clientParams );
159 $this->client
= $params['client'];
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'] ??
'';
170 // The parent constructor calls setLogger() which sets the logger in $this->client
171 parent
::__construct( $params );
173 // Make sure URL ends with /
174 $this->url
= rtrim( $params['url'], '/' ) . '/';
176 $this->attrMap
[self
::ATTR_DURABILITY
] = self
::QOS_DURABILITY_DISK
;
179 public function setLogger( LoggerInterface
$logger ) {
180 parent
::setLogger( $logger );
181 $this->client
->setLogger( $logger );
184 protected function doGet( $key, $flags = 0, &$casToken = null ) {
185 $getToken = ( $casToken === self
::PASS_BY_REF
);
190 'url' => $this->url
. rawurlencode( $key ),
191 'headers' => $this->httpParams
['readHeaders'],
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 ) {
204 } elseif ( $rcode === 0 ||
( $rcode >= 400 && $rcode != 404 ) ) {
205 $this->handleError( 'Failed to fetch {cacheKey}', $rcode, $rerr, $rhdrs, $rbody,
206 [ 'cacheKey' => $key ] );
209 $this->updateOpStats( self
::METRIC_OP_GET
, [ $key => [ 0, $valueSize ] ] );
214 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
216 'method' => $this->httpParams
['writeMethod'],
217 'url' => $this->url
. rawurlencode( $key ),
218 'body' => $this->encodeBody( $value ),
219 'headers' => $this->httpParams
['writeHeaders'],
222 [ $rcode, , $rhdrs, $rbody, $rerr ] = $this->client
->run( $req );
223 $res = ( $rcode === 200 ||
$rcode === 201 ||
$rcode === 204 );
225 $this->handleError( 'Failed to store {cacheKey}', $rcode, $rerr, $rhdrs, $rbody,
226 [ 'cacheKey' => $key ] );
229 $this->updateOpStats( self
::METRIC_OP_SET
, [ $key => [ strlen( $rbody ), 0 ] ] );
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 );
244 protected function doDelete( $key, $flags = 0 ) {
246 'method' => 'DELETE',
247 'url' => $this->url
. rawurlencode( $key ),
248 'headers' => $this->httpParams
['deleteHeaders'],
251 [ $rcode, , $rhdrs, $rbody, $rerr ] = $this->client
->run( $req );
252 $res = in_array( $rcode, [ 200, 204, 205, 404, 410 ] );
254 $this->handleError( 'Failed to delete {cacheKey}', $rcode, $rerr, $rhdrs, $rbody,
255 [ 'cacheKey' => $key ] );
258 $this->updateOpStats( self
::METRIC_OP_DELETE
, [ $key ] );
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;
279 * Processes the response body.
281 * @param string $body request body to process
283 * @return mixed|bool the processed body, or false on error
285 private function decodeBody( $body ) {
286 $pieces = explode( '.', $body, 3 );
287 if ( count( $pieces ) !== 3 ||
$pieces[0] !== $this->serializationType
) {
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 ) ) ) {
298 switch ( $this->serializationType
) {
300 $value = json_decode( $serialized, true );
301 return ( json_last_error() === JSON_ERROR_NONE
) ?
$value : false;
304 return unserialize( $serialized );
307 throw new \
DomainException(
308 "Unknown serialization type: $this->serializationType"
314 * Prepares the request body (the "value" portion of our key/value store) for transmission.
316 * @param string $body request body to prepare
318 * @return string the prepared body
320 private function encodeBody( $body ) {
321 switch ( $this->serializationType
) {
323 $value = json_encode( $body );
324 if ( $value === false ) {
325 throw new InvalidArgumentException( __METHOD__
. ": body could not be encoded." );
330 $value = serialize( $body );
334 throw new \
DomainException(
335 "Unknown serialization type: $this->serializationType"
339 if ( $this->hmacKey
!== '' ) {
340 $hmac = base64_encode(
341 hash_hmac( 'sha256', $value, $this->hmacKey
, true )
346 return $this->serializationType
. '.' . $hmac . '.' . $value;
350 * Handle storage error
352 * @param string $msg Error message
353 * @param int $rcode Error code from client
354 * @param string $rerr Error message from client
355 * @param array $rhdrs Response headers
356 * @param string $rbody Error body from client (if any)
357 * @param array $context Error context for PSR-3 logging
359 protected function handleError( $msg, $rcode, $rerr, $rhdrs, $rbody, $context = [] ) {
360 $message = "$msg : ({code}) {error}";
366 if ( $this->extendedErrorBodyFields
!== [] ) {
367 $body = $this->decodeBody( $rbody );
370 foreach ( $this->extendedErrorBodyFields
as $field ) {
371 if ( isset( $body[$field] ) ) {
372 $extraFields .= " : ({$field}) {$body[$field]}";
375 if ( $extraFields !== '' ) {
376 $message .= " {extra_fields}";
377 $context['extra_fields'] = $extraFields;
382 $this->logger
->error( $message, $context );
383 $this->setLastError( $rcode === 0 ? self
::ERR_UNREACHABLE
: self
::ERR_UNEXPECTED
);
387 /** @deprecated class alias since 1.43 */
388 class_alias( RESTBagOStuff
::class, 'RESTBagOStuff' );