4 * Interface to key-value storage on HTTP RESTful server, such as RESTBase.
5 * Uses URL of the form URL/{KEY} to store/fetch/delete.
6 * E.g., when base URL is /v1/sessions/ then the store would do:
7 * PUT /v1/sessions/12345758
9 * GET /v1/sessions/12345758
11 * DELETE /v1/sessions/12345758
15 * $wgObjectCaches['sessions'] = array(
16 * 'class' => 'RESTBagOStuff',
17 * 'url' => 'http://localhost:7231/wikimedia.org/v1/sessions/'
21 class RESTBagOStuff
extends BagOStuff
{
24 * @var MultiHttpClient
29 * REST URL to use for storage.
34 public function __construct( $params ) {
35 if ( empty( $params['url'] ) ) {
36 throw new InvalidArgumentException( 'URL parameter is required' );
38 parent
::__construct( $params );
39 if ( empty( $params['client'] ) ) {
40 $this->client
= new MultiHttpClient( [] );
42 $this->client
= $params['client'];
44 // Make sure URL ends with /
45 $this->url
= rtrim( $params['url'], '/' ) . '/';
50 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
51 * @return mixed Returns false on failure and if the item does not exist
53 protected function doGet( $key, $flags = 0 ) {
56 'url' => $this->url
. rawurlencode( $key ),
59 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client
->run( $req );
60 if ( $rcode === 200 ) {
61 if ( is_string( $rbody ) ) {
62 return unserialize( $rbody );
66 if ( $rcode === 0 ||
( $rcode >= 400 && $rcode != 404 ) ) {
67 return $this->handleError( "Failed to fetch $key", $rcode, $rerr );
73 * Handle storage error
74 * @param string $msg Error message
75 * @param int $rcode Error code from client
76 * @param string $rerr Error message from client
79 protected function handleError( $msg, $rcode, $rerr ) {
80 $this->logger
->error( "$msg : ({code}) {error}", [
84 $this->setLastError( $rcode === 0 ? self
::ERR_UNREACHABLE
: self
::ERR_UNEXPECTED
);
93 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
94 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
95 * @return bool Success
97 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
100 'url' => $this->url
. rawurlencode( $key ),
101 'body' => serialize( $value )
103 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client
->run( $req );
104 if ( $rcode === 200 ||
$rcode === 201 ) {
107 return $this->handleError( "Failed to store $key", $rcode, $rerr );
114 * @return bool True if the item was deleted or not found, false on failure
116 public function delete( $key ) {
118 'method' => 'DELETE',
119 'url' => $this->url
. rawurlencode( $key ),
121 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client
->run( $req );
122 if ( $rcode === 200 ||
$rcode === 204 ||
$rcode === 205 ) {
125 return $this->handleError( "Failed to delete $key", $rcode, $rerr );