xp-forge/aws

AWS 核心库,适用于 XP 框架

v2.6.0 2024-08-18 21:33 UTC

This package is auto-updated.

Last update: 2024-09-18 21:40:28 UTC


README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

提供常见 AWS 功能的低级且轻量级库(大小小于官方 PHP SDK 的 3%!

调用 lambda

use com\amazon\aws\{Credentials, ServiceEndpoint};
use util\Secret;
use util\cmd\Console;
use util\log\Logging;

$credentials= new Credentials($accessKey, new Secret($secretKey));

$api= (new ServiceEndpoint('lambda', $credentials))->in('eu-central-1')->version('2015-03-31');
$api->setTrace(Logging::all()->toConsole());

$r= $api->resource('/functions/greet/invocations')->transmit(['name' => getenv('USER')]);

Console::writeLine($r);
Console::writeLine($r->value());

凭证提供者

AWS 凭证存储在不同的位置,具体取决于运行环境。 CredentialProvider 类支持以下方式

  • 环境变量:使用 AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY 和(如果存在)AWS_SESSION_TOKEN
  • 共享凭证和配置文件:从 ~/.aws/config 和(如果存在)~/.aws/credentials 读取凭证(尊重通过环境变量设置的备用位置)
  • SSO:使用配置的 SSO 和 AWS CLI 的 login 命令创建的缓存的凭证,包括 SSO 会话支持
  • Amazon ECS 容器凭证:使用容器 API 获取(如果需要,刷新)凭证

查看 https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html

共享 S3 资源

use com\amazon\aws\{ServiceEndpoint, CredentialProvider};
use util\cmd\Console;

$s3= (new ServiceEndpoint('s3', CredentialProvider::default()))
  ->in('eu-central-1')
  ->using('my-bucket')
;
$link= $s3->sign('/path/to/resource.png', timeout: 180);

Console::writeLine($link);

将数据流式传输到 S3

use com\amazon\aws\api\SignatureV4;
use com\amazon\aws\{ServiceEndpoint, CredentialProvider};
use io\File;
use util\cmd\Console;

$s3= (new ServiceEndpoint('s3', CredentialProvider::default()))
  ->in('eu-central-1')
  ->using('my-bucket')
;

$file= new File('large.txt');
$file->open(File::READ);

try {
  $transfer= $s3->open('PUT', 'target/'.$file->filename, [
    'x-amz-content-sha256' => SignatureV4::UNSIGNED, // Or calculate from file
    'Content-Type'         => 'text/plain',
    'Content-Length'       => $file->size(),
  ]);
  while (!$file->eof()) {
    $transfer->write($file->read());
  }
  $response= $transfer->finish();

  Console::writeLine($response);
} finally {
  $file->close();
}

从 Bedrock AI 模型流式传输响应

查看 https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html

use com\amazon\aws\{ServiceEndpoint, CredentialProvider};
use util\cmd\Console;

$model= 'anthropic.claude-3-5-sonnet-20240620-v1:0';
$runtime= (new ServiceEndpoint('bedrock', CredentialProvider::default()))
  ->using('bedrock-runtime.')
  ->in('eu-central-1')
;

$response= $runtime->resource('/model/{0}/converse-stream', [$model])->transmit([
  'system' => [['text' => 'Use informal language']],
  'messages' => [
    ['role' => 'user', 'content' => [['text' => $argv[1]]]],
  ],
  'inferenceConfig' => [
    'maxTokens'   => 1000,
    'temperature' => 0.5,
  ],
]);
foreach ($response->events() as $event) {
  Console::writeLine($event->header(':event-type'), ': ', $event->value());
}

另请参阅