MediaWiki REL1_32
VirtualRESTServiceClient.php
Go to the documentation of this file.
1<?php
47 private $http;
49 private $instances = [];
50
51 const VALID_MOUNT_REGEX = '#^/[0-9a-z]+/([0-9a-z]+/)*$#';
52
56 public function __construct( MultiHttpClient $http ) {
57 $this->http = $http;
58 }
59
70 public function mount( $prefix, $instance ) {
71 if ( !preg_match( self::VALID_MOUNT_REGEX, $prefix ) ) {
72 throw new UnexpectedValueException( "Invalid service mount point '$prefix'." );
73 } elseif ( isset( $this->instances[$prefix] ) ) {
74 throw new UnexpectedValueException( "A service is already mounted on '$prefix'." );
75 }
76 if ( !( $instance instanceof VirtualRESTService ) ) {
77 if ( !isset( $instance['class'] ) || !isset( $instance['config'] ) ) {
78 throw new UnexpectedValueException( "Missing 'class' or 'config' ('$prefix')." );
79 }
80 }
81 $this->instances[$prefix] = $instance;
82 }
83
89 public function unmount( $prefix ) {
90 if ( !preg_match( self::VALID_MOUNT_REGEX, $prefix ) ) {
91 throw new UnexpectedValueException( "Invalid service mount point '$prefix'." );
92 } elseif ( !isset( $this->instances[$prefix] ) ) {
93 throw new UnexpectedValueException( "No service is mounted on '$prefix'." );
94 }
95 unset( $this->instances[$prefix] );
96 }
97
104 public function getMountAndService( $path ) {
105 $cmpFunc = function ( $a, $b ) {
106 $al = substr_count( $a, '/' );
107 $bl = substr_count( $b, '/' );
108 return $bl <=> $al; // largest prefix first
109 };
110
111 $matches = []; // matching prefixes (mount points)
112 foreach ( $this->instances as $prefix => $unused ) {
113 if ( strpos( $path, $prefix ) === 0 ) {
114 $matches[] = $prefix;
115 }
116 }
117 usort( $matches, $cmpFunc );
118
119 // Return the most specific prefix and corresponding service
120 return $matches
121 ? [ $matches[0], $this->getInstance( $matches[0] ) ]
122 : [ null, null ];
123 }
124
141 public function run( array $req ) {
142 return $this->runMulti( [ $req ] )[0];
143 }
144
163 public function runMulti( array $reqs ) {
164 foreach ( $reqs as $index => &$req ) {
165 if ( isset( $req[0] ) ) {
166 $req['method'] = $req[0]; // short-form
167 unset( $req[0] );
168 }
169 if ( isset( $req[1] ) ) {
170 $req['url'] = $req[1]; // short-form
171 unset( $req[1] );
172 }
173 $req['chain'] = []; // chain or list of replaced requests
174 }
175 unset( $req ); // don't assign over this by accident
176
177 $curUniqueId = 0;
178 $armoredIndexMap = []; // (original index => new index)
179
180 $doneReqs = []; // (index => request)
181 $executeReqs = []; // (index => request)
182 $replaceReqsByService = []; // (prefix => index => request)
183 $origPending = []; // (index => 1) for original requests
184
185 foreach ( $reqs as $origIndex => $req ) {
186 // Re-index keys to consecutive integers (they will be swapped back later)
187 $index = $curUniqueId++;
188 $armoredIndexMap[$origIndex] = $index;
189 $origPending[$index] = 1;
190 if ( preg_match( '#^(http|ftp)s?://#', $req['url'] ) ) {
191 // Absolute FTP/HTTP(S) URL, run it as normal
192 $executeReqs[$index] = $req;
193 } else {
194 // Must be a virtual HTTP URL; resolve it
195 list( $prefix, $service ) = $this->getMountAndService( $req['url'] );
196 if ( !$service ) {
197 throw new UnexpectedValueException( "Path '{$req['url']}' has no service." );
198 }
199 // Set the URL to the mount-relative portion
200 $req['url'] = substr( $req['url'], strlen( $prefix ) );
201 $replaceReqsByService[$prefix][$index] = $req;
202 }
203 }
204
205 // Function to get IDs that won't collide with keys in $armoredIndexMap
206 $idFunc = function () use ( &$curUniqueId ) {
207 return $curUniqueId++;
208 };
209
210 $rounds = 0;
211 do {
212 if ( ++$rounds > 5 ) { // sanity
213 throw new Exception( "Too many replacement rounds detected. Aborting." );
214 }
215 // Track requests executed this round that have a prefix/service.
216 // Note that this also includes requests where 'response' was forced.
217 $checkReqIndexesByPrefix = [];
218 // Resolve the virtual URLs valid and qualified HTTP(S) URLs
219 // and add any required authentication headers for the backend.
220 // Services can also replace requests with new ones, either to
221 // defer the original or to set a proxy response to the original.
222 $newReplaceReqsByService = [];
223 foreach ( $replaceReqsByService as $prefix => $servReqs ) {
224 $service = $this->getInstance( $prefix );
225 foreach ( $service->onRequests( $servReqs, $idFunc ) as $index => $req ) {
226 // Services use unique IDs for replacement requests
227 if ( isset( $servReqs[$index] ) || isset( $origPending[$index] ) ) {
228 // A current or original request which was not modified
229 } else {
230 // Replacement request that will convert to original requests
231 $newReplaceReqsByService[$prefix][$index] = $req;
232 }
233 if ( isset( $req['response'] ) ) {
234 // Replacement requests with pre-set responses should not execute
235 unset( $executeReqs[$index] );
236 unset( $origPending[$index] );
237 $doneReqs[$index] = $req;
238 } else {
239 // Original or mangled request included
240 $executeReqs[$index] = $req;
241 }
242 $checkReqIndexesByPrefix[$prefix][$index] = 1;
243 }
244 }
245 // Run the actual work HTTP requests
246 foreach ( $this->http->runMulti( $executeReqs ) as $index => $ranReq ) {
247 $doneReqs[$index] = $ranReq;
248 unset( $origPending[$index] );
249 }
250 $executeReqs = [];
251 // Services can also replace requests with new ones, either to
252 // defer the original or to set a proxy response to the original.
253 // Any replacement requests executed above will need to be replaced
254 // with new requests (eventually the original). The responses can be
255 // forced by setting 'response' rather than actually be sent over the wire.
256 $newReplaceReqsByService = [];
257 foreach ( $checkReqIndexesByPrefix as $prefix => $servReqIndexes ) {
258 $service = $this->getInstance( $prefix );
259 // $doneReqs actually has the requests (with 'response' set)
260 $servReqs = array_intersect_key( $doneReqs, $servReqIndexes );
261 foreach ( $service->onResponses( $servReqs, $idFunc ) as $index => $req ) {
262 // Services use unique IDs for replacement requests
263 if ( isset( $servReqs[$index] ) || isset( $origPending[$index] ) ) {
264 // A current or original request which was not modified
265 } else {
266 // Replacement requests with pre-set responses should not execute
267 $newReplaceReqsByService[$prefix][$index] = $req;
268 }
269 if ( isset( $req['response'] ) ) {
270 // Replacement requests with pre-set responses should not execute
271 unset( $origPending[$index] );
272 $doneReqs[$index] = $req;
273 } else {
274 // Update the request in case it was mangled
275 $executeReqs[$index] = $req;
276 }
277 }
278 }
279 // Update index of requests to inspect for replacement
280 $replaceReqsByService = $newReplaceReqsByService;
281 } while ( count( $origPending ) );
282
283 $responses = [];
284 // Update $reqs to include 'response' and normalized request 'headers'.
285 // This maintains the original order of $reqs.
286 foreach ( $reqs as $origIndex => $req ) {
287 $index = $armoredIndexMap[$origIndex];
288 if ( !isset( $doneReqs[$index] ) ) {
289 throw new UnexpectedValueException( "Response for request '$index' is NULL." );
290 }
291 $responses[$origIndex] = $doneReqs[$index]['response'];
292 }
293
294 return $responses;
295 }
296
301 private function getInstance( $prefix ) {
302 if ( !isset( $this->instances[$prefix] ) ) {
303 throw new RuntimeException( "No service registered at prefix '{$prefix}'." );
304 }
305
306 if ( !( $this->instances[$prefix] instanceof VirtualRESTService ) ) {
307 $config = $this->instances[$prefix]['config'];
308 $class = $this->instances[$prefix]['class'];
309 $service = new $class( $config );
310 if ( !( $service instanceof VirtualRESTService ) ) {
311 throw new UnexpectedValueException( "Registered service has the wrong class." );
312 }
313 $this->instances[$prefix] = $service;
314 }
315
316 return $this->instances[$prefix];
317 }
318}
Apache License January http
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Class to handle multiple HTTP requests.
Virtual HTTP service client loosely styled after a Virtual File System.
mount( $prefix, $instance)
Map a prefix to service handler.
array $instances
Map of (prefix => VirtualRESTService|array)
unmount( $prefix)
Unmap a prefix to service handler.
run(array $req)
Execute a virtual HTTP(S) request.
runMulti(array $reqs)
Execute a set of virtual HTTP(S) requests concurrently.
__construct(MultiHttpClient $http)
getMountAndService( $path)
Get the prefix and service that a virtual path is serviced by.
Virtual HTTP service instance that can be mounted on to a VirtualRESTService.
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
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
this hook is for auditing only $req
Definition hooks.txt:1018
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:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))