Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Client Laravel Package

tarantool/client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tarantool/client
    

    For Decimal (Tarantool ≥2.3) and UUID support, install extensions:

    pecl install decimal uuid
    
  2. First Connection:

    use Tarantool\Client\Client;
    
    $client = Client::fromDsn('tcp://127.0.0.1:3301');
    

    Or via defaults:

    $client = Client::fromDefaults(); // Connects to 127.0.0.1:3301
    
  3. First Query (Binary Protocol):

    $space = $client->getSpace('users');
    $result = $space->select(\Tarantool\Client\Criteria::key([1]));
    print_r($result); // Returns [[1, "user_data"]]
    
  4. First SQL Query (if enabled):

    $result = $client->execute("SELECT * FROM users WHERE id = 1");
    print_r($result);
    

Implementation Patterns

1. Connection Management

  • Reusable Connections: Use persistent: true in options to avoid reconnecting:
    $client = Client::fromOptions([
        'uri' => 'tcp://127.0.0.1:3301',
        'persistent' => true,
    ]);
    
  • Connection Pooling: For high-throughput apps, wrap the client in a singleton or dependency-injected service.

2. Middleware Workflows

  • Authentication:
    $client = Client::fromDefaults()
        ->withMiddleware(new \Tarantool\Client\Middleware\AuthenticationMiddleware('user', 'pass'));
    
  • Retry Logic:
    $client = Client::fromDefaults()
        ->withMiddleware(\Tarantool\Client\Middleware\RetryMiddleware::exponential(3));
    
  • Logging:
    $client = Client::fromDefaults()
        ->withMiddleware(new \Tarantool\Client\Middleware\LoggingMiddleware(new \Monolog\Logger('tarantool')));
    

3. Space Operations

  • CRUD Patterns:
    // Create/Insert
    $space->insert([1, 'data']);
    
    // Read
    $user = $space->select(\Tarantool\Client\Criteria::key([1]))[0];
    
    // Update
    $space->update([1], \Tarantool\Client\Operations::set(1, 'updated_data'));
    
    // Delete
    $space->delete([1]);
    
  • Indexed Queries:
    $space->select(\Tarantool\Client\Criteria::index('secondary')
        ->andKey(['value'])
        ->andLimit(10));
    

4. SQL Protocol

  • Parameterized Queries:
    $result = $client->execute("SELECT * FROM users WHERE id = ?", [1]);
    
  • Transactions:
    $client->beginTransaction();
    try {
        $client->execute("INSERT INTO users VALUES (?, ?)", [2, 'new_user']);
        $client->commit();
    } catch (\Exception $e) {
        $client->rollback();
        throw $e;
    }
    

5. Custom Types

  • Decimal/UUID Handling:
    $space->insert([1, \Tarantool\Client\Decimal::fromString('123.45'), \Ramsey\Uuid\Uuid::uuid4()]);
    

6. Error Handling

  • Global Exception Handling:
    try {
        $client->execute("SELECT * FROM nonexistent");
    } catch (\Tarantool\Client\Exception\CommunicationFailed $e) {
        // Handle connection errors
    } catch (\Tarantool\Client\Exception\RequestFailed $e) {
        // Handle request errors (e.g., invalid query)
    }
    

Gotchas and Tips

Pitfalls

  1. Middleware Order Matters:

    • Placing RetryMiddleware before AuthenticationMiddleware ensures re-authentication on retry.
    • Example of incorrect order (no re-auth on retry):
      $client->withMiddleware(
          new \Tarantool\Client\Middleware\AuthenticationMiddleware('user', 'pass'),
          \Tarantool\Client\Middleware\RetryMiddleware::linear()
      );
      
  2. Persistent Connections:

    • Disabling persistent: true may cause performance overhead in long-running apps due to repeated reconnects.
    • Fix: Always enable persistence for production:
      'persistent' => env('APP_ENV') !== 'local',
      
  3. SQL vs. Binary Protocol:

    • The SQL protocol is not enabled by default in Tarantool. Ensure your server supports it (box.cfg{sql_enabled = true}).
    • Binary protocol is more performant for bulk operations but requires manual schema handling.
  4. Decimal/UUID Extensions:

    • Without decimal or uuid extensions, operations on these types will fail with UnsupportedTypeException.
    • Workaround: Use strings or fall back to base64 encoding.
  5. Timeouts:

    • Default connect_timeout (5s) and socket_timeout (5s) may be too short for unreliable networks.
    • Tip: Increase timeouts for cloud deployments:
      'connect_timeout' => 10.0,
      'socket_timeout' => 30.0,
      
  6. Large Payloads:

    • Sending large tuples (e.g., >1MB) may hit PHP’s max_input_vars or Tarantool’s msgpack limits.
    • Solution: Stream data or split operations.

Debugging Tips

  1. Enable Logging Middleware:

    $client->withMiddleware(new \Tarantool\Client\Middleware\LoggingMiddleware(
        new \Monolog\Logger('tarantool', ['handlers' => [new \Monolog\Handler\StreamHandler('php://stderr')]])
    ));
    
    • Logs raw requests/responses for debugging.
  2. Check Connection State:

    • Use StreamConnection::isConnected() to verify active connections in middleware:
      $client->withMiddleware(new class implements \Tarantool\Client\Middleware {
          public function handle(\Tarantool\Client\Request $request, callable $next) {
              if (!$request->getConnection()->isConnected()) {
                  throw new \RuntimeException("Connection lost!");
              }
              return $next($request);
          }
      });
      
  3. Validate Tarantool Schema:

    • Mismatched field types (e.g., sending a string to a number field) cause silent failures.
    • Fix: Use Operations::set('field_name', value) (Tarantool ≥2.3) for explicit field mapping.
  4. Handle Retry Exhaustion:

    • Customize retry behavior to avoid infinite loops:
      \Tarantool\Client\Middleware\RetryMiddleware::exponential(3, 100) // Max delay: 100ms
      

Extension Points

  1. Custom Middleware:

    • Implement \Tarantool\Client\Middleware to add features like:
      • Request/response transformation.
      • Rate limiting.
      • Circuit breakers.
    • Example:
      $client->withMiddleware(new class implements \Tarantool\Client\Middleware {
          public function handle(\Tarantool\Client\Request $request, callable $next) {
              if ($request instanceof \Tarantool\Client\Request\CallRequest && $request->getFunction() === 'admin.ping') {
                  return new \Tarantool\Client\Response\SuccessResponse([['pong']]);
              }
              return $next($request);
          }
      });
      
  2. Custom Packer/Unpacker:

    • Override PurePacker for custom serialization (e.g., Protobuf):
      $packer = new class implements \Tarantool\Client\Packer {
          public function pack(array $data) { /* ... */ }
          public function unpack(string $data) { /* ... */ }
      };
      $client = new \Tarantool\Client\Client(new \Tarantool\Client\Handler\DefaultHandler(
          $connection, $packer
      ));
      
  3. DSN Parsing:

    • Extend \Tarantool\Client\DsnParser to support custom URI schemes (e.g., tarantool://).
  4. Event Listeners:

    • Attach to Client::on() events (e.g., connect, disconnect) for lifecycle hooks:
      $client->on('connect', function () {
          \Log::info("Connected to Tarantool");
      });
      

Performance Tips

  1. Batch Operations:
    • Use multi() for bulk inserts/updates:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver