MediaWiki  master
RESTBagOStuff.php
Go to the documentation of this file.
1 <?php
2 
4 
53  const DEFAULT_CONN_TIMEOUT = 1.2;
54 
58  const DEFAULT_REQ_TIMEOUT = 3.0;
59 
63  private $client;
64 
69  private $url;
70 
74  private $httpParams;
75 
80 
81  public function __construct( $params ) {
82  $params['segmentationSize'] = $params['segmentationSize'] ?? INF;
83  if ( empty( $params['url'] ) ) {
84  throw new InvalidArgumentException( 'URL parameter is required' );
85  }
86 
87  if ( empty( $params['client'] ) ) {
88  // Pass through some params to the HTTP client.
89  $clientParams = [
90  'connTimeout' => $params['connTimeout'] ?? self::DEFAULT_CONN_TIMEOUT,
91  'reqTimeout' => $params['reqTimeout'] ?? self::DEFAULT_REQ_TIMEOUT,
92  ];
93  foreach ( [ 'caBundlePath', 'proxy' ] as $key ) {
94  if ( isset( $params[$key] ) ) {
95  $clientParams[$key] = $params[$key];
96  }
97  }
98  $this->client = new MultiHttpClient( $clientParams );
99  } else {
100  $this->client = $params['client'];
101  }
102 
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'] ?? [];
108 
109  // The parent constructor calls setLogger() which sets the logger in $this->client
110  parent::__construct( $params );
111 
112  // Make sure URL ends with /
113  $this->url = rtrim( $params['url'], '/' ) . '/';
114 
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;
117  }
118 
119  public function setLogger( LoggerInterface $logger ) {
120  parent::setLogger( $logger );
121  $this->client->setLogger( $logger );
122  }
123 
124  protected function doGet( $key, $flags = 0, &$casToken = null ) {
125  $casToken = null;
126 
127  $req = [
128  'method' => 'GET',
129  'url' => $this->url . rawurlencode( $key ),
130  'headers' => $this->httpParams['readHeaders'],
131  ];
132 
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 );
138  $casToken = ( $value !== false ) ? $rbody : null;
139 
140  return $value;
141  }
142  return false;
143  }
144  if ( $rcode === 0 || ( $rcode >= 400 && $rcode != 404 ) ) {
145  return $this->handleError( "Failed to fetch $key", $rcode, $rerr, $rhdrs, $rbody );
146  }
147  return false;
148  }
149 
150  protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
151  // @TODO: respect WRITE_SYNC (e.g. EACH_QUORUM)
152  // @TODO: respect $exptime
153  $req = [
154  'method' => $this->httpParams['writeMethod'],
155  'url' => $this->url . rawurlencode( $key ),
156  'body' => $this->encodeBody( $value ),
157  'headers' => $this->httpParams['writeHeaders'],
158  ];
159 
160  list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
161  if ( $rcode === 200 || $rcode === 201 || $rcode === 204 ) {
162  return true;
163  }
164  return $this->handleError( "Failed to store $key", $rcode, $rerr, $rhdrs, $rbody );
165  }
166 
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 );
171  }
172 
173  return false; // key already set
174  }
175 
176  protected function doDelete( $key, $flags = 0 ) {
177  // @TODO: respect WRITE_SYNC (e.g. EACH_QUORUM)
178  $req = [
179  'method' => 'DELETE',
180  'url' => $this->url . rawurlencode( $key ),
181  'headers' => $this->httpParams['deleteHeaders'],
182  ];
183 
184  list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->client->run( $req );
185  if ( in_array( $rcode, [ 200, 204, 205, 404, 410 ] ) ) {
186  return true;
187  }
188  return $this->handleError( "Failed to delete $key", $rcode, $rerr, $rhdrs, $rbody );
189  }
190 
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;
198  }
199 
200  return false;
201  }
202 
209  private function decodeBody( $body ) {
210  $value = json_decode( $body, true );
211  return ( json_last_error() === JSON_ERROR_NONE ) ? $value : false;
212  }
213 
221  private function encodeBody( $body ) {
222  $value = json_encode( $body );
223  if ( $value === false ) {
224  throw new InvalidArgumentException( __METHOD__ . ": body could not be encoded." );
225  }
226  return $value;
227  }
228 
238  protected function handleError( $msg, $rcode, $rerr, $rhdrs, $rbody ) {
239  $message = "$msg : ({code}) {error}";
240  $context = [
241  'code' => $rcode,
242  'error' => $rerr
243  ];
244 
245  if ( $this->extendedErrorBodyFields !== [] ) {
246  $body = $this->decodeBody( $rbody );
247  if ( $body ) {
248  $extraFields = '';
249  foreach ( $this->extendedErrorBodyFields as $field ) {
250  if ( isset( $body[$field] ) ) {
251  $extraFields .= " : ({$field}) {$body[$field]}";
252  }
253  }
254  if ( $extraFields !== '' ) {
255  $message .= " {extra_fields}";
256  $context['extra_fields'] = $extraFields;
257  }
258  }
259  }
260 
261  $this->logger->error( $message, $context );
262  $this->setLastError( $rcode === 0 ? self::ERR_UNREACHABLE : self::ERR_UNEXPECTED );
263  return false;
264  }
265 }
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
MultiHttpClient $client
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
add( $key, $value, $exptime=0, $flags=0)
$value
doDelete( $key, $flags=0)
__construct( $params)
decodeBody( $body)
Processes the response body.
handleError( $msg, $rcode, $rerr, $rhdrs, $rbody)
Handle storage error.
incr( $key, $value=1)
const DEFAULT_CONN_TIMEOUT
Default connection timeout in seconds.
$params
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
doGet( $key, $flags=0, &$casToken=null)
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Storage medium specific cache for storing items (e.g.
array $httpParams
http parameters: readHeaders, writeHeaders, deleteHeaders, writeMethod
array $extendedErrorBodyFields
additional body fields to log on error, if possible
Interface to key-value storage behind an HTTP server.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only $req
Definition: hooks.txt:960
LoggerInterface $logger
Definition: BagOStuff.php:65
encodeBody( $body)
Prepares the request body (the "value" portion of our key/value store) for transmission.
doSet( $key, $value, $exptime=0, $flags=0)
setLastError( $err)
Set the "last error" registry.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2621
const DEFAULT_REQ_TIMEOUT
Default request timeout.
isInteger( $value)
Check if a value is an integer.
Class to handle multiple HTTP requests.
string $url
REST URL to use for storage.
setLogger(LoggerInterface $logger)