MediaWiki REL1_35
RESTBagOStuff.php
Go to the documentation of this file.
1<?php
2
3use 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 $casToken = null;
141
142 $req = [
143 'method' => 'GET',
144 'url' => $this->url . rawurlencode( $key ),
145 'headers' => $this->httpParams['readHeaders'],
146 ];
147
148 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
149 if ( $rcode === 200 ) {
150 if ( is_string( $rbody ) ) {
151 $value = $this->decodeBody( $rbody );
153 $casToken = ( $value !== false ) ? $rbody : null;
154
155 return $value;
156 }
157 return false;
158 }
159 if ( $rcode === 0 || ( $rcode >= 400 && $rcode != 404 ) ) {
160 return $this->handleError( "Failed to fetch $key", $rcode, $rerr, $rhdrs, $rbody );
161 }
162 return false;
163 }
164
165 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
166 // @TODO: respect WRITE_SYNC (e.g. EACH_QUORUM)
167 // @TODO: respect $exptime
168 $req = [
169 'method' => $this->httpParams['writeMethod'],
170 'url' => $this->url . rawurlencode( $key ),
171 'body' => $this->encodeBody( $value ),
172 'headers' => $this->httpParams['writeHeaders'],
173 ];
174
175 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
176 if ( $rcode === 200 || $rcode === 201 || $rcode === 204 ) {
177 return true;
178 }
179 return $this->handleError( "Failed to store $key", $rcode, $rerr, $rhdrs, $rbody );
180 }
181
182 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
183 // @TODO: make this atomic
184 if ( $this->get( $key ) === false ) {
185 return $this->set( $key, $value, $exptime, $flags );
186 }
187
188 return false; // key already set
189 }
190
191 protected function doDelete( $key, $flags = 0 ) {
192 // @TODO: respect WRITE_SYNC (e.g. EACH_QUORUM)
193 $req = [
194 'method' => 'DELETE',
195 'url' => $this->url . rawurlencode( $key ),
196 'headers' => $this->httpParams['deleteHeaders'],
197 ];
198
199 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
200 if ( in_array( $rcode, [ 200, 204, 205, 404, 410 ] ) ) {
201 return true;
202 }
203 return $this->handleError( "Failed to delete $key", $rcode, $rerr, $rhdrs, $rbody );
204 }
205
206 public function incr( $key, $value = 1, $flags = 0 ) {
207 // @TODO: make this atomic
208 $n = $this->get( $key, self::READ_LATEST );
209 if ( $this->isInteger( $n ) ) { // key exists?
210 $n = max( $n + (int)$value, 0 );
211 // @TODO: respect $exptime
212 return $this->set( $key, $n ) ? $n : false;
213 }
214
215 return false;
216 }
217
218 public function decr( $key, $value = 1, $flags = 0 ) {
219 return $this->incr( $key, -$value, $flags );
220 }
221
228 private function decodeBody( $body ) {
229 $pieces = explode( '.', $body, 3 );
230 if ( count( $pieces ) !== 3 || $pieces[0] !== $this->serializationType ) {
231 return false;
232 }
233 list( , $hmac, $serialized ) = $pieces;
234 if ( $this->hmacKey !== '' ) {
235 $checkHmac = hash_hmac( 'sha256', $serialized, $this->hmacKey, true );
236 if ( !hash_equals( $checkHmac, base64_decode( $hmac ) ) ) {
237 return false;
238 }
239 }
240
241 switch ( $this->serializationType ) {
242 case 'JSON':
243 $value = json_decode( $serialized, true );
244 return ( json_last_error() === JSON_ERROR_NONE ) ? $value : false;
245
246 case 'PHP':
247 return unserialize( $serialized );
248
249 default:
250 throw new \DomainException(
251 "Unknown serialization type: $this->serializationType"
252 );
253 }
254 }
255
263 private function encodeBody( $body ) {
264 switch ( $this->serializationType ) {
265 case 'JSON':
266 $value = json_encode( $body );
267 if ( $value === false ) {
268 throw new InvalidArgumentException( __METHOD__ . ": body could not be encoded." );
269 }
270 break;
271
272 case 'PHP':
273 $value = serialize( $body );
274 break;
275
276 default:
277 throw new \DomainException(
278 "Unknown serialization type: $this->serializationType"
279 );
280 }
281
282 if ( $this->hmacKey !== '' ) {
283 $hmac = base64_encode(
284 hash_hmac( 'sha256', $value, $this->hmacKey, true )
285 );
286 } else {
287 $hmac = '';
288 }
289 return $this->serializationType . '.' . $hmac . '.' . $value;
290 }
291
301 protected function handleError( $msg, $rcode, $rerr, $rhdrs, $rbody ) {
302 $message = "$msg : ({code}) {error}";
303 $context = [
304 'code' => $rcode,
305 'error' => $rerr
306 ];
307
308 if ( $this->extendedErrorBodyFields !== [] ) {
309 $body = $this->decodeBody( $rbody );
310 if ( $body ) {
311 $extraFields = '';
312 foreach ( $this->extendedErrorBodyFields as $field ) {
313 if ( isset( $body[$field] ) ) {
314 $extraFields .= " : ({$field}) {$body[$field]}";
315 }
316 }
317 if ( $extraFields !== '' ) {
318 $message .= " {extra_fields}";
319 $context['extra_fields'] = $extraFields;
320 }
321 }
322 }
323
324 $this->logger->error( $message, $context );
325 $this->setLastError( $rcode === 0 ? self::ERR_UNREACHABLE : self::ERR_UNEXPECTED );
326 return false;
327 }
328}
serialize()
const READ_LATEST
Bitfield constants for get()/getMulti(); these are only advisory.
Definition BagOStuff.php:87
LoggerInterface $logger
Definition BagOStuff.php:73
Storage medium specific cache for storing items (e.g.
isInteger( $value)
Check if a value is an integer.
setLastError( $err)
Set the "last error" registry.
Class to handle multiple HTTP requests.
Interface to key-value storage behind an HTTP server.
array $httpParams
http parameters: readHeaders, writeHeaders, deleteHeaders, writeMethod
__construct( $params)
string $serializationType
Optional serialization type to use.
setLogger(LoggerInterface $logger)
decr( $key, $value=1, $flags=0)
Decrease stored value of $key by $value while preserving its TTL.
const DEFAULT_CONN_TIMEOUT
Default connection timeout in seconds.
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
decodeBody( $body)
Processes the response body.
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
const DEFAULT_REQ_TIMEOUT
Default request timeout.
doGet( $key, $flags=0, &$casToken=null)
doDelete( $key, $flags=0)
Delete an item.
array $extendedErrorBodyFields
additional body fields to log on error, if possible
incr( $key, $value=1, $flags=0)
Increase stored value of $key by $value while preserving its TTL.
string $hmacKey
Optional HMAC Key for protecting the serialized blob.
encodeBody( $body)
Prepares the request body (the "value" portion of our key/value store) for transmission.
handleError( $msg, $rcode, $rerr, $rhdrs, $rbody)
Handle storage error.
string $url
REST URL to use for storage.
MultiHttpClient $client
foreach( $res as $row) $serialized