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

Thrift Laravel Package

packaged/thrift

Laravel package for generating and running Apache Thrift services. Provides artisan commands and tooling to compile IDL, organize generated PHP code, and integrate Thrift clients/servers into your app for fast, typed RPC between services.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require packaged/thrift
    

    Ensure your system has the Thrift compiler (thrift) installed and in PATH.

  2. Basic Usage

    • Define a .thrift schema file (e.g., app/Contracts/User.thrift):
      namespace php user
      service UserService {
        string getName(1: i32 userId)
      }
      
    • Generate PHP classes:
      thrift --gen php app/Contracts/User.thrift
      
    • Load the generated client in Laravel:
      use User\UserService\Client;
      
      $transport = new THttpClient('http://thrift-server:8080');
      $protocol  = new TBinaryProtocol($transport);
      $client    = new Client($protocol);
      $result    = $client->getName(1); // Returns "John Doe"
      
  3. First Use Case

    • RPC Calls: Replace REST API calls with Thrift for high-performance microservices.
    • Schema Evolution: Use Thrift’s strict typing to enforce contracts between services.

Implementation Patterns

Workflows

  1. Service-to-Service Communication

    • Request/Response:
      $transport = new TSocket('thrift-server', 9090);
      $transport->open();
      $protocol = new TBinaryProtocol($transport);
      $client   = new UserService\Client($protocol);
      $result   = $client->getName(1);
      $transport->close();
      
    • Async Calls (with TNonblockingSocket):
      $socket = new TNonblockingSocket('thrift-server', 9090);
      $client = new UserService\Client(new TBinaryProtocol($socket));
      $client->getName(1, $result); // Non-blocking
      
  2. Event-Driven Patterns

    • Use Thrift’s TProcessor to handle events in a Laravel queue worker:
      $processor = new UserService\Processor(new UserServiceHandler());
      $transport = new TServerTransport('0.0.0.0', 9090);
      $server    = new TServer($processor, $transport);
      $server->serve(); // Run in a separate process (e.g., Laravel Horizon)
      
  3. Data Serialization

    • Serialize Eloquent models to Thrift structs:
      $user = User::find(1);
      $thriftUser = new UserService\User();
      $thriftUser->setId($user->id);
      $thriftUser->setName($user->name);
      

Integration Tips

  • Laravel Service Providers: Bind Thrift clients/factories in AppServiceProvider:
    $this->app->singleton(UserService\Client::class, function ($app) {
        $transport = new THttpClient(config('thrift.user_service_url'));
        return new UserService\Client(new TBinaryProtocol($transport));
    });
    
  • Middleware for Auth: Extend TTransport to inject headers:
    class AuthenticatedTransport extends THttpClient {
        public function __construct($url, $token) {
            parent::__construct($url);
            $this->setHeader('Authorization', 'Bearer ' . $token);
        }
    }
    
  • Testing: Use MockTransport for unit tests:
    $mockTransport = new class extends TTransport {
        public function read(...$args) { return 'mocked_response'; }
        public function write(...$args) {}
    };
    $client = new UserService\Client(new TBinaryProtocol($mockTransport));
    

Gotchas and Tips

Pitfalls

  1. Schema Changes

    • Thrift is not backward-compatible by default. Use optional fields and versioning:
      struct User {
        1: required i32 id,
        2: optional string name, // Add new fields with higher IDs
        3: optional string email // Versioned structs
      }
      
    • Regenerate all client/server classes after schema changes.
  2. Memory Leaks

    • Unclosed Transports: Always call $transport->close() or use try-finally:
      try {
          $transport->open();
          // ...
      } finally {
          $transport->close();
      }
      
    • Connection Pooling: Reuse TSocket/THttpClient objects instead of creating new ones per request.
  3. Protocol Mismatches

    • Ensure client and server use the same protocol (e.g., TBinaryProtocol). Mixing TCompactProtocol and TBinaryProtocol will fail silently.
  4. Laravel Caching

    • Thrift structs cannot be cached directly. Convert to arrays or JSON first:
      cache()->put('user', $thriftUser->toArray());
      

Debugging

  • Enable Verbose Logging:
    TTransport::setDebugOutput(true); // Logs raw Thrift traffic
    
  • Wireshark/TShark: Capture Thrift traffic on port 9090 (default) to inspect binary payloads:
    tshark -i any -Y "port 9090" -w thrift.pcap
    
  • Common Errors:
    • TTransportException: Check if the server is running and the port is correct.
    • TProtocolException: Schema mismatch (regenerate classes).
    • TApplicationException: Invalid method calls (verify service contract).

Extension Points

  1. Custom Protocols Extend TProtocol for domain-specific optimizations:

    class CustomProtocol extends TBinaryProtocol {
        public function writeString($str) {
            // Custom compression logic
            parent::writeString(gzcompress($str));
        }
    }
    
  2. Laravel HTTP Client Integration Wrap Thrift in a Laravel Macroable facade:

    if (!Http::hasMacro('thrift')) {
        Http::macro('thrift', function ($service, $method, $args) {
            $client = app($service);
            return $client->$method(...$args);
        });
    }
    

    Usage:

    $result = Http::thrift(UserService\Client::class, 'getName', [1]);
    
  3. Thrift + Laravel Events Dispatch events when Thrift calls complete:

    $client = new UserService\Client($protocol);
    event(new ThriftCallStarted(UserService\Client::class, 'getName', [1]));
    $result = $client->getName(1);
    event(new ThriftCallCompleted(UserService\Client::class, 'getName', $result));
    
  4. Performance Tuning

    • Buffer Size: Adjust TTransport buffer for large payloads:
      $socket = new TSocket('server', 9090);
      $socket->setSendTimeout(5000); // 5s timeout
      $socket->setRecvBuffer(1024 * 1024); // 1MB buffer
      
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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky