Sajya Server

repository·master·Indexed 42 days ago

https://github.com/sajya/server

A Laravel-based implementation of the JSON-RPC 2.0 protocol. It provides tools for full specification compliance, including automatic parameter validation, support for batch and notification requests, and a custom `rpc` route macro. Features include Artisan commands for scaffolding procedures (`make:procedure`) and generating HTML API documentation (`sajya:docs`), as well as flexible procedure resolution via delimiters and proxy fallbacks.

Tokens
3.9K
Snippets
20
Records
25
Agent score
54%

What's inside Sajya

  1. Introduction to Sajya

    master
    Sajya is a library for Laravel developers that enables the implementation of the JSON-RPC 2.0 specification. It provides tools to achieve full compliance with the JSON-RPC 2.0 spec, including automatic parameter validation, support for batch requests, and handling of notification requests (fire-and-forget).
  2. How procedure resolution and proxies work

    master

    The App class resolves JSON-RPC methods by splitting the requested method string using the configured delimiter (default @).

    Resolution Logic

    1. Direct Match: It looks for a registered Procedure class where the class's name property matches the part before the delimiter, and the class has a public method matching the part after the delimiter.
    2. Proxy Fallback: If no direct method match is found, the App searches for a registered procedure that implements the Sajya\Server\Proxy interface. If found, it attempts to call the __invoke method on that proxy class.

    Example Method Mapping

    If your delimiter is @ and you have a procedure UserProcedure with name = 'user':

    • Request method user@getProfile $\rightarrow$ calls UserProcedure::getProfile()
    • Request method user@someUnknown $\rightarrow$ calls UserProcedure::__invoke() (if UserProcedure implements Proxy)
  3. Handle InternalErrorException in JSON-RPC

    master

    The InternalErrorException is a specific type of RpcException used to signal internal server errors within the JSON-RPC protocol. When this error is encountered, it follows the standard JSON-RPC error code for internal errors.

    Error Details:

    • JSON-RPC Error Code: -32603
    • Default Message: Internal error
    • Data: Can optionally contain additional error context via the $data parameter.
  4. Handle InvalidParams exceptions

    master

    The Sajya\Server\Exceptions\InvalidParams exception is thrown when request parameters fail validation. It is a specialized RpcException that follows the JSON-RPC error specification. When caught, it provides a standard error code and message.

    Error Details:

    • Code: -32602 (Standard JSON-RPC code for 'Invalid params')
    • Message: 'Invalid params'
    • Data: Can contain additional context or details about the specific validation failure via the $data parameter.
  5. Manage JSON-RPC Request properties

    master

    The Request class provides fluent setter methods to configure the properties of a JSON-RPC request. Most setters return $this to allow for method chaining.

    • setMethod(string $name): Sets the name of the requested method.
    • setParams(array $params): Merges new parameters into the existing params collection.
    • setId($name): Sets the request identifier (cast to a string).
    • setVersion(string $version): Sets the JSON-RPC version (defaults to '2.0').
    use Sajya\Server\Http\Request;
    
    $request = (new Request())
        ->setMethod('sum')
        ->setParams(['a' => 1, 'b' => 2])
        ->setId(123)
        ->setVersion('2.0');
  6. Serialize a Request to JSON

    master

    The Request class implements JsonSerializable. When serialized (e.g., via json_encode()), it produces a JSON object containing the jsonrpc version, the method, and optionally the params and id if they are present.

    $request = (new Request())->setMethod('ping')->setId('abc');
    
    echo json_encode($request);
    // Output: {"jsonrpc":"2.0","method":"ping","id":"abc"}
  7. Initialize the Sajya App

    master

    The Sajya\Server\App class is the main entrypoint for managing JSON-RPC requests. You initialize it by providing an array of procedure classes and an optional delimiter.

    Constructor Parameters

    • array $procedures: An array of class names. Each class must extend Sajya\Server\Procedure.
    • ?string $delimiter: The character used to separate the procedure name from the method name in the JSON-RPC method string. If not provided, it defaults to @ or the value configured in config('sajya.delimiter').

    If a class provided in $procedures does not extend Procedure, the application will abort with a 500 error.

    use Sajya\Server\App;
    
    // Initialize with specific procedures and a custom delimiter
    $app = new App([
        App\Procedures\UserProcedure::class,
        App\Procedures\OrderProcedure::class,
    ], ':');
  8. Check if a request is a notification using isNotification()

    master

    In JSON-RPC, a notification is a request that does not include an id. You can determine if the current Request instance is a notification by calling isNotification(), which returns true if the request ID is empty.

    if ($request->isNotification()) {
        // Handle as a notification (no response expected)
    }
  9. Terminate the application with terminate()

    master

    The terminate() method handles the request processing and then triggers the Laravel application termination process. This is useful for ensuring the JSON-RPC response is returned while allowing the underlying framework to clean up.

    Parameters

    • string $content: The raw JSON-RPC request content.

    Returns

    • Sajya\Server\Http\Response[]|Sajya\Server\Http\Response|null
    $app->terminate($request->getContent());
  10. Create a JSON-RPC response with makeFromResult()

    master

    The makeFromResult() static method is the primary way to instantiate a Response object. It automatically synchronizes the response's id and version with the provided Request object, ensuring the response matches the incoming RPC call. If no Request is provided, a new instance is created.

    use Sajya\Server\Http\Response;
    use Sajya\Server\Http\Request;
    
    // Assuming $result is the data you want to return
    $response = Response::makeFromResult($result, $request);