Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
80.93% covered (warning)
80.93%
539 / 666
53.85% covered (warning)
53.85%
7 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
FunctionCallHandler
80.93% covered (warning)
80.93%
539 / 666
53.85% covered (warning)
53.85%
7 / 13
70.75
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 run
84.27% covered (warning)
84.27%
75 / 89
0.00% covered (danger)
0.00%
0 / 1
5.10
 getTargetFunction
78.48% covered (warning)
78.48%
62 / 79
0.00% covered (danger)
0.00%
0 / 1
5.25
 getLanguageZid
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
2
 buildArgumentsForCall
100.00% covered (success)
100.00%
80 / 80
100.00% covered (success)
100.00%
1 / 1
8
 buildParsedArgument
100.00% covered (success)
100.00%
86 / 86
100.00% covered (success)
100.00%
1 / 1
6
 isArgumentValidReference
100.00% covered (success)
100.00%
69 / 69
100.00% covered (success)
100.00%
1 / 1
5
 buildRenderedOutput
100.00% covered (success)
100.00%
74 / 74
100.00% covered (success)
100.00%
1 / 1
4
 makeRequest
26.40% covered (danger)
26.40%
33 / 125
0.00% covered (danger)
0.00%
0 / 1
49.87
 applyCacheControl
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 getResponseBodySchemaFileName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 needsWriteAccess
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getParamSettings
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * WikiLambda ZObject function calling REST API
4 *
5 * @file
6 * @ingroup Extensions
7 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
8 * @license MIT
9 */
10
11namespace MediaWiki\Extension\WikiLambda\RESTAPI;
12
13use Exception;
14use JsonException;
15use MediaWiki\Api\ApiMain;
16use MediaWiki\Api\ApiUsageException;
17use MediaWiki\Context\DerivativeContext;
18use MediaWiki\Context\RequestContext;
19use MediaWiki\Extension\WikiLambda\ActionAPI\WikiLambdaApiBase;
20use MediaWiki\Extension\WikiLambda\HttpStatus;
21use MediaWiki\Extension\WikiLambda\Registry\ZErrorTypeRegistry;
22use MediaWiki\Extension\WikiLambda\Registry\ZLangRegistry;
23use MediaWiki\Extension\WikiLambda\Registry\ZTypeRegistry;
24use MediaWiki\Extension\WikiLambda\WikiLambdaServices;
25use MediaWiki\Extension\WikiLambda\ZErrorException;
26use MediaWiki\Extension\WikiLambda\ZErrorFactory;
27use MediaWiki\Extension\WikiLambda\ZObjectFactory;
28use MediaWiki\Extension\WikiLambda\ZObjects\ZError;
29use MediaWiki\Extension\WikiLambda\ZObjects\ZFunction;
30use MediaWiki\Extension\WikiLambda\ZObjects\ZFunctionCall;
31use MediaWiki\Extension\WikiLambda\ZObjects\ZObject;
32use MediaWiki\Extension\WikiLambda\ZObjects\ZQuote;
33use MediaWiki\Extension\WikiLambda\ZObjects\ZReference;
34use MediaWiki\Extension\WikiLambda\ZObjects\ZResponseEnvelope;
35use MediaWiki\Extension\WikiLambda\ZObjects\ZString;
36use MediaWiki\Extension\WikiLambda\ZObjects\ZType;
37use MediaWiki\Extension\WikiLambda\ZObjectStore;
38use MediaWiki\Extension\WikiLambda\ZObjectUtils;
39use MediaWiki\Logger\LoggerFactory;
40use MediaWiki\Request\FauxRequest;
41use MediaWiki\Rest\Handler;
42use MediaWiki\Rest\Response;
43use MediaWiki\Rest\ResponseInterface;
44use stdClass;
45use Wikimedia\Message\MessageValue;
46use Wikimedia\ParamValidator\ParamValidator;
47use Wikimedia\Telemetry\SpanInterface;
48use Wikimedia\Telemetry\TracerInterface;
49
50/**
51 * Simple REST API to call a ZFunction with text arguments for cross-wiki embedding
52 * in wikitext, via `GET /wikifunctions/v0/call/{zid}/{arguments}`, or more fully,
53 * `GET /wikifunctions/v0/call/{zid}/{arguments}/{parselang}/{renderlang}`
54 */
55class FunctionCallHandler extends WikiLambdaRESTHandler {
56
57    private ZLangRegistry $langRegistry;
58
59    public function __construct(
60        private readonly TracerInterface $tracer,
61        private readonly ZObjectStore $zObjectStore
62    ) {
63        // Non-injected items
64        $this->langRegistry = ZLangRegistry::singleton();
65        $this->logger = LoggerFactory::getInstance( 'WikiLambda' );
66    }
67
68    /**
69     * @param string $target
70     * @param string $arguments
71     * @param string $parseLang
72     * @param string $renderLang
73     * @return Response
74     */
75    public function run(
76        $target,
77        $arguments = '',
78        $parseLang = 'en',
79        $renderLang = 'en'
80    ) {
81        // Initial setup; logging and instrumentation
82        $span = $this->tracer->createSpan( 'WikiLambda FunctionCallHandler' )
83            ->setSpanKind( SpanInterface::SPAN_KIND_CLIENT )
84            ->start();
85        $span->activate();
86
87        $this->logger->debug(
88            __METHOD__ . ' triggered to evaluate a call to {target}',
89            [ 'target' => $target ]
90        );
91
92        // 0. Make sure that this call is not being run in a client instance
93        if ( !WikiLambdaServices::getMode()->isRepo() ) {
94            $errorMessage = __METHOD__ . ' called repo mode is not enabled';
95            $this->logger->debug( $errorMessage );
96            $span->setAttributes( [
97                    'response.status_code' => HttpStatus::BAD_REQUEST,
98                    'exception.message' => $errorMessage
99                ] );
100            $span->end();
101            // WikiLambda repo code isn't loaded, so we can't use a ZError here sadly.
102            $this->dieRESTfully( 'wikilambda-restapi-disabled-repo-mode-only', [], HttpStatus::BAD_REQUEST );
103        }
104
105        // 1. Get the target function or die with ZError
106        $targetFunction = $this->getTargetFunction( $target, $span );
107
108        // 2. Validate parser and renderer language codes and get their Zids
109        $parseLanguageZid = $this->getLanguageZid( $parseLang, 'parselang', $span );
110        $renderLanguageZid = $this->getLanguageZid( $renderLang, 'renderlang', $span );
111
112        // 3. Build the arguments for the call given their expected types (or dies if something is wrong)
113        $argumentsForCall = $this->buildArgumentsForCall(
114            $target,
115            $arguments,
116            $parseLanguageZid,
117            $targetFunction,
118            $span
119        );
120
121        // 4. Set up the final, full call with all the above sub-calls embedded
122        $callObject = new ZFunctionCall( new ZReference( $target ), $argumentsForCall );
123
124        // 5. (T362252): Check if there's a renderer for this return type (if so, it will be used)
125        $targetReturnType = $targetFunction->getValueByKey( ZTypeRegistry::Z_FUNCTION_RETURN_TYPE )->getZValue();
126
127        // Types that can be directly rendered:
128        // * String/Z6
129        // * HTML Fragment/Z89
130        // * Object/Z1 (only when the function call returns a string)
131        $renderableOutputTypes = [
132            ZTypeRegistry::Z_STRING,
133            ZTypeRegistry::Z_HTML_FRAGMENT,
134            ZTypeRegistry::Z_OBJECT
135        ];
136
137        if ( !in_array( $targetReturnType, $renderableOutputTypes ) ) {
138            $callObject = $this->buildRenderedOutput(
139                $target,
140                $targetReturnType,
141                $renderLanguageZid,
142                $callObject,
143                $span
144            );
145        }
146
147        // 6. Down-convert the ZFunctionCall Object to a stdClass object
148        $call = $callObject->getSerialized();
149
150        // 7. Execute the call
151        try {
152            $requestCall = json_encode( $call, JSON_THROW_ON_ERROR );
153            $response = $this->makeRequest( $requestCall, $renderLang, $span );
154        } catch ( ZErrorException $e ) {
155            $errorMessage = __METHOD__ . ' called on {target} but got a ZErrorException, {error}';
156            $this->logger->debug(
157                $errorMessage,
158                [
159                    'target' => $target,
160                    'error' => $e->getMessage(),
161                    'exception' => $e
162                ]
163            );
164            $span->setAttributes( [
165                    'response.status_code' => HttpStatus::BAD_REQUEST,
166                    'exception.message' => $errorMessage
167                ] );
168            // Dies with one of these ZErrors:
169            // * Z_ERROR_API_FAILURE/Z530
170            // * Z_ERROR_EVALUATION/Z507
171            // * Z_ERROR_INVALID_EVALUATION_RESULT/Z560
172            $this->dieRESTfullyWithZError( $e->getZError(), HttpStatus::BAD_REQUEST, [ 'data' => $e->getZError() ] );
173        } catch ( JsonException $e ) {
174            $errorMessage = __METHOD__ . ' called on {target} but got a JsonException, {error}';
175            $this->logger->info(
176                $errorMessage,
177                [
178                    'target' => $target,
179                    'error' => $e->getMessage(),
180                    'exception' => $e
181                ]
182            );
183            $span->setAttributes( [
184                    'response.status_code' => HttpStatus::BAD_REQUEST,
185                    'exception.message' => $errorMessage
186                ] );
187            $this->dieRESTfullyWithZError(
188                ZErrorFactory::createZErrorInstance(
189                    ZErrorTypeRegistry::Z_ERROR_INVALID_SYNTAX, [
190                        'input' => var_export( $call, true ),
191                        'message' => $e->getMessage()
192                    ]
193                ),
194                HttpStatus::BAD_REQUEST,
195                [
196                    'target' => $target,
197                    'error' => $e->getMessage()
198                ]
199            );
200        } finally {
201            $span->end();
202        }
203
204        // Finally, return the values as JSON (if not already early-returned as an error)
205        return $this->getResponseFactory()->createJson( $response ?? '' );
206    }
207
208    /**
209     * Verifies the validity of the given target function Zid and returns its
210     * object (inner ZFunction object) if everything went well.
211     *
212     * Dies with ZError if:
213     * * Given function Id is not a valid Zid
214     * * Target function Zid does not exist
215     * * Target function cannot be fetched
216     * * Fetched target function is not valid
217     * * Fetched target Zid does not belong to a function
218     *
219     * @param string $target
220     * @param SpanInterface $span
221     * @return ZFunction
222     */
223    private function getTargetFunction( $target, $span ) {
224        // 1. Check if target function Id is a valid Zid
225        if ( !ZObjectUtils::isValidOrNullZObjectReference( $target ) ) {
226            $errorMessage = __METHOD__ . ' called on {target} which is a non-ZID, e.g. an inline function';
227            $this->logger->debug(
228                $errorMessage,
229                [ 'target' => $target ]
230            );
231            $span->setAttributes( [
232                'response.status_code' => HttpStatus::BAD_REQUEST,
233                'exception.message' => $errorMessage
234            ] )->end();
235
236            // Dies with Z_ERROR_ID_NOT_FOUND
237            $this->dieRESTfullyWithZError(
238                ZErrorFactory::createZErrorInstance( ZErrorTypeRegistry::Z_ERROR_ID_NOT_FOUND, [ 'data' => $target ] ),
239                HttpStatus::BAD_REQUEST,
240                [ 'target' => $target ]
241            );
242        }
243
244        // 2. Check if target function Zid can be successfully fetched; try cache first, then DB
245        $targetObject = $this->zObjectStore->fetchZObject( $target );
246        if ( !$targetObject ) {
247            $errorMessage = __METHOD__ . ' called on {target} which is somehow non-ZObject in our namespace';
248            $this->logger->debug(
249                $errorMessage,
250                [ 'target' => $target ]
251            );
252            $span->setAttributes( [
253                'response.status_code' => HttpStatus::BAD_REQUEST,
254                'exception.message' => $errorMessage
255            ] )->end();
256
257            // Dies with Z_ERROR_ID_NOT_FOUND
258            $this->dieRESTfullyWithZError(
259                ZErrorFactory::createZErrorInstance( ZErrorTypeRegistry::Z_ERROR_ID_NOT_FOUND, [ 'data' => $target ] ),
260                HttpStatus::BAD_REQUEST,
261                [ 'target' => $target ]
262            );
263        }
264
265        // 3. Check if target function is valid
266        if ( !$targetObject->isValid() ) {
267            $errorMessage = __METHOD__ . ' called on {target} which is an invalid ZObject';
268            $this->logger->info(
269                $errorMessage,
270                [
271                    'target' => $target,
272                    'childError' => $targetObject->getErrors()->getMessage(),
273                ]
274            );
275            $span->setAttributes( [
276                'response.status_code' => HttpStatus::BAD_REQUEST,
277                'exception.message' => $errorMessage
278            ] )->end();
279
280            // Dies with Z_ERROR_NOT_WELLFORMED
281            $this->dieRESTfullyWithZError(
282                ZErrorFactory::createValidationZError( $targetObject->getErrors() ),
283                HttpStatus::BAD_REQUEST,
284                [ 'target' => $target ]
285            );
286        }
287
288        // 5. Check if target function is a function
289        if ( $targetObject->getZType() !== ZTypeRegistry::Z_FUNCTION ) {
290            $errorMessage = __METHOD__ . ' called on {target} which is not a Function but a {type}';
291            $this->logger->debug(
292                $errorMessage,
293                [
294                    'target' => $target,
295                    'type' => $targetObject->getZType()
296                ]
297            );
298            $span->setAttributes( [
299                'response.status_code' => HttpStatus::BAD_REQUEST,
300                'exception.message' => $errorMessage
301            ] )->end();
302
303            // Dies with Z_ERROR_ARGUMENT_TYPE_MISMATCH
304            $this->dieRESTfullyWithZError(
305                ZErrorFactory::createZErrorInstance(
306                    ZErrorTypeRegistry::Z_ERROR_ARGUMENT_TYPE_MISMATCH,
307                    [
308                        'expected' => ZTypeRegistry::Z_FUNCTION,
309                        'actual' => $targetObject->getZType(),
310                        'argument' => $target
311                    ]
312                ),
313                HttpStatus::BAD_REQUEST,
314                [
315                    'target' => $target,
316                    'mode' => 'function'
317                ]
318            );
319        }
320
321        // Success! Return inner ZFunction object
322        $functionObject = $targetObject->getInnerZObject();
323        '@phan-var ZFunction $functionObject';
324        return $functionObject;
325    }
326
327    /**
328     * Read a language Bcp47 code argument and find its equivalents Natural Language/Z60 Zid.
329     * This is called for:
330     * * parseLang
331     * * renderLang
332     * * input arguments of type Z60
333     *
334     * @param string $langCode
335     * @param string $argKey
336     * @param SpanInterface $span
337     * @return string language zid
338     */
339    private function getLanguageZid( $langCode, $argKey, $span ): string {
340        // Check that the requested language code is one we know of and support
341        try {
342            $languageZid = $this->langRegistry->getLanguageZidFromCode( $langCode );
343        } catch ( ZErrorException $error ) {
344            $errorMessage =
345                __METHOD__ . ' called with {argKey} {langCode} which is not found / errored: {error}';
346            $this->logger->debug(
347                $errorMessage,
348                [
349                    'argKey' => $argKey,
350                    'langCode' => $langCode,
351                    'error' => $error->getMessage()
352                ]
353            );
354            $span->setAttributes( [
355                'response.status_code' => HttpStatus::BAD_REQUEST,
356                'exception.message' => $errorMessage
357            ] )->end();
358
359            // Die with Z_ERROR_LANG_NOT_FOUND
360            $this->dieRESTfullyWithZError(
361                $error->getZError(),
362                HttpStatus::BAD_REQUEST,
363                [ 'target' => $langCode ]
364            );
365        }
366
367        // Success! Return the langugae zids
368        return $languageZid;
369    }
370
371    /**
372     * @param string $target
373     * @param string $argumentsString
374     * @param string $parseLanguageZid
375     * @param ZFunction $targetFunction
376     * @param SpanInterface $span
377     * @return array
378     */
379    private function buildArgumentsForCall(
380        $target,
381        $argumentsString,
382        $parseLanguageZid,
383        $targetFunction,
384        $span
385    ): array {
386        // 1. Split and decode arguments
387        $encodedArguments = explode( '|', $argumentsString );
388        $arguments = array_map(
389            static fn ( $val ): string => ZObjectUtils::decodeStringParamFromNetwork( $val ),
390            $encodedArguments
391        );
392
393        // 2. Check that the given input count matches with the number of arguments in the function signature
394        $expectedArguments = $targetFunction->getArgumentDeclarations();
395        if ( count( $arguments ) !== count( $expectedArguments ) ) {
396            $errorMessage =
397                __METHOD__ . ' called on {target} with the wrong number of arguments, {givenCount} not {expectedCount}';
398            $this->logger->debug(
399                $errorMessage,
400                [
401                    'target' => $target,
402                    'givenCount' => count( $arguments ),
403                    'expectedCount' => count( $expectedArguments )
404                ]
405            );
406            $span->setAttributes( [
407                'response.status_code' => HttpStatus::BAD_REQUEST,
408                'exception.message' => $errorMessage
409            ] )->end();
410
411            // Die with Z_ERROR_ARGUMENT_COUNT_MISMATCH
412            $this->dieRESTfullyWithZError(
413                ZErrorFactory::createZErrorInstance(
414                    ZErrorTypeRegistry::Z_ERROR_ARGUMENT_COUNT_MISMATCH,
415                    [
416                        'expected' => strval( count( $expectedArguments ) ),
417                        'actual' => strval( count( $arguments ) ),
418                        'arguments' => $arguments
419                    ]
420                ),
421                HttpStatus::BAD_REQUEST,
422                [ 'target' => $target ]
423            );
424        }
425
426        $argumentsForCall = [];
427
428        // 3. For each argument in the function signature:
429        //    * check that the input type is supported, and
430        //    * build the appropriate input object from the string.
431        foreach ( $expectedArguments as $expectedArgumentIndex => $expectedArgument ) {
432            $argumentKey = $expectedArgument->getValueByKey( ZTypeRegistry::Z_ARGUMENTDECLARATION_ID )->getZValue();
433            $providedArgument = $arguments[array_keys( $arguments )[$expectedArgumentIndex]];
434            $targetTypeZid = $expectedArgument->getValueByKey( ZTypeRegistry::Z_ARGUMENTDECLARATION_TYPE )->getZValue();
435
436            // A) If expected type is String/Z6 or Object/Z1: build String object (canonical or normal if zid)
437            if ( ( $targetTypeZid === ZTypeRegistry::Z_STRING ) || ( $targetTypeZid === ZTypeRegistry::Z_OBJECT ) ) {
438                $argumentsForCall[$argumentKey] = new ZString( $providedArgument );
439                continue;
440            }
441
442            // B) For Wikidata input types:
443            //    * If expected type is Wikidata entity: build wikidata fetch function call object
444            //    * If expected type is Wikidata reference: build wikidata reference object
445            $allowedEntityTypes = [
446                ZTypeRegistry::Z_WIKIDATA_LEXEME,
447                ZTypeRegistry::Z_WIKIDATA_ITEM
448            ];
449            $allowedReferenceTypes = [
450                ZTypeRegistry::Z_WIKIDATA_REFERENCE_LEXEME,
451                ZTypeRegistry::Z_WIKIDATA_REFERENCE_ITEM
452            ];
453
454            // Handle Wikidata entity types (e.g., Z6001, Z6005, etc.) as function arguments:
455            // We build a ZFunctionCall to the appropriate Wikidata fetch function (e.g., Z6825 for lexeme),
456            // with the argument being a Wikidata reference type (e.g., { Z1K1: Z6095, Z6095K1: 'L123' })
457            if ( in_array( $targetTypeZid, $allowedEntityTypes ) ) {
458                $entityMap = ZTypeRegistry::WIKIDATA_ENTITY_TYPE_MAP[$targetTypeZid] ?? null;
459                if ( $entityMap ) {
460                    $referenceType = $entityMap['reference_type'];
461                    $referenceKey = $entityMap['reference_key'];
462                    $fetchFunction = $entityMap['fetch_function'];
463                    $fetchKey = $entityMap['fetch_key'];
464
465                    // Build the reference ZObject for the entity (e.g., { Z1K1: Z6095, Z6095K1: 'L123' })
466                    $referenceObject = new ZObject(
467                        new ZReference( $referenceType ),
468                        [ $referenceKey => new ZString( $providedArgument ) ]
469                    );
470                    // Build the ZFunctionCall to the fetch function, passing the reference object as the argument
471                    $argumentsForCall[$argumentKey] = new ZFunctionCall(
472                        new ZReference( $fetchFunction ),
473                        [ $fetchKey => $referenceObject ]
474                    );
475                    continue;
476                }
477            }
478
479            // Handle Wikidata reference types (e.g., Z6091, Z6095, etc.) as function arguments:
480            // We build a ZObject of the given Wikidata reference type.
481            if ( in_array( $targetTypeZid, $allowedReferenceTypes ) ) {
482                $argumentsForCall[$argumentKey] = new ZObject(
483                    new ZReference( $targetTypeZid ),
484                    [ $targetTypeZid . 'K1' => new ZString( $providedArgument ) ]
485                    );
486                continue;
487            }
488
489            // C) If any other type, build either parser function call or reference to enum instance
490            $argumentsForCall[$argumentKey] = $this->buildParsedArgument(
491                $target,
492                $targetTypeZid,
493                $argumentKey,
494                $parseLanguageZid,
495                $providedArgument,
496                $span
497            );
498        }
499
500        return $argumentsForCall;
501    }
502
503    /**
504     * Builds the argument for any other custom type, which means that we need to
505     * fetch the type first in order to figure out whether:
506     * * The type is an enum or any other type that can be referenced, and the arg is a reference
507     * * The type has a parser function so it can be parsed from an input string
508     *
509     * @param string $target - target function zid
510     * @param string $targetTypeZid - target function argument type zid
511     * @param string $argumentKey - target function argument key
512     * @param string $parseLanguageZid - zid of the parser language
513     * @param string $providedArgument - provided string value for the argument
514     * @param SpanInterface $span
515     * @return ZObject
516     */
517    private function buildParsedArgument(
518        $target,
519        $targetTypeZid,
520        $argumentKey,
521        $parseLanguageZid,
522        $providedArgument,
523        $span
524    ): ZObject {
525        // Fetch target input type to figure out if it has a parser function; try cache first, else DB
526        $targetType = $this->zObjectStore->fetchZObject( $targetTypeZid );
527        if ( !$targetType ) {
528            $errorMessage = __METHOD__ . ' called on {target} which has a not-found input type {typeZid} at key {key}';
529            $this->logger->debug(
530                $errorMessage,
531                [
532                    'target' => $target,
533                    'typeZid' => $targetTypeZid,
534                    'key' => $argumentKey
535                ]
536            );
537            $span->setAttributes( [
538                'response.status_code' => HttpStatus::BAD_REQUEST,
539                'exception.message' => $errorMessage
540            ] )->end();
541
542            // Dies with Z_ERROR_ID_NOT_FOUND
543            $this->dieRESTfullyWithZError(
544                ZErrorFactory::createZErrorInstance(
545                    ZErrorTypeRegistry::Z_ERROR_ID_NOT_FOUND, [ 'data' => $targetTypeZid ]
546                ),
547                HttpStatus::BAD_REQUEST,
548                [
549                    'target' => $target,
550                    'mode' => 'input'
551                ]
552            );
553        }
554
555        $targetTypeObject = $targetType->getInnerZObject();
556        if ( !( $targetTypeObject instanceof ZType ) ) {
557            // It's somehow not to a Type, because:
558            // * Argument is a generic type; the function input is not supported.
559            // * There is an error in the content; the function is not wellformed (not very likely).
560            $errorMessage =
561                __METHOD__ . ' called on {target} which has a non-Type argument, {typeZid} at key {key}';
562            $this->logger->debug(
563                $errorMessage,
564                [
565                    'target' => $target,
566                    'typeZid' => $targetTypeZid,
567                    'key' => $argumentKey
568                ]
569            );
570            $span->setAttributes( [
571                'response.status_code' => HttpStatus::BAD_REQUEST,
572                'exception.message' => $errorMessage
573            ] )->end();
574
575            // Die with Z_ERROR_NOT_IMPLEMENTED_YET
576            $this->dieRESTfullyWithZError(
577                ZErrorFactory::createZErrorInstance(
578                    ZErrorTypeRegistry::Z_ERROR_NOT_IMPLEMENTED_YET, [ 'data' => $target ]
579                ),
580                HttpStatus::BAD_REQUEST,
581                [
582                    'target' => $target,
583                    'mode' => 'input'
584                ]
585            );
586        }
587
588        // Check if the argument is a ZID to an instance of the right Type:
589        // * if so, builds a ZReference object
590        // * if not a reference, proceeds with building parser function
591        if ( $this->isArgumentValidReference( $providedArgument, $targetTypeObject, $target, $span ) ) {
592            return new ZReference( $providedArgument );
593        }
594
595        // If type is a language and value is not a zid, get language zid from Bcp47code
596        if ( $targetTypeZid === ZTypeRegistry::Z_LANGUAGE ) {
597            $languageZid = $this->getLanguageZid( $providedArgument, $argumentKey, $span );
598            return new ZReference( $languageZid );
599        }
600
601        // At this point, we know it's a string input to a non-string Type, so we need to parse it
602        $typeParser = $targetTypeObject->getParserFunction();
603
604        // Type has no parser
605        if ( $typeParser === false ) {
606            // User is trying to use a parameter that can't be parsed from text
607            $errorMessage =
608                __METHOD__ . ' called on {target} with an unparseable input, {targetTypeZid} at key {key}';
609            $this->logger->debug(
610                $errorMessage,
611                [
612                    'target' => $target,
613                    'targetTypeZid' => $targetTypeZid,
614                    'key' => $argumentKey
615                ]
616            );
617            $span->setAttributes( [
618                'response.status_code' => HttpStatus::BAD_REQUEST,
619                'exception.message' => $errorMessage
620            ] )->end();
621
622            // Die with Z_ERROR_NOT_IMPLEMENTED_YET
623            $this->dieRESTfullyWithZError(
624                ZErrorFactory::createZErrorInstance(
625                    ZErrorTypeRegistry::Z_ERROR_NOT_IMPLEMENTED_YET, [ 'data' => $target ]
626                ),
627                HttpStatus::BAD_REQUEST,
628                [
629                    'target' => $target,
630                    'mode' => 'input'
631                ]
632            );
633        }
634
635        // At this point, we know the argument should be parsed and a parser is available, so let's schedule it
636        return new ZFunctionCall( new ZReference( $typeParser ), [
637            $typeParser . "K1" => new ZString( $providedArgument ),
638            $typeParser . "K2" => new ZReference( $parseLanguageZid )
639        ] );
640    }
641
642    /**
643     * Verifies the validity of a referenced argument with respect to the expected type:
644     * * if the string argument is a reference to a valid type, returns true
645     * * if the string argument is not a reference, returns false
646     * * if it's a wrong reference or a reference to a non-valid type, dies with error
647     *
648     * @param string $providedArgument
649     * @param ZType $targetTypeObject
650     * @param string $targetFunction
651     * @param SpanInterface $span
652     * @return bool
653     */
654    private function isArgumentValidReference(
655        $providedArgument,
656        $targetTypeObject,
657        $targetFunction,
658        $span
659    ): bool {
660        // The provided argument is a string value (not a reference): it should be parsed
661        // This excludes Z6s and Z1s as they have already been handled.
662        if ( !ZObjectUtils::isValidZObjectReference( $providedArgument ) ) {
663            return false;
664        }
665
666        // If the provided argument is a reference to a ZObject, we fetch it; try cache first, else DB
667        $referencedArgument = $this->zObjectStore->fetchZObject( $providedArgument );
668        if ( $referencedArgument === false ) {
669            // Fatal — it's a ZID but not to an extant Object.
670            $errorMessage =
671                __METHOD__ . ' called on {providedArgument} for function {targetFunction} but it doesn\'t exist';
672            $this->logger->debug(
673                $errorMessage,
674                [
675                    'providedArgument' => $providedArgument,
676                    'targetFunction' => $targetFunction
677                ]
678            );
679            $span->setAttributes( [
680                'response.status_code' => HttpStatus::BAD_REQUEST,
681                'exception.message' => $errorMessage
682            ] )->end();
683
684            // Die with Z_ERROR_ID_NOT_FOUND
685            $this->dieRESTfullyWithZError(
686                ZErrorFactory::createZErrorInstance(
687                    ZErrorTypeRegistry::Z_ERROR_ID_NOT_FOUND, [ 'data' => $providedArgument ]
688                ),
689                HttpStatus::BAD_REQUEST,
690                [
691                    'target' => $targetFunction,
692                    'mode' => 'input'
693                ]
694            );
695        }
696
697        $referencedArgumentType = $referencedArgument->getInnerZObject()->getZType();
698        $expectedArgumentType = $targetTypeObject->getTypeId()->getZValue();
699
700        if ( $referencedArgumentType !== $expectedArgumentType ) {
701            // Failure — it's a ZID but not to an instance of the right Type.
702            $errorMessage = __METHOD__ . ' called on {arg} for function {function} but it\'s not a {expectedType}';
703            $this->logger->debug(
704                $errorMessage,
705                [
706                    'arg' => $providedArgument,
707                    'function' => $targetFunction,
708                    'expectedType' => $expectedArgumentType
709                ]
710            );
711            $span->setAttributes( [
712                    'response.status_code' => HttpStatus::BAD_REQUEST,
713                    'exception.message' => $errorMessage
714                ] );
715            $span->end();
716            $this->dieRESTfullyWithZError(
717                ZErrorFactory::createZErrorInstance(
718                    ZErrorTypeRegistry::Z_ERROR_ARGUMENT_TYPE_MISMATCH,
719                    [
720                        'expected' => $expectedArgumentType,
721                        'actual' => $referencedArgumentType,
722                        'argument' => $providedArgument
723                    ]
724                ),
725                HttpStatus::BAD_REQUEST,
726                [
727                    'target' => $targetFunction,
728                    'mode' => 'input'
729                ]
730            );
731        }
732
733        // If the argument is passed as reference but is not an enum,
734        // we should probably flag this, as it's a weird use case:
735        if ( !$targetTypeObject->isEnumType() ) {
736            $this->logger->debug(
737                __METHOD__ . ' found reference {arg} of non-enum type {type} as input to {function}',
738                [
739                    'arg' => $providedArgument,
740                    'type' => $referencedArgumentType,
741                    'function' => $targetFunction
742                ]
743            );
744        }
745
746        // Given argument is a reference to an instance of the expected type: it should not be parsed
747        // * e.g. Expected type is enum Boolean/Z40, given arg is True/Z41
748        // * e.g. Expected type is String/Z6, given arg is reference to a persisted Z6
749        return true;
750    }
751
752    /**
753     * Builds a renderer function call that wraps the given function call if:
754     * * The expected output type is a valid type, and
755     * * The output type has a renderer function
756     *
757     * @param string $target - zid of the target function
758     * @param string $targetReturnType - zid of the return type of the target function
759     * @param string $renderLanguageZid - zid of the render language
760     * @param ZFunctionCall $callObject - function call object
761     * @param SpanInterface $span
762     */
763    private function buildRenderedOutput(
764        $target,
765        $targetReturnType,
766        $renderLanguageZid,
767        $callObject,
768        $span
769    ): ZFunctionCall {
770        // Fetch target output type to figure out if it has a renderer function; try cache first, else DB
771        $typeObject = $this->zObjectStore->fetchZObject( $targetReturnType );
772        if ( !$typeObject ) {
773            $errorMessage = __METHOD__ . ' called on {target} which has a not-found output type {typeZid}';
774            $this->logger->debug(
775                $errorMessage,
776                [
777                    'target' => $target,
778                    'typeZid' => $targetReturnType
779                ]
780            );
781            $span->setAttributes( [
782                'response.status_code' => HttpStatus::BAD_REQUEST,
783                'exception.message' => $errorMessage
784            ] )->end();
785
786            // Dies with Z_ERROR_ID_NOT_FOUND
787            $this->dieRESTfullyWithZError(
788                ZErrorFactory::createZErrorInstance( ZErrorTypeRegistry::Z_ERROR_ID_NOT_FOUND, [ 'data' => $target ] ),
789                HttpStatus::BAD_REQUEST,
790                [
791                    'target' => $target,
792                    'mode' => 'output'
793                ]
794            );
795        }
796
797        $targetReturnTypeObject = $typeObject->getInnerZObject();
798        if ( !( $targetReturnTypeObject instanceof ZType ) ) {
799            // It's somehow not to a Type, because:
800            // * Output is a generic type; the function input is not supported.
801            // * There is an error in the content; the function is not wellformed (not very likely).
802            $errorMessage = __METHOD__ . ' called on {target} which has a non-Type output, {targetReturnType}';
803            $this->logger->debug(
804                $errorMessage,
805                [
806                    'target' => $target,
807                    'targetReturnType' => $targetReturnType
808                ]
809            );
810            $span->setAttributes( [
811                'response.status_code' => HttpStatus::BAD_REQUEST,
812                'exception.message' => $errorMessage
813            ] )->end();
814
815            // Die with Z_ERROR_NOT_IMPLEMENTED_YET
816            $this->dieRESTfullyWithZError(
817                ZErrorFactory::createZErrorInstance(
818                    ZErrorTypeRegistry::Z_ERROR_NOT_IMPLEMENTED_YET, [ 'data' => $target ]
819                ),
820                HttpStatus::BAD_REQUEST,
821                [
822                    'target' => $target,
823                    'mode' => 'output'
824                ]
825            );
826        }
827
828        $rendererFunction = $targetReturnTypeObject->getRendererFunction();
829
830        if ( $rendererFunction === false ) {
831            // User is trying to use a ZFunction that returns something which doesn't have a renderer
832            $errorMessage = __METHOD__ . ' called on {target} with an unrenderable output, {targetReturnType}';
833            $this->logger->debug(
834                $errorMessage,
835                [
836                    'target' => $target,
837                    'targetReturnType' => $targetReturnType
838                ]
839            );
840            $span->setAttributes( [
841                'response.status_code' => HttpStatus::BAD_REQUEST,
842                'exception.message' => $errorMessage
843            ] )->end();
844
845            // Die with Z_ERROR_NOT_IMPLEMENTED_YET
846            $this->dieRESTfullyWithZError(
847                ZErrorFactory::createZErrorInstance(
848                    ZErrorTypeRegistry::Z_ERROR_NOT_IMPLEMENTED_YET, [ 'data' => $target ]
849                ),
850                HttpStatus::BAD_REQUEST,
851                [
852                    'target' => $target,
853                    'mode' => 'output'
854                ]
855            );
856        }
857
858        // At this point, we know that we must render, so wrap the function call in that
859        return new ZFunctionCall( new ZReference( $rendererFunction ), [
860            $rendererFunction . "K1" => $callObject,
861            $rendererFunction . "K2" => new ZReference( $renderLanguageZid )
862        ] );
863    }
864
865    /**
866     * A convenience function for making a ZFunctionCall and returning its result to embed within a page.
867     * Throws different ZErrorExceptions wrapping the ZErrors:
868     * * Z_ERROR_API_FAILURE: for any exceptions thrown by the Api before completing the Orchestrator request
869     * * Z_ERROR_EVALUATION: for any errors in the Orchestrator or its response
870     * * Z_ERROR_INVALID_EVALUATION_RESULT: for successful Orchestrator response but unexpected response
871     *
872     * @param string $call The ZFunctionCall to make, as a JSON object turned into a string
873     * @param string $renderLanguageCode The code of the language in which to render errors, e.g. fr
874     * @param SpanInterface $span Trace instance for adding spans to a trace
875     * @return stdClass Currently the only permissable response objects are strings
876     * @throws ZErrorException
877     */
878    private function makeRequest( $call, $renderLanguageCode, $span ): stdClass {
879        // TODO (T407490): Can we do an Orchestrator call directly here using WikiLambdaApiBase::executeFunctionCall()
880        // (But note that we're not an ActionAPI class, so can't extend that… Meh.)
881        // Also, consider if we can do an Orchestrator call simply calling
882        // OrchestratorRequest instead of layering APIs.
883        $api = new ApiMain( new FauxRequest() );
884        $request = new FauxRequest(
885            [
886                'format' => 'json',
887                'action' => 'wikilambda_function_call',
888                'wikilambda_function_call_zobject' => $call,
889                'uselang' => $renderLanguageCode
890            ],
891            /* wasPosted */
892            true
893        );
894
895        // As we're re-calling the Action API, tell it so it doesn't increase the rate limit
896        $request->setHeader( WikiLambdaApiBase::REST_REENTRY_HEADER, '1' );
897
898        // Propagate request origin header if present in the REST headers
899        $origin = $this->getRequest()->getHeaderLine( 'X-WikiLambda-Request-Origin' );
900        if ( $origin ) {
901            $request->setHeader( 'X-WikiLambda-Request-Origin', $origin );
902        }
903
904        $context = new DerivativeContext( RequestContext::getMain() );
905        $context->setRequest( $request );
906        $api->setContext( $context );
907
908        // 1. Handle Exceptions thrown by ApiFunctionCall and throw Z_ERROR_API_FAILURE
909
910        // Using FauxRequest means ApiMain is internal and hence $api->execute()
911        // doesn't do any error handling. We need to catch any Exceptions:
912        // * dieWithError: throws ApiUsageException with key="apierror-*"
913        // * dieWithZError: throws ApiUsageException with key="wikilambda-zerror"
914        // * other exceptions: throws MWException
915        try {
916            $api->execute();
917        } catch ( ApiUsageException $e ) {
918            $apiMessage = $e->getStatusValue()->getErrors()[0]['message'];
919            '@phan-var \MediaWiki\Api\ApiMessage $apiMessage';
920
921            // Log error message thrown by ApiFunctionCall; this is almost certainly a 429 /
922            // "You have too many function calls executing right now." error.
923            $errorMessage = __METHOD__ . ' executed ApiFunctionCall which threw an ApiUsageException: {error}';
924            $this->logger->info(
925                $errorMessage,
926                [ 'error' => $e->getMessage(), 'exception' => $e ]
927            );
928            $span->setSpanStatus( SpanInterface::SPAN_STATUS_ERROR )
929                ->setAttributes( [
930                    'error.message' => $errorMessage
931                ] );
932
933            if ( $apiMessage->getApiCode() === 'wikilambda-zerror' ) {
934                // Throw ZErrorException with Z_ERROR_API_FAILURE with propagated error:
935                $zerror = ZObjectFactory::create( $apiMessage->getApiData()[ 'zerror' ] );
936                '@phan-var \MediaWiki\Extension\WikiLambda\ZObjects\ZError $zerror';
937                $span->setSpanStatus( SpanInterface::SPAN_STATUS_ERROR )
938                    ->setAttributes( [
939                        'error.message' => $zerror
940                    ] );
941                throw new ZErrorException( ZErrorFactory::createApiFailureError( $zerror, $call ) );
942            }
943
944            $errorMessage = $e->getMessage();
945            $span->setSpanStatus( SpanInterface::SPAN_STATUS_ERROR )
946                ->setAttributes( [
947                    'error.message' => $errorMessage
948                ] );
949            // Throw ZErrorException with Z_ERROR_API_FAILURE error:
950            throw new ZErrorException( ZErrorFactory::createApiFailureError( $errorMessage, $call ) );
951        } catch ( Exception $e ) {
952            // Log unhandled exception thrown by ApiFunctionCall
953            $errorMessage = __METHOD__ . ' executed ApiFunctionCall which threw an unhandled exception: {error}';
954            $this->logger->warning(
955                $errorMessage,
956                [ 'error' => $e->getMessage(), 'exception' => $e ]
957            );
958            $span->setSpanStatus( SpanInterface::SPAN_STATUS_ERROR )
959                ->setAttributes( [
960                    'error.message' => $errorMessage
961                ] );
962            // Throw ZErrorException with Z_ERROR_API_FAILURE error:
963            throw new ZErrorException( ZErrorFactory::createApiFailureError( $e->getMessage(), $call ) );
964        } finally {
965            $span->end();
966        }
967
968        $outerResponse = $api->getResult()->getResultData( [], [ 'Strip' => 'all' ] );
969
970        // 2. Handle non valid Orchestrator responses and throw Z_ERROR_EVALUATION
971
972        // Now we know that the request has not failed before it even got to the orchestrator, get the response
973        // JSON string as a ZResponseEnvelope (falling back to an empty string in case it's unset).
974        $response = ZObjectFactory::create(
975            json_decode( $outerResponse['wikilambda_function_call']['data'] ?? '' )
976        );
977
978        if ( !( $response instanceof ZResponseEnvelope ) ) {
979            // The server's not given us a result! This is an unexpected system error
980            $responseType = $response->getZType();
981
982            // Log non-valid Orchestrator response
983            $errorMessage =
984                __METHOD__ . ' got a non-valid response from the server of type {responseType} with call: {call}';
985            $this->logger->error(
986                $errorMessage,
987                [
988                    'responseType' => $responseType,
989                    'call' => $call
990                ]
991            );
992
993            $span->setSpanStatus( SpanInterface::SPAN_STATUS_ERROR )
994                ->setAttributes( [
995                    'error.message' => $errorMessage
996                ] );
997            $span->end();
998            // Throw ZErrorException for evaluation error:
999            throw new ZErrorException( ZErrorFactory::createEvaluationError(
1000                "Server returned a non-result of type '$responseType'!",
1001                $call
1002            ) );
1003        }
1004
1005        // 3. Handle valid Orchestrator responses that might have errors: throw Z_ERROR_EVALUATION
1006
1007        if ( $response->hasErrors() ) {
1008            // If the server has responded with a Z22 with errors, throw evaluation error
1009            $zerror = $response->getErrors();
1010
1011            // Log a debug message, Orchestrator returned a valid response but function call failed
1012            $errorMessage = __METHOD__ . ' got an error-ful Z22 back from the server: {error}';
1013            $this->logger->debug(
1014                $errorMessage,
1015                [ 'error' => $zerror->getSerialized() ]
1016            );
1017            $span->setSpanStatus( SpanInterface::SPAN_STATUS_ERROR )
1018                ->setAttributes( [
1019                    'error.message' => $errorMessage
1020                ] );
1021            $span->end();
1022            if ( !( $zerror instanceof ZError ) ) {
1023                // Throw ZErrorException for evaluation error, wrap the non error in a Z500:
1024                throw new ZErrorException( ZErrorFactory::createEvaluationError( new ZQuote( $zerror ), $call ) );
1025            }
1026
1027            // Throw ZErrorException for evaluation error, propagate existing zerror:
1028            throw new ZErrorException( ZErrorFactory::createZErrorInstance(
1029                ZErrorTypeRegistry::Z_ERROR_EVALUATION,
1030                [
1031                    'functionCall' => $call,
1032                    'error' => $zerror
1033                ]
1034            ) );
1035        }
1036
1037        // Response envelope value (Z22K1)
1038        $responseValue = $response->getZValue();
1039        // If the response value is not a ZString or ZHtmlFragment, we can't handle it
1040        if (
1041            $responseValue->getZType() !== ZTypeRegistry::Z_STRING &&
1042            $responseValue->getZType() !== ZTypeRegistry::Z_HTML_FRAGMENT
1043        ) {
1044            // Log a debug message, Orchestrator returned a valid response but not a string
1045            $errorMessage =
1046                __METHOD__ . ' got a non-string output from the server of type {responseType} with call: {call}';
1047            $this->logger->debug(
1048                $errorMessage,
1049                [
1050                    'responseType' => $responseValue->getZType(),
1051                    'call' => $call
1052                ]
1053            );
1054            $span->setSpanStatus( SpanInterface::SPAN_STATUS_ERROR )
1055                ->setAttributes( [
1056                    'error.message' => $errorMessage
1057                ] );
1058            $span->end();
1059            // Throw ZErrorException for invalid evaluator result
1060            throw new ZErrorException( ZErrorFactory::createZErrorInstance(
1061                ZErrorTypeRegistry::Z_ERROR_INVALID_EVALUATION_RESULT, [ 'result' => $responseValue ]
1062            ) );
1063        }
1064
1065        $span->setSpanStatus( SpanInterface::SPAN_STATUS_OK );
1066        $span->end();
1067
1068        // SUCCESS! if type is Z6 (string) or Z89 (HTML fragment), return the value
1069        return (object)[
1070            'value' => trim( $responseValue->getZValue() ),
1071            'type' => $responseValue->getZType()
1072        ];
1073    }
1074
1075    /** @inheritDoc */
1076    public function applyCacheControl( ResponseInterface $response ) {
1077        if ( $response->getStatusCode() >= 200 && $response->getStatusCode() < 300 ) {
1078            $response->setHeader( 'Cache-Control', 'public,must-revalidate,s-maxage=' . 60 * 60 * 24 );
1079        }
1080    }
1081
1082    /** @inheritDoc */
1083    public function getResponseBodySchemaFileName( string $method ): ?string {
1084        return __DIR__ . '/Schema/CallResponse.json';
1085    }
1086
1087    /** @inheritDoc */
1088    public function needsWriteAccess(): bool {
1089        // This is a rough approximation, as we have no access to the User object in the REST API, but
1090        // we want the system to scale back access to this endpoint.
1091        return true;
1092    }
1093
1094    /** @inheritDoc */
1095    public function getParamSettings() {
1096        return [
1097            'zid' => [
1098                Handler::PARAM_SOURCE => 'path',
1099                ParamValidator::PARAM_TYPE => 'string',
1100                ParamValidator::PARAM_ISMULTI => false,
1101                ParamValidator::PARAM_REQUIRED => true,
1102                Handler::PARAM_DESCRIPTION => new MessageValue( 'wikifunctions-rest-module-v0-call-param-zid-desc' ),
1103            ],
1104            'arguments' => [
1105                Handler::PARAM_SOURCE => 'path',
1106                ParamValidator::PARAM_TYPE => 'string',
1107                ParamValidator::PARAM_ISMULTI => false,
1108                ParamValidator::PARAM_REQUIRED => false,
1109                Handler::PARAM_DESCRIPTION => new MessageValue(
1110                    'wikifunctions-rest-module-v0-call-param-arguments-desc'
1111                ),
1112            ],
1113            'parselang' => [
1114                Handler::PARAM_SOURCE => 'path',
1115                ParamValidator::PARAM_TYPE => 'string',
1116                ParamValidator::PARAM_DEFAULT => 'en',
1117                ParamValidator::PARAM_REQUIRED => false,
1118                Handler::PARAM_DESCRIPTION => new MessageValue(
1119                    'wikifunctions-rest-module-v0-call-param-parselang-desc'
1120                ),
1121            ],
1122            'renderlang' => [
1123                Handler::PARAM_SOURCE => 'path',
1124                ParamValidator::PARAM_TYPE => 'string',
1125                ParamValidator::PARAM_DEFAULT => 'en',
1126                ParamValidator::PARAM_REQUIRED => false,
1127                Handler::PARAM_DESCRIPTION => new MessageValue(
1128                    'wikifunctions-rest-module-v0-call-param-renderlang-desc'
1129                ),
1130            ],
1131        ];
1132    }
1133}