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

Cloud Core Laravel Package

google/cloud-core

Core infrastructure library for Google Cloud PHP clients. Provides shared components like authentication, retries, request handling, and utilities used across Google Cloud service packages. Not intended for direct use; typically installed as a dependency.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require google/cloud-core
    

    Note: This package is not used directly—it’s a dependency for other Google Cloud PHP packages (e.g., google/cloud-storage, google/cloud-bigquery). Install the specific service package instead.

  2. First Use Case: Initialize a Google Cloud client (e.g., Storage) with authentication:

    use Google\Cloud\Core\Authentication\CredentialsLoader;
    use Google\Cloud\Storage\StorageClient;
    
    $credentials = (new CredentialsLoader())->makeCredentials();
    $storage = new StorageClient(['credentials' => $credentials]);
    
    • Key Files: The package auto-detects credentials from:
      • Environment variable GOOGLE_APPLICATION_CREDENTIALS (JSON key file path).
      • Default locations (~/.config/gcloud/application_default_credentials.json).
      • ADC (Application Default Credentials) for GCP environments (e.g., Cloud Run, GKE).
  3. Where to Look First:

    • API Documentation: Core traits, exceptions, and utilities.
    • Debugging Guide: Enable debug logging with:
      putenv('GOOGLE_CLOUD_DEBUG=1'); // Logs HTTP requests/responses
      
    • Service-Specific Packages: For actual usage, refer to packages like google/cloud-storage or google/cloud-bigquery, which build on google/cloud-core.

Implementation Patterns

1. Authentication Workflows

Standardized Credential Handling

  • Laravel Service Provider Pattern: Centralize credential loading in a Laravel service provider to avoid repetition:
    // app/Providers/GoogleCloudServiceProvider.php
    public function register()
    {
        $this->app->singleton('google.credentials', function () {
            return (new \Google\Cloud\Core\Authentication\CredentialsLoader())
                ->makeCredentials();
        });
    }
    
    • Inject credentials into other services:
      $storage = new \Google\Cloud\Storage\StorageClient([
          'credentials' => $this->app->make('google.credentials'),
      ]);
      

Environment-Based Credentials

  • Use .env for flexibility:
    GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
    
    • The package auto-loads credentials from this path if set.

ADC for GCP Environments

  • In Cloud Run, GKE, or Compute Engine, ADC is pre-configured. No manual setup needed:
    $client = new \Google\Cloud\PubSub\PubSubClient(); // Automatically uses ADC
    

2. Retry and Resilience

Exponential Backoff

  • Enable retry policies for transient failures (e.g., rate limits, network issues):
    $storage = new \Google\Cloud\Storage\StorageClient([
        'retry' => [
            'max_attempts' => 3,
            'timeout' => 30.0, // seconds
        ],
    ]);
    
    • Custom Retry Logic: Extend Google\Cloud\Core\Retry\RetryPolicy for service-specific rules.

Idempotency and Conflict Resolution

  • Use Google\Cloud\Core\Idempotency\IdempotencyMiddleware for APIs supporting idempotent operations (e.g., Pub/Sub):
    $pubsub = new \Google\Cloud\PubSub\PubSubClient([
        'middleware' => [new \Google\Cloud\Core\Idempotency\IdempotencyMiddleware()],
    ]);
    

3. Request Validation

Options Validation

  • Validate API options before sending requests (e.g., ensure required fields are present):
    use Google\Cloud\Core\ApiHelperTrait;
    
    class MyService {
        use ApiHelperTrait;
    
        public function upload($bucket, $object, $source) {
            $options = [
                'name' => $object,
                'source' => $source,
            ];
            $this->validateOptions($options, [
                'name' => 'string',
                'source' => 'string|resource',
            ]);
            // Proceed with upload
        }
    }
    
    • Custom Validators: Implement Google\Cloud\Core\OptionsValidator\ValidatorInterface for complex rules.

4. Debugging and Observability

Debug Logging

  • Enable debug logs for HTTP traffic:
    putenv('GOOGLE_CLOUD_DEBUG=1');
    putenv('GOOGLE_CLOUD_DEBUG_LEVEL=5'); // Verbose (0–5)
    
    • Logs appear in stderr (useful for Cloud Logging integration).

Distributed Tracing

  • Integrate with OpenTelemetry or Google Cloud Trace:
    use Google\Cloud\Core\Trace\TraceContext;
    
    $traceContext = new TraceContext();
    $traceContext->addSpan('my_operation', ['custom_attribute' => 'value']);
    
    • Laravel Integration: Use middleware to propagate traces:
      $request->headers->set('x-cloud-trace-context', $traceContext->toHeader());
      

5. Emulator Support

Local Development

  • Test against Google Cloud emulators (e.g., Firestore, Pub/Sub):
    $firestore = new \Google\Cloud\Firestore\FirestoreClient([
        'emulatorHost' => 'localhost:8080',
        'projectId' => 'my-project',
    ]);
    
    • Environment Variable: Set GOOGLE_CLOUD_PROJECT for emulator projects.

Gotchas and Tips

1. Authentication Pitfalls

Deprecated keyFile/keyFilePath Options

  • Issue: These options are deprecated in favor of GOOGLE_APPLICATION_CREDENTIALS.
    // ❌ Deprecated (still works but warns)
    $client = new \Google\Cloud\Storage\StorageClient([
        'keyFile' => '/path/to/key.json',
    ]);
    
    • Fix: Use environment variables or ADC instead.

ADC in Non-GCP Environments

  • Issue: ADC fails silently in local/dev environments without proper setup.
    • Fix: Explicitly load credentials:
      $credentials = (new \Google\Cloud\Core\Authentication\CredentialsLoader())
          ->fromFile('/path/to/service-account.json');
      

Service Account Permissions

  • Gotcha: Missing permissions (e.g., storage.objects.get) cause Google\Cloud\Core\Exception\GoogleException.
    • Tip: Use gcloud auth print-access-token to test permissions locally.

2. Retry and Timeout Quirks

Retry Overrides

  • Issue: Retry policies may conflict with service-specific defaults.
    • Tip: Set retry at the client level (not per-operation):
      $client = new \Google\Cloud\BigQuery\BigQueryClient([
          'retry' => ['max_attempts' => 5],
      ]);
      

Timeouts

  • Gotcha: Default timeouts (e.g., 60s) may be too short for large operations.
    • Fix: Adjust timeouts per-operation:
      $client->upload(
          $bucket,
          $object,
          $source,
          ['timeout' => 300] // 5 minutes
      );
      

3. Validation and Type Safety

Strict Option Validation

  • Gotcha: validateOptions() throws Google\Cloud\Core\Exception\InvalidArgumentException for invalid types.
    • Tip: Use PHP 8.2+ union types for flexibility:
      $this->validateOptions($options, [
          'name' => 'string|null',
          'source' => 'string|resource|array',
      ]);
      

Protobuf Schema Mismatches

  • Issue: Custom protobuf messages may not align with Google’s schemas.
    • Fix: Use Google\Cloud\Core\Protobuf\Message for validation:
      $message = new \Google\Cloud\BigQuery\V2\QueryRequest();
      $message->setQuery('SELECT * FROM `dataset.table`');
      

4. Debugging and Performance

Debug Logging Overhead

  • Gotcha: GOOGLE_CLOUD_DEBUG=1 adds significant overhead (~20–30% latency).
    • Tip: Disable in production:
      if (app()->environment('production')) {
          putenv('GOOGLE_CLOUD_DEBUG=0');
      }
      

Memory Leaks in Streaming

  • Issue: Large streams (e.g., GCS downloads) may exhaust memory.
    • Fix: Use chunked reading:
      $object = $storage->bucket($bucket)->object($object);
      
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope