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’s LongRunning Operations API. Install via Composer, supports REST and optional gRPC for streaming, and integrates with Google Cloud PHP authentication and debugging guides. Beta but largely stable.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require google/longrunning
    

    Ensure ext-grpc is installed for gRPC support (recommended for high-throughput scenarios).

  2. Set Up Authentication: Use a service account key file (JSON) and configure credentials via the Google\Auth\Credentials class or environment variables:

    use Google\Auth\Credentials\ServiceAccountCredentials;
    use Google\LongRunning\LongRunningClient;
    
    $credentials = ServiceAccountCredentials::fromStream(__DIR__.'/path/to/service-account.json');
    $client = new LongRunningClient(['credentials' => $credentials]);
    
  3. First Use Case: Poll an Operation Trigger a GCP operation (e.g., via google/cloud-compute or another GCP SDK) and poll its status:

    $operationName = 'projects/my-project/regions/us-central1/operations/op-123456789';
    $operation = $client->getOperation($operationName);
    
    // Poll until completion with exponential backoff
    $result = $client->pollUntilDone($operation);
    
  4. Check Documentation:


Implementation Patterns

Core Workflows

1. Triggering and Polling Operations

  • Pattern: Use a GCP SDK (e.g., google/cloud-compute) to start an operation, then poll its status with LongRunningClient.
  • Example:
    // Start an operation (e.g., via Compute Engine SDK)
    $instance = $computeClient->instances->insert('my-project', 'my-zone', $config);
    $operationName = $instance->getName();
    
    // Poll the operation
    $operation = $client->getOperation($operationName);
    $result = $client->pollUntilDone($operation);
    

2. Cancelling Operations

  • Pattern: Cancel long-running operations programmatically (e.g., user-triggered cancellation in Laravel).
  • Example:
    $operationName = 'projects/my-project/regions/us-central1/operations/op-123456789';
    $client->cancelOperation($operationName);
    

3. Listing Operations

  • Pattern: List operations for a project/region to monitor batch jobs or debug failures.
  • Example:
    $filter = 'region=us-central1';
    $operations = $client->listOperations('projects/my-project', ['filter' => $filter]);
    foreach ($operations as $operation) {
        if ($operation->getStatus() === 'FAILED') {
            // Handle failure (e.g., log, notify user)
        }
    }
    

4. Exponential Backoff Polling

  • Pattern: Configure retry settings to optimize API calls and reduce costs.
  • Example:
    $client = new LongRunningClient([
        'credentials' => $credentials,
        'retrySettings' => [
            'maxAttempts' => 10,
            'initialBackoff' => 1.0, // seconds
            'maxBackoff' => 60.0,   // seconds
            'backoffFactor' => 2.0,
        ],
    ]);
    

5. Integrating with Laravel Jobs

  • Pattern: Use LongRunningClient in Laravel background jobs to poll GCP operations.
  • Example:
    use Google\LongRunning\LongRunningClient;
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class PollGcpOperation implements ShouldQueue
    {
        use Queueable;
    
        protected $operationName;
    
        public function __construct(string $operationName)
        {
            $this->operationName = $operationName;
        }
    
        public function handle(LongRunningClient $client)
        {
            $operation = $client->getOperation($this->operationName);
            $result = $client->pollUntilDone($operation);
            // Process $result (e.g., save to DB, notify user)
        }
    }
    

Integration Tips

1. Dependency Injection

Bind LongRunningClient in Laravel’s service container for easy access:

// config/app.php
'providers' => [
    // ...
    App\Providers\GoogleLongRunningServiceProvider::class,
];

// App\Providers\GoogleLongRunningServiceProvider.php
public function register()
{
    $this->app->singleton(LongRunningClient::class, function ($app) {
        $credentials = ServiceAccountCredentials::fromStream(storage_path('app/gcp-credentials.json'));
        return new LongRunningClient(['credentials' => $credentials]);
    });
}

2. Error Handling

  • Catch Google\ApiCore\ApiException for API errors (e.g., invalid operation names, permission denied).
  • Use Google\ApiCore\Operation\Operation methods like getError() to inspect failures:
    try {
        $result = $client->pollUntilDone($operation);
    } catch (ApiException $e) {
        $error = $operation->getError();
        logger()->error("GCP Operation Failed: {$error['message']}");
    }
    

3. gRPC vs. REST

  • Use gRPC for high-throughput scenarios (e.g., batch operations, >50 concurrent polls). Ensure ext-grpc is installed and configure the client:
    $client = new LongRunningClient([
        'credentials' => $credentials,
        'grpcOptions' => [
            'ssl_target_name_override' => 'your-service-account-id',
        ],
    ]);
    
  • Use REST for simplicity or environments where gRPC isn’t feasible.

4. Logging and Debugging

  • Enable debug logging to inspect API calls:
    $client = new LongRunningClient([
        'credentials' => $credentials,
        'logger' => new \Monolog\Logger('gcp', [
            new \Monolog\Handler\StreamHandler(storage_path('logs/gcp.log'), \Monolog\Logger::DEBUG),
        ]),
    ]);
    
  • Refer to the Debugging Guide for advanced debugging.

5. Partial Success Handling

  • Use the partial_success flag in listOperations to handle batch jobs where some resources succeed and others fail:
    $operations = $client->listOperations('projects/my-project', [
        'filter' => 'region=us-central1',
        'partial_success' => true,
    ]);
    

Gotchas and Tips

Pitfalls

1. Authentication Issues

  • Gotcha: Incorrect service account permissions or missing IAM roles (e.g., roles/longrunning.operations.getter).
  • Fix: Ensure the service account has the required roles for the GCP service (e.g., roles/compute.admin for Compute Engine).
  • Tip: Use Google\Auth\Credentials::fromStream() with a JSON key file and validate scopes:
    $credentials = ServiceAccountCredentials::fromStream($keyFilePath)
        ->withQuotaProject('your-project-id')
        ->withScopes([Google_Service_ComputeEngine::CLOUD_PLATFORM]);
    

2. Operation Name Format

  • Gotcha: Invalid operation name format (e.g., missing projects/ or regions/).
  • Fix: Use the correct format:
    projects/{PROJECT_ID}/regions/{REGION}/operations/{OPERATION_ID}
    
  • Tip: Extract operation names from GCP SDK responses (e.g., $instance->getName() in Compute Engine).

3. Polling Timeouts

  • Gotcha: Operations stuck in PENDING or RUNNING due to misconfigured polling.
  • Fix: Use pollUntilDone() with custom retry settings or implement a watchdog timeout:
    $startTime = time();
    while (true) {
        $operation = $client->getOperation($operationName);
        if ($operation->getDone()) {
            break;
        }
        if (time() - $startTime > 3600) { // 1-hour timeout
            throw new \RuntimeException("Operation timed out");
        }
        sleep(5);
    }
    

4. gRPC Configuration

  • Gotcha: gRPC failures due to missing ssl_target_name_override or incorrect channel settings.
  • Fix: Configure gRPC options explicitly:
    $client = new LongRunningClient([
        'credentials' => $credentials,
        'grpcOptions' => [
            'ssl_target_name_override' => 'your-service-account-id@your-project-id.iam.gserviceaccount.com
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui