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

Longrunning Laravel Package

google/longrunning

Idiomatic PHP client for Google Long‑Running Operations API. Install via Composer and use with REST or gRPC to manage operations (poll, cancel, delete, list) across Google Cloud services. Part of google-cloud-php; authentication/debug guides included.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package:

    composer require google/longrunning
    

    For gRPC support (recommended for high-throughput scenarios):

    composer require google/longrunning google/grpc
    
  2. Authenticate (follow Google Cloud PHP Auth Guide):

    use Google\Auth\Credentials\ServiceAccountCredentials;
    use Google\Cloud\LongRunning\LongRunningClient;
    
    $credentials = ServiceAccountCredentials::fromStream(__DIR__.'/path/to/service-account.json');
    $client = new LongRunningClient(['credentials' => $credentials]);
    
  3. First use case: Poll an operation

    $operationName = 'projects/my-project/locations/global/operations/op-123';
    $operation = $client->getOperation($operationName);
    
    // Poll until completion (with exponential backoff)
    $result = $client->pollUntilDone($operation);
    

Where to Look First

  • API Documentation for operation metadata fields (e.g., done, error, response).
  • Samples in the Google Cloud PHP repo for real-world examples (e.g., BigQuery, Compute Engine).
  • Laravel Integration: Pair with ShouldQueue jobs to offload polling to queues (see Implementation Patterns).

Implementation Patterns

Core Workflows

1. Polling Operations in Laravel Jobs

Use ShouldQueue to decouple polling from the request lifecycle:

use Google\Cloud\LongRunning\LongRunningClient;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class PollGcpOperation implements ShouldQueue
{
    use Dispatchable, Queueable;

    public function __construct(
        protected string $operationName,
        protected LongRunningClient $client
    ) {}

    public function handle()
    {
        $operation = $this->client->getOperation($this->operationName);
        $result = $this->client->pollUntilDone($operation);

        // Store result or trigger next job
        $this->dispatch(new ProcessOperationResult($result));
    }
}

2. Exponential Backoff Polling

Customize retry logic for cost efficiency:

$operation = $client->getOperation($operationName);
$retryPolicy = new \Google\ApiCore\RetryPolicy([
    'maxAttempts' => 10,
    'initialBackoff' => 1.0, // seconds
    'maxBackoff' => 60.0,   // seconds
    'backoffFactor' => 2.0,
]);

$result = $client->pollUntilDone($operation, $retryPolicy);

3. Listing Operations with Partial Success

Handle batch operations where some resources succeed/fail:

$filter = 'done=true'; // Only completed operations
$operations = $client->listOperations(
    'projects/my-project/locations/global',
    ['filter' => $filter]
);

foreach ($operations->getOperations() as $op) {
    if ($op->getDone()) {
        if ($op->getError()) {
            // Handle partial failure
            logger()->error('Partial failure:', ['operation' => $op->getName()]);
        } else {
            // Process successful result
            $result = $op->getResponse();
        }
    }
}

4. Cancelling Operations

Abort long-running tasks (e.g., user-triggered cancellation):

$operationName = 'projects/my-project/locations/global/operations/op-123';
$client->cancelOperation($operationName);

5. gRPC vs. REST Trade-offs

  • Use gRPC for:
    • High-throughput scenarios (>50 concurrent operations).
    • Streaming methods (e.g., ListOperations with server-side pagination).
    • Lower latency (2–3x faster than REST).
  • Use REST for:
    • Simplicity (no ext-grpc dependency).
    • Debugging (easier to inspect HTTP requests).

Configure transport in the client:

$client = new LongRunningClient([
    'credentials' => $credentials,
    'transport' => 'grpc', // or 'rest'
]);

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Binding: Bind the client in AppServiceProvider for dependency injection:

    public function register()
    {
        $this->app->singleton(LongRunningClient::class, function ($app) {
            $credentials = ServiceAccountCredentials::fromStream(
                $app['path.to.service.account']
            );
            return new LongRunningClient(['credentials' => $credentials]);
        });
    }
    
  2. Horizon Dashboard Integration: Extend Horizon’s job table to display GCP operation statuses:

    // In a Horizon dashboard widget
    $operationName = $job->payload['operation_name'];
    $operation = $client->getOperation($operationName);
    return view('horizon.job', [
        'status' => $operation->getDone() ? 'Completed' : 'Running',
        'progress' => $operation->getMetadata()['progress'] ?? 0,
    ]);
    
  3. Event-Driven Polling: Use Laravel Events to trigger actions on operation completion:

    // After polling completes
    event(new GcpOperationCompleted($operationName, $result));
    

    Listen in an Event Service Provider:

    protected $listen = [
        GcpOperationCompleted::class => [
            SendSlackNotification::class,
            UpdateDatabase::class,
        ],
    ];
    

Debugging and Observability

  • Logging: Enable client logging for debugging:
    $client = new LongRunningClient([
        'credentials' => $credentials,
        'logger' => new \Monolog\Logger('gcp_operations'),
    ]);
    
  • Metrics: Track operation durations with Laravel Telescope or Prometheus:
    $start = microtime(true);
    $result = $client->pollUntilDone($operation);
    $duration = microtime(true) - $start;
    \App\Models\OperationMetric::create([
        'operation_name' => $operationName,
        'duration_seconds' => $duration,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Credential Handling:

    • Never hardcode credentials in your codebase. Use environment variables or Laravel’s config/services.php:
      'google' => [
          'service_account' => env('GOOGLE_SERVICE_ACCOUNT_JSON'),
      ],
      
    • Avoid untrusted credentials: The package warns against accepting credentials from untrusted sources (e.g., user uploads). Validate inputs rigorously.
  2. Operation Name Format:

    • Operation names are service-specific and must follow the format:
      projects/{project}/locations/{location}/operations/{operation_id}
      
    • Example for BigQuery:
      projects/my-project/locations/us/operations/op-123
      
    • Gotcha: Incorrect names cause NOT_FOUND errors. Double-check with the service’s documentation.
  3. gRPC Dependencies:

    • PHP 8.1+ required for gRPC support.
    • Install ext-grpc:
      pecl install grpc
      
    • Fallback to REST: If gRPC fails, the client defaults to REST (but loses streaming features).
  4. Exponential Backoff Misconfiguration:

    • Default backoff may be too aggressive for some services. Adjust RetryPolicy:
      $retryPolicy = new \Google\ApiCore\RetryPolicy([
          'initialBackoff' => 0.5, // Start with 500ms
          'maxBackoff' => 30.0,   // Cap at 30 seconds
      ]);
      
    • Avoid API quotas: Too many rapid retries can hit GCP’s rate limits.
  5. Partial Success Handling:

    • ListOperations returns unreachable resources if some operations fail. Check:
      $operations = $client->listOperations($parent, [
          'filter' => 'done=true',
          'partialSuccess' => true, // Enable partial success flag
      ]);
      
    • Gotcha: If partialSuccess is false, unreachable operations are omitted.
  6. Timeouts:

    • Default timeout: 60 seconds for gRPC, 30 seconds for REST.
    • Override globally:
      $client = new LongRunningClient([
          'timeout' => 120, // 120 seconds
      ]);
      
    • Per-operation: Use `pollUntil
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
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