-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adapt for latest http-client #10
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
c996d2b
Adapt for latest http-client
danog a65379b
Adapt and add guzzle AmpHandler
danog 9de3766
Cleanup
danog 6ac3f25
Add support for timeout options
danog 7cf81c4
Remove useless deps
danog d84f024
Fixup psalm
danog e68822c
Implement proxy and remaining options except decode_content and socks…
danog 0325bea
Add socks5 support
danog 19e68f2
Fix?
danog 1489b21
Implement DNS type restriction
danog e642ea1
Improve curl
danog 5643671
Add support for sink option
danog 62d5600
Cache all custom client instances
danog 775de5b
Do not complain about curl options for now
danog File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,12 @@ | ||
<?php | ||
|
||
$config = new Amp\CodeStyle\Config; | ||
|
||
$config->getFinder() | ||
->in(__DIR__ . '/examples') | ||
->in(__DIR__ . '/src') | ||
->in(__DIR__ . '/test'); | ||
->in(__DIR__ . "/examples") | ||
->in(__DIR__ . "/src") | ||
->in(__DIR__ . "/test"); | ||
|
||
$cacheDir = getenv('TRAVIS') ? getenv('HOME') . '/.php-cs-fixer' : __DIR__; | ||
|
||
$config->setCacheFile($cacheDir . '/.php_cs.cache'); | ||
|
||
return $config; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,18 @@ | ||
<?php | ||
<?php declare(strict_types=1); | ||
|
||
use Amp\Http\Client\Psr7\PsrAdapter; | ||
use Amp\Http\Client\Request; | ||
use Amp\Http\Client\Psr7\AmpHandler; | ||
use GuzzleHttp\Client; | ||
use Laminas\Diactoros\RequestFactory; | ||
use Laminas\Diactoros\ResponseFactory; | ||
use GuzzleHttp\HandlerStack; | ||
|
||
use function Amp\async; | ||
use function Amp\ByteStream\getStdout; | ||
|
||
require __DIR__ . '/../vendor/autoload.php'; | ||
|
||
$psrAdapter = new PsrAdapter(new RequestFactory, new ResponseFactory); | ||
$client = new Client(['handler' => HandlerStack::create(new AmpHandler)]); | ||
|
||
$request = new Request('https://api.github.com/'); | ||
$future = async($client->get(...), 'https://api.github.com/', ['delay' => 1000]); | ||
|
||
$psrResponse = (new Client)->send($psrAdapter->toPsrRequest($request)); | ||
$response = $psrAdapter->fromPsrResponse($psrResponse, $request); | ||
getStdout()->write("First output: ".$client->get('https://api.github.com/')->getBody().PHP_EOL); | ||
|
||
print $response->getBody()->buffer(); | ||
getStdout()->write("Deferred output: ".$future->await()->getBody().PHP_EOL); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,13 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<phpunit | ||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.0/phpunit.xsd" | ||
bootstrap="vendor/autoload.php" | ||
colors="true" | ||
> | ||
<testsuites> | ||
<testsuite name="Main"> | ||
<directory>test</directory> | ||
</testsuite> | ||
</testsuites> | ||
<filter> | ||
<whitelist> | ||
<directory suffix=".php">src</directory> | ||
</whitelist> | ||
</filter> | ||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true"> | ||
<coverage> | ||
<include> | ||
<directory suffix=".php">src</directory> | ||
</include> | ||
</coverage> | ||
<testsuites> | ||
<testsuite name="Main"> | ||
<directory>test</directory> | ||
</testsuite> | ||
</testsuites> | ||
</phpunit> | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<files psalm-version="5.14.1@b9d355e0829c397b9b3b47d0c0ed042a8a70284d"> | ||
<file src="src/AmpHandler.php"> | ||
<PossiblyNullReference> | ||
<code>fromPsrRequest</code> | ||
</PossiblyNullReference> | ||
</file> | ||
<file src="src/PsrAdapter.php"> | ||
<ArgumentTypeCoercion> | ||
<code><![CDATA[$source->getMethod()]]></code> | ||
<code><![CDATA[$source->getProtocolVersion()]]></code> | ||
<code><![CDATA[[$source->getProtocolVersion()]]]></code> | ||
</ArgumentTypeCoercion> | ||
</file> | ||
</files> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,207 @@ | ||
<?php declare(strict_types=1); | ||
|
||
namespace Amp\Http\Client\Psr7; | ||
|
||
use Amp\CancelledException; | ||
use Amp\DeferredCancellation; | ||
use Amp\Dns\DnsRecord; | ||
use Amp\File\File; | ||
use Amp\Http\Client\Connection\DefaultConnectionFactory; | ||
use Amp\Http\Client\Connection\UnlimitedConnectionPool; | ||
use Amp\Http\Client\HttpClient; | ||
use Amp\Http\Client\HttpClientBuilder; | ||
use Amp\Http\Tunnel\Http1TunnelConnector; | ||
use Amp\Http\Tunnel\Https1TunnelConnector; | ||
use Amp\Http\Tunnel\Socks5TunnelConnector; | ||
use Amp\Socket\Certificate; | ||
use Amp\Socket\ClientTlsContext; | ||
use Amp\Socket\ConnectContext; | ||
use AssertionError; | ||
use GuzzleHttp\Promise\Promise; | ||
use GuzzleHttp\Promise\PromiseInterface; | ||
use GuzzleHttp\Psr7\Request; | ||
use GuzzleHttp\Psr7\Response; | ||
use GuzzleHttp\Psr7\Uri; | ||
use GuzzleHttp\RequestOptions; | ||
use GuzzleHttp\Utils; | ||
use Psr\Http\Message\RequestFactoryInterface; | ||
use Psr\Http\Message\RequestInterface; | ||
use Psr\Http\Message\ResponseFactoryInterface; | ||
use Psr\Http\Message\ResponseInterface; | ||
use Throwable; | ||
|
||
use function Amp\async; | ||
use function Amp\ByteStream\pipe; | ||
use function Amp\delay; | ||
use function Amp\File\openFile; | ||
|
||
/** | ||
* Handler for guzzle which uses amphp/http-client. | ||
*/ | ||
final class AmpHandler | ||
{ | ||
private static ?PsrAdapter $psrAdapter; | ||
private readonly HttpClient $client; | ||
/** @var array<string, HttpClient> */ | ||
private array $cachedClients = []; | ||
public function __construct(?HttpClient $client = null) | ||
{ | ||
if (!\interface_exists(PromiseInterface::class)) { | ||
throw new AssertionError("Please require guzzle to use the guzzle AmpHandler!"); | ||
} | ||
$this->client = $client ?? ( | ||
(new HttpClientBuilder) | ||
->followRedirects(0) | ||
->build() | ||
); | ||
self::$psrAdapter ??= new PsrAdapter(new class implements RequestFactoryInterface { | ||
public function createRequest(string $method, $uri): RequestInterface | ||
{ | ||
return new Request($method, $uri); | ||
} | ||
}, new class implements ResponseFactoryInterface { | ||
public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface | ||
{ | ||
return new Response($code, reason: $reasonPhrase); | ||
} | ||
}); | ||
} | ||
|
||
public function __invoke(RequestInterface $request, array $options): PromiseInterface | ||
{ | ||
if (isset($options['curl'])) { | ||
//throw new AssertionError("Cannot provide curl options when using AMP backend!"); | ||
} | ||
$deferred = new DeferredCancellation; | ||
$cancellation = $deferred->getCancellation(); | ||
$future = async(function () use ($request, $options, $cancellation) { | ||
if (isset($options['delay'])) { | ||
delay($options['delay'] / 1000.0, cancellation: $cancellation); | ||
} | ||
/** @psalm-suppress PossiblyNullReference Initialized in the constructor */ | ||
$request = self::$psrAdapter->fromPsrRequest($request); | ||
if (isset($options[RequestOptions::TIMEOUT])) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. also this: this is not portable |
||
$request->setTransferTimeout((float) $options[RequestOptions::TIMEOUT]); | ||
$request->setInactivityTimeout((float) $options[RequestOptions::TIMEOUT]); | ||
} | ||
if (isset($options[RequestOptions::CONNECT_TIMEOUT])) { | ||
$request->setTcpConnectTimeout((float) $options[RequestOptions::CONNECT_TIMEOUT]); | ||
} | ||
|
||
$client = $this->client; | ||
if (isset($options[RequestOptions::CERT]) || | ||
isset($options[RequestOptions::PROXY]) || ( | ||
isset($options[RequestOptions::VERIFY]) | ||
&& $options[RequestOptions::VERIFY] !== true | ||
) || | ||
isset($options[RequestOptions::FORCE_IP_RESOLVE]) | ||
) { | ||
$cacheKey = []; | ||
foreach ([RequestOptions::FORCE_IP_RESOLVE, RequestOptions::VERIFY, RequestOptions::PROXY, RequestOptions::CERT] as $k) { | ||
$cacheKey[$k] = $options[$k] ?? null; | ||
} | ||
$cacheKey = json_encode($cacheKey); | ||
if (isset($this->cachedClients[$cacheKey])) { | ||
$client = $this->cachedClients[$cacheKey]; | ||
} else { | ||
$tlsContext = null; | ||
if (isset($options[RequestOptions::CERT])) { | ||
$tlsContext ??= new ClientTlsContext(); | ||
if (\is_string($options[RequestOptions::CERT])) { | ||
$tlsContext = $tlsContext->withCertificate(new Certificate( | ||
$options[RequestOptions::CERT], | ||
$options[RequestOptions::SSL_KEY] ?? null, | ||
)); | ||
} else { | ||
$tlsContext = $tlsContext->withCertificate(new Certificate( | ||
$options[RequestOptions::CERT][0], | ||
$options[RequestOptions::SSL_KEY] ?? null, | ||
$options[RequestOptions::CERT][1] | ||
)); | ||
} | ||
} | ||
if (isset($options[RequestOptions::VERIFY])) { | ||
$tlsContext ??= new ClientTlsContext(); | ||
if ($options[RequestOptions::VERIFY] === false) { | ||
$tlsContext = $tlsContext->withoutPeerVerification(); | ||
} elseif (\is_string($options[RequestOptions::VERIFY])) { | ||
$tlsContext = $tlsContext->withCaFile($options[RequestOptions::VERIFY]); | ||
} | ||
} | ||
|
||
$connector = null; | ||
if (isset($options[RequestOptions::PROXY])) { | ||
if (!\is_array($options['proxy'])) { | ||
$connector = $options['proxy']; | ||
} else { | ||
$scheme = $request->getUri()->getScheme(); | ||
if (isset($options['proxy'][$scheme])) { | ||
$host = $request->getUri()->getHost(); | ||
if (!isset($options['proxy']['no']) || !Utils::isHostInNoProxy($host, $options['proxy']['no'])) { | ||
$connector = $options['proxy'][$scheme]; | ||
} | ||
} | ||
} | ||
|
||
if ($connector !== null) { | ||
$connector = new Uri($connector); | ||
$connector = match ($connector->getScheme()) { | ||
'http' => new Http1TunnelConnector($connector->getHost().':'.$connector->getPort()), | ||
'https' => new Https1TunnelConnector($connector->getHost().':'.$connector->getPort(), new ClientTlsContext($connector->getHost())), | ||
'socks5' => new Socks5TunnelConnector($connector->getHost().':'.$connector->getPort()) | ||
}; | ||
} | ||
} | ||
|
||
$connectContext = new ConnectContext; | ||
if ($tlsContext) { | ||
$connectContext = $connectContext->withTlsContext($tlsContext); | ||
} | ||
if (isset($options[RequestOptions::FORCE_IP_RESOLVE])) { | ||
$connectContext->withDnsTypeRestriction(match ($options[RequestOptions::FORCE_IP_RESOLVE]) { | ||
'v4' => DnsRecord::A, | ||
'v6' => DnsRecord::AAAA, | ||
}); | ||
} | ||
|
||
$client = (new HttpClientBuilder) | ||
->usingPool(new UnlimitedConnectionPool(new DefaultConnectionFactory(connector: $connector, connectContext: $connectContext))) | ||
->build(); | ||
|
||
$this->cachedClients[$cacheKey] = $client; | ||
} | ||
} | ||
if (isset($options['amp']['protocols'])) { | ||
$request->setProtocolVersions($options['amp']['protocols']); | ||
} | ||
$response = $client->request( | ||
$request, | ||
$cancellation | ||
); | ||
if (isset($options[RequestOptions::SINK])) { | ||
if (!\is_string($options[RequestOptions::SINK])) { | ||
throw new AssertionError("Only a file name can be provided as sink!"); | ||
} | ||
if (!\interface_exists(File::class)) { | ||
throw new AssertionError("Please require amphp/file to use the sink option!"); | ||
} | ||
$f = openFile($options[RequestOptions::SINK], 'w'); | ||
pipe($response->getBody(), $f, $cancellation); | ||
} | ||
return self::$psrAdapter->toPsrResponse($response); | ||
}); | ||
$future->ignore(); | ||
$promise = new Promise(function () use ($future, $cancellation, &$promise) { | ||
try { | ||
$promise->resolve($future->await()); | ||
} catch (CancelledException $e) { | ||
if (!$cancellation->isRequested()) { | ||
$promise->reject($e); | ||
} | ||
} catch (Throwable $e) { | ||
$promise->reject($e); | ||
} | ||
}, $deferred->cancel(...)); | ||
return $promise; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is the line that hardcodes guzzle's PSR-7