MediaWiki REL1_31
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 if ( $al === $bl ) {
109 return 0; // should not actually happen
110 }
111 return ( $al < $bl ) ? 1 : -1; // largest prefix first
112 };
113
114 $matches = []; // matching prefixes (mount points)
115 foreach ( $this->instances as $prefix => $unused ) {
116 if ( strpos( $path, $prefix ) === 0 ) {
117 $matches[] = $prefix;
118 }
119 }
120 usort( $matches, $cmpFunc );
121
122 // Return the most specific prefix and corresponding service
123 return $matches
124 ? [ $matches[0], $this->getInstance( $matches[0] ) ]
125 : [ null, null ];
126 }
127
144 public function run( array $req ) {
145 return $this->runMulti( [ $req ] )[0];
146 }
147
166 public function runMulti( array $reqs ) {
167 foreach ( $reqs as $index => &$req ) {
168 if ( isset( $req[0] ) ) {
169 $req['method'] = $req[0]; // short-form
170 unset( $req[0] );
171 }
172 if ( isset( $req[1] ) ) {
173 $req['url'] = $req[1]; // short-form
174 unset( $req[1] );
175 }
176 $req['chain'] = []; // chain or list of replaced requests
177 }
178 unset( $req ); // don't assign over this by accident
179
180 $curUniqueId = 0;
181 $armoredIndexMap = []; // (original index => new index)
182
183 $doneReqs = []; // (index => request)
184 $executeReqs = []; // (index => request)
185 $replaceReqsByService = []; // (prefix => index => request)
186 $origPending = []; // (index => 1) for original requests
187
188 foreach ( $reqs as $origIndex => $req ) {
189 // Re-index keys to consecutive integers (they will be swapped back later)
190 $index = $curUniqueId++;
191 $armoredIndexMap[$origIndex] = $index;
192 $origPending[$index] = 1;
193 if ( preg_match( '#^(http|ftp)s?://#', $req['url'] ) ) {
194 // Absolute FTP/HTTP(S) URL, run it as normal
195 $executeReqs[$index] = $req;
196 } else {
197 // Must be a virtual HTTP URL; resolve it
198 list( $prefix, $service ) = $this->getMountAndService( $req['url'] );
199 if ( !$service ) {
200 throw new UnexpectedValueException( "Path '{$req['url']}' has no service." );
201 }
202 // Set the URL to the mount-relative portion
203 $req['url'] = substr( $req['url'], strlen( $prefix ) );
204 $replaceReqsByService[$prefix][$index] = $req;
205 }
206 }
207
208 // Function to get IDs that won't collide with keys in $armoredIndexMap
209 $idFunc = function () use ( &$curUniqueId ) {
210 return $curUniqueId++;
211 };
212
213 $rounds = 0;
214 do {
215 if ( ++$rounds > 5 ) { // sanity
216 throw new Exception( "Too many replacement rounds detected. Aborting." );
217 }
218 // Track requests executed this round that have a prefix/service.
219 // Note that this also includes requests where 'response' was forced.
220 $checkReqIndexesByPrefix = [];
221 // Resolve the virtual URLs valid and qualified HTTP(S) URLs
222 // and add any required authentication headers for the backend.
223 // Services can also replace requests with new ones, either to
224 // defer the original or to set a proxy response to the original.
225 $newReplaceReqsByService = [];
226 foreach ( $replaceReqsByService as $prefix => $servReqs ) {
227 $service = $this->getInstance( $prefix );
228 foreach ( $service->onRequests( $servReqs, $idFunc ) as $index => $req ) {
229 // Services use unique IDs for replacement requests
230 if ( isset( $servReqs[$index] ) || isset( $origPending[$index] ) ) {
231 // A current or original request which was not modified
232 } else {
233 // Replacement request that will convert to original requests
234 $newReplaceReqsByService[$prefix][$index] = $req;
235 }
236 if ( isset( $req['response'] ) ) {
237 // Replacement requests with pre-set responses should not execute
238 unset( $executeReqs[$index] );
239 unset( $origPending[$index] );
240 $doneReqs[$index] = $req;
241 } else {
242 // Original or mangled request included
243 $executeReqs[$index] = $req;
244 }
245 $checkReqIndexesByPrefix[$prefix][$index] = 1;
246 }
247 }
248 // Run the actual work HTTP requests
249 foreach ( $this->http->runMulti( $executeReqs ) as $index => $ranReq ) {
250 $doneReqs[$index] = $ranReq;
251 unset( $origPending[$index] );
252 }
253 $executeReqs = [];
254 // Services can also replace requests with new ones, either to
255 // defer the original or to set a proxy response to the original.
256 // Any replacement requests executed above will need to be replaced
257 // with new requests (eventually the original). The responses can be
258 // forced by setting 'response' rather than actually be sent over the wire.
259 $newReplaceReqsByService = [];
260 foreach ( $checkReqIndexesByPrefix as $prefix => $servReqIndexes ) {
261 $service = $this->getInstance( $prefix );
262 // $doneReqs actually has the requests (with 'response' set)
263 $servReqs = array_intersect_key( $doneReqs, $servReqIndexes );
264 foreach ( $service->onResponses( $servReqs, $idFunc ) as $index => $req ) {
265 // Services use unique IDs for replacement requests
266 if ( isset( $servReqs[$index] ) || isset( $origPending[$index] ) ) {
267 // A current or original request which was not modified
268 } else {
269 // Replacement requests with pre-set responses should not execute
270 $newReplaceReqsByService[$prefix][$index] = $req;
271 }
272 if ( isset( $req['response'] ) ) {
273 // Replacement requests with pre-set responses should not execute
274 unset( $origPending[$index] );
275 $doneReqs[$index] = $req;
276 } else {
277 // Update the request in case it was mangled
278 $executeReqs[$index] = $req;
279 }
280 }
281 }
282 // Update index of requests to inspect for replacement
283 $replaceReqsByService = $newReplaceReqsByService;
284 } while ( count( $origPending ) );
285
286 $responses = [];
287 // Update $reqs to include 'response' and normalized request 'headers'.
288 // This maintains the original order of $reqs.
289 foreach ( $reqs as $origIndex => $req ) {
290 $index = $armoredIndexMap[$origIndex];
291 if ( !isset( $doneReqs[$index] ) ) {
292 throw new UnexpectedValueException( "Response for request '$index' is NULL." );
293 }
294 $responses[$origIndex] = $doneReqs[$index]['response'];
295 }
296
297 return $responses;
298 }
299
304 private function getInstance( $prefix ) {
305 if ( !isset( $this->instances[$prefix] ) ) {
306 throw new RuntimeException( "No service registered at prefix '{$prefix}'." );
307 }
308
309 if ( !( $this->instances[$prefix] instanceof VirtualRESTService ) ) {
310 $config = $this->instances[$prefix]['config'];
311 $class = $this->instances[$prefix]['class'];
312 $service = new $class( $config );
313 if ( !( $service instanceof VirtualRESTService ) ) {
314 throw new UnexpectedValueException( "Registered service has the wrong class." );
315 }
316 $this->instances[$prefix] = $service;
317 }
318
319 return $this->instances[$prefix];
320 }
321}
Apache License January http
Class to handle concurrent 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 hook is for auditing only $req
Definition hooks.txt:990