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. Installation:

    composer require google/longrunning
    

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

    pecl install grpc
    composer require google/longrunning-grpc
    
  2. Authentication: Configure a service account with the required GCP permissions (e.g., roles/cloud-platform.viewer for read-only operations). Use the google/auth package for authentication:

    use Google\Auth\Credentials\ServiceAccountCredentials;
    use Google\Cloud\LongRunning\LongRunningClient;
    
    $credentials = ServiceAccountCredentials::fromStream('path/to/service-account.json');
    $client = new LongRunningClient(['credentials' => $credentials]);
    
  3. First Use Case: Poll a long-running operation (e.g., from a Laravel job):

    use Google\Cloud\LongRunning\LongRunningClient;
    use Google\Cloud\LongRunning\Operation;
    
    $client = app(LongRunningClient::class); // Inject via Laravel service provider
    $operationName = 'projects/my-project/locations/my-location/operations/my-operation-id';
    
    $operation = $client->getOperation($operationName);
    
    // Poll until completion
    $result = $operation->pollUntilDone();
    $metadata = $result->getMetadata();
    $response = $result->getResponse();
    

Where to Look First

  • Official API Docs: Google LongRunning API Reference
  • Laravel Integration: Create a service provider to bind the authenticated client:
    // app/Providers/GoogleLongRunningServiceProvider.php
    public function register()
    {
        $this->app->singleton(LongRunningClient::class, function ($app) {
            $credentials = ServiceAccountCredentials::fromStream(config('services.google.credentials_path'));
            return new LongRunningClient(['credentials' => $credentials]);
        });
    }
    
  • gRPC Setup: Follow Google Cloud PHP gRPC Guide if targeting high-throughput scenarios.

Implementation Patterns

Usage Patterns

1. Polling Operations in Laravel Jobs

Use the pollUntilDone() method in a queued job to wait for GCP operation completion:

// app/Jobs/ProcessGcpOperation.php
public function handle(LongRunningClient $client)
{
    $operationName = 'projects/my-project/locations/my-location/operations/' . $this->operationId;
    $operation = $client->getOperation($operationName);

    // Poll with exponential backoff (customize as needed)
    $result = $operation->pollUntilDone([
        'timeout' => 3600, // 1 hour timeout
        'retryDelay' => 5, // Initial delay in seconds
        'maxRetryDelay' => 60, // Max delay in seconds
    ]);

    // Process the result
    $this->processResult($result->getResponse());
}

2. Cancelling Operations

Cancel a long-running operation (e.g., user-triggered cancellation):

public function cancelOperation(LongRunningClient $client, string $operationName)
{
    $client->cancelOperation($operationName);
    // Optionally notify the user via Laravel Notifications
}

3. Listing Operations

Fetch a list of operations (e.g., for admin dashboards):

public function listOperations(LongRunningClient $client, string $parent)
{
    $operations = $client->listOperations($parent, [
        'filter' => 'state=RUNNING', // Optional filter
        'pageSize' => 100,
    ]);

    foreach ($operations as $operation) {
        // Render in Blade or process further
    }
}

4. Streaming with gRPC

For high-throughput scenarios, use gRPC to stream operation updates:

// Requires gRPC extension and google/longrunning-grpc
$client = new \Google\Cloud\LongRunning\Grpc\LongRunningClient(['credentials' => $credentials]);
$stream = $client->listOperations($parent, ['stream' => true]);

foreach ($stream as $operation) {
    // Process each operation as it arrives
}

Workflows

Laravel Job Workflow for GCP Operations

  1. Trigger: Dispatch a job when a user action requires a GCP operation (e.g., file upload triggers BigQuery export).
    ProcessGcpOperation::dispatch($operationId)->onQueue('gcp');
    
  2. Poll: The job uses pollUntilDone() to wait for the operation to complete.
  3. Notify: On completion, notify the user via Laravel Notifications or update the UI (e.g., via Laravel Echo/Pusher).
  4. Retry: Handle failures with Laravel’s job retries or dead queues.

Admin Dashboard Integration

  • Use listOperations() to fetch all running operations for a project/location.
  • Display progress bars or cancellation buttons in a Blade view:
    @foreach($operations as $operation)
        <div class="operation-status">
            <progress value="{{ $operation->getProgress() }}" max="100"></progress>
            <button onclick="cancelOperation('{{ $operation->getName() }}')">Cancel</button>
        </div>
    @endforeach
    

Exponential Backoff Polling

Customize polling behavior to optimize API calls and costs:

$operation->pollUntilDone([
    'retryDelay' => 2, // Start with 2-second delay
    'maxRetryDelay' => 30, // Cap at 30 seconds
    'multiplier' => 2, // Exponential backoff multiplier
]);

Integration Tips

1. Laravel Service Provider

Centralize client configuration and authentication:

// config/services.php
'google' => [
    'credentials_path' => storage_path('app/google-credentials.json'),
    'project_id' => 'my-project-id',
];

// app/Providers/AppServiceProvider.php
public function boot()
{
    $this->app->singleton(LongRunningClient::class, function ($app) {
        $credentials = ServiceAccountCredentials::fromStream(
            $app['config']['services.google.credentials_path']
        );
        return new LongRunningClient([
            'credentials' => $credentials,
            'scopes' => [Google\Cloud\Core\Grpc\GrpcServiceClient::CLOUD_PLATFORM_SCOPE],
        ]);
    });
}

2. Horizon Monitoring

Extend Laravel Horizon to monitor GCP operations:

// app/Console/Commands/MonitorGcpOperations.php
public function handle()
{
    $client = app(LongRunningClient::class);
    $operations = $client->listOperations('projects/my-project');

    foreach ($operations as $operation) {
        Horizon::job(ProcessGcpOperation::class, ['operationId' => $operation->getName()]);
    }
}

3. Blade Directives for Operation Status

Create a Blade directive to render operation statuses:

// app/View/Composers/OperationStatusComposer.php
public function compose($view)
{
    $view->with('operationStatus', $this->getOperationStatus($operationName));
}

// In Blade:
@operationStatus($operationName)
    <div class="status-{{ $status }}">{{ $message }}</div>
@endoperationStatus

4. gRPC vs. REST Trade-offs

  • Use gRPC for:
    • High-throughput scenarios (>100 concurrent operations).
    • Low-latency requirements (e.g., real-time dashboards).
    • Streaming responses (e.g., live operation updates).
  • Use REST for:
    • Simplicity (no gRPC extension required).
    • Low-volume or one-off operations.
    • Environments where gRPC is not supported.

Gotchas and Tips

Pitfalls

1. Authentication Errors

  • Issue: Google\Auth\Exception\InvalidCredentialsException when the service account lacks permissions.
  • Fix: Ensure the service account has the correct IAM roles (e.g., roles/cloud-platform.viewer for read operations). Verify the credentials file path and JSON content.
  • Debug: Use the google/auth package’s debug tools:
    $credentials->debug();
    

2. Operation Not Found

  • Issue: Google\Cloud\LongRunning\Exception\NotFoundException when polling a non-existent operation.
  • Fix: Validate the operation name format (projects/{project}/locations/{location}/operations/{operation}). Use listOperations() to verify the operation exists before polling.
  • Tip: Implement a retry mechanism for transient "not found" errors.

3. Exponential Backoff Misconfiguration

  • Issue: Polling too aggressively, hitting API quotas or causing timeouts.
  • Fix: Configure `poll
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport