| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Rest\Module; |
| 4 |
|
| 5 |
use LogicException; |
| 6 |
use MediaWiki\Profiler\ProfilingContext; |
| 7 |
use MediaWiki\Rest\BasicAccess\BasicAuthorizerInterface; |
| 8 |
use MediaWiki\Rest\CorsUtils; |
| 9 |
use MediaWiki\Rest\Handler; |
| 10 |
use MediaWiki\Rest\HttpException; |
| 11 |
use MediaWiki\Rest\LocalizedHttpException; |
| 12 |
use MediaWiki\Rest\PathTemplateMatcher\ModuleConfigurationException; |
| 13 |
use MediaWiki\Rest\Reporter\ErrorReporter; |
| 14 |
use MediaWiki\Rest\RequestInterface; |
| 15 |
use MediaWiki\Rest\ResponseException; |
| 16 |
use MediaWiki\Rest\ResponseFactory; |
| 17 |
use MediaWiki\Rest\ResponseInterface; |
| 18 |
use MediaWiki\Rest\Router; |
| 19 |
use MediaWiki\Rest\Validator\Validator; |
| 20 |
use Throwable; |
| 21 |
use Wikimedia\Message\MessageValue; |
| 22 |
use Wikimedia\ObjectFactory\ObjectFactory; |
| 23 |
use Wikimedia\Stats\StatsFactory; |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
abstract class Module { |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
public const CACHE_CONFIG_HASH_KEY = 'CONFIG-HASH'; |
| 39 |
|
| 40 |
protected string $pathPrefix; |
| 41 |
protected ResponseFactory $responseFactory; |
| 42 |
private BasicAuthorizerInterface $basicAuth; |
| 43 |
private ObjectFactory $objectFactory; |
| 44 |
private Validator $restValidator; |
| 45 |
private ErrorReporter $errorReporter; |
| 46 |
private Router $router; |
| 47 |
|
| 48 |
private StatsFactory $stats; |
| 49 |
private ?CorsUtils $cors = null; |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
public function __construct( |
| 61 |
Router $router, |
| 62 |
string $pathPrefix, |
| 63 |
ResponseFactory $responseFactory, |
| 64 |
BasicAuthorizerInterface $basicAuth, |
| 65 |
ObjectFactory $objectFactory, |
| 66 |
Validator $restValidator, |
| 67 |
ErrorReporter $errorReporter |
| 68 |
) { |
| 69 |
$this->router = $router; |
| 70 |
$this->pathPrefix = $pathPrefix; |
| 71 |
$this->responseFactory = $responseFactory; |
| 72 |
$this->basicAuth = $basicAuth; |
| 73 |
$this->objectFactory = $objectFactory; |
| 74 |
$this->restValidator = $restValidator; |
| 75 |
$this->errorReporter = $errorReporter; |
| 76 |
|
| 77 |
$this->stats = StatsFactory::newNull(); |
| 78 |
} |
| 79 |
|
| 80 |
public function getPathPrefix(): string { |
| 81 |
return $this->pathPrefix; |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
abstract public function getCacheData(): array; |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
abstract public function initFromCacheData( array $cacheData ): bool; |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
public function getHandlerForPath( |
| 136 |
string $path, |
| 137 |
RequestInterface $request, |
| 138 |
bool $initForExecute = false |
| 139 |
): Handler { |
| 140 |
$requestMethod = strtoupper( $request->getMethod() ); |
| 141 |
|
| 142 |
$match = $this->findHandlerMatch( $path, $requestMethod ); |
| 143 |
|
| 144 |
if ( !$match['found'] && $requestMethod === 'HEAD' ) { |
| 145 |
|
| 146 |
$match = $this->findHandlerMatch( $path, 'GET' ); |
| 147 |
} |
| 148 |
|
| 149 |
if ( !$match['found'] ) { |
| 150 |
$this->throwNoMatch( |
| 151 |
$path, |
| 152 |
$request->getMethod(), |
| 153 |
$match['methods'] ?? [] |
| 154 |
); |
| 155 |
} |
| 156 |
|
| 157 |
if ( isset( $match['handler'] ) ) { |
| 158 |
$handler = $match['handler']; |
| 159 |
} elseif ( isset( $match['spec'] ) ) { |
| 160 |
$handler = $this->instantiateHandlerObject( $match['spec'] ); |
| 161 |
} else { |
| 162 |
throw new LogicException( |
| 163 |
'Match does not specify a handler instance or object spec.' |
| 164 |
); |
| 165 |
} |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
$config = $match['config'] ?? []; |
| 170 |
$config['path'] ??= $match['path']; |
| 171 |
|
| 172 |
|
| 173 |
$handler->initContext( $this, $match['path'], $config ); |
| 174 |
|
| 175 |
|
| 176 |
$this->getRouter()->prepareHandler( $handler ); |
| 177 |
|
| 178 |
if ( $initForExecute ) { |
| 179 |
|
| 180 |
$pathParams = array_map( 'rawurldecode', $match['params'] ?? [] ); |
| 181 |
$request->setPathParams( $pathParams ); |
| 182 |
|
| 183 |
$handler->initForExecute( $request ); |
| 184 |
} |
| 185 |
|
| 186 |
return $handler; |
| 187 |
} |
| 188 |
|
| 189 |
public function getRouter(): Router { |
| 190 |
return $this->router; |
| 191 |
} |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
abstract protected function findHandlerMatch( |
| 217 |
string $path, |
| 218 |
string $requestMethod |
| 219 |
): array; |
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
protected function throwNoMatch( string $path, string $method, array $allowed ): void { |
| 233 |
|
| 234 |
|
| 235 |
if ( $this->cors && $method === 'OPTIONS' && $allowed ) { |
| 236 |
|
| 237 |
$response = $this->cors->createPreflightResponse( $allowed ); |
| 238 |
throw new ResponseException( $response ); |
| 239 |
} |
| 240 |
|
| 241 |
if ( $allowed ) { |
| 242 |
|
| 243 |
$response = $this->responseFactory->createLocalizedHttpError( 405, |
| 244 |
( new MessageValue( 'rest-wrong-method' ) ) |
| 245 |
->textParams( $method ) |
| 246 |
->commaListParams( $allowed ) |
| 247 |
->numParams( count( $allowed ) ) |
| 248 |
); |
| 249 |
$response->setHeader( 'Allow', $allowed ); |
| 250 |
throw new ResponseException( $response ); |
| 251 |
} else { |
| 252 |
|
| 253 |
$msg = ( new MessageValue( 'rest-no-match' ) ) |
| 254 |
->plaintextParams( $path ); |
| 255 |
throw new LocalizedHttpException( $msg, 404 ); |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
public function execute( string $path, RequestInterface $request ): ResponseInterface { |
| 263 |
$handler = null; |
| 264 |
$startTime = microtime( true ); |
| 265 |
|
| 266 |
try { |
| 267 |
$handler = $this->getHandlerForPath( $path, $request, true ); |
| 268 |
|
| 269 |
$response = $this->executeHandler( $handler ); |
| 270 |
} catch ( HttpException $e ) { |
| 271 |
$extraData = []; |
| 272 |
if ( $this->router->isRestbaseCompatEnabled( $request ) |
| 273 |
&& $e instanceof LocalizedHttpException |
| 274 |
) { |
| 275 |
$extraData = $this->router->getRestbaseCompatErrorData( $request, $e ); |
| 276 |
} |
| 277 |
$response = $this->responseFactory->createFromException( $e, $extraData ); |
| 278 |
} catch ( Throwable $e ) { |
| 279 |
|
| 280 |
$this->errorReporter->reportError( $e, $handler, $request ); |
| 281 |
$response = $this->responseFactory->createFromException( $e ); |
| 282 |
} |
| 283 |
|
| 284 |
$this->recordMetrics( $handler, $request, $response, $startTime ); |
| 285 |
|
| 286 |
return $response; |
| 287 |
} |
| 288 |
|
| 289 |
private function recordMetrics( |
| 290 |
?Handler $handler, |
| 291 |
RequestInterface $request, |
| 292 |
ResponseInterface $response, |
| 293 |
float $startTime |
| 294 |
) { |
| 295 |
$latency = ( microtime( true ) - $startTime ) * 1000; |
| 296 |
|
| 297 |
|
| 298 |
$pathForMetrics = $this->getPathPrefix(); |
| 299 |
|
| 300 |
if ( $pathForMetrics !== '' ) { |
| 301 |
$pathForMetrics = '/' . $pathForMetrics; |
| 302 |
} |
| 303 |
|
| 304 |
$pathForMetrics .= $handler ? $handler->getPath() : '/UNKNOWN'; |
| 305 |
|
| 306 |
|
| 307 |
$pathForMetrics = strtr( $pathForMetrics, '{}:/.', '---__' ); |
| 308 |
|
| 309 |
$statusCode = $response->getStatusCode(); |
| 310 |
$requestMethod = $request->getMethod(); |
| 311 |
if ( $statusCode >= 400 ) { |
| 312 |
|
| 313 |
$this->stats->getCounter( 'rest_api_errors_total' ) |
| 314 |
->setLabel( 'path', $pathForMetrics ) |
| 315 |
->setLabel( 'method', $requestMethod ) |
| 316 |
->setLabel( 'status', "$statusCode" ) |
| 317 |
->copyToStatsdAt( [ "rest_api_errors.$pathForMetrics.$requestMethod.$statusCode" ] ) |
| 318 |
->increment(); |
| 319 |
} else { |
| 320 |
|
| 321 |
$this->stats->getTiming( 'rest_api_latency_seconds' ) |
| 322 |
->setLabel( 'path', $pathForMetrics ) |
| 323 |
->setLabel( 'method', $requestMethod ) |
| 324 |
->setLabel( 'status', "$statusCode" ) |
| 325 |
->copyToStatsdAt( "rest_api_latency.$pathForMetrics.$requestMethod.$statusCode" ) |
| 326 |
->observe( $latency ); |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
abstract public function getDefinedPaths(): array; |
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
abstract public function getAllowedMethods( string $relPath ): array; |
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
protected function instantiateHandlerObject( array $spec ): Handler { |
| 352 |
|
| 353 |
$handler = $this->objectFactory->createObject( |
| 354 |
$spec, |
| 355 |
[ 'assertClass' => Handler::class ] |
| 356 |
); |
| 357 |
|
| 358 |
return $handler; |
| 359 |
} |
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
protected function executeHandler( Handler $handler ): ResponseInterface { |
| 366 |
ProfilingContext::singleton()->init( MW_ENTRY_POINT, $handler->getPath() ); |
| 367 |
|
| 368 |
$authResult = $this->basicAuth->authorize( $handler->getRequest(), $handler ); |
| 369 |
if ( $authResult ) { |
| 370 |
return $this->responseFactory->createHttpError( 403, [ 'error' => $authResult ] ); |
| 371 |
} |
| 372 |
|
| 373 |
|
| 374 |
$handler->checkSession(); |
| 375 |
|
| 376 |
|
| 377 |
$handler->validate( $this->restValidator ); |
| 378 |
|
| 379 |
|
| 380 |
$earlyResponse = $handler->checkPreconditions(); |
| 381 |
if ( $earlyResponse ) { |
| 382 |
return $earlyResponse; |
| 383 |
} |
| 384 |
|
| 385 |
|
| 386 |
$response = $handler->execute(); |
| 387 |
if ( !( $response instanceof ResponseInterface ) ) { |
| 388 |
$response = $this->responseFactory->createFromReturnValue( $response ); |
| 389 |
} |
| 390 |
|
| 391 |
|
| 392 |
$handler->applyConditionalResponseHeaders( $response ); |
| 393 |
|
| 394 |
$handler->applyCacheControl( $response ); |
| 395 |
|
| 396 |
return $response; |
| 397 |
} |
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
public function setCors( CorsUtils $cors ): self { |
| 404 |
$this->cors = $cors; |
| 405 |
|
| 406 |
return $this; |
| 407 |
} |
| 408 |
|
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
public function setStats( StatsFactory $stats ): self { |
| 417 |
$this->stats = $stats; |
| 418 |
|
| 419 |
return $this; |
| 420 |
} |
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
|
| 434 |
|
| 435 |
|
| 436 |
public static function loadJsonFile( string $fileName ): array { |
| 437 |
$json = file_get_contents( $fileName ); |
| 438 |
if ( $json === false ) { |
| 439 |
throw new ModuleConfigurationException( |
| 440 |
"Failed to load file `$fileName`" |
| 441 |
); |
| 442 |
} |
| 443 |
|
| 444 |
$spec = json_decode( $json, true ); |
| 445 |
|
| 446 |
if ( !is_array( $spec ) ) { |
| 447 |
throw new ModuleConfigurationException( |
| 448 |
"Failed to parse `$fileName` as a JSON object" |
| 449 |
); |
| 450 |
} |
| 451 |
|
| 452 |
return $spec; |
| 453 |
} |
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
public function getOpenApiInfo() { |
| 463 |
return []; |
| 464 |
} |
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
public function getModuleDescription(): array { |
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
$moduleId = $this->getPathPrefix(); |
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
$infoFields = [ 'version', 'title', 'description' ]; |
| 486 |
|
| 487 |
return [ |
| 488 |
'moduleId' => $moduleId, |
| 489 |
'info' => array_intersect_key( |
| 490 |
$this->getOpenApiInfo(), |
| 491 |
array_flip( $infoFields ) |
| 492 |
), |
| 493 |
'base' => $this->getRouter()->getRouteUrl( |
| 494 |
'/' . $moduleId |
| 495 |
), |
| 496 |
'spec' => $this->getRouter()->getRouteUrl( |
| 497 |
'/specs/v0/module/{module}', |
| 498 |
[ 'module' => $moduleId == '' ? '-' : $moduleId ] |
| 499 |
) |
| 500 |
]; |
| 501 |
} |
| 502 |
} |