diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6294066..d525c62 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -28,16 +28,38 @@ jobs: with: path: server + - name: Resolve runtime branch + id: runtime-ref + run: | + branch="${GITHUB_HEAD_REF:-$GITHUB_REF_NAME}" + if git ls-remote --exit-code --heads https://github.com/php-skir/runtime.git "$branch" > /dev/null; then + echo "ref=$branch" >> "$GITHUB_OUTPUT" + else + echo "ref=main" >> "$GITHUB_OUTPUT" + fi + - name: Checkout runtime uses: actions/checkout@v7 with: repository: php-skir/runtime + ref: ${{ steps.runtime-ref.outputs.ref }} path: runtime + - name: Resolve client branch + id: client-ref + run: | + branch="${GITHUB_HEAD_REF:-$GITHUB_REF_NAME}" + if git ls-remote --exit-code --heads https://github.com/php-skir/client.git "$branch" > /dev/null; then + echo "ref=$branch" >> "$GITHUB_OUTPUT" + else + echo "ref=main" >> "$GITHUB_OUTPUT" + fi + - name: Checkout client uses: actions/checkout@v7 with: repository: php-skir/client + ref: ${{ steps.client-ref.outputs.ref }} path: client - name: Setup PHP @@ -79,16 +101,38 @@ jobs: with: path: server + - name: Resolve runtime branch + id: runtime-ref + run: | + branch="${GITHUB_HEAD_REF:-$GITHUB_REF_NAME}" + if git ls-remote --exit-code --heads https://github.com/php-skir/runtime.git "$branch" > /dev/null; then + echo "ref=$branch" >> "$GITHUB_OUTPUT" + else + echo "ref=main" >> "$GITHUB_OUTPUT" + fi + - name: Checkout runtime uses: actions/checkout@v7 with: repository: php-skir/runtime + ref: ${{ steps.runtime-ref.outputs.ref }} path: runtime + - name: Resolve client branch + id: client-ref + run: | + branch="${GITHUB_HEAD_REF:-$GITHUB_REF_NAME}" + if git ls-remote --exit-code --heads https://github.com/php-skir/client.git "$branch" > /dev/null; then + echo "ref=$branch" >> "$GITHUB_OUTPUT" + else + echo "ref=main" >> "$GITHUB_OUTPUT" + fi + - name: Checkout client uses: actions/checkout@v7 with: repository: php-skir/client + ref: ${{ steps.client-ref.outputs.ref }} path: client - name: Setup PHP @@ -110,7 +154,7 @@ jobs: resources/boost/skills/skir-server-development/references/procedures-and-routing.md \ resources/boost/skills/skir-server-development/references/scaffolding.md \ resources/boost/skills/skir-server-development/references/structures-and-validation.md \ - resources/boost/skills/skir-server-development/references/studio-codecs-and-testing.md + resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md do grep -Fxq "$asset" build/archive-files.txt done @@ -123,8 +167,8 @@ jobs: run: | composer config minimum-stability dev composer config prefer-stable true - composer config repositories.runtime '{"type":"path","url":"../runtime","options":{"symlink":false}}' --json - composer config repositories.client '{"type":"path","url":"../client","options":{"symlink":false}}' --json + composer config repositories.runtime '{"type":"path","url":"../runtime","options":{"symlink":false,"versions":{"php-skir/runtime":"0.2.x-dev"}}}' --json + composer config repositories.client '{"type":"path","url":"../client","options":{"symlink":false,"versions":{"php-skir/client":"0.2.x-dev"}}}' --json composer config repositories.server '{"type":"path","url":"../server","options":{"symlink":false}}' --json if [ "${{ matrix.scenario }}" = 'both' ] then @@ -154,7 +198,7 @@ jobs: test -f .agents/skills/skir-server-development/references/procedures-and-routing.md test -f .agents/skills/skir-server-development/references/scaffolding.md test -f .agents/skills/skir-server-development/references/structures-and-validation.md - test -f .agents/skills/skir-server-development/references/studio-codecs-and-testing.md + test -f .agents/skills/skir-server-development/references/studio-protocol-and-testing.md if [ "${{ matrix.scenario }}" = 'both' ] then grep -Fq 'php-skir/client' AGENTS.md @@ -183,16 +227,38 @@ jobs: with: path: server + - name: Resolve runtime branch + id: runtime-ref + run: | + branch="${GITHUB_HEAD_REF:-$GITHUB_REF_NAME}" + if git ls-remote --exit-code --heads https://github.com/php-skir/runtime.git "$branch" > /dev/null; then + echo "ref=$branch" >> "$GITHUB_OUTPUT" + else + echo "ref=main" >> "$GITHUB_OUTPUT" + fi + - name: Checkout runtime uses: actions/checkout@v7 with: repository: php-skir/runtime + ref: ${{ steps.runtime-ref.outputs.ref }} path: runtime + - name: Resolve client branch + id: client-ref + run: | + branch="${GITHUB_HEAD_REF:-$GITHUB_REF_NAME}" + if git ls-remote --exit-code --heads https://github.com/php-skir/client.git "$branch" > /dev/null; then + echo "ref=$branch" >> "$GITHUB_OUTPUT" + else + echo "ref=main" >> "$GITHUB_OUTPUT" + fi + - name: Checkout client uses: actions/checkout@v7 with: repository: php-skir/client + ref: ${{ steps.client-ref.outputs.ref }} path: client - name: Setup PHP diff --git a/README.md b/README.md index bf9a05a..5df9742 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ SkirRPC offers many of the same benefits as gRPC—shared method definitions, ge - Route procedures to attributed or invokable Laravel controllers with native dependency injection, middleware, authorization, and Form Requests. See [Routing](docs/routing.md). - Keep generated providers and manual handlers available for non-controller layouts. See [Routing](docs/routing.md#generated-procedure-providers). - Inspect an endpoint's procedures through its opt-in Studio. See [Studio](docs/routing.md#studio). -- Configure dense JSON, standard JSON, or base64 dense JSON package-wide or per endpoint. See [Codecs](docs/codecs.md). +- Speak the standard SkirRPC protocol, so clients generated for any Skir language can call your endpoints. See [Wire protocol](docs/protocol.md). ## Quick start @@ -34,13 +34,13 @@ composer require php-skir/server std-out/simple-data-objects npm install --save-dev skir skir-simple-data-objects-generator ``` -The package defaults match the paths used below. To customize manifest locations, generator execution, controller layout, Form Request generation, Studio, or codecs, publish `config/skir-server.php`: +The package defaults match the paths used below. To customize manifest locations, generator execution, controller layout, Form Request generation, or Studio, publish `config/skir-server.php`: ```bash php artisan vendor:publish --tag=skir-server-config ``` -See [Scaffolding configuration](docs/scaffolding.md#configure-manifests-and-destinations) for the current keys and defaults. Calling `studio()` or `studio(false)` on a route overrides the Studio default, while an explicit codec passed to `Route::skirRpc()` overrides the configured codec. +See [Scaffolding configuration](docs/scaffolding.md#configure-manifests-and-destinations) for the current keys and defaults. Calling `studio()` or `studio(false)` on a route overrides the Studio default. Define a Skir method: diff --git a/composer.json b/composer.json index ec8bc7b..51b623b 100644 --- a/composer.json +++ b/composer.json @@ -25,13 +25,13 @@ "php": "^8.4", "laravel/framework": "^13.0", "nikic/php-parser": "^5.8", - "php-skir/runtime": "^0.1@dev|^0.2@dev", + "php-skir/runtime": "^0.2@dev", "symfony/process": "^7.4|^8.0" }, "require-dev": { "laravel/pint": "^1.29", "orchestra/testbench": "^11.0", - "php-skir/client": "^0.1@dev|^0.2@dev", + "php-skir/client": "^0.2@dev", "phpunit/phpunit": "^12.5" }, "autoload": { @@ -49,14 +49,20 @@ "type": "path", "url": "../runtime", "options": { - "symlink": false + "symlink": false, + "versions": { + "php-skir/runtime": "0.2.x-dev" + } } }, { "type": "path", "url": "../client", "options": { - "symlink": false + "symlink": false, + "versions": { + "php-skir/client": "0.2.x-dev" + } } } ], diff --git a/config/skir-server.php b/config/skir-server.php index f92d712..4831f50 100644 --- a/config/skir-server.php +++ b/config/skir-server.php @@ -2,12 +2,9 @@ declare(strict_types=1); -use Skir\Server\Codecs\DenseJsonCodec; - return [ 'studio_enabled' => env('SKIR_SERVER_STUDIO_ENABLED', false), 'studio_query_key' => env('SKIR_SERVER_STUDIO_QUERY_KEY', 'studio'), - 'codec' => DenseJsonCodec::class, 'manifests' => [ base_path('app/Skir/skirout/skir-server-manifest.json'), diff --git a/docs/codecs.md b/docs/codecs.md deleted file mode 100644 index 314b0bf..0000000 --- a/docs/codecs.md +++ /dev/null @@ -1,73 +0,0 @@ -# Codecs - -A codec controls how SkirRPC endpoints decode request values and encode response values. Configure a package-wide default or select a codec per route with the third argument to `Route::skirRpc()`. - -## Default codec - -The shipped configuration uses dense JSON. To use standard JSON as the package-wide default, publish the configuration and set `codec` to `StandardJsonCodec::class`: - -```php - env('SKIR_SERVER_STUDIO_ENABLED', false), - 'studio_query_key' => env('SKIR_SERVER_STUDIO_QUERY_KEY', 'studio'), - 'codec' => StandardJsonCodec::class, -]; -``` - -The codec class is resolved through Laravel's container and must implement `Skir\Server\Codecs\SkirCodec`. The built-in codec classes are `DenseJsonCodec`, `StandardJsonCodec`, and `Base64DenseJsonCodec`, all in the `Skir\Server\Codecs` namespace. An explicit codec passed as the third argument to `Route::skirRpc()` overrides the configured default for that route. - -## Dense JSON - -Dense JSON uses the generated method descriptor to decode and encode Skir's compact JSON representation. With the shipped configuration, omitting the third argument uses Dense JSON: - -```php -use App\Http\Skir\UserController; -use Illuminate\Support\Facades\Route; -use Skir\Server\Facades\Skir; - -Route::skirRpc('/api/skir', [ - Skir::controller(UserController::class), -]); -``` - -To force Dense JSON for this route regardless of the configured default, pass it explicitly: - -```php -use Skir\Server\Codecs\SkirCodecs; - -Route::skirRpc('/api/skir', [ - Skir::controller(UserController::class), -], SkirCodecs::denseJson()); -``` - -## Standard JSON - -Standard JSON passes the decoded JSON request value and response value through without dense conversion. Use it when the HTTP boundary should remain human-readable and the registered procedures handle that shape: - -```php -use Skir\Server\Codecs\SkirCodecs; - -Route::skirRpc('/api/skir-readable', [ - Skir::controller(UserController::class), -], SkirCodecs::standardJson()); -``` - -## Base64 dense JSON - -Base64 dense JSON accepts a base64-encoded dense JSON string in the envelope's `request` field and returns the response in the same form: - -```php -use Skir\Server\Codecs\SkirCodecs; - -Route::skirRpc('/api/skir-base64', [ - Skir::controller(UserController::class), -], SkirCodecs::base64DenseJson()); -``` - -The outer SkirRPC envelope remains JSON; only the request and response values are represented as base64-encoded dense JSON. diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..92d8381 --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,50 @@ +# Wire protocol + +Endpoints registered with `Route::skirRpc()` speak the standard SkirRPC protocol, so any Skir client can call them: the `php-skir/client` package, or clients generated for TypeScript, Python, Go and the other languages Skir supports. + +## Requests + +A call is a `POST` whose body is either a JSON object or a colon-separated string. A `GET` carries the same string in its query string. + +### JSON object + +```bash +curl -X POST -H 'Content-Type: application/json' \ + -d '{"method": "Square", "request": 5.0}' \ + https://example.test/api/skir +``` + +`method` is the method name or its number. `request` may be dense or readable JSON. The response is **readable** JSON, which makes this form handy for debugging with curl. + +### Colon-separated + +```text +Square:1001::5 +Square:1001:readable:5 +``` + +This is the form upstream Skir clients send: `name:number:format:request`. When the number is present it identifies the method and the name is informational; when it is empty, the method is looked up by name. The response is **dense** JSON unless the format is `readable`. + +A `GET` request uses the same string as its query string, for example `/api/skir?Square:1001::5`. + +## Responses + +A successful call returns `200` with `Content-Type: application/json` and the encoded response value: + +```json +25 +``` + +Failures return a JSON error body with a Skir error code: + +| Status | Code | When | +| --- | --- | --- | +| 422 | `skir_invalid_request` | The body is not a valid SkirRPC request, the method name is ambiguous, or the request value does not match the method's request type. | +| 404 | `skir_method_not_found` | No method with that name or number is registered on the endpoint. | +| 422 | `skir_validation_failed` | A Form Request rejected the decoded input. | +| 403 | `skir_authorization_failed` | A Form Request's `authorize()` returned `false`. | +| 500 | `skir_invalid_response` | The method returned a value that cannot be serialized as its response type. | + +## Studio + +A `GET` without a query string, or with the configured Studio query key (`?studio` by default), renders Studio when it is enabled. See [Studio](routing.md#studio). diff --git a/docs/routing.md b/docs/routing.md index e47187b..7342294 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -286,17 +286,7 @@ app(SkirServer::class)->addMethod( ); ``` -The endpoint accepts SkirRPC envelopes. With the default dense JSON codec: - -```json -{"method":"Square","request":5.0} -``` - -The response is the raw encoded Skir value: - -```json -25 -``` +The endpoint accepts standard SkirRPC requests, for example the body `Square:1001::5`, and answers with the encoded response value, `25`. See [Wire protocol](protocol.md) for every request form. GET requests are also supported. Pass the method and a JSON-encoded request value as query parameters: diff --git a/resources/boost/guidelines/core.blade.php b/resources/boost/guidelines/core.blade.php index 23d58fc..74849fd 100644 --- a/resources/boost/guidelines/core.blade.php +++ b/resources/boost/guidelines/core.blade.php @@ -9,7 +9,7 @@ `authorize()` and `rules()`; scaffolded Form Requests deny access and validate nothing by default. Method middleware does not protect Studio. Put middleware on the outer Skir route when Studio or the -complete endpoint must be private. Keep the server codec aligned with clients. +complete endpoint must be private. -Use the `skir-server-development` skill for procedure routing, scaffolding, Studio, codec, or testing +Use the `skir-server-development` skill for procedure routing, scaffolding, Studio, protocol, or testing work. diff --git a/resources/boost/skills/skir-server-development/SKILL.md b/resources/boost/skills/skir-server-development/SKILL.md index 7059784..a28fbf5 100644 --- a/resources/boost/skills/skir-server-development/SKILL.md +++ b/resources/boost/skills/skir-server-development/SKILL.md @@ -17,8 +17,8 @@ boundaries. - Choosing or implementing generated standard PHP objects, Spatie Laravel Data objects, or Simple Data Objects—including input hydration and validation: read [structures and validation](references/structures-and-validation.md). -- Studio exposure, codecs, failures, or test coverage: read - [Studio, codecs, and testing](references/studio-codecs-and-testing.md). +- Studio exposure, the wire protocol, failures, or test coverage: read + [Studio, protocol, and testing](references/studio-protocol-and-testing.md). - Tasks crossing these areas: read every relevant reference before changing code. ## Workflow @@ -30,4 +30,4 @@ boundaries. 3. Implement explicit validation and authorization before registration. Decide separately whether method middleware or outer-route protection owns the boundary. 4. Test success plus applicable validation, authorization, malformed input, duplicate registration, - Studio, middleware, and codec failures. + Studio, middleware, and malformed-request failures. diff --git a/resources/boost/skills/skir-server-development/references/studio-codecs-and-testing.md b/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md similarity index 74% rename from resources/boost/skills/skir-server-development/references/studio-codecs-and-testing.md rename to resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md index 966d9dd..aa2dd7f 100644 --- a/resources/boost/skills/skir-server-development/references/studio-codecs-and-testing.md +++ b/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md @@ -1,4 +1,4 @@ -# Studio, Codecs, and Testing +# Studio, Protocol, and Testing ## Studio exposure @@ -16,14 +16,13 @@ Method middleware does not protect Studio. Put authentication and authorization when Studio or every RPC call must share that boundary. Test the Studio GET independently from a method invocation. -## Codecs +## Protocol -The configured `codec` must implement `SkirCodec`. Laravel resolves the class through the container; -an explicit third argument to `Route::skirRpc()` overrides the package default for that route. - -Built-in implementations are `DenseJsonCodec`, `StandardJsonCodec`, and `Base64DenseJsonCodec`. -The matching factories are available through `SkirCodecs`. Clients and servers must use -the same codec. +Endpoints speak the standard SkirRPC protocol; there is nothing to configure. A request body is +either a JSON object `{"method": ..., "request": ...}` (answered in readable JSON) or +`name:number:format:request` (answered in dense JSON unless the format is `readable`). `GET` carries +the colon-separated form in the query string. Methods are looked up by number, or by name when the +number is empty. ## Required behavior coverage @@ -37,14 +36,13 @@ paths applicable to the change: - protected and intentionally public Studio behavior; - malformed JSON, missing method, unknown method, and invalid payload envelopes; - duplicate method registration from controllers, providers, or manual handlers; -- configured and route-specific codec success plus invalid codec configuration; +- both request forms (JSON object and colon-separated), lookup by name and by number; - controller middleware ordering, short-circuit responses, and the terminable middleware rejection; - regressions for explicit `null`, boundary request shapes, and any corrected failure contract. Assert status, Skir error code/details, response content type/body, authorization boundary, and side -effects. For Studio, assert both rendered procedure metadata and protection on the outer route. For -codec changes, use genuine encoded request/response bodies rather than treating codecs as -interchangeable. +effects. For Studio, assert both rendered procedure metadata and protection on the outer route. Use +genuine encoded request/response bodies. When a test fails, first identify whether the mismatch belongs to route protection, method registration, Laravel resolution, payload decoding, procedure execution, or response encoding. Fix diff --git a/src/Codecs/Base64DenseJsonCodec.php b/src/Codecs/Base64DenseJsonCodec.php deleted file mode 100644 index ee97b52..0000000 --- a/src/Codecs/Base64DenseJsonCodec.php +++ /dev/null @@ -1,39 +0,0 @@ -getMessage(), $exception); - } - - return DenseJson::decode($descriptor->requestType, $denseRequest); - } - - public function encodeResponse(MethodDescriptor $descriptor, mixed $response): mixed - { - return base64_encode(DenseJson::toJson($descriptor->responseType, $response)); - } -} diff --git a/src/Codecs/DenseJsonCodec.php b/src/Codecs/DenseJsonCodec.php deleted file mode 100644 index 5267768..0000000 --- a/src/Codecs/DenseJsonCodec.php +++ /dev/null @@ -1,21 +0,0 @@ -requestType, $request); - } - - public function encodeResponse(MethodDescriptor $descriptor, mixed $response): mixed - { - return DenseJson::encode($descriptor->responseType, $response); - } -} diff --git a/src/Codecs/SkirCodec.php b/src/Codecs/SkirCodec.php deleted file mode 100644 index 7145566..0000000 --- a/src/Codecs/SkirCodec.php +++ /dev/null @@ -1,14 +0,0 @@ -header('content-type', 'text/html; charset=UTF-8'); } - $codec = $server->codec(); - $payload = $this->payloadFromRequest($request); - $method = $this->methodFromPayload($payload); - $procedure = $server->procedure($method); - $requestPayload = array_key_exists('request', $payload) ? $payload['request'] : 0; - $decodedRequest = $codec->decodeRequest($procedure->descriptor, $requestPayload); + $rpcRequest = RpcRequest::parse($this->rpcBody($request)); + $procedure = $server->procedure($rpcRequest->method); + $decodedRequest = DenseJson::decode($procedure->descriptor->requestType, $rpcRequest->payload); return $this->requestScope->run( $request, $decodedRequest, - function (Request $methodRequest, mixed $decodedPayload) use ($codec, $procedure): Response { + function (Request $methodRequest, mixed $decodedPayload) use ($rpcRequest, $procedure): Response { $context = new RequestContext($methodRequest, $procedure->descriptor); $prepared = $procedure->prepare($decodedPayload, $context); @@ -65,7 +63,7 @@ function (Request $methodRequest, mixed $decodedPayload) use ($codec, $procedure ->send($methodRequest) ->through($this->procedureMiddleware($prepared)) ->then(fn (): Response => $this->invokeAndEncodeResponse( - $codec, + $rpcRequest, $procedure, $prepared, )); @@ -81,25 +79,22 @@ function (Request $methodRequest, mixed $decodedPayload) use ($codec, $procedure } private function invokeAndEncodeResponse( - SkirCodec $codec, + RpcRequest $rpcRequest, RegisteredProcedure $procedure, PreparedProcedure $prepared, ): Response { + $result = $prepared->invoke(); + $responseType = $procedure->descriptor->responseType; + try { - return $this->encodeResponse($codec, $procedure, $prepared->invoke()); + $json = $rpcRequest->readable + ? ReadableJson::toJson($responseType, $result) + : DenseJson::toJson($responseType, $result); } catch (SkirRuntimeException $exception) { - throw SkirServerException::invalidRequest($exception->getMessage()); + throw SkirServerException::invalidResponse($procedure->descriptor->name, $exception->getMessage()); } - } - private function encodeResponse( - SkirCodec $codec, - RegisteredProcedure $procedure, - mixed $result, - ): Response { - $encodedResponse = $codec->encodeResponse($procedure->descriptor, $result); - - return response()->json($encodedResponse, Response::HTTP_OK); + return response($json, Response::HTTP_OK, ['Content-Type' => 'application/json']); } /** @return list */ @@ -133,7 +128,7 @@ private function isStudioRequest(Request $request): bool $queryKey = (string) ($request->route()?->defaults['skirStudioQueryKey'] ?? 'studio'); - return $request->query->has($queryKey); + return $this->rpcBody($request) === '' || $request->query->has($queryKey); } private function studioEnabled(Request $request): bool @@ -141,54 +136,13 @@ private function studioEnabled(Request $request): bool return ($request->route()?->defaults['skirStudioEnabled'] ?? false) === true; } - /** - * @return array{ - * method?: mixed, - * request?: mixed - * } - */ - private function payloadFromRequest(Request $request): array + private function rpcBody(Request $request): string { if ($this->usesQueryString($request)) { - return $this->payloadFromQueryString($request); - } - - try { - $decodedPayload = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR); - } catch (JsonException $exception) { - throw SkirServerException::invalidRequest("Invalid JSON: {$exception->getMessage()}"); - } - - if (! is_object($decodedPayload)) { - throw SkirServerException::invalidRequest('Skir requests must be JSON objects.'); - } - - return $request->json()->all(); - } - - /** - * @return array{ - * method?: mixed, - * request?: mixed - * } - */ - private function payloadFromQueryString(Request $request): array - { - $payload = [ - 'method' => $request->query('method'), - ]; - - if (! $request->query->has('request')) { - return $payload; + return rawurldecode((string) $request->server->get('QUERY_STRING', '')); } - try { - $payload['request'] = json_decode((string) $request->query('request'), true, flags: JSON_THROW_ON_ERROR); - } catch (JsonException $exception) { - throw SkirServerException::invalidRequest("Invalid dense JSON: {$exception->getMessage()}"); - } - - return $payload; + return $request->getContent(); } private function usesQueryString(Request $request): bool @@ -199,23 +153,4 @@ private function usesQueryString(Request $request): bool return $request->isMethod('HEAD'); } - - /** - * @param array{ - * method?: mixed, - * request?: mixed - * } $payload - */ - private function methodFromPayload(array $payload): string - { - if (! array_key_exists('method', $payload)) { - throw SkirServerException::invalidRequest('Skir requests must include a string [method] value.'); - } - - if (! is_string($payload['method'])) { - throw SkirServerException::invalidRequest('Skir requests must include a string [method] value.'); - } - - return $payload['method']; - } } diff --git a/src/Http/RpcRequest.php b/src/Http/RpcRequest.php new file mode 100644 index 0000000..9257b85 --- /dev/null +++ b/src/Http/RpcRequest.php @@ -0,0 +1,84 @@ +getMessage()}"); + } + } +} diff --git a/src/ProcedureRegistry.php b/src/ProcedureRegistry.php index ecb4fdc..f0e4a22 100644 --- a/src/ProcedureRegistry.php +++ b/src/ProcedureRegistry.php @@ -9,25 +9,38 @@ final class ProcedureRegistry { - /** @var array */ + /** @var array */ private array $procedures = []; public function add(MethodDescriptor $descriptor, callable $handler): void { - if (array_key_exists($descriptor->name, $this->procedures)) { - throw SkirServerException::duplicateMethod($descriptor->name); + if (array_key_exists($descriptor->number, $this->procedures)) { + throw SkirServerException::duplicateMethod($descriptor->name, $descriptor->number); } - $this->procedures[$descriptor->name] = new RegisteredProcedure($descriptor, $handler); + $this->procedures[$descriptor->number] = new RegisteredProcedure($descriptor, $handler); } - public function get(string $method): RegisteredProcedure + public function get(string|int $method): RegisteredProcedure { - return $this->procedures[$method] ?? throw SkirServerException::methodNotFound($method); + if (is_int($method)) { + return $this->procedures[$method] ?? throw SkirServerException::methodNotFound((string) $method); + } + + $matches = array_values(array_filter( + $this->procedures, + fn (RegisteredProcedure $procedure): bool => $procedure->descriptor->name === $method, + )); + + if (count($matches) > 1) { + throw SkirServerException::ambiguousMethod($method); + } + + return $matches[0] ?? throw SkirServerException::methodNotFound($method); } /** - * @return array + * @return array */ public function all(): array { diff --git a/src/SkirServer.php b/src/SkirServer.php index d8fbce1..e781d80 100644 --- a/src/SkirServer.php +++ b/src/SkirServer.php @@ -5,14 +5,11 @@ namespace Skir\Server; use Skir\Runtime\MethodDescriptor; -use Skir\Server\Codecs\DenseJsonCodec; -use Skir\Server\Codecs\SkirCodec; final readonly class SkirServer { public function __construct( private ProcedureRegistry $procedures, - private SkirCodec $codec = new DenseJsonCodec, ) {} public function addMethod(MethodDescriptor $descriptor, callable $handler): void @@ -20,18 +17,13 @@ public function addMethod(MethodDescriptor $descriptor, callable $handler): void $this->procedures->add($descriptor, $handler); } - public function procedure(string $method): RegisteredProcedure + public function procedure(string|int $method): RegisteredProcedure { return $this->procedures->get($method); } - public function codec(): SkirCodec - { - return $this->codec; - } - /** - * @return array + * @return array */ public function procedures(): array { diff --git a/src/SkirServerServiceProvider.php b/src/SkirServerServiceProvider.php index dfc3a37..c75d1c0 100644 --- a/src/SkirServerServiceProvider.php +++ b/src/SkirServerServiceProvider.php @@ -9,8 +9,6 @@ use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider; use ReflectionClass; -use Skir\Server\Codecs\DenseJsonCodec; -use Skir\Server\Codecs\SkirCodec; use Skir\Server\Commands\GeneratorRunner; use Skir\Server\Commands\MakeSkirCommand; use Skir\Server\Commands\MakeSkirRequestCommand; @@ -41,29 +39,6 @@ public function register(): void )); $this->app->singleton(ProcedureRegistry::class); - $this->app->singleton(SkirCodec::class, function (): SkirCodec { - $codec = config('skir-server.codec', DenseJsonCodec::class); - - if (! is_string($codec)) { - throw SkirServerException::invalidConfiguredCodec($codec); - } - - if (! is_a($codec, SkirCodec::class, true)) { - throw SkirServerException::invalidConfiguredCodec($codec); - } - - if ($codec === SkirCodec::class) { - throw SkirServerException::invalidConfiguredCodec($codec); - } - - if (! $this->app->bound($codec)) { - if (! (new ReflectionClass($codec))->isInstantiable()) { - throw SkirServerException::invalidConfiguredCodec($codec); - } - } - - return $this->app->make($codec); - }); $this->app->singleton(SkirServer::class); $this->app->singleton(ManifestRepository::class); $this->app->bind(GeneratorRunner::class, SymfonyGeneratorRunner::class); @@ -114,7 +89,7 @@ public function boot(): void } }; - $router->macro('skirRpc', function (string $uri, array $providers = [], ?SkirCodec $codec = null) use ($resolveProvider) { + $router->macro('skirRpc', function (string $uri, array $providers = []) use ($resolveProvider) { /** @var Router $this */ $route = $this ->match(['GET', 'POST'], $uri, SkirRpcController::class) @@ -122,12 +97,10 @@ public function boot(): void ->defaults('skirStudioQueryKey', (string) config('skir-server.studio_query_key', 'studio')); if ($providers === []) { - if ($codec === null) { - return $route; - } + return $route; } - $server = new SkirServer(new ProcedureRegistry, $codec ?? app(SkirCodec::class)); + $server = new SkirServer(new ProcedureRegistry); foreach ($providers as $provider) { $resolvedProvider = $resolveProvider($provider); diff --git a/tests/Feature/BoostAssetsTest.php b/tests/Feature/BoostAssetsTest.php index 2c02c3b..e36f13a 100644 --- a/tests/Feature/BoostAssetsTest.php +++ b/tests/Feature/BoostAssetsTest.php @@ -21,7 +21,7 @@ final class BoostAssetsTest extends TestCase 'resources/boost/skills/skir-server-development/references/procedures-and-routing.md', 'resources/boost/skills/skir-server-development/references/scaffolding.md', 'resources/boost/skills/skir-server-development/references/structures-and-validation.md', - 'resources/boost/skills/skir-server-development/references/studio-codecs-and-testing.md', + 'resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md', ]; #[Test] @@ -96,7 +96,7 @@ public function it_keeps_server_guidance_anchored_to_the_released_package(): voi ); $this->assertSourceAnchorsAreDocumented( 'config/skir-server.php', - ['studio_enabled', 'studio_query_key', 'codec'], + ['studio_enabled', 'studio_query_key'], $guidance, ); @@ -127,9 +127,8 @@ public function it_keeps_server_guidance_anchored_to_the_released_package(): voi 'rules()', 'studio()', 'studio(false)', - 'DenseJsonCodec', - 'StandardJsonCodec', - 'Base64DenseJsonCodec', + 'name:number:format:request', + 'readable JSON', 'skir_validation_failed', 'skir_authorization_failed', 'malformed', diff --git a/tests/Feature/ClientServerCodecContractTest.php b/tests/Feature/ClientServerCodecContractTest.php deleted file mode 100644 index 521acde..0000000 --- a/tests/Feature/ClientServerCodecContractTest.php +++ /dev/null @@ -1,234 +0,0 @@ -profileMethod(); - $clientCodec = $this->clientCodec($codecName); - $serverCodec = $this->serverCodec($codecName); - [$clientRequest, $expectedServerRequest] = $this->requestValues($codecName); - [$serverResponse, $expectedClientResponse] = $this->responseValues($codecName); - $receivedRequest = null; - $route = $this->app['router']->skirRpc("/contract/{$codecName}", [], $serverCodec); - $server = $route->defaults['skirServer']; - - $this->assertInstanceOf(SkirServer::class, $server); - - $server->addMethod( - $descriptor, - function (mixed $request) use (&$receivedRequest, $serverResponse): mixed { - $receivedRequest = $request; - - return $serverResponse; - }, - ); - - $response = $this->postClientRequest( - "/contract/{$codecName}", - $descriptor, - $clientCodec, - $clientRequest, - ); - - $response->assertOk()->assertHeader('content-type', $this->contentType($clientCodec)); - $this->assertSame( - $this->canonicalValue($expectedServerRequest), - $this->canonicalValue($receivedRequest), - ); - $this->assertSame( - $this->canonicalValue($expectedClientResponse), - $this->canonicalValue($clientCodec->decodeResponse($descriptor, $response->getContent())), - ); - } - - /** - * @return iterable - */ - public static function codecs(): iterable - { - yield 'dense JSON' => ['dense-json']; - yield 'standard JSON' => ['standard-json']; - yield 'base64 dense JSON' => ['base64-dense-json']; - } - - private function clientCodec(string $codecName): SkirClientCodec - { - return match ($codecName) { - 'dense-json' => SkirClientCodecs::denseJson(), - 'standard-json' => SkirClientCodecs::standardJson(), - 'base64-dense-json' => SkirClientCodecs::base64DenseJson(), - }; - } - - private function serverCodec(string $codecName): SkirCodec - { - return match ($codecName) { - 'dense-json' => SkirCodecs::denseJson(), - 'standard-json' => SkirCodecs::standardJson(), - 'base64-dense-json' => SkirCodecs::base64DenseJson(), - }; - } - - private function profileMethod(): MethodDescriptor - { - $statusType = Type::enum([ - Variant::constant('active', 1), - Variant::wrapper('suspended_reason', 2, Type::string()), - ]); - $profileType = Type::struct([ - Field::value('id', 0, Type::int32()), - Field::value('tags', 1, Type::array(Type::string())), - Field::value('status', 2, $statusType), - Field::value('avatar', 3, Type::bytes()), - Field::value('note', 4, Type::optional(Type::string())), - ]); - - return new MethodDescriptor('UpdateProfile', 7001, $profileType, $profileType); - } - - /** - * @return array{array, array} - */ - private function requestValues(string $codecName): array - { - if ($codecName === 'standard-json') { - $request = [ - 'id' => 42, - 'tags' => ['admin', 'beta'], - 'status' => ['suspended_reason' => 'manual review'], - 'avatar' => 'AQID', - 'note' => null, - ]; - - return [$request, $request]; - } - - $request = [ - 'id' => 42, - 'tags' => ['admin', 'beta'], - 'status' => EnumValue::wrapper('suspended_reason', 'manual review'), - 'avatar' => "\x01\x02\x03", - 'note' => null, - ]; - - return [$request, $request]; - } - - /** - * @return array{array, array} - */ - private function responseValues(string $codecName): array - { - if ($codecName === 'standard-json') { - $response = [ - 'id' => 42, - 'tags' => ['verified'], - 'status' => 'active', - 'avatar' => 'BAUG', - 'note' => 'updated', - ]; - - return [$response, $response]; - } - - $response = [ - 'id' => 42, - 'tags' => ['verified'], - 'status' => EnumValue::constant('active'), - 'avatar' => "\x04\x05\x06", - 'note' => 'updated', - ]; - - return [$response, $response]; - } - - private function postClientRequest( - string $uri, - MethodDescriptor $descriptor, - SkirClientCodec $codec, - mixed $request, - ): TestResponse { - if ($codec instanceof SkirClientHttpCodec) { - return $this->call( - 'POST', - $uri, - server: ['CONTENT_TYPE' => $codec->contentType()], - content: $codec->encodeRequestBody($descriptor, $request), - ); - } - - return $this->call( - 'POST', - $uri, - server: ['CONTENT_TYPE' => 'application/json'], - content: $this->jsonEncode([ - 'method' => $descriptor->name, - 'request' => $codec->encodeRequest($descriptor, $request), - ]), - ); - } - - private function contentType(SkirClientCodec $codec): string - { - return $codec instanceof SkirClientHttpCodec ? $codec->contentType() : 'application/json'; - } - - private function canonicalValue(mixed $value): mixed - { - if ($value instanceof EnumValue) { - return [ - '__skir_enum' => [ - 'name' => $value->name, - 'value' => $this->canonicalValue($value->value), - 'wrapper' => $value->wrapper, - ], - ]; - } - - if (! is_array($value)) { - return $value; - } - - $canonicalValue = []; - - foreach ($value as $key => $item) { - $canonicalValue[$key] = $this->canonicalValue($item); - } - - return $canonicalValue; - } - - /** - * @param array $value - * - * @throws JsonException - */ - private function jsonEncode(array $value): string - { - return json_encode($value, JSON_THROW_ON_ERROR); - } -} diff --git a/tests/Feature/ClientServerContractTest.php b/tests/Feature/ClientServerContractTest.php new file mode 100644 index 0000000..4852883 --- /dev/null +++ b/tests/Feature/ClientServerContractTest.php @@ -0,0 +1,76 @@ +profileMethod(); + $request = [ + 'id' => 42, + 'tags' => ['admin', 'beta'], + 'status' => EnumValue::wrapper('suspended_reason', 'manual review'), + 'avatar' => "\x01\x02\x03", + 'note' => null, + ]; + $response = [ + 'id' => 42, + 'tags' => ['verified'], + 'status' => EnumValue::constant('active'), + 'avatar' => "\x04\x05\x06", + 'note' => 'updated', + ]; + $receivedRequest = null; + + app(SkirServer::class)->addMethod( + $descriptor, + function (array $decodedRequest) use (&$receivedRequest, $response): array { + $receivedRequest = $decodedRequest; + + return $response; + }, + ); + + $clientRequest = new SkirRpcRequest($descriptor, $request, '/skir'); + + $httpResponse = $this + ->call('POST', '/skir', content: (string) $clientRequest->body()) + ->assertOk() + ->assertHeader('content-type', 'application/json'); + + $this->assertEquals($request, $receivedRequest); + $this->assertEquals($response, DenseJson::fromJson($descriptor->responseType, $httpResponse->getContent())); + } + + private function profileMethod(): MethodDescriptor + { + $statusType = Type::enum([ + Variant::constant('active', 1), + Variant::wrapper('suspended_reason', 2, Type::string()), + ]); + $profileType = Type::struct([ + Field::value('id', 0, Type::int32()), + Field::value('tags', 1, Type::array(Type::string())), + Field::value('status', 2, $statusType), + Field::value('avatar', 3, Type::bytes()), + Field::value('note', 4, Type::optional(Type::string())), + ]); + + return new MethodDescriptor('UpdateProfile', 7001, $profileType, $profileType); + } +} diff --git a/tests/Feature/LaravelControllerDispatchTest.php b/tests/Feature/LaravelControllerDispatchTest.php index c84eb9d..bf4947e 100644 --- a/tests/Feature/LaravelControllerDispatchTest.php +++ b/tests/Feature/LaravelControllerDispatchTest.php @@ -25,9 +25,9 @@ use RuntimeException; use Skir\Runtime\Field; use Skir\Runtime\MethodDescriptor; +use Skir\Runtime\ReadableJson; use Skir\Runtime\Type; use Skir\Server\Attributes\SkirMethod; -use Skir\Server\Codecs\SkirCodecs; use Skir\Server\Contracts\SkirMethodReference; use Skir\Server\Exceptions\SkirServerException; use Skir\Server\Exceptions\UnsupportedControllerParameterException; @@ -81,7 +81,7 @@ public function it_prepares_laravel_controller_middleware_and_dispatches_native_ $this->assertSame(spl_object_id($context), NativeDispatchController::$contextObjectId); $this->assertSame( ['name' => 'Maxim:container:Native Skir'], - $server->codec()->encodeResponse(NativeDispatchMethod::Update->descriptor(), $result), + ReadableJson::encode(NativeDispatchMethod::Update->descriptor()->responseType, $result), ); } @@ -164,7 +164,7 @@ public function skir_method_dispatches_invokable_controllers(): void { Route::skirRpc('/invokable-controller', [ Skir::method(NativeDispatchMethod::Invokable, InvokableDispatchController::class), - ], SkirCodecs::standardJson()); + ]); $this ->postJson('/invokable-controller', [ @@ -415,28 +415,28 @@ public function package_exceptions_keep_their_skir_envelope_inside_the_middlewar } #[Test] - public function codec_runtime_exceptions_keep_their_skir_envelope_inside_the_middleware_pipeline(): void + public function unserializable_responses_keep_their_skir_envelope_inside_the_middleware_pipeline(): void { $this->be(new GenericUser(['id' => 42])); - Route::skirRpc('/pipeline-codec-error', [ + Route::skirRpc('/pipeline-unserializable-response', [ Skir::controller(RoutingPipelineController::class), ]); $this - ->postJson('/pipeline-codec-error', [ - 'method' => 'RuntimeCodecFailure', + ->postJson('/pipeline-unserializable-response', [ + 'method' => 'UnserializableResponse', 'request' => null, ]) - ->assertUnprocessable() + ->assertServerError() ->assertHeader('X-Skir-Middleware', 'applied') ->assertExactJson([ 'error' => [ - 'code' => 'skir_invalid_request', - 'message' => 'Skir array values must be PHP arrays.', + 'code' => 'skir_invalid_response', + 'message' => 'Skir method [UnserializableResponse] returned a value that cannot be serialized: Skir array values must be PHP arrays.', ], ]); - $this->assertTransportRequestStateRestored('/pipeline-codec-error'); + $this->assertTransportRequestStateRestored('/pipeline-unserializable-response'); } #[Test] @@ -684,7 +684,7 @@ private function registerController(string $uri, string $controller): LaravelRou { return Route::skirRpc($uri, [ Skir::controller($controller), - ], SkirCodecs::standardJson()); + ]); } private function serverFromRoute(LaravelRoute $route): SkirServer @@ -737,7 +737,7 @@ enum NativeDispatchMethod implements SkirMethodReference case AuthorizationFailure; case PackageFailure; case UnexpectedFailure; - case RuntimeCodecFailure; + case UnserializableResponse; case FilteredMiddleware; case LegacyMiddleware; case Invokable; @@ -852,8 +852,8 @@ public function descriptor(): MethodDescriptor Type::optional(Type::struct([])), Type::string(), ), - self::RuntimeCodecFailure => new MethodDescriptor( - 'RuntimeCodecFailure', + self::UnserializableResponse => new MethodDescriptor( + 'UnserializableResponse', 6017, Type::optional(Type::struct([])), Type::array(Type::string()), @@ -1242,10 +1242,10 @@ public function unexpectedFailure(): never throw new RuntimeException('Unexpected procedure failure.'); } - #[SkirMethod(NativeDispatchMethod::RuntimeCodecFailure)] + #[SkirMethod(NativeDispatchMethod::UnserializableResponse)] #[ControllerMiddlewareAttribute(ScopedUserResolverMiddleware::class)] #[ControllerMiddlewareAttribute(ResponsePostProcessingMiddleware::class)] - public function runtimeCodecFailure(): string + public function unserializableResponse(): string { return 'not-an-array'; } diff --git a/tests/Feature/NullableControllerRequestTest.php b/tests/Feature/NullableControllerRequestTest.php index 716e9bb..2082a3b 100644 --- a/tests/Feature/NullableControllerRequestTest.php +++ b/tests/Feature/NullableControllerRequestTest.php @@ -10,16 +10,15 @@ use Illuminate\Testing\TestResponse; use InvalidArgumentException; use PHPUnit\Framework\Attributes\Test; +use Skir\Runtime\Field; use Skir\Runtime\MethodDescriptor; use Skir\Runtime\Type; -use Skir\Server\Codecs\SkirCodecs; use Skir\Server\Contracts\SkirMethodReference; use Skir\Server\Exceptions\SkirServerException; use Skir\Server\Facades\Skir; use Skir\Server\Http\Requests\SkirFormRequest; use Skir\Server\SkirContext; use Skir\Server\Tests\TestCase; -use TypeError; final class NullableControllerRequestTest extends TestCase { @@ -39,7 +38,7 @@ public function nullable_standard_generated_requests_receive_null_without_hydrat $this->postNullRequest('/nullable-standard', 'Standard') ->assertOk() - ->assertExactJson(['received' => null]); + ->assertExactJson([]); $this->assertSame(0, NullableStandardRequest::$hydrations); } @@ -53,7 +52,7 @@ public function nullable_laravel_data_requests_receive_null_without_hydration(): $this->postNullRequest('/nullable-data', 'Data') ->assertOk() - ->assertExactJson(['received' => null]); + ->assertExactJson([]); $this->assertSame(0, NullableDataRequest::$hydrations); } @@ -67,9 +66,8 @@ public function nullable_enums_receive_null_without_hydration(): void $this->postNullRequest('/nullable-enum', 'EnumValue') ->assertOk() - ->assertExactJson(['received' => null]); + ->assertExactJson([]); - $this->assertSame(0, NullableRequestStatusHydrations::$count); } #[Test] @@ -91,7 +89,7 @@ public function nullable_form_requests_authorize_null_without_validation_or_hydr $this->postNullRequest('/nullable-form-request/acme', 'FormRequest') ->assertOk() - ->assertExactJson(['received' => null]); + ->assertExactJson([]); $this->assertSame(1, NullableGeneratedFormRequest::$authorizations); $this->assertSame(1, NullableGeneratedFormRequest::$instances); @@ -203,47 +201,28 @@ public function non_null_nullable_requests_still_hydrate_and_validate(): void } #[Test] - public function nonnullable_null_requests_keep_their_existing_failures(): void + public function null_for_a_nonnullable_struct_request_decodes_to_the_default_struct(): void { $this->registerRoute(NullableRequestMethod::NonnullableStandard, NonnullableStandardController::class); - $this->registerRoute(NullableRequestMethod::NonnullableFormRequest, NonnullableFormRequestController::class); - - try { - $this->withoutExceptionHandling() - ->postNullRequest('/nonnullable-standard', 'NonnullableStandard'); - - $this->fail('A nonnullable generated request must reject null.'); - } catch (TypeError $exception) { - $this->assertStringContainsString('must be of type array, null given', $exception->getMessage()); - } + $this->registerRoute(NullableRequestMethod::NonnullableData, NonnullableDataController::class); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Skir Form Requests require a decoded array/object payload.'); + $this->postNullRequest('/nonnullable-standard', 'NonnullableStandard') + ->assertOk() + ->assertExactJson(['received' => '']); + $this->postNullRequest('/nonnullable-data', 'NonnullableData') + ->assertOk() + ->assertExactJson(['received' => '']); - $this->postNullRequest('/nonnullable-form-request', 'NonnullableFormRequest'); } #[Test] - public function nonnullable_enum_null_requests_keep_their_existing_failure(): void + public function null_for_a_nonnullable_string_request_is_rejected(): void { $this->registerRoute(NullableRequestMethod::NonnullableEnum, NonnullableEnumController::class); - $this->withoutExceptionHandling(); - $this->expectException(TypeError::class); - - $this->postNullRequest('/nonnullable-enum', 'NonnullableEnum'); - } - - #[Test] - public function nonnullable_laravel_data_null_requests_keep_their_existing_failure(): void - { - $this->registerRoute(NullableRequestMethod::NonnullableData, NonnullableDataController::class); - - $this->withoutExceptionHandling(); - $this->expectException(TypeError::class); - $this->expectExceptionMessage('must be of type array, null given'); - - $this->postNullRequest('/nonnullable-data', 'NonnullableData'); + $this->postNullRequest('/nonnullable-enum', 'NonnullableEnum') + ->assertUnprocessable() + ->assertJsonPath('error.code', 'skir_invalid_request'); } #[Test] @@ -288,7 +267,7 @@ private function registerRoute( ): void { $route = Route::skirRpc($this->routePath($method), [ Skir::method($method, $controller), - ], SkirCodecs::standardJson()); + ]); if ($method === NullableRequestMethod::FormRequest) { $route->middleware('web'); @@ -356,17 +335,23 @@ enum NullableRequestMethod implements SkirMethodReference public function descriptor(): MethodDescriptor { + $named = Type::struct([Field::value('name', 0, Type::string())]); $requestType = match ($this) { + self::EnumValue => Type::optional(Type::string()), + self::NonnullableEnum => Type::string(), self::NonnullableStandard, self::NonnullableFormRequest, - self::NonnullableEnum, - self::NonnullableData => Type::struct([]), - self::ContextOnly => Type::struct([]), + self::NonnullableData => $named, + self::ContextOnly, self::NoPayload => Type::struct([]), - default => Type::optional(Type::struct([])), + default => Type::optional($named), }; + $responseType = Type::struct([ + Field::value('received', 0, Type::optional(Type::string())), + Field::value('method', 1, Type::optional(Type::string())), + ]); - return new MethodDescriptor($this->name, $this->value(), $requestType, Type::struct([])); + return new MethodDescriptor($this->name, $this->value(), $requestType, $responseType); } private function value(): int diff --git a/tests/Feature/SkirCodecFailureTest.php b/tests/Feature/SkirCodecFailureTest.php deleted file mode 100644 index 2c088a2..0000000 --- a/tests/Feature/SkirCodecFailureTest.php +++ /dev/null @@ -1,85 +0,0 @@ -postJson('/base64-validation', [ - 'method' => 'CountItems', - 'request' => $request, - ]) - ->assertUnprocessable() - ->assertJsonPath('error.code', 'skir_invalid_request'); - } - - #[Test] - public function it_rejects_a_missing_base64_request_value(): void - { - Route::skirRpc('/base64-missing', [ - new CodecSquareProvider, - ], SkirCodecs::base64DenseJson()); - - $this - ->postJson('/base64-missing', [ - 'method' => 'CountItems', - ]) - ->assertUnprocessable() - ->assertJsonPath('error.code', 'skir_invalid_request'); - } - - #[Test] - public function codec_factories_return_the_expected_codec_types(): void - { - $this->assertInstanceOf(DenseJsonCodec::class, SkirCodecs::denseJson()); - $this->assertInstanceOf(StandardJsonCodec::class, SkirCodecs::standardJson()); - $this->assertInstanceOf(Base64DenseJsonCodec::class, SkirCodecs::base64DenseJson()); - } - - /** - * @return array - */ - public static function invalidBase64Requests(): array - { - return [ - 'non-string' => [5], - 'invalid base64' => ['***'], - 'invalid decoded JSON' => [base64_encode('{')], - 'invalid dense JSON type' => [base64_encode('"five"')], - ]; - } -} - -final class CodecSquareProvider implements ProcedureProvider -{ - public function register(SkirServer $server): void - { - $server->addMethod( - new MethodDescriptor('CountItems', 1001, Type::array(Type::int32()), Type::int32()), - fn (array $items): int => count($items), - ); - } -} diff --git a/tests/Feature/SkirFormRequestTest.php b/tests/Feature/SkirFormRequestTest.php index 01392dd..1509ff5 100644 --- a/tests/Feature/SkirFormRequestTest.php +++ b/tests/Feature/SkirFormRequestTest.php @@ -21,7 +21,6 @@ use Skir\Runtime\Field; use Skir\Runtime\MethodDescriptor; use Skir\Runtime\Type; -use Skir\Server\Codecs\SkirCodecs; use Skir\Server\Contracts\SkirMethodReference; use Skir\Server\Exceptions\AmbiguousControllerRequestException; use Skir\Server\Facades\Skir; @@ -157,7 +156,7 @@ public function skir_uses_the_laravel_data_generator_contract_once_after_validat ], )->assertOk()->json(); - $this->assertSame('Laravel Data', $result); + $this->assertSame(['name' => 'Laravel Data'], $result); $this->assertSame(1, LaravelDataFixture::$factoryCalls); $this->assertSame('makeFromSkirPayload', LaravelDataFixture::$factory); $this->assertSame([ @@ -185,7 +184,7 @@ public function skir_uses_the_standard_php_generator_contract_once_after_validat ], )->assertOk()->json(); - $this->assertSame('Standard PHP', $result); + $this->assertSame(['name' => 'Standard PHP'], $result); $this->assertSame(1, StandardPhpFixture::$factoryCalls); $this->assertSame('fromArray', StandardPhpFixture::$factory); $this->assertSame([ @@ -423,7 +422,7 @@ public function it_keeps_direct_generated_object_injection_available_without_a_f { Route::skirRpc('/direct-payload-rpc', [ Skir::method(FormRequestSkirMethod::DirectUser, DirectPayloadController::class), - ], SkirCodecs::standardJson()); + ]); $this ->postJson('/direct-payload-rpc', [ @@ -447,7 +446,7 @@ public function it_rejects_multiple_direct_skir_request_parameters_before_hydrat $this->be(new GenericUser(['id' => 42])); Route::skirRpc('/ambiguous-direct-payload-rpc', [ Skir::method(FormRequestSkirMethod::AmbiguousDirectUser, AmbiguousDirectPayloadController::class), - ], SkirCodecs::standardJson()); + ]); $this->withoutExceptionHandling(); @@ -483,16 +482,12 @@ public function get_requests_scope_form_requests_to_the_decoded_object_payload() RenameUserFormController::$requestPayload = []; Route::skirRpc('/get-form-request', [ Skir::method(FormRequestSkirMethod::RenameUser, RenameUserFormController::class), - ], SkirCodecs::standardJson()); - $query = http_build_query([ - 'method' => 'RenameUser', - 'request' => json_encode([ - 'id' => 42, - 'name' => ' Maxim ', - 'metadata' => 'decoded', - ], JSON_THROW_ON_ERROR), - 'transportOnly' => 'must-not-leak', ]); + $query = rawurlencode('RenameUser:3001:readable:'.json_encode([ + 'id' => 42, + 'name' => ' Maxim ', + 'metadata' => 'decoded', + ], JSON_THROW_ON_ERROR)); $this ->withHeader('Accept', 'application/json') @@ -517,7 +512,7 @@ private function postDecodedFormRequest(string $controller, array $decodedPayloa { $route = Route::skirRpc('/native-form-request/{tenant}', [ Skir::method(FormRequestSkirMethod::RenameUser, $controller), - ], SkirCodecs::standardJson()); + ]); $route->middleware('web'); $this->withoutMiddleware(TrimStrings::class); $this->be(new GenericUser(['id' => 42])); @@ -784,23 +779,25 @@ protected function skirClass(): string final class LaravelDataContractController { - public function __invoke(LaravelDataContractSkirRequest $request): string + /** @return array{name: string} */ + public function __invoke(LaravelDataContractSkirRequest $request): array { /** @var LaravelDataFixture $payload */ $payload = $request->skir(); - return $payload->name; + return ['name' => $payload->name]; } } final class StandardPhpContractController { - public function __invoke(StandardPhpContractSkirRequest $request): string + /** @return array{name: string} */ + public function __invoke(StandardPhpContractSkirRequest $request): array { /** @var StandardPhpFixture $payload */ $payload = $request->skir(); - return $payload->name; + return ['name' => $payload->name]; } } diff --git a/tests/Feature/SkirRouteConfigurationTest.php b/tests/Feature/SkirRouteConfigurationTest.php index 3013ad3..c0e9516 100644 --- a/tests/Feature/SkirRouteConfigurationTest.php +++ b/tests/Feature/SkirRouteConfigurationTest.php @@ -15,7 +15,6 @@ use PHPUnit\Framework\Attributes\Test; use Skir\Runtime\MethodDescriptor; use Skir\Runtime\Type; -use Skir\Server\Codecs\SkirCodec; use Skir\Server\Exceptions\SkirServerException; use Skir\Server\ProcedureProvider; use Skir\Server\Routing\SkirRouteDefinition; @@ -110,7 +109,7 @@ public function it_resolves_container_bound_provider_interfaces(): void ]); $this->assertSame( - ['ContainerBoundMethod'], + [5007], array_keys($this->serverFromRoute($route)->procedures()), ); } @@ -125,7 +124,7 @@ public function it_resolves_lazily_bound_provider_interfaces(): void ]); $this->assertSame( - ['LazyBoundMethod'], + [5008], array_keys($this->serverFromRoute($route)->procedures()), ); } @@ -150,7 +149,7 @@ public function it_preserves_the_order_of_mixed_route_definitions_and_procedure_ ]); $this->assertSame( - ['RouteDefinitionMethod', 'ProcedureProviderMethod'], + [5005, 5006], array_keys($this->serverFromRoute($route)->procedures()), ); } @@ -175,58 +174,6 @@ public function manual_and_generated_style_providers_do_not_run_controller_middl $this->assertSame(0, ProviderControllerMiddleware::$invocations); } - #[Test] - public function a_custom_codec_with_no_providers_creates_an_isolated_server(): void - { - app(SkirServer::class)->addMethod( - new MethodDescriptor('GlobalMethod', 5001, Type::string(), Type::string()), - fn (string $request): string => $request, - ); - - $route = Route::skirRpc('/custom-codec', [], new MarkerCodec); - $server = $this->serverFromRoute($route); - $server->addMethod( - new MethodDescriptor('RouteMethod', 5002, Type::string(), Type::string()), - fn (string $request): string => $request, - ); - - $this - ->postJson('/custom-codec', [ - 'method' => 'RouteMethod', - 'request' => 'value', - ]) - ->assertOk() - ->assertExactJson(['encoded' => 'value']); - - $this - ->postJson('/custom-codec', [ - 'method' => 'GlobalMethod', - 'request' => 'value', - ]) - ->assertNotFound(); - } - - #[Test] - public function route_specific_codecs_do_not_leak_between_endpoints(): void - { - Route::skirRpc('/first-codec', [new RouteEchoProvider], new MarkerCodec('first')); - Route::skirRpc('/second-codec', [new RouteEchoProvider], new MarkerCodec('second')); - - $this - ->postJson('/first-codec', [ - 'method' => 'Echo', - 'request' => 'value', - ]) - ->assertExactJson(['encoded' => 'first:value']); - - $this - ->postJson('/second-codec', [ - 'method' => 'Echo', - 'request' => 'value', - ]) - ->assertExactJson(['encoded' => 'second:value']); - } - #[Test] public function studio_can_be_explicitly_disabled(): void { @@ -381,25 +328,3 @@ public function register(SkirServer $server): void ); } } - -final readonly class MarkerCodec implements SkirCodec -{ - public function __construct( - private string $prefix = '', - ) {} - - public function decodeRequest(MethodDescriptor $descriptor, mixed $request): mixed - { - return $request; - } - - /** - * @return array{encoded: mixed} - */ - public function encodeResponse(MethodDescriptor $descriptor, mixed $response): array - { - $encoded = $this->prefix === '' ? $response : "{$this->prefix}:{$response}"; - - return ['encoded' => $encoded]; - } -} diff --git a/tests/Feature/SkirRpcControllerTest.php b/tests/Feature/SkirRpcControllerTest.php index 259a2ec..91d3f99 100644 --- a/tests/Feature/SkirRpcControllerTest.php +++ b/tests/Feature/SkirRpcControllerTest.php @@ -8,12 +8,10 @@ use Illuminate\Routing\Route as LaravelRoute; use Illuminate\Support\Facades\Route; use PHPUnit\Framework\Attributes\Test; -use Skir\Runtime\DenseJson; use Skir\Runtime\Field; use Skir\Runtime\MethodDescriptor; use Skir\Runtime\Type; use Skir\Server\Attributes\SkirMethod; -use Skir\Server\Codecs\SkirCodecs; use Skir\Server\Contracts\SkirMethodReference; use Skir\Server\Exceptions\SkirServerException; use Skir\Server\Facades\Skir; @@ -25,6 +23,111 @@ final class SkirRpcControllerTest extends TestCase { + #[Test] + public function it_answers_colon_separated_requests_in_dense_json(): void + { + Route::skirRpc('/colon-rpc', [RenameUserProcedureProvider::class]); + + $this + ->call('POST', '/colon-rpc', content: 'RenameUser:1003::[42,"Ruben"]') + ->assertOk() + ->assertHeader('content-type', 'application/json') + ->assertContent('[42,"Ruben updated"]'); + } + + #[Test] + public function it_answers_colon_separated_requests_in_readable_json_when_asked(): void + { + Route::skirRpc('/colon-readable-rpc', [RenameUserProcedureProvider::class]); + + $this + ->call('POST', '/colon-readable-rpc', content: 'RenameUser:1003:readable:[42,"Ruben"]') + ->assertOk() + ->assertExactJson([ + 'id' => 42, + 'name' => 'Ruben updated', + ]); + } + + #[Test] + public function it_looks_up_methods_by_name_when_the_number_is_empty(): void + { + Route::skirRpc('/by-name-rpc', [SquareProcedureProvider::class]); + + $this + ->call('POST', '/by-name-rpc', content: 'Square:::5') + ->assertOk() + ->assertContent('25'); + } + + #[Test] + public function the_method_number_wins_over_the_name(): void + { + Route::skirRpc('/by-number-rpc', [SquareProcedureProvider::class]); + + $this + ->call('POST', '/by-number-rpc', content: 'Anything:1001::5') + ->assertOk() + ->assertContent('25'); + } + + #[Test] + public function it_accepts_a_method_number_in_json_object_requests(): void + { + Route::skirRpc('/json-number-rpc', [SquareProcedureProvider::class]); + + $this + ->postJson('/json-number-rpc', [ + 'method' => 1001, + 'request' => 5, + ]) + ->assertOk() + ->assertContent('25'); + } + + #[Test] + public function it_reads_get_requests_from_the_query_string(): void + { + Route::skirRpc('/get-rpc', [RenameUserProcedureProvider::class]); + + $this + ->get('/get-rpc?'.rawurlencode('RenameUser:1003::[42,"Ruben"]')) + ->assertOk() + ->assertContent('[42,"Ruben updated"]'); + } + + #[Test] + public function it_rejects_ambiguous_method_names(): void + { + $server = app(SkirServer::class); + $server->addMethod(new MethodDescriptor('Same', 2001, Type::int32(), Type::int32()), fn (int $value): int => $value); + $server->addMethod(new MethodDescriptor('Same', 2002, Type::int32(), Type::int32()), fn (int $value): int => $value); + + $this + ->call('POST', '/skir', content: 'Same:::1') + ->assertUnprocessable() + ->assertJsonPath('error.code', 'skir_invalid_request'); + + $this + ->call('POST', '/skir', content: 'Same:2002::1') + ->assertOk() + ->assertContent('1'); + } + + #[Test] + public function it_reports_responses_that_do_not_match_the_response_type(): void + { + app(SkirServer::class)->addMethod( + new MethodDescriptor('Broken', 2003, Type::int32(), Type::string()), + fn (int $value): array => [$value], + ); + + $this + ->call('POST', '/skir', content: 'Broken:2003::1') + ->assertServerError() + ->assertJsonPath('error.code', 'skir_invalid_response'); + } + #[Test] public function it_dispatches_a_posted_skir_rpc_request(): void { @@ -65,7 +168,7 @@ public function it_decodes_struct_requests_and_encodes_struct_responses(): void 'request' => [42, 'Ruben'], ]) ->assertOk() - ->assertExactJson([42, 'Ruben from 127.0.0.1']); + ->assertExactJson(['id' => 42, 'name' => 'Ruben from 127.0.0.1']); } #[Test] @@ -77,7 +180,7 @@ public function it_dispatches_a_get_request_from_the_query_string(): void ); $this - ->getJson('/skir?method=Square&request=5.0') + ->getJson('/skir?Square:1001::5.0') ->assertOk() ->assertContent('25'); } @@ -93,7 +196,7 @@ public function it_dispatches_a_head_request_from_the_query_string(): void $this ->call( 'HEAD', - '/skir?method=Square&request=5.0', + '/skir?Square:1001::5.0', server: ['HTTP_ACCEPT' => 'application/json'], ) ->assertOk() @@ -216,7 +319,7 @@ public function it_registers_attributed_public_controller_methods(): void 'request' => [42, 'Maxim'], ]) ->assertOk() - ->assertExactJson([42, 'Maxim updated']); + ->assertExactJson(['id' => 42, 'name' => 'Maxim updated']); $this ->postJson('/attribute-rpc', [ @@ -255,7 +358,7 @@ public function it_allows_multiple_controllers_on_one_endpoint(): void public function it_rejects_duplicate_methods_on_one_endpoint(): void { $this->expectException(SkirServerException::class); - $this->expectExceptionMessage('Skir method [Square] is already registered on this endpoint.'); + $this->expectExceptionMessage('Skir method [Square] with number [1001] is already registered on this endpoint.'); Route::skirRpc('/duplicate-rpc', [ Skir::method(TestSkirMethod::Square, SquareController::class), @@ -312,14 +415,14 @@ public function it_keeps_route_procedure_registries_isolated(): void } #[Test] - public function it_can_use_standard_json_payloads_for_an_endpoint(): void + public function it_answers_json_object_requests_in_readable_json(): void { - Route::skirRpc('/standard-rpc', [ + Route::skirRpc('/readable-rpc', [ RenameUserProcedureProvider::class, - ], SkirCodecs::standardJson()); + ]); $this - ->postJson('/standard-rpc', [ + ->postJson('/readable-rpc', [ 'method' => 'RenameUser', 'request' => [ 'id' => 42, @@ -333,22 +436,6 @@ public function it_can_use_standard_json_payloads_for_an_endpoint(): void ]); } - #[Test] - public function it_can_use_base64_encoded_dense_json_payloads_for_an_endpoint(): void - { - Route::skirRpc('/base64-rpc', [ - SquareProcedureProvider::class, - ], SkirCodecs::base64DenseJson()); - - $this - ->postJson('/base64-rpc', [ - 'method' => 'Square', - 'request' => base64_encode(DenseJson::toJson(Type::float32(), 5.0)), - ]) - ->assertOk() - ->assertContent(json_encode(base64_encode(DenseJson::toJson(Type::float32(), 25.0)), JSON_THROW_ON_ERROR)); - } - #[Test] public function it_injects_the_primary_skir_context(): void { @@ -405,7 +492,7 @@ public function it_returns_a_package_local_error_for_invalid_request_envelopes() ->assertExactJson([ 'error' => [ 'code' => 'skir_invalid_request', - 'message' => 'Skir requests must include a string [method] value.', + 'message' => 'Skir requests must include a [method] field.', ], ]); } diff --git a/tests/Feature/SkirRpcValidationTest.php b/tests/Feature/SkirRpcValidationTest.php index 2c936c5..793a631 100644 --- a/tests/Feature/SkirRpcValidationTest.php +++ b/tests/Feature/SkirRpcValidationTest.php @@ -16,8 +16,8 @@ final class SkirRpcValidationTest extends TestCase { #[Test] - #[DataProvider('nonStringMethods')] - public function it_rejects_non_string_method_values(mixed $method): void + #[DataProvider('invalidMethods')] + public function it_rejects_invalid_method_values(mixed $method): void { $this ->postJson('/skir', [ @@ -28,7 +28,7 @@ public function it_rejects_non_string_method_values(mixed $method): void ->assertExactJson([ 'error' => [ 'code' => 'skir_invalid_request', - 'message' => 'Skir requests must include a string [method] value.', + 'message' => 'The [method] field must be a string or a number.', ], ]); } @@ -49,7 +49,7 @@ public function it_rejects_malformed_json_envelopes(): void #[Test] #[DataProvider('nonObjectJsonEnvelopes')] - public function it_rejects_non_object_json_envelopes(string $content): void + public function it_rejects_bodies_that_are_neither_json_objects_nor_colon_separated(string $content): void { $this ->call( @@ -62,7 +62,7 @@ public function it_rejects_non_object_json_envelopes(string $content): void ->assertExactJson([ 'error' => [ 'code' => 'skir_invalid_request', - 'message' => 'Skir requests must be JSON objects.', + 'message' => 'Skir requests must be a JSON object or [method:number:format:request].', ], ]); } @@ -73,7 +73,7 @@ public function it_rejects_malformed_get_request_json(): void $this->registerSquare(); $this - ->getJson('/skir?method=Square&request=%7B') + ->getJson('/skir?Square:1001::%7B') ->assertUnprocessable() ->assertJsonPath('error.code', 'skir_invalid_request'); } @@ -157,11 +157,11 @@ public function it_rejects_unsupported_http_methods(): void /** * @return array */ - public static function nonStringMethods(): array + public static function invalidMethods(): array { return [ 'null' => [null], - 'integer' => [1001], + 'boolean' => [true], 'array' => [['Square']], ]; } diff --git a/tests/Feature/SkirServerConfigurationTest.php b/tests/Feature/SkirServerConfigurationTest.php index 2a32187..062ee69 100644 --- a/tests/Feature/SkirServerConfigurationTest.php +++ b/tests/Feature/SkirServerConfigurationTest.php @@ -7,12 +7,7 @@ use Illuminate\Routing\Route as LaravelRoute; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; -use LogicException; use PHPUnit\Framework\Attributes\Test; -use Skir\Runtime\MethodDescriptor; -use Skir\Server\Codecs\DenseJsonCodec; -use Skir\Server\Codecs\SkirCodec; -use Skir\Server\Exceptions\SkirServerException; use Skir\Server\ProcedureProvider; use Skir\Server\SkirServer; use Skir\Server\SkirServerServiceProvider; @@ -115,119 +110,6 @@ public function studio_configuration_is_snapshotted_when_the_route_is_registered ->assertDontSee('Skir RPC Studio'); } - #[Test] - public function dense_json_is_the_default_codec(): void - { - $this->assertSame(DenseJsonCodec::class, config('skir-server.codec')); - } - - #[Test] - public function the_configured_codec_is_used_by_global_and_isolated_servers(): void - { - config(['skir-server.codec' => ConfiguredCodec::class]); - - $globalServer = app(SkirServer::class); - $route = Route::skirRpc('/configured-codec', [ - new ConfigurationProcedureProvider, - ]); - $isolatedServer = $this->serverFromRoute($route); - $configuredCodec = $globalServer->codec(); - - $this->assertInstanceOf(ConfiguredCodec::class, $configuredCodec); - $this->assertInstanceOf(ConfiguredCodecDependency::class, $configuredCodec->dependency); - $this->assertSame($configuredCodec, $isolatedServer->codec()); - } - - #[Test] - public function configured_codec_construction_exceptions_are_preserved(): void - { - config(['skir-server.codec' => FailingConfiguredCodec::class]); - - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Configured codec construction failed.'); - - app(SkirCodec::class); - } - - #[Test] - public function an_unbound_abstract_configured_codec_is_rejected(): void - { - config(['skir-server.codec' => AbstractConfiguredCodec::class]); - - $this->expectException(SkirServerException::class); - $this->expectExceptionMessage( - 'Configured Skir codec ['.AbstractConfiguredCodec::class.'] must implement ' - .'[Skir\\Server\\Codecs\\SkirCodec].', - ); - - app(SkirCodec::class); - } - - #[Test] - public function the_codec_contract_cannot_be_configured_as_its_own_implementation(): void - { - config(['skir-server.codec' => SkirCodec::class]); - - $this->expectException(SkirServerException::class); - $this->expectExceptionMessage( - 'Configured Skir codec ['.SkirCodec::class.'] must implement ' - .'[Skir\\Server\\Codecs\\SkirCodec].', - ); - - app(SkirCodec::class); - } - - #[Test] - public function a_container_bound_codec_abstraction_can_be_configured(): void - { - config(['skir-server.codec' => AbstractConfiguredCodec::class]); - $this->app->bind(AbstractConfiguredCodec::class, ContainerBoundConfiguredCodec::class); - - $this->assertInstanceOf(ContainerBoundConfiguredCodec::class, app(SkirCodec::class)); - } - - #[Test] - public function an_explicit_route_codec_overrides_the_configured_codec(): void - { - config(['skir-server.codec' => InvalidConfiguredCodec::class]); - - $explicitCodec = new ExplicitCodec; - $route = Route::skirRpc( - '/explicit-codec', - [new ConfigurationProcedureProvider], - $explicitCodec, - ); - - $this->assertSame($explicitCodec, $this->serverFromRoute($route)->codec()); - } - - #[Test] - public function an_invalid_configured_codec_is_rejected(): void - { - config(['skir-server.codec' => InvalidConfiguredCodec::class]); - - $this->expectException(SkirServerException::class); - $this->expectExceptionMessage( - 'Configured Skir codec ['.InvalidConfiguredCodec::class.'] must implement ' - .'[Skir\\Server\\Codecs\\SkirCodec].', - ); - - app(SkirServer::class); - } - - #[Test] - public function a_non_string_configured_codec_is_rejected(): void - { - config(['skir-server.codec' => []]); - - $this->expectException(SkirServerException::class); - $this->expectExceptionMessage( - 'Configured Skir codec [array] must implement [Skir\\Server\\Codecs\\SkirCodec].', - ); - - app(SkirCodec::class); - } - #[Test] public function package_configuration_is_publishable(): void { @@ -255,71 +137,6 @@ private function serverFromRoute(LaravelRoute $route): SkirServer } } -final readonly class ConfiguredCodec implements SkirCodec -{ - public function __construct(public ConfiguredCodecDependency $dependency) {} - - public function decodeRequest(MethodDescriptor $descriptor, mixed $request): mixed - { - return $request; - } - - public function encodeResponse(MethodDescriptor $descriptor, mixed $response): mixed - { - return $response; - } -} - -final class ConfiguredCodecDependency {} - -final class FailingConfiguredCodec implements SkirCodec -{ - public function __construct() - { - throw new LogicException('Configured codec construction failed.'); - } - - public function decodeRequest(MethodDescriptor $descriptor, mixed $request): mixed - { - return $request; - } - - public function encodeResponse(MethodDescriptor $descriptor, mixed $response): mixed - { - return $response; - } -} - -abstract class AbstractConfiguredCodec implements SkirCodec -{ - public function decodeRequest(MethodDescriptor $descriptor, mixed $request): mixed - { - return $request; - } - - public function encodeResponse(MethodDescriptor $descriptor, mixed $response): mixed - { - return $response; - } -} - -final class ContainerBoundConfiguredCodec extends AbstractConfiguredCodec {} - -final class ExplicitCodec implements SkirCodec -{ - public function decodeRequest(MethodDescriptor $descriptor, mixed $request): mixed - { - return $request; - } - - public function encodeResponse(MethodDescriptor $descriptor, mixed $response): mixed - { - return $response; - } -} - -final class InvalidConfiguredCodec {} - final class ConfigurationProcedureProvider implements ProcedureProvider { public function register(SkirServer $server): void {} diff --git a/tests/Unit/ProcedureRegistryTest.php b/tests/Unit/ProcedureRegistryTest.php index a848237..d0e1255 100644 --- a/tests/Unit/ProcedureRegistryTest.php +++ b/tests/Unit/ProcedureRegistryTest.php @@ -9,7 +9,6 @@ use PHPUnit\Framework\TestCase; use Skir\Runtime\MethodDescriptor; use Skir\Runtime\Type; -use Skir\Server\Codecs\DenseJsonCodec; use Skir\Server\Exceptions\SkirServerException; use Skir\Server\ProcedureRegistry; use Skir\Server\SkirContext; @@ -26,11 +25,11 @@ public function it_stores_and_lists_registered_procedures(): void $registry->add($descriptor, fn (float $value): float => $value * $value); $this->assertSame($descriptor, $registry->get('Square')->descriptor); - $this->assertSame(['Square'], array_keys($registry->all())); + $this->assertSame([6001], array_keys($registry->all())); } #[Test] - public function it_rejects_duplicate_procedure_names(): void + public function it_rejects_duplicate_method_numbers(): void { $registry = new ProcedureRegistry; $registry->add($this->descriptor('Square'), fn (float $value): float => $value); @@ -41,7 +40,7 @@ public function it_rejects_duplicate_procedure_names(): void } catch (SkirServerException $exception) { $this->assertSame('skir_duplicate_method', $exception->errorCode); $this->assertSame(422, $exception->status); - $this->assertSame('Skir method [Square] is already registered on this endpoint.', $exception->getMessage()); + $this->assertSame('Skir method [Square] with number [6001] is already registered on this endpoint.', $exception->getMessage()); } } @@ -77,11 +76,10 @@ public function registered_procedures_receive_the_request_and_context(): void } #[Test] - public function the_server_uses_dense_json_by_default(): void + public function a_new_server_has_no_procedures(): void { $server = new SkirServer(new ProcedureRegistry); - $this->assertInstanceOf(DenseJsonCodec::class, $server->codec()); $this->assertSame([], $server->procedures()); } diff --git a/tests/Unit/RpcRequestTest.php b/tests/Unit/RpcRequestTest.php new file mode 100644 index 0000000..0804e1c --- /dev/null +++ b/tests/Unit/RpcRequestTest.php @@ -0,0 +1,98 @@ +assertSame(1001, $request->method); + $this->assertSame([5, 'a:b'], $request->payload); + $this->assertFalse($request->readable); + } + + #[Test] + public function it_parses_a_colon_separated_request_by_name_when_the_number_is_empty(): void + { + $request = RpcRequest::parse('Square:::5'); + + $this->assertSame('Square', $request->method); + $this->assertSame(5, $request->payload); + } + + #[Test] + public function it_answers_in_readable_json_when_the_colon_format_asks_for_it(): void + { + $this->assertTrue(RpcRequest::parse('Square:1001:readable:5')->readable); + } + + #[Test] + public function it_parses_negative_method_numbers(): void + { + $this->assertSame(-7, RpcRequest::parse('Negative:-7::0')->method); + } + + #[Test] + public function it_keeps_large_integers_as_strings(): void + { + $this->assertSame('18446744073709551615', RpcRequest::parse('Big:1::18446744073709551615')->payload); + } + + #[Test] + public function it_parses_a_json_object_request_and_answers_in_readable_json(): void + { + $request = RpcRequest::parse('{"method": "Square", "request": {"value": 5}}'); + + $this->assertSame('Square', $request->method); + $this->assertSame(['value' => 5], $request->payload); + $this->assertTrue($request->readable); + } + + #[Test] + public function it_accepts_a_method_number_in_a_json_object_request(): void + { + $this->assertSame(1001, RpcRequest::parse(' {"method": 1001, "request": null}')->method); + } + + /** + * @return array + */ + public static function invalidRequests(): array + { + return [ + 'empty body' => ['', 'Skir requests must be a JSON object or [method:number:format:request].'], + 'too few colons' => ['Square:1001:5', 'Skir requests must be a JSON object or [method:number:format:request].'], + 'non-numeric method number' => ['Square:abc::5', 'Invalid Skir method number [abc].'], + 'invalid colon payload JSON' => ['Square:1001::{', 'Invalid JSON: Syntax error'], + 'invalid JSON object' => ['{"method":', 'Invalid JSON: Syntax error'], + 'JSON that is not an object' => [' 5', 'Skir requests must be JSON objects.'], + 'missing method' => ['{"request": 5}', 'Skir requests must include a [method] field.'], + 'invalid method type' => ['{"method": true, "request": 5}', 'The [method] field must be a string or a number.'], + 'missing request' => ['{"method": "Square"}', 'Skir requests must include a [request] field.'], + ]; + } + + #[Test] + #[DataProvider('invalidRequests')] + public function it_rejects_invalid_requests(string $body, string $message): void + { + try { + RpcRequest::parse($body); + $this->fail('Expected the request to be rejected.'); + } catch (SkirServerException $exception) { + $this->assertSame('skir_invalid_request', $exception->errorCode); + $this->assertSame($message, $exception->getMessage()); + } + } +} diff --git a/tests/Unit/SkirServerExceptionTest.php b/tests/Unit/SkirServerExceptionTest.php index 5cd0eec..b8bc8c4 100644 --- a/tests/Unit/SkirServerExceptionTest.php +++ b/tests/Unit/SkirServerExceptionTest.php @@ -43,10 +43,10 @@ public static function packageExceptions(): array 'Skir method [Missing] is not registered.', ], 'duplicate method' => [ - SkirServerException::duplicateMethod('Duplicate'), + SkirServerException::duplicateMethod('Duplicate', 7), 'skir_duplicate_method', 422, - 'Skir method [Duplicate] is already registered on this endpoint.', + 'Skir method [Duplicate] with number [7] is already registered on this endpoint.', ], 'invalid route provider' => [ SkirServerException::invalidRouteProvider(new InvalidRouteProvider), @@ -62,24 +62,8 @@ public static function packageExceptions(): array 'Skir route provider [App\\Skir\\MissingProvider] must implement ' .'[Skir\\Server\\Routing\\SkirRouteDefinition] or [Skir\\Server\\ProcedureProvider].', ], - 'invalid configured codec' => [ - SkirServerException::invalidConfiguredCodec('App\\Codecs\\InvalidCodec'), - 'skir_invalid_configured_codec', - 500, - 'Configured Skir codec [App\\Codecs\\InvalidCodec] must implement ' - .'[Skir\\Server\\Codecs\\SkirCodec].', - ], - 'invalid configured codec type' => [ - SkirServerException::invalidConfiguredCodec(new InvalidConfiguredCodec), - 'skir_invalid_configured_codec', - 500, - 'Configured Skir codec ['.InvalidConfiguredCodec::class.'] must implement ' - .'[Skir\\Server\\Codecs\\SkirCodec].', - ], ]; } } final class InvalidRouteProvider {} - -final class InvalidConfiguredCodec {}