3 use Psr\Log\LoggerInterface
;
6 * Interface to key-value storage behind an HTTP server.
8 * Uses URL of the form "baseURL/{KEY}" to store, fetch, and delete values.
10 * E.g., when base URL is `/sessions/v1`, then the store would do:
12 * `PUT /sessions/v1/12345758`
16 * `GET /sessions/v1/12345758`
20 * `DELETE /sessions/v1/12345758`
22 * Minimal generic configuration:
25 * $wgObjectCaches['sessions'] = array(
26 * 'class' => 'RESTBagOStuff',
27 * 'url' => 'http://localhost:7231/wikimedia.org/somepath/'
31 * Configuration for Kask (session storage):
33 * $wgObjectCaches['sessions'] = array(
34 * 'class' => 'RESTBagOStuff',
35 * 'url' => 'https://kaskhost:1234/sessions/v1/',
37 * 'readHeaders' => [],
38 * 'writeHeaders' => [ 'content-type' => 'application/octet-stream' ],
39 * 'deleteHeaders' => [],
40 * 'writeMethod' => 'POST',
42 * 'extendedErrorBodyFields' => [ 'type', 'title', 'detail', 'instance' ]
44 * $wgSessionCacheType = 'sessions';
47 class RESTBagOStuff
extends BagOStuff
{
49 * Default connection timeout in seconds. The kernel retransmits the SYN
50 * packet after 1 second, so 1.2 seconds allows for 1 retransmit without
53 const DEFAULT_CONN_TIMEOUT
= 1.2;
56 * Default request timeout
58 const DEFAULT_REQ_TIMEOUT
= 3.0;
61 * @var MultiHttpClient
66 * REST URL to use for storage.
72 * @var array http parameters: readHeaders, writeHeaders, deleteHeaders, writeMethod
77 * @var array additional body fields to log on error, if possible
79 private $extendedErrorBodyFields;
81 public function __construct( $params ) {
82 $params['segmentationSize'] = $params['segmentationSize'] ?? INF
;
83 if ( empty( $params['url'] ) ) {
84 throw new InvalidArgumentException( 'URL parameter is required' );
87 if ( empty( $params['client'] ) ) {
88 // Pass through some params to the HTTP client.
90 'connTimeout' => $params['connTimeout'] ?? self
::DEFAULT_CONN_TIMEOUT
,
91 'reqTimeout' => $params['reqTimeout'] ?? self
::DEFAULT_REQ_TIMEOUT
,
93 foreach ( [ 'caBundlePath', 'proxy' ] as $key ) {
94 if ( isset( $params[$key] ) ) {
95 $clientParams[$key] = $params[$key];
98 $this->client
= new MultiHttpClient( $clientParams );
100 $this->client
= $params['client'];
103 $this->httpParams
['writeMethod'] = $params['httpParams']['writeMethod'] ??
'PUT';
104 $this->httpParams
['readHeaders'] = $params['httpParams']['readHeaders'] ??
[];
105 $this->httpParams
['writeHeaders'] = $params['httpParams']['writeHeaders'] ??
[];
106 $this->httpParams
['deleteHeaders'] = $params['httpParams']['deleteHeaders'] ??
[];
107 $this->extendedErrorBodyFields
= $params['extendedErrorBodyFields'] ??
[];
109 // The parent constructor calls setLogger() which sets the logger in $this->client
110 parent
::__construct( $params );
112 // Make sure URL ends with /
113 $this->url
= rtrim( $params['url'], '/' ) . '/';
115 // Default config, R+W > N; no locks on reads though; writes go straight to state-machine
116 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_QC
;
119 public function setLogger( LoggerInterface
$logger ) {
120 parent
::setLogger( $logger );
121 $this->client
->setLogger( $logger );
124 protected function doGet( $key, $flags = 0, &$casToken = null ) {
129 'url' => $this->url
. rawurlencode( $key ),
130 'headers' => $this->httpParams
['readHeaders'],
133 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client
->run( $req );
134 if ( $rcode === 200 ) {
135 if ( is_string( $rbody ) ) {
136 $value = $this->decodeBody( $rbody );
137 /// @FIXME: use some kind of hash or UUID header as CAS token
138 $casToken = ( $value !== false ) ?
$rbody : null;
144 if ( $rcode === 0 ||
( $rcode >= 400 && $rcode != 404 ) ) {
145 return $this->handleError( "Failed to fetch $key", $rcode, $rerr, $rhdrs, $rbody );
150 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
151 // @TODO: respect WRITE_SYNC (e.g. EACH_QUORUM)
152 // @TODO: respect $exptime
154 'method' => $this->httpParams
['writeMethod'],
155 'url' => $this->url
. rawurlencode( $key ),
156 'body' => $this->encodeBody( $value ),
157 'headers' => $this->httpParams
['writeHeaders'],
160 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client
->run( $req );
161 if ( $rcode === 200 ||
$rcode === 201 ||
$rcode === 204 ) {
164 return $this->handleError( "Failed to store $key", $rcode, $rerr, $rhdrs, $rbody );
167 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
168 // @TODO: make this atomic
169 if ( $this->get( $key ) === false ) {
170 return $this->set( $key, $value, $exptime, $flags );
173 return false; // key already set
176 protected function doDelete( $key, $flags = 0 ) {
177 // @TODO: respect WRITE_SYNC (e.g. EACH_QUORUM)
179 'method' => 'DELETE',
180 'url' => $this->url
. rawurlencode( $key ),
181 'headers' => $this->httpParams
['deleteHeaders'],
184 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client
->run( $req );
185 if ( in_array( $rcode, [ 200, 204, 205, 404, 410 ] ) ) {
188 return $this->handleError( "Failed to delete $key", $rcode, $rerr, $rhdrs, $rbody );
191 public function incr( $key, $value = 1 ) {
192 // @TODO: make this atomic
193 $n = $this->get( $key, self
::READ_LATEST
);
194 if ( $this->isInteger( $n ) ) { // key exists?
195 $n = max( $n +
intval( $value ), 0 );
196 // @TODO: respect $exptime
197 return $this->set( $key, $n ) ?
$n : false;
204 * Processes the response body.
206 * @param string $body request body to process
207 * @return mixed|bool the processed body, or false on error
209 private function decodeBody( $body ) {
210 $value = json_decode( $body, true );
211 return ( json_last_error() === JSON_ERROR_NONE
) ?
$value : false;
215 * Prepares the request body (the "value" portion of our key/value store) for transmission.
217 * @param string $body request body to prepare
218 * @return string the prepared body, or an empty string on error
219 * @throws LogicException
221 private function encodeBody( $body ) {
222 $value = json_encode( $body );
223 if ( $value === false ) {
224 throw new InvalidArgumentException( __METHOD__
. ": body could not be encoded." );
230 * Handle storage error
231 * @param string $msg Error message
232 * @param int $rcode Error code from client
233 * @param string $rerr Error message from client
234 * @param array $rhdrs Response headers
235 * @param string $rbody Error body from client (if any)
238 protected function handleError( $msg, $rcode, $rerr, $rhdrs, $rbody ) {
239 $message = "$msg : ({code}) {error}";
245 if ( $this->extendedErrorBodyFields
!== [] ) {
246 $body = $this->decodeBody( $rbody );
249 foreach ( $this->extendedErrorBodyFields
as $field ) {
250 if ( isset( $body[$field] ) ) {
251 $extraFields .= " : ({$field}) {$body[$field]}";
254 if ( $extraFields !== '' ) {
255 $message .= " {extra_fields}";
256 $context['extra_fields'] = $extraFields;
261 $this->logger
->error( $message, $context );
262 $this->setLastError( $rcode === 0 ? self
::ERR_UNREACHABLE
: self
::ERR_UNEXPECTED
);