3 * Virtual HTTP service client
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Virtual HTTP service client loosely styled after a Virtual File System
26 * Services can be mounted on path prefixes so that virtual HTTP operations
27 * against sub-paths will map to those services. Operations can actually be
28 * done using HTTP messages over the wire or may simple be emulated locally.
30 * Virtual HTTP request maps are arrays that use the following format:
31 * - method : GET/HEAD/PUT/POST/DELETE
32 * - url : HTTP/HTTPS URL or virtual service path with a registered prefix
33 * - query : <query parameter field/value associative array> (uses RFC 3986)
34 * - headers : <header name/value associative array>
35 * - body : source to get the HTTP request body from;
36 * this can simply be a string (always), a resource for
37 * PUT requests, and a field/value array for POST request;
38 * array bodies are encoded as multipart/form-data and strings
39 * use application/x-www-form-urlencoded (headers sent automatically)
40 * - stream : resource to stream the HTTP response body to
41 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
45 class VirtualRESTServiceClient
{
46 /** @var MultiHttpClient */
48 /** @var array Map of (prefix => VirtualRESTService|array) */
49 private $instances = [];
51 const VALID_MOUNT_REGEX
= '#^/[0-9a-z]+/([0-9a-z]+/)*$#';
54 * @param MultiHttpClient $http
56 public function __construct( MultiHttpClient
$http ) {
61 * Map a prefix to service handler
63 * If $instance is in array, it must have these keys:
64 * - class : string; fully qualified VirtualRESTService class name
65 * - config : array; map of parameters that is the first __construct() argument
67 * @param string $prefix Virtual path
68 * @param VirtualRESTService|array $instance Service or info to yield the service
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'." );
76 if ( !( $instance instanceof VirtualRESTService
) ) {
77 if ( !isset( $instance['class'] ) ||
!isset( $instance['config'] ) ) {
78 throw new UnexpectedValueException( "Missing 'class' or 'config' ('$prefix')." );
81 $this->instances
[$prefix] = $instance;
85 * Unmap a prefix to service handler
87 * @param string $prefix Virtual path
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'." );
95 unset( $this->instances
[$prefix] );
99 * Get the prefix and service that a virtual path is serviced by
101 * @param string $path
102 * @return array (prefix,VirtualRESTService) or (null,null) if none found
104 public function getMountAndService( $path ) {
105 $cmpFunc = function ( $a, $b ) {
106 $al = substr_count( $a, '/' );
107 $bl = substr_count( $b, '/' );
109 return 0; // should not actually happen
111 return ( $al < $bl ) ?
1 : -1; // largest prefix first
114 $matches = []; // matching prefixes (mount points)
115 foreach ( $this->instances
as $prefix => $unused ) {
116 if ( strpos( $path, $prefix ) === 0 ) {
117 $matches[] = $prefix;
120 usort( $matches, $cmpFunc );
122 // Return the most specific prefix and corresponding service
124 ?
[ $matches[0], $this->getInstance( $matches[0] ) ]
129 * Execute a virtual HTTP(S) request
131 * This method returns a response map of:
132 * - code : HTTP response code or 0 if there was a serious cURL error
133 * - reason : HTTP response reason (empty if there was a serious cURL error)
134 * - headers : <header name/value associative array>
135 * - body : HTTP response body or resource (if "stream" was set)
136 * - error : Any cURL error string
137 * The map also stores integer-indexed copies of these values. This lets callers do:
139 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $client->run( $req );
141 * @param array $req Virtual HTTP request maps
142 * @return array Response array for request
144 public function run( array $req ) {
145 return $this->runMulti( [ $req ] )[0];
149 * Execute a set of virtual HTTP(S) requests concurrently
151 * A map of requests keys to response maps is returned. Each response map has:
152 * - code : HTTP response code or 0 if there was a serious cURL error
153 * - reason : HTTP response reason (empty if there was a serious cURL error)
154 * - headers : <header name/value associative array>
155 * - body : HTTP response body or resource (if "stream" was set)
156 * - error : Any cURL error string
157 * The map also stores integer-indexed copies of these values. This lets callers do:
159 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $responses[0];
162 * @param array $reqs Map of Virtual HTTP request maps
163 * @return array $reqs Map of corresponding response values with the same keys/order
166 public function runMulti( array $reqs ) {
167 foreach ( $reqs as $index => &$req ) {
168 if ( isset( $req[0] ) ) {
169 $req['method'] = $req[0]; // short-form
172 if ( isset( $req[1] ) ) {
173 $req['url'] = $req[1]; // short-form
176 $req['chain'] = []; // chain or list of replaced requests
178 unset( $req ); // don't assign over this by accident
181 $armoredIndexMap = []; // (original index => new index)
183 $doneReqs = []; // (index => request)
184 $executeReqs = []; // (index => request)
185 $replaceReqsByService = []; // (prefix => index => request)
186 $origPending = []; // (index => 1) for original requests
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;
197 // Must be a virtual HTTP URL; resolve it
198 list( $prefix, $service ) = $this->getMountAndService( $req['url'] );
200 throw new UnexpectedValueException( "Path '{$req['url']}' has no service." );
202 // Set the URL to the mount-relative portion
203 $req['url'] = substr( $req['url'], strlen( $prefix ) );
204 $replaceReqsByService[$prefix][$index] = $req;
208 // Function to get IDs that won't collide with keys in $armoredIndexMap
209 $idFunc = function () use ( &$curUniqueId ) {
210 return $curUniqueId++
;
215 if ( ++
$rounds > 5 ) { // sanity
216 throw new Exception( "Too many replacement rounds detected. Aborting." );
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
233 // Replacement request that will convert to original requests
234 $newReplaceReqsByService[$prefix][$index] = $req;
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;
242 // Original or mangled request included
243 $executeReqs[$index] = $req;
245 $checkReqIndexesByPrefix[$prefix][$index] = 1;
248 // Run the actual work HTTP requests
249 foreach ( $this->http
->runMulti( $executeReqs ) as $index => $ranReq ) {
250 $doneReqs[$index] = $ranReq;
251 unset( $origPending[$index] );
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
269 // Replacement requests with pre-set responses should not execute
270 $newReplaceReqsByService[$prefix][$index] = $req;
272 if ( isset( $req['response'] ) ) {
273 // Replacement requests with pre-set responses should not execute
274 unset( $origPending[$index] );
275 $doneReqs[$index] = $req;
277 // Update the request in case it was mangled
278 $executeReqs[$index] = $req;
282 // Update index of requests to inspect for replacement
283 $replaceReqsByService = $newReplaceReqsByService;
284 } while ( count( $origPending ) );
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." );
294 $responses[$origIndex] = $doneReqs[$index]['response'];
301 * @param string $prefix
302 * @return VirtualRESTService
304 private function getInstance( $prefix ) {
305 if ( !isset( $this->instances
[$prefix] ) ) {
306 throw new RuntimeException( "No service registered at prefix '{$prefix}'." );
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." );
316 $this->instances
[$prefix] = $service;
319 return $this->instances
[$prefix];