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

Core Laravel Package

async-aws/core

AsyncAws Core provides the shared foundation for AsyncAws AWS clients, including request signing, HTTP utilities, configuration and credential handling. Also includes an STS client for authentication. Install via composer and build AWS integrations with a lightweight SDK.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require async-aws/core

Requires PHP 8.2+ and Symfony HTTP Client (or Guzzle).

  1. Basic Usage:

    use AsyncAws\Core\AwsClientFactory;
    use AsyncAws\Core\Credential\CredentialProvider;
    
    // Load credentials from default AWS config (~/.aws/credentials)
    $credentialProvider = CredentialProvider::createDefault();
    
    // Create a client factory
    $clientFactory = new AwsClientFactory($credentialProvider);
    
    // Use the factory to create clients (e.g., STS)
    $stsClient = $clientFactory->sts();
    
  2. First Use Case: Assume a role using STS:

    $result = $stsClient->assumeRole([
        'RoleArn' => 'arn:aws:iam::123456789012:role/MyRole',
        'RoleSessionName' => 'MySession'
    ]);
    
    $credentials = $result->getCredentials();
    

Key Entry Points

  • AwsClientFactory: Central hub for creating AWS service clients (STS, S3, etc.).
  • CredentialProvider: Manages AWS credentials (supports profiles, SSO, environment variables).
  • Configuration: Configures clients (region, endpoint, debug mode).

Implementation Patterns

1. Client Creation and Configuration

  • Dynamic Client Creation: Use AwsClientFactory to instantiate clients dynamically:

    $clientFactory = new AwsClientFactory($credentialProvider);
    $s3Client = $clientFactory->s3(); // Requires `async-aws/s3` package
    $ec2Client = $clientFactory->ec2(); // Requires `async-aws/ec2` package
    
  • Custom Endpoints: Override default endpoints (e.g., for localstack):

    $configuration = new Configuration([
        'endpoint' => 'http://localhost:4566',
        'region' => 'us-east-1',
    ]);
    $clientFactory = new AwsClientFactory($credentialProvider, $configuration);
    
  • Region Handling: Use @region in input objects for multi-region operations:

    $result = $s3Client->getObject([
        '@region' => 'eu-west-1',
        'Bucket' => 'my-bucket',
        'Key' => 'file.txt',
    ]);
    

2. Credential Management

  • SSO Support: Configure SSO credentials via SsoOidcProvider:

    $ssoProvider = new SsoOidcProvider(
        'https://my-sso-portal.awsapps.com/start',
        'my-account-id',
        'my-role-name'
    );
    $credentialProvider = new CredentialProvider($ssoProvider);
    
  • Environment Variables: Fallback to environment variables if no profile is specified:

    putenv('AWS_ACCESS_KEY_ID=AKIA...');
    putenv('AWS_SECRET_ACCESS_KEY=...');
    putenv('AWS_DEFAULT_REGION=us-east-1');
    
  • Credential Caching: Cache credentials to avoid repeated STS calls:

    $cache = new SymfonyCacheProvider(new FilesystemCache('/tmp/aws_cache'));
    $credentialProvider = new CredentialProvider($cache);
    

3. Request Handling

  • Presigned URLs: Generate presigned URLs for S3 objects:

    $presignedUrl = $s3Client->presign('getObject', [
        'Bucket' => 'my-bucket',
        'Key' => 'file.txt',
        'Expires' => '+1 hour',
    ]);
    
  • Streaming Responses: Handle large responses efficiently:

    $result = $s3Client->getObject(['Bucket' => 'my-bucket', 'Key' => 'large-file.zip']);
    $stream = $result->getBody();
    while ($chunk = $stream->read()) {
        // Process chunk
    }
    
  • Retryable Clients: Configure retry logic for transient failures:

    $httpClient = $clientFactory->createHttpClient([
        'retryable_status_codes' => [429, 500, 502, 503, 504],
    ]);
    

4. Testing and Mocking

  • Mock Responses: Use ResultMockFactory for unit testing:

    $mockFactory = new ResultMockFactory();
    $mockResult = $mockFactory->createSuccess([
        'Credentials' => [
            'AccessKeyId' => 'AKIA...',
            'SecretAccessKey' => '...',
            'SessionToken' => '...',
        ],
    ]);
    
    $stsClient->assumeRole(...)->willReturn($mockResult);
    
  • Failing Responses: Simulate AWS errors:

    $mockFactory->createFailing(
        new ClientException('InvalidAccessKeyId', 403, [], 'RequestId:...')
    );
    

5. Error Handling

  • Custom Exceptions: Map AWS error codes to custom exceptions via RequestContext:

    $context = new RequestContext();
    $context->addErrorMapping('InvalidAccessKeyId', InvalidCredentialsException::class);
    $result = $s3Client->getObject([...], $context);
    
  • Debugging: Enable debug logging:

    $configuration = new Configuration(['debug' => true]);
    

Gotchas and Tips

Common Pitfalls

  1. Region Mismatch:

    • Ensure the region in your Configuration matches the region in the AWS service.
    • Use @region in input objects for dynamic region switching.
    • Fix: Verify region consistency across clients and operations.
  2. Credential Expiry:

    • STS credentials expire (default: 1 hour). Handle refresh proactively:
      $credentials = $result->getCredentials();
      if ($credentials->isExpired()) {
          $credentials = $stsClient->getSessionToken()->getCredentials();
      }
      
  3. Chunked Requests:

    • Avoid chunked requests for S3 unless necessary (default sendChunkedBody: false).
    • Fix: Set 'sendChunkedBody' => true in Configuration if required.
  4. SSO Dependencies:

    • SSO requires async-aws/sso-oidc and league/oauth2-client.
    • Fix: Install dependencies explicitly:
      composer require async-aws/sso-oidc league/oauth2-client
      
  5. Endpoint Discovery:

    • Custom endpoints should not contain %region% or %service% placeholders (deprecated in v2.0).
    • Fix: Use static endpoints (e.g., 'endpoint' => 'https://s3.us-east-1.amazonaws.com').
  6. PHP 8.5+ Deprecations:

    • Avoid using null as an array offset (e.g., $array[null]).
    • Fix: Use isset($array['key']) or array_key_exists().
  7. Thread Safety:

    • AWS credentials and configurations are not thread-safe by default.
    • Fix: Use a cache provider (e.g., SymfonyCacheProvider) for shared environments.
  8. Large Responses:

    • Streaming responses (ResponseBodyStream) may fail if the underlying stream is closed prematurely.
    • Fix: Buffer responses in a temporary file:
      $configuration = new Configuration(['buffer_response' => true]);
      

Debugging Tips

  1. Enable Debug Mode:

    $configuration = new Configuration(['debug' => true]);
    

    Logs HTTP requests/responses to stderr.

  2. Inspect Raw Responses: Use getResponse() to access the underlying Psr\Http\Message\Response:

    $response = $result->getResponse();
    $body = (string) $response->getBody();
    
  3. Validate Inputs: Use Input::validate() to check input objects before sending requests:

    use AsyncAws\Core\Input;
    
    $input = new Input(['Bucket' => 'my-bucket', 'Key' => 'file.txt']);
    $input->validate();
    
  4. Check for Deprecated Methods:

    • Methods like getEndpointMetadata() are deprecated in v2.0. Use getEndpoint() instead.

Performance Optimizations

  1. Reuse Clients: Instantiate clients once and reuse them (e.g., in a service container):

    $container->bind(AwsClientFactory::class, function () {
        return new AwsClientFactory(CredentialProvider::createDefault());
    });
    
  2. Batch Operations: Use pagination and batching where possible (e.g., ListObjectsV2 with MaxKeys).

  3. Disable Retries for Idempotent Operations: Reduce latency for safe operations:

    $
    
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony