VirtualRESTServiceClient.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <?php
  2. /**
  3. * Virtual HTTP service client
  4. *
  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.
  9. *
  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.
  14. *
  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
  19. *
  20. * @file
  21. */
  22. /**
  23. * Virtual HTTP service client loosely styled after a Virtual File System
  24. *
  25. * Services can be mounted on path prefixes so that virtual HTTP operations
  26. * against sub-paths will map to those services. Operations can actually be
  27. * done using HTTP messages over the wire or may simple be emulated locally.
  28. *
  29. * Virtual HTTP request maps are arrays that use the following format:
  30. * - method : GET/HEAD/PUT/POST/DELETE
  31. * - url : HTTP/HTTPS URL or virtual service path with a registered prefix
  32. * - query : <query parameter field/value associative array> (uses RFC 3986)
  33. * - headers : <header name/value associative array>
  34. * - body : source to get the HTTP request body from;
  35. * this can simply be a string (always), a resource for
  36. * PUT requests, and a field/value array for POST request;
  37. * array bodies are encoded as multipart/form-data and strings
  38. * use application/x-www-form-urlencoded (headers sent automatically)
  39. * - stream : resource to stream the HTTP response body to
  40. * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
  41. *
  42. * @since 1.23
  43. */
  44. class VirtualRESTServiceClient {
  45. /** @var MultiHttpClient */
  46. private $http;
  47. /** @var array Map of (prefix => VirtualRESTService|array) */
  48. private $instances = [];
  49. const VALID_MOUNT_REGEX = '#^/[0-9a-z]+/([0-9a-z]+/)*$#';
  50. /**
  51. * @param MultiHttpClient $http
  52. */
  53. public function __construct( MultiHttpClient $http ) {
  54. $this->http = $http;
  55. }
  56. /**
  57. * Map a prefix to service handler
  58. *
  59. * If $instance is in array, it must have these keys:
  60. * - class : string; fully qualified VirtualRESTService class name
  61. * - config : array; map of parameters that is the first __construct() argument
  62. *
  63. * @param string $prefix Virtual path
  64. * @param VirtualRESTService|array $instance Service or info to yield the service
  65. */
  66. public function mount( $prefix, $instance ) {
  67. if ( !preg_match( self::VALID_MOUNT_REGEX, $prefix ) ) {
  68. throw new UnexpectedValueException( "Invalid service mount point '$prefix'." );
  69. } elseif ( isset( $this->instances[$prefix] ) ) {
  70. throw new UnexpectedValueException( "A service is already mounted on '$prefix'." );
  71. }
  72. if ( !( $instance instanceof VirtualRESTService ) ) {
  73. if ( !isset( $instance['class'] ) || !isset( $instance['config'] ) ) {
  74. throw new UnexpectedValueException( "Missing 'class' or 'config' ('$prefix')." );
  75. }
  76. }
  77. $this->instances[$prefix] = $instance;
  78. }
  79. /**
  80. * Unmap a prefix to service handler
  81. *
  82. * @param string $prefix Virtual path
  83. */
  84. public function unmount( $prefix ) {
  85. if ( !preg_match( self::VALID_MOUNT_REGEX, $prefix ) ) {
  86. throw new UnexpectedValueException( "Invalid service mount point '$prefix'." );
  87. } elseif ( !isset( $this->instances[$prefix] ) ) {
  88. throw new UnexpectedValueException( "No service is mounted on '$prefix'." );
  89. }
  90. unset( $this->instances[$prefix] );
  91. }
  92. /**
  93. * Get the prefix and service that a virtual path is serviced by
  94. *
  95. * @param string $path
  96. * @return array (prefix,VirtualRESTService) or (null,null) if none found
  97. */
  98. public function getMountAndService( $path ) {
  99. $cmpFunc = function ( $a, $b ) {
  100. $al = substr_count( $a, '/' );
  101. $bl = substr_count( $b, '/' );
  102. return $bl <=> $al; // largest prefix first
  103. };
  104. $matches = []; // matching prefixes (mount points)
  105. foreach ( $this->instances as $prefix => $unused ) {
  106. if ( strpos( $path, $prefix ) === 0 ) {
  107. $matches[] = $prefix;
  108. }
  109. }
  110. usort( $matches, $cmpFunc );
  111. // Return the most specific prefix and corresponding service
  112. return $matches
  113. ? [ $matches[0], $this->getInstance( $matches[0] ) ]
  114. : [ null, null ];
  115. }
  116. /**
  117. * Execute a virtual HTTP(S) request
  118. *
  119. * This method returns a response map of:
  120. * - code : HTTP response code or 0 if there was a serious cURL error
  121. * - reason : HTTP response reason (empty if there was a serious cURL error)
  122. * - headers : <header name/value associative array>
  123. * - body : HTTP response body or resource (if "stream" was set)
  124. * - error : Any cURL error string
  125. * The map also stores integer-indexed copies of these values. This lets callers do:
  126. * @code
  127. * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $client->run( $req );
  128. * @endcode
  129. * @param array $req Virtual HTTP request maps
  130. * @return array Response array for request
  131. */
  132. public function run( array $req ) {
  133. return $this->runMulti( [ $req ] )[0];
  134. }
  135. /**
  136. * Execute a set of virtual HTTP(S) requests concurrently
  137. *
  138. * A map of requests keys to response maps is returned. Each response map has:
  139. * - code : HTTP response code or 0 if there was a serious cURL error
  140. * - reason : HTTP response reason (empty if there was a serious cURL error)
  141. * - headers : <header name/value associative array>
  142. * - body : HTTP response body or resource (if "stream" was set)
  143. * - error : Any cURL error string
  144. * The map also stores integer-indexed copies of these values. This lets callers do:
  145. * @code
  146. * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $responses[0];
  147. * @endcode
  148. *
  149. * @param array $reqs Map of Virtual HTTP request maps
  150. * @return array $reqs Map of corresponding response values with the same keys/order
  151. * @throws Exception
  152. */
  153. public function runMulti( array $reqs ) {
  154. foreach ( $reqs as $index => &$req ) {
  155. if ( isset( $req[0] ) ) {
  156. $req['method'] = $req[0]; // short-form
  157. unset( $req[0] );
  158. }
  159. if ( isset( $req[1] ) ) {
  160. $req['url'] = $req[1]; // short-form
  161. unset( $req[1] );
  162. }
  163. $req['chain'] = []; // chain or list of replaced requests
  164. }
  165. unset( $req ); // don't assign over this by accident
  166. $curUniqueId = 0;
  167. $armoredIndexMap = []; // (original index => new index)
  168. $doneReqs = []; // (index => request)
  169. $executeReqs = []; // (index => request)
  170. $replaceReqsByService = []; // (prefix => index => request)
  171. $origPending = []; // (index => 1) for original requests
  172. foreach ( $reqs as $origIndex => $req ) {
  173. // Re-index keys to consecutive integers (they will be swapped back later)
  174. $index = $curUniqueId++;
  175. $armoredIndexMap[$origIndex] = $index;
  176. $origPending[$index] = 1;
  177. if ( preg_match( '#^(http|ftp)s?://#', $req['url'] ) ) {
  178. // Absolute FTP/HTTP(S) URL, run it as normal
  179. $executeReqs[$index] = $req;
  180. } else {
  181. // Must be a virtual HTTP URL; resolve it
  182. list( $prefix, $service ) = $this->getMountAndService( $req['url'] );
  183. if ( !$service ) {
  184. throw new UnexpectedValueException( "Path '{$req['url']}' has no service." );
  185. }
  186. // Set the URL to the mount-relative portion
  187. $req['url'] = substr( $req['url'], strlen( $prefix ) );
  188. $replaceReqsByService[$prefix][$index] = $req;
  189. }
  190. }
  191. // Function to get IDs that won't collide with keys in $armoredIndexMap
  192. $idFunc = function () use ( &$curUniqueId ) {
  193. return $curUniqueId++;
  194. };
  195. $rounds = 0;
  196. do {
  197. if ( ++$rounds > 5 ) { // sanity
  198. throw new Exception( "Too many replacement rounds detected. Aborting." );
  199. }
  200. // Track requests executed this round that have a prefix/service.
  201. // Note that this also includes requests where 'response' was forced.
  202. $checkReqIndexesByPrefix = [];
  203. // Resolve the virtual URLs valid and qualified HTTP(S) URLs
  204. // and add any required authentication headers for the backend.
  205. // Services can also replace requests with new ones, either to
  206. // defer the original or to set a proxy response to the original.
  207. $newReplaceReqsByService = [];
  208. foreach ( $replaceReqsByService as $prefix => $servReqs ) {
  209. $service = $this->getInstance( $prefix );
  210. foreach ( $service->onRequests( $servReqs, $idFunc ) as $index => $req ) {
  211. // Services use unique IDs for replacement requests
  212. if ( isset( $servReqs[$index] ) || isset( $origPending[$index] ) ) {
  213. // A current or original request which was not modified
  214. } else {
  215. // Replacement request that will convert to original requests
  216. $newReplaceReqsByService[$prefix][$index] = $req;
  217. }
  218. if ( isset( $req['response'] ) ) {
  219. // Replacement requests with pre-set responses should not execute
  220. unset( $executeReqs[$index] );
  221. unset( $origPending[$index] );
  222. $doneReqs[$index] = $req;
  223. } else {
  224. // Original or mangled request included
  225. $executeReqs[$index] = $req;
  226. }
  227. $checkReqIndexesByPrefix[$prefix][$index] = 1;
  228. }
  229. }
  230. // Run the actual work HTTP requests
  231. foreach ( $this->http->runMulti( $executeReqs ) as $index => $ranReq ) {
  232. $doneReqs[$index] = $ranReq;
  233. unset( $origPending[$index] );
  234. }
  235. $executeReqs = [];
  236. // Services can also replace requests with new ones, either to
  237. // defer the original or to set a proxy response to the original.
  238. // Any replacement requests executed above will need to be replaced
  239. // with new requests (eventually the original). The responses can be
  240. // forced by setting 'response' rather than actually be sent over the wire.
  241. $newReplaceReqsByService = [];
  242. foreach ( $checkReqIndexesByPrefix as $prefix => $servReqIndexes ) {
  243. $service = $this->getInstance( $prefix );
  244. // $doneReqs actually has the requests (with 'response' set)
  245. $servReqs = array_intersect_key( $doneReqs, $servReqIndexes );
  246. foreach ( $service->onResponses( $servReqs, $idFunc ) as $index => $req ) {
  247. // Services use unique IDs for replacement requests
  248. if ( isset( $servReqs[$index] ) || isset( $origPending[$index] ) ) {
  249. // A current or original request which was not modified
  250. } else {
  251. // Replacement requests with pre-set responses should not execute
  252. $newReplaceReqsByService[$prefix][$index] = $req;
  253. }
  254. if ( isset( $req['response'] ) ) {
  255. // Replacement requests with pre-set responses should not execute
  256. unset( $origPending[$index] );
  257. $doneReqs[$index] = $req;
  258. } else {
  259. // Update the request in case it was mangled
  260. $executeReqs[$index] = $req;
  261. }
  262. }
  263. }
  264. // Update index of requests to inspect for replacement
  265. $replaceReqsByService = $newReplaceReqsByService;
  266. } while ( count( $origPending ) );
  267. $responses = [];
  268. // Update $reqs to include 'response' and normalized request 'headers'.
  269. // This maintains the original order of $reqs.
  270. foreach ( $reqs as $origIndex => $req ) {
  271. $index = $armoredIndexMap[$origIndex];
  272. if ( !isset( $doneReqs[$index] ) ) {
  273. throw new UnexpectedValueException( "Response for request '$index' is NULL." );
  274. }
  275. $responses[$origIndex] = $doneReqs[$index]['response'];
  276. }
  277. return $responses;
  278. }
  279. /**
  280. * @param string $prefix
  281. * @return VirtualRESTService
  282. */
  283. private function getInstance( $prefix ) {
  284. if ( !isset( $this->instances[$prefix] ) ) {
  285. throw new RuntimeException( "No service registered at prefix '{$prefix}'." );
  286. }
  287. if ( !( $this->instances[$prefix] instanceof VirtualRESTService ) ) {
  288. $config = $this->instances[$prefix]['config'];
  289. $class = $this->instances[$prefix]['class'];
  290. $service = new $class( $config );
  291. if ( !( $service instanceof VirtualRESTService ) ) {
  292. throw new UnexpectedValueException( "Registered service has the wrong class." );
  293. }
  294. $this->instances[$prefix] = $service;
  295. }
  296. return $this->instances[$prefix];
  297. }
  298. }