MediaWiki  master
VirtualRESTServiceClient.php
Go to the documentation of this file.
1 <?php
47  private $http;
49  private $instances = [];
50 
51  private 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  // @phan-suppress-next-line PhanRedundantCondition
121  return $matches
122  ? [ $matches[0], $this->getInstance( $matches[0] ) ]
123  : [ null, null ];
124  }
125 
142  public function run( array $req ) {
143  return $this->runMulti( [ $req ] )[0];
144  }
145 
164  public function runMulti( array $reqs ) {
165  foreach ( $reqs as $index => &$req ) {
166  if ( isset( $req[0] ) ) {
167  $req['method'] = $req[0]; // short-form
168  unset( $req[0] );
169  }
170  if ( isset( $req[1] ) ) {
171  $req['url'] = $req[1]; // short-form
172  unset( $req[1] );
173  }
174  $req['chain'] = []; // chain or list of replaced requests
175  }
176  unset( $req ); // don't assign over this by accident
177 
178  $curUniqueId = 0;
179  $armoredIndexMap = []; // (original index => new index)
180 
181  $doneReqs = []; // (index => request)
182  $executeReqs = []; // (index => request)
183  $replaceReqsByService = []; // (prefix => index => request)
184  $origPending = []; // (index => 1) for original requests
185 
186  foreach ( $reqs as $origIndex => $req ) {
187  // Re-index keys to consecutive integers (they will be swapped back later)
188  $index = $curUniqueId++;
189  $armoredIndexMap[$origIndex] = $index;
190  $origPending[$index] = 1;
191  if ( preg_match( '#^(http|ftp)s?://#', $req['url'] ) ) {
192  // Absolute FTP/HTTP(S) URL, run it as normal
193  $executeReqs[$index] = $req;
194  } else {
195  // Must be a virtual HTTP URL; resolve it
196  list( $prefix, $service ) = $this->getMountAndService( $req['url'] );
197  if ( !$service ) {
198  throw new UnexpectedValueException( "Path '{$req['url']}' has no service." );
199  }
200  // Set the URL to the mount-relative portion
201  $req['url'] = substr( $req['url'], strlen( $prefix ) );
202  $replaceReqsByService[$prefix][$index] = $req;
203  }
204  }
205 
206  // Function to get IDs that won't collide with keys in $armoredIndexMap
207  $idFunc = function () use ( &$curUniqueId ) {
208  return $curUniqueId++;
209  };
210 
211  $rounds = 0;
212  do {
213  if ( ++$rounds > 5 ) { // sanity
214  throw new Exception( "Too many replacement rounds detected. Aborting." );
215  }
216  // Track requests executed this round that have a prefix/service.
217  // Note that this also includes requests where 'response' was forced.
218  $checkReqIndexesByPrefix = [];
219  // Resolve the virtual URLs valid and qualified HTTP(S) URLs
220  // and add any required authentication headers for the backend.
221  // Services can also replace requests with new ones, either to
222  // defer the original or to set a proxy response to the original.
223  $newReplaceReqsByService = [];
224  foreach ( $replaceReqsByService as $prefix => $servReqs ) {
225  $service = $this->getInstance( $prefix );
226  foreach ( $service->onRequests( $servReqs, $idFunc ) as $index => $req ) {
227  // Services use unique IDs for replacement requests
228  if ( isset( $servReqs[$index] ) || isset( $origPending[$index] ) ) {
229  // A current or original request which was not modified
230  } else {
231  // Replacement request that will convert to original requests
232  $newReplaceReqsByService[$prefix][$index] = $req;
233  }
234  if ( isset( $req['response'] ) ) {
235  // Replacement requests with pre-set responses should not execute
236  unset( $executeReqs[$index] );
237  unset( $origPending[$index] );
238  $doneReqs[$index] = $req;
239  } else {
240  // Original or mangled request included
241  $executeReqs[$index] = $req;
242  }
243  $checkReqIndexesByPrefix[$prefix][$index] = 1;
244  }
245  }
246 
247  // Expand protocol-relative URLs
248  foreach ( $executeReqs as $index => &$req ) {
249  if ( preg_match( '#^//#', $req['url'] ) ) {
250  $req['url'] = wfExpandUrl( $req['url'], PROTO_CURRENT );
251  }
252  }
253 
254  // Run the actual work HTTP requests
255  foreach ( $this->http->runMulti( $executeReqs ) as $index => $ranReq ) {
256  $doneReqs[$index] = $ranReq;
257  unset( $origPending[$index] );
258  }
259  $executeReqs = [];
260  // Services can also replace requests with new ones, either to
261  // defer the original or to set a proxy response to the original.
262  // Any replacement requests executed above will need to be replaced
263  // with new requests (eventually the original). The responses can be
264  // forced by setting 'response' rather than actually be sent over the wire.
265  $newReplaceReqsByService = [];
266  foreach ( $checkReqIndexesByPrefix as $prefix => $servReqIndexes ) {
267  $service = $this->getInstance( $prefix );
268  // $doneReqs actually has the requests (with 'response' set)
269  $servReqs = array_intersect_key( $doneReqs, $servReqIndexes );
270  foreach ( $service->onResponses( $servReqs, $idFunc ) as $index => $req ) {
271  // Services use unique IDs for replacement requests
272  if ( isset( $servReqs[$index] ) || isset( $origPending[$index] ) ) {
273  // A current or original request which was not modified
274  } else {
275  // Replacement requests with pre-set responses should not execute
276  $newReplaceReqsByService[$prefix][$index] = $req;
277  }
278  if ( isset( $req['response'] ) ) {
279  // Replacement requests with pre-set responses should not execute
280  unset( $origPending[$index] );
281  $doneReqs[$index] = $req;
282  } else {
283  // Update the request in case it was mangled
284  $executeReqs[$index] = $req;
285  }
286  }
287  }
288  // Update index of requests to inspect for replacement
289  $replaceReqsByService = $newReplaceReqsByService;
290  } while ( count( $origPending ) );
291 
292  $responses = [];
293  // Update $reqs to include 'response' and normalized request 'headers'.
294  // This maintains the original order of $reqs.
295  foreach ( $reqs as $origIndex => $req ) {
296  $index = $armoredIndexMap[$origIndex];
297  if ( !isset( $doneReqs[$index] ) ) {
298  throw new UnexpectedValueException( "Response for request '$index' is NULL." );
299  }
300  $responses[$origIndex] = $doneReqs[$index]['response'];
301  }
302 
303  return $responses;
304  }
305 
310  private function getInstance( $prefix ) {
311  if ( !isset( $this->instances[$prefix] ) ) {
312  throw new RuntimeException( "No service registered at prefix '{$prefix}'." );
313  }
314 
315  if ( !( $this->instances[$prefix] instanceof VirtualRESTService ) ) {
316  $config = $this->instances[$prefix]['config'];
317  $class = $this->instances[$prefix]['class'];
318  $service = new $class( $config );
319  if ( !( $service instanceof VirtualRESTService ) ) {
320  throw new UnexpectedValueException( "Registered service has the wrong class." );
321  }
322  $this->instances[$prefix] = $service;
323  }
324 
325  return $this->instances[$prefix];
326  }
327 }
VirtualRESTServiceClient\run
run(array $req)
Execute a virtual HTTP(S) request.
Definition: VirtualRESTServiceClient.php:142
MultiHttpClient
Class to handle multiple HTTP requests.
Definition: MultiHttpClient.php:55
VirtualRESTServiceClient\$instances
array $instances
Map of (prefix => VirtualRESTService|array)
Definition: VirtualRESTServiceClient.php:49
VirtualRESTServiceClient\$http
MultiHttpClient $http
Definition: VirtualRESTServiceClient.php:47
VirtualRESTServiceClient\runMulti
runMulti(array $reqs)
Execute a set of virtual HTTP(S) requests concurrently.
Definition: VirtualRESTServiceClient.php:164
VirtualRESTServiceClient\VALID_MOUNT_REGEX
const VALID_MOUNT_REGEX
Definition: VirtualRESTServiceClient.php:51
$matches
$matches
Definition: NoLocalSettings.php:24
VirtualRESTServiceClient
Virtual HTTP service client loosely styled after a Virtual File System.
Definition: VirtualRESTServiceClient.php:45
VirtualRESTServiceClient\mount
mount( $prefix, $instance)
Map a prefix to service handler.
Definition: VirtualRESTServiceClient.php:70
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:211
VirtualRESTServiceClient\getMountAndService
getMountAndService( $path)
Get the prefix and service that a virtual path is serviced by.
Definition: VirtualRESTServiceClient.php:104
VirtualRESTServiceClient\getInstance
getInstance( $prefix)
Definition: VirtualRESTServiceClient.php:310
VirtualRESTServiceClient\__construct
__construct(MultiHttpClient $http)
Definition: VirtualRESTServiceClient.php:56
VirtualRESTServiceClient\unmount
unmount( $prefix)
Unmap a prefix to service handler.
Definition: VirtualRESTServiceClient.php:89
$path
$path
Definition: NoLocalSettings.php:25
VirtualRESTService
Virtual HTTP service instance that can be mounted on to a VirtualRESTService.
Definition: VirtualRESTService.php:36
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:490