Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 211 |
|
0.00% |
0 / 20 |
CRAP | |
0.00% |
0 / 1 |
| Module | |
0.00% |
0 / 211 |
|
0.00% |
0 / 20 |
4160 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| getJsonLocalizer | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getPathPrefix | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getCacheData | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
| initFromCacheData | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
| initForExecute | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getHandlerForPath | |
0.00% |
0 / 32 |
|
0.00% |
0 / 1 |
72 | |||
| getRouter | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| findHandlerMatch | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
| throwNoMatch | |
0.00% |
0 / 15 |
|
0.00% |
0 / 1 |
42 | |||
| runRestCheckCanExecuteHook | |
0.00% |
0 / 14 |
|
0.00% |
0 / 1 |
42 | |||
| execute | |
0.00% |
0 / 20 |
|
0.00% |
0 / 1 |
20 | |||
| recordMetrics | |
0.00% |
0 / 56 |
|
0.00% |
0 / 1 |
182 | |||
| getDefinedPaths | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
| getAllowedMethods | n/a |
0 / 0 |
n/a |
0 / 0 |
0 | |||||
| instantiateHandlerObject | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
12 | |||
| instantiateAdapter | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
42 | |||
| executeHandler | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
20 | |||
| setCors | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| setStats | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| getOpenApiInfo | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getOpenApiExternalDocs | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getOpenApiTags | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getDeprecatedDate | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getModuleDescription | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
12 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace MediaWiki\Rest\Module; |
| 4 | |
| 5 | use LogicException; |
| 6 | use MediaWiki\HookContainer\HookContainer; |
| 7 | use MediaWiki\Profiler\ProfilingContext; |
| 8 | use MediaWiki\Rest\BasicAccess\BasicAuthorizerInterface; |
| 9 | use MediaWiki\Rest\CorsUtils; |
| 10 | use MediaWiki\Rest\Handler; |
| 11 | use MediaWiki\Rest\Handler\GenericActionHandler; |
| 12 | use MediaWiki\Rest\Handler\GenericItemHandler; |
| 13 | use MediaWiki\Rest\Handler\GenericListHandler; |
| 14 | use MediaWiki\Rest\Hook\HookRunner; |
| 15 | use MediaWiki\Rest\HttpException; |
| 16 | use MediaWiki\Rest\JsonFileLoaderTrait; |
| 17 | use MediaWiki\Rest\JsonLocalizer; |
| 18 | use MediaWiki\Rest\LocalizedHttpException; |
| 19 | use MediaWiki\Rest\PathTemplateMatcher\ModuleConfigurationException; |
| 20 | use MediaWiki\Rest\Reporter\ErrorReporter; |
| 21 | use MediaWiki\Rest\RequestInterface; |
| 22 | use MediaWiki\Rest\ResponseException; |
| 23 | use MediaWiki\Rest\ResponseFactory; |
| 24 | use MediaWiki\Rest\ResponseInterface; |
| 25 | use MediaWiki\Rest\Router; |
| 26 | use MediaWiki\Rest\Validator\Validator; |
| 27 | use PHPUnit\Exception as PHPUnitException; |
| 28 | use Throwable; |
| 29 | use Wikimedia\Assert\Assert; |
| 30 | use Wikimedia\Message\MessageValue; |
| 31 | use Wikimedia\ObjectFactory\ObjectFactory; |
| 32 | use Wikimedia\Stats\StatsFactory; |
| 33 | use Wikimedia\Timestamp\ConvertibleTimestamp; |
| 34 | |
| 35 | /** |
| 36 | * A REST module represents a collection of endpoints. |
| 37 | * The module object is responsible for generating a response for a given |
| 38 | * request. This is typically done by routing requests to the appropriate |
| 39 | * request handler. |
| 40 | * |
| 41 | * @since 1.43 |
| 42 | */ |
| 43 | abstract class Module { |
| 44 | use JsonFileLoaderTrait; |
| 45 | |
| 46 | /** |
| 47 | * @internal for use in cached module data |
| 48 | */ |
| 49 | public const CACHE_CONFIG_HASH_KEY = 'CONFIG-HASH'; |
| 50 | |
| 51 | private StatsFactory $stats; |
| 52 | private ?CorsUtils $cors = null; |
| 53 | private readonly HookRunner $hookRunner; |
| 54 | |
| 55 | // Set by initForExecute() when the module is initialized to handle a |
| 56 | // request. Null while the module is uninitialized (e.g. when generating |
| 57 | // OpenAPI specs). |
| 58 | private ?ResponseFactory $responseFactory = null; |
| 59 | |
| 60 | public function __construct( |
| 61 | private readonly Router $router, |
| 62 | protected readonly string $pathPrefix, |
| 63 | protected readonly JsonLocalizer $jsonLocalizer, |
| 64 | private readonly BasicAuthorizerInterface $basicAuth, |
| 65 | private readonly ObjectFactory $objectFactory, |
| 66 | private readonly Validator $restValidator, |
| 67 | private readonly ErrorReporter $errorReporter, |
| 68 | HookContainer $hookContainer, |
| 69 | ) { |
| 70 | $this->hookRunner = new HookRunner( $hookContainer ); |
| 71 | $this->stats = StatsFactory::newNull(); |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * @since 1.47 |
| 76 | */ |
| 77 | public function getJsonLocalizer(): JsonLocalizer { |
| 78 | return $this->jsonLocalizer; |
| 79 | } |
| 80 | |
| 81 | public function getPathPrefix(): string { |
| 82 | return $this->pathPrefix; |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Return data that can later be used to initialize a new instance of |
| 87 | * this module in a fast and efficient way. |
| 88 | * |
| 89 | * @see initFromCacheData() |
| 90 | * |
| 91 | * @return array An associative array suitable to be processed by |
| 92 | * initFromCacheData. Implementations are free to choose the format. |
| 93 | */ |
| 94 | abstract public function getCacheData(): array; |
| 95 | |
| 96 | /** |
| 97 | * Initialize from the given cache data if possible. |
| 98 | * This allows fast initialization based on data that was cached during |
| 99 | * a previous invocation of the module. |
| 100 | * |
| 101 | * Implementations are responsible for verifying that the cache data |
| 102 | * matches the information provided to the constructor, to protect against |
| 103 | * a situation where configuration was updated in a way that affects the |
| 104 | * operation of the module. |
| 105 | * |
| 106 | * @param array $cacheData Data generated by getCacheData(), implementations |
| 107 | * are free to choose the format. |
| 108 | * |
| 109 | * @return bool true if the cache data could be used, |
| 110 | * false if it was discarded. |
| 111 | * @see getCacheData() |
| 112 | */ |
| 113 | abstract public function initFromCacheData( array $cacheData ): bool; |
| 114 | |
| 115 | /** |
| 116 | * Initialize this module for handling requests via execute(). |
| 117 | * |
| 118 | * @internal |
| 119 | */ |
| 120 | public function initForExecute( ResponseFactory $responseFactory ) { |
| 121 | $this->responseFactory = $responseFactory; |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Create a Handler for the given path, taking into account the request |
| 126 | * method. |
| 127 | * |
| 128 | * If $prepExecution is true, the handler's prepareForExecute() method will |
| 129 | * be called, which will call postInitSetup(). The $request object will be |
| 130 | * updated with any path parameters and parsed body data. |
| 131 | * |
| 132 | * @unstable |
| 133 | * |
| 134 | * @param string $path |
| 135 | * @param RequestInterface $request The request to handle. If $forExecution |
| 136 | * is true, this will be updated with the path parameters and parsed |
| 137 | * body data as appropriate. |
| 138 | * @param bool $initForExecute Whether the handler and the request should be |
| 139 | * prepared for execution. Callers that only need the Handler object |
| 140 | * for access to meta-data should set this to false. |
| 141 | * |
| 142 | * @return Handler |
| 143 | * @throws HttpException If no handler was found |
| 144 | */ |
| 145 | public function getHandlerForPath( |
| 146 | string $path, |
| 147 | RequestInterface $request, |
| 148 | bool $initForExecute = false |
| 149 | ): Handler { |
| 150 | Assert::precondition( |
| 151 | !$initForExecute || $this->responseFactory !== null, |
| 152 | 'The $initForExecute flag cannot be true if initForExecute() has not been called' |
| 153 | ); |
| 154 | |
| 155 | $requestMethod = strtoupper( $request->getMethod() ); |
| 156 | |
| 157 | $match = $this->findHandlerMatch( $path, $requestMethod ); |
| 158 | |
| 159 | if ( !$match['found'] && $requestMethod === 'HEAD' ) { |
| 160 | // For a HEAD request, execute the GET handler instead if one exists. |
| 161 | $match = $this->findHandlerMatch( $path, 'GET' ); |
| 162 | } |
| 163 | |
| 164 | if ( !$match['found'] ) { |
| 165 | $this->throwNoMatch( |
| 166 | $path, |
| 167 | $request->getMethod(), |
| 168 | $match['methods'] ?? [] |
| 169 | ); |
| 170 | } |
| 171 | |
| 172 | if ( isset( $match['handler'] ) ) { |
| 173 | $handler = $match['handler']; |
| 174 | } elseif ( isset( $match['spec'] ) ) { |
| 175 | $handler = $this->instantiateHandlerObject( $match['spec'] ); |
| 176 | } else { |
| 177 | throw new LogicException( |
| 178 | 'Match does not specify a handler instance or object spec.' |
| 179 | ); |
| 180 | } |
| 181 | |
| 182 | // For backwards compatibility only. Handlers should get the path by |
| 183 | // calling getPath(), not from the config array. |
| 184 | $config = $match['config'] ?? []; |
| 185 | $config['path'] ??= $match['path']; |
| 186 | |
| 187 | // Remember the method the module was registered for. |
| 188 | // Useful during spec generation. |
| 189 | // NOTE: With this in place, we no longer need $method as a parameter |
| 190 | // in spec generation. But we can't change the method signatures |
| 191 | // without breaking subclasses. |
| 192 | $config['method'] ??= $requestMethod; |
| 193 | |
| 194 | $openApiSpec = $match['openApiSpec'] ?? []; |
| 195 | |
| 196 | // Provide context about the module |
| 197 | $handler->initContext( $this, $match['path'], $config, $openApiSpec ); |
| 198 | |
| 199 | // Inject services and state from the router |
| 200 | $this->getRouter()->prepareHandler( $handler ); |
| 201 | |
| 202 | if ( $initForExecute ) { |
| 203 | // Use rawurldecode so a "+" in path params is not interpreted as a space character. |
| 204 | $pathParams = array_map( rawurldecode( ... ), $match['params'] ?? [] ); |
| 205 | $request->setPathParams( $pathParams ); |
| 206 | |
| 207 | $handler->initForExecute( $request, $this->responseFactory ); |
| 208 | } |
| 209 | |
| 210 | return $handler; |
| 211 | } |
| 212 | |
| 213 | public function getRouter(): Router { |
| 214 | return $this->router; |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Determines which handler to use for the given path and returns an array |
| 219 | * describing the handler and initialization context. |
| 220 | * |
| 221 | * @param string $path |
| 222 | * @param string $requestMethod |
| 223 | * |
| 224 | * @return array<string,mixed> |
| 225 | * - bool "found": Whether a match was found. If true, the `handler` |
| 226 | * or `spec` field must be set. |
| 227 | * - Handler handler: the Handler object to use. Either "handler" or |
| 228 | * "spec" must be given. |
| 229 | * - array "spec":" an object spec for use with ObjectFactory |
| 230 | * - array "config": the route config, to be passed to Handler::initContext() |
| 231 | * - string "path": the path the handler is responsible for, |
| 232 | * including placeholders for path parameters. |
| 233 | * - string[] "params": path parameters, to be passed the |
| 234 | * Request::setPathPrams() |
| 235 | * - string[] "methods": supported methods, if the path is known but |
| 236 | * the method did not match. Only meaningful if "found" is false. |
| 237 | * To be used in the Allow header of a 405 response and included |
| 238 | * in CORS pre-flight. |
| 239 | */ |
| 240 | abstract protected function findHandlerMatch( |
| 241 | string $path, |
| 242 | string $requestMethod |
| 243 | ): array; |
| 244 | |
| 245 | /** |
| 246 | * Implementations of getHandlerForPath() should call this method when they |
| 247 | * cannot handle the requested path. |
| 248 | * |
| 249 | * @param string $path The requested path |
| 250 | * @param string $method The HTTP method of the current request |
| 251 | * @param string[] $allowed The allowed HTTP methods allowed by the path |
| 252 | * |
| 253 | * @return never |
| 254 | * @throws HttpException |
| 255 | */ |
| 256 | protected function throwNoMatch( string $path, string $method, array $allowed ): never { |
| 257 | // Check for CORS Preflight. This response will *not* allow the request unless |
| 258 | // an Access-Control-Allow-Origin header is added to this response. |
| 259 | if ( $this->cors && $this->responseFactory && $method === 'OPTIONS' && $allowed ) { |
| 260 | // IDEA: Create a CorsHandler, which getHandlerForPath can return in this case. |
| 261 | $response = $this->cors->createPreflightResponse( $allowed, $this->responseFactory ); |
| 262 | throw new ResponseException( $response ); |
| 263 | } |
| 264 | |
| 265 | if ( $allowed ) { |
| 266 | // There are allowed methods for this patch, so reply with Method Not Allowed. |
| 267 | $response = $this->responseFactory->createLocalizedHttpError( 405, |
| 268 | ( new MessageValue( 'rest-wrong-method' ) ) |
| 269 | ->textParams( $method ) |
| 270 | ->commaListParams( $allowed ) |
| 271 | ->numParams( count( $allowed ) ) |
| 272 | ); |
| 273 | $response->setHeader( 'Allow', $allowed ); |
| 274 | throw new ResponseException( $response ); |
| 275 | } else { |
| 276 | // There are no allowed methods for this path, so the path was not found at all. |
| 277 | $msg = ( new MessageValue( 'rest-no-match' ) ) |
| 278 | ->plaintextParams( $path ); |
| 279 | throw new LocalizedHttpException( $msg, 404 ); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | private function runRestCheckCanExecuteHook( |
| 284 | Handler $handler, |
| 285 | string $path, |
| 286 | RequestInterface $request |
| 287 | ): void { |
| 288 | $error = null; |
| 289 | $canExecute = $this->hookRunner->onRestCheckCanExecute( $this, $handler, $path, $request, $error ); |
| 290 | if ( $canExecute !== ( $error === null ) ) { |
| 291 | throw new LogicException( |
| 292 | 'Hook RestCheckCanExecute returned ' . ( $canExecute ? 'true' : 'false' ) |
| 293 | . ' but ' . ( $error ? 'did' : 'did not' ) . ' set an error' |
| 294 | ); |
| 295 | } elseif ( $error instanceof HttpException ) { |
| 296 | throw $error; |
| 297 | } elseif ( $error ) { |
| 298 | throw new LogicException( |
| 299 | 'RestCheckCanExecute must set a HttpException when returning false, ' |
| 300 | . 'but got ' . get_class( $error ) |
| 301 | ); |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /** |
| 306 | * Find the handler for a request and execute it |
| 307 | */ |
| 308 | public function execute( string $path, RequestInterface $request ): ResponseInterface { |
| 309 | $handler = null; |
| 310 | $startTime = ConvertibleTimestamp::hrtime(); |
| 311 | |
| 312 | Assert::precondition( |
| 313 | $this->responseFactory !== null, |
| 314 | 'execute() cannot be called before initForExecute()' |
| 315 | ); |
| 316 | |
| 317 | try { |
| 318 | $handler = $this->getHandlerForPath( $path, $request, true ); |
| 319 | $this->runRestCheckCanExecuteHook( $handler, $path, $request ); |
| 320 | $response = $this->executeHandler( $handler ); |
| 321 | $this->hookRunner->onRestAfterExecute( $this, $handler, $path, $request, $response ); |
| 322 | } catch ( HttpException $e ) { |
| 323 | $response = $this->responseFactory->createFromException( $e ); |
| 324 | $this->hookRunner->onRestAfterExecute( $this, $handler, $path, $request, $response ); |
| 325 | } catch ( Throwable $e ) { |
| 326 | if ( $e instanceof PHPUnitException ) { |
| 327 | throw $e; |
| 328 | } |
| 329 | // Note that $handler is allowed to be null here. |
| 330 | $this->errorReporter->reportError( $e, $handler, $request ); |
| 331 | $response = $this->responseFactory->createFromException( $e ); |
| 332 | } |
| 333 | |
| 334 | $this->recordMetrics( $handler, $request, $response, $startTime ); |
| 335 | return $response; |
| 336 | } |
| 337 | |
| 338 | private function recordMetrics( |
| 339 | ?Handler $handler, |
| 340 | RequestInterface $request, |
| 341 | ResponseInterface $response, |
| 342 | float $startTime |
| 343 | ) { |
| 344 | $latency = ConvertibleTimestamp::hrtime() - $startTime; |
| 345 | |
| 346 | // NOTE: The "/" prefix is for consistency with old logs. It's rather ugly. |
| 347 | if ( $handler ) { |
| 348 | $pathForMetrics = $handler->getRoutePath(); |
| 349 | } else { |
| 350 | $prefix = $this->getPathPrefix(); |
| 351 | $pathForMetrics = ( $prefix !== '' ) ? "/$prefix/UNKNOWN" : '/UNKNOWN'; |
| 352 | } |
| 353 | |
| 354 | // Replace any characters that may have a special meaning in the metrics DB. |
| 355 | $pathForMetrics = strtr( $pathForMetrics, '{}:/.', '---__' ); |
| 356 | |
| 357 | $statusCode = $response->getStatusCode(); |
| 358 | $requestMethod = $request->getMethod(); |
| 359 | if ( $statusCode >= 400 ) { |
| 360 | // count how often we return which error code |
| 361 | $this->stats->getCounter( 'rest_api_errors_total' ) |
| 362 | ->setLabel( 'path', $pathForMetrics ) |
| 363 | ->setLabel( 'method', $requestMethod ) |
| 364 | ->setLabel( 'status', "$statusCode" ) |
| 365 | ->increment(); |
| 366 | } else { |
| 367 | // measure how long it takes to generate a response |
| 368 | $this->stats->getTiming( 'rest_api_latency_seconds' ) |
| 369 | ->setLabel( 'path', $pathForMetrics ) |
| 370 | ->setLabel( 'method', $requestMethod ) |
| 371 | ->setLabel( 'status', "$statusCode" ) |
| 372 | ->observeNanoseconds( $latency ); |
| 373 | } |
| 374 | |
| 375 | // New unified metrics for the API |
| 376 | // Only record those if there's a handler |
| 377 | if ( !$handler ) { |
| 378 | return; |
| 379 | } |
| 380 | $moduleDescription = $this->getModuleDescription(); |
| 381 | |
| 382 | $metricsLabels = [ |
| 383 | 'api_module' => $moduleDescription['moduleId'], |
| 384 | // as a starting point, we'll use the Handler class name for the endpoint |
| 385 | 'api_endpoint' => $handler::class, |
| 386 | 'path' => $pathForMetrics, |
| 387 | 'method' => $requestMethod, |
| 388 | 'status' => "$statusCode", |
| 389 | ]; |
| 390 | |
| 391 | $approvedLabels = [ |
| 392 | 'api_module', |
| 393 | 'api_endpoint', |
| 394 | 'path', |
| 395 | 'method', |
| 396 | 'status', |
| 397 | ]; |
| 398 | |
| 399 | // Hit metrics |
| 400 | $metricHitStats = $this->stats->getCounter( 'rest_api_modules_hit_total' ) |
| 401 | ->setLabel( 'api_type', 'REST_API' ); |
| 402 | // Iterate over the approved labels and set the labels for the metric |
| 403 | foreach ( $approvedLabels as $label ) { |
| 404 | // Set a fallback value for empty strings |
| 405 | $value = ( |
| 406 | array_key_exists( $label, $metricsLabels ) && |
| 407 | is_string( $metricsLabels[$label] ) && |
| 408 | trim( $metricsLabels[$label] ) !== '' |
| 409 | ) ? $metricsLabels[$label] : 'EMPTY_VALUE'; |
| 410 | |
| 411 | $metricHitStats->setLabel( $label, $value ); |
| 412 | } |
| 413 | $metricHitStats->increment(); |
| 414 | |
| 415 | // Latency metrics |
| 416 | $metricLatencyStats = $this->stats->getTiming( 'rest_api_modules_latency' ) |
| 417 | ->setLabel( 'api_type', 'REST_API' ); |
| 418 | // Iterate over the approved labels and set the labels for the metric |
| 419 | foreach ( $approvedLabels as $label ) { |
| 420 | // Set a fallback value for empty strings |
| 421 | $value = ( |
| 422 | array_key_exists( $label, $metricsLabels ) && |
| 423 | is_string( $metricsLabels[$label] ) && |
| 424 | trim( $metricsLabels[$label] ) !== '' |
| 425 | ) ? $metricsLabels[$label] : 'EMPTY_VALUE'; |
| 426 | |
| 427 | $metricLatencyStats->setLabel( $label, $value ); |
| 428 | } |
| 429 | $metricLatencyStats->observeNanoseconds( $latency ); |
| 430 | } |
| 431 | |
| 432 | /** |
| 433 | * @internal for testing |
| 434 | * |
| 435 | * @return array[] An associative array, mapping path patterns to |
| 436 | * a list of request methods supported for the path. |
| 437 | */ |
| 438 | abstract public function getDefinedPaths(): array; |
| 439 | |
| 440 | /** |
| 441 | * Get the allowed methods for a path. |
| 442 | * Useful to check for 405 wrong method and for generating OpenAPI specs. |
| 443 | * |
| 444 | * @param string $relPath A concrete request path. |
| 445 | * @return string[] A list of allowed HTTP request methods for the path. |
| 446 | * If the path is not supported, the list will be empty. |
| 447 | */ |
| 448 | abstract public function getAllowedMethods( string $relPath ): array; |
| 449 | |
| 450 | /** |
| 451 | * Creates a handler from the given spec, but does not initialize it. |
| 452 | */ |
| 453 | protected function instantiateHandlerObject( array $spec ): Handler { |
| 454 | if ( isset( $spec['adapter'] ) ) { |
| 455 | if ( isset( $spec['class'] ) ) { |
| 456 | throw new ModuleConfigurationException( |
| 457 | '"adapter" cannot be used together with "class"' |
| 458 | ); |
| 459 | } |
| 460 | |
| 461 | return $this->instantiateAdapter( $spec['adapter'] ); |
| 462 | } |
| 463 | |
| 464 | /** @var $handler Handler (annotation for PHPStorm) */ |
| 465 | $handler = $this->objectFactory->createObject( |
| 466 | $spec, |
| 467 | [ 'assertClass' => Handler::class ] |
| 468 | ); |
| 469 | |
| 470 | return $handler; |
| 471 | } |
| 472 | |
| 473 | private function instantiateAdapter( array $adapterSpec ): Handler { |
| 474 | $require = static function ( string $key ) use ( $adapterSpec ) { |
| 475 | if ( !isset( $adapterSpec[ $key ] ) ) { |
| 476 | throw new ModuleConfigurationException( |
| 477 | "adapter spec is missing '$key'" |
| 478 | ); |
| 479 | } |
| 480 | |
| 481 | return $adapterSpec[ $key ]; |
| 482 | }; |
| 483 | |
| 484 | // SEAM: move this to a factory that can be registered with the Module, |
| 485 | // to avoid a conceptual dependency between Rest API and Action API. |
| 486 | |
| 487 | switch ( $require( 'type' ) ) { |
| 488 | case 'action': |
| 489 | return new GenericActionHandler( $require( 'action' ), $adapterSpec ); |
| 490 | case 'list': |
| 491 | return new GenericListHandler( $require( 'list' ), $adapterSpec ); |
| 492 | case 'item': |
| 493 | return new GenericItemHandler( $require( 'list' ), $adapterSpec ); |
| 494 | default: |
| 495 | throw new ModuleConfigurationException( |
| 496 | "unknown adapter type '{$adapterSpec['type']}'" |
| 497 | ); |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | /** |
| 502 | * Execute a fully-constructed handler |
| 503 | * @throws HttpException |
| 504 | */ |
| 505 | protected function executeHandler( Handler $handler ): ResponseInterface { |
| 506 | ProfilingContext::singleton()->init( MW_ENTRY_POINT, $handler->getRoutePath() ); |
| 507 | // Check for basic authorization, to avoid leaking data from private wikis |
| 508 | $authResult = $this->basicAuth->authorize( $handler->getRequest(), $handler ); |
| 509 | if ( $authResult ) { |
| 510 | return $this->responseFactory->createHttpError( 403, [ 'error' => $authResult ] ); |
| 511 | } |
| 512 | |
| 513 | // Check session (and session provider) |
| 514 | $handler->checkSession(); |
| 515 | |
| 516 | // Validate the parameters |
| 517 | $handler->validate( $this->restValidator ); |
| 518 | |
| 519 | // Check conditional request headers |
| 520 | $earlyResponse = $handler->checkPreconditions(); |
| 521 | if ( $earlyResponse ) { |
| 522 | return $earlyResponse; |
| 523 | } |
| 524 | |
| 525 | // Run the main part of the handler |
| 526 | $response = $handler->execute(); |
| 527 | if ( !( $response instanceof ResponseInterface ) ) { |
| 528 | $response = $this->responseFactory->createFromReturnValue( $response ); |
| 529 | } |
| 530 | |
| 531 | // Deprecation header per RFC 9745 |
| 532 | $handler->applyDeprecationHeader( $response ); |
| 533 | |
| 534 | // Set Last-Modified and ETag headers in the response if available |
| 535 | $handler->applyConditionalResponseHeaders( $response ); |
| 536 | |
| 537 | $handler->applyCacheControl( $response ); |
| 538 | |
| 539 | return $response; |
| 540 | } |
| 541 | |
| 542 | public function setCors( CorsUtils $cors ): self { |
| 543 | $this->cors = $cors; |
| 544 | |
| 545 | return $this; |
| 546 | } |
| 547 | |
| 548 | /** |
| 549 | * @internal for use by Router |
| 550 | * |
| 551 | * @param StatsFactory $stats |
| 552 | * |
| 553 | * @return self |
| 554 | */ |
| 555 | public function setStats( StatsFactory $stats ): self { |
| 556 | $this->stats = $stats; |
| 557 | |
| 558 | return $this; |
| 559 | } |
| 560 | |
| 561 | /** |
| 562 | * Return an array with data to be included in an OpenAPI "info" object |
| 563 | * describing this module. |
| 564 | * |
| 565 | * The return value may contain localization placeholders that need to be |
| 566 | * resolved using JsonLocalizer to produce human-readable values. |
| 567 | * |
| 568 | * @see https://spec.openapis.org/oas/v3.0.0#info-object |
| 569 | * @return array |
| 570 | */ |
| 571 | public function getOpenApiInfo() { |
| 572 | return []; |
| 573 | } |
| 574 | |
| 575 | /** |
| 576 | * Return an array with data to be included as the root-level OpenAPI |
| 577 | * "externalDocs" object describing this module's external documentation. |
| 578 | * |
| 579 | * @see https://spec.openapis.org/oas/v3.0.0#external-documentation-object |
| 580 | * @since 1.47 |
| 581 | * @return array |
| 582 | */ |
| 583 | public function getOpenApiExternalDocs(): array { |
| 584 | return []; |
| 585 | } |
| 586 | |
| 587 | /** |
| 588 | * Return an array with data to be included in an OpenAPI "tags" object |
| 589 | * describing this module's tags. |
| 590 | * |
| 591 | * Each tag should be an associative array with 'name' and |
| 592 | * 'description' keys. Example: |
| 593 | * [ [ 'name' => 'pages', 'description' => 'Page operations' ] ] |
| 594 | * |
| 595 | * @see https://spec.openapis.org/oas/v3.0.0#tag-object |
| 596 | * @since 1.47 |
| 597 | * @return array[] |
| 598 | */ |
| 599 | public function getOpenApiTags(): array { |
| 600 | return []; |
| 601 | } |
| 602 | |
| 603 | /** |
| 604 | * Return the timestamp at which this was or will be deprecated, or null if none. |
| 605 | * |
| 606 | * @see Handler::getDeprecatedDate() |
| 607 | * @since 1.47 |
| 608 | */ |
| 609 | public function getDeprecatedDate(): ?int { |
| 610 | return $this->getOpenApiInfo()['deprecationSettings']['since'] ?? null; |
| 611 | } |
| 612 | |
| 613 | /** |
| 614 | * Returns fields to be included when describing this module in the |
| 615 | * discovery document. |
| 616 | * |
| 617 | * Supported keys are described in /docs/discovery-1.1.json#/definitions/Module |
| 618 | * |
| 619 | * The return value may contain localization placeholders that need to be |
| 620 | * resolved using JsonLocalizer to produce human-readable values. |
| 621 | * For instance, it may contain x-i18n-description instead of description. |
| 622 | * |
| 623 | * @see /docs/discovery-1.1.json |
| 624 | * @see /docs/mwapi-1.2.json |
| 625 | * @see DiscoveryHandler |
| 626 | */ |
| 627 | public function getModuleDescription(): array { |
| 628 | // Note that each module object is designated for only one audience, |
| 629 | // even if the spec allows multiple. |
| 630 | $moduleId = $this->getPathPrefix(); |
| 631 | $moduleInfo = $this->getOpenApiInfo(); |
| 632 | |
| 633 | // Fields from openApiSpec info to include. |
| 634 | // Note that mwapi-1.2 and earlier are based on OAS 3.0, so they don't support the |
| 635 | // "summary" property introduced in 3.1. |
| 636 | // NOTE: If you add fields here, you must update both the discovery spec |
| 637 | // (docs/rest/discovery-1.1.json) and the module definition spec (docs/rest/mwapi-1.2.json). |
| 638 | // Adding fields requires a minor version bump of both specs, and their references |
| 639 | // must be synchronized. |
| 640 | $infoFields = [ 'version', 'title', 'description', 'deprecationSettings', |
| 641 | 'x-i18n-title', 'x-i18n-description', ]; |
| 642 | |
| 643 | if ( isset( $moduleInfo['oadSpecPath'] ) ) { |
| 644 | $spec = $this->getRouter()->getRouteUrl( '/' . $moduleId . $moduleInfo['oadSpecPath'] ); |
| 645 | } else { |
| 646 | $spec = $this->getRouter()->getRouteUrl( |
| 647 | '/specs/v0/module/{module}', // hard-coding this here isn't very pretty |
| 648 | [ 'module' => $moduleId == '' ? '-' : $moduleId ] |
| 649 | ); |
| 650 | } |
| 651 | |
| 652 | return [ |
| 653 | 'moduleId' => $moduleId, |
| 654 | 'info' => array_intersect_key( $moduleInfo, array_flip( $infoFields ) ), |
| 655 | 'base' => $this->getRouter()->getRouteUrl( '/' . $moduleId ), |
| 656 | 'spec' => $spec |
| 657 | ]; |
| 658 | } |
| 659 | } |