Skip to content

Commit

Permalink
Migrate new example
Browse files Browse the repository at this point in the history
  • Loading branch information
kelunik committed Nov 24, 2020
1 parent c77bb6f commit 3739788
Showing 1 changed file with 52 additions and 67 deletions.
119 changes: 52 additions & 67 deletions examples/streaming/3-large-response-slow-read.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
<?php

use Amp\File\File;
use Amp\File\StatCache;
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\HttpException;
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
use Amp\Loop;
use function Amp\delay;
use function Amp\getCurrentTime;

Expand All @@ -21,78 +17,67 @@ function formatBytes(int $size, int $precision = 2): string
return \round(1024 ** ($base - \floor($base)), $precision) . ' ' . $suffixes[(int) $base];
}

Loop::run(static function (): \Generator {
try {
$start = getCurrentTime();

// Instantiate the HTTP client
$client = HttpClientBuilder::buildDefault();

$request = new Request('https://1906714720.rsc.cdn77.org/img/cdn77-test-14mb.jpg');
$request->setBodySizeLimit(128 * 1024 * 1024); // 128 MB
$request->setTransferTimeout(120 * 1000); // 120 seconds

// Make an asynchronous HTTP request
$promise = $client->request($request);

// Client::request() is asynchronous! It doesn't return a response. Instead, it returns a promise to resolve the
// response at some point in the future when we've received the headers of the response. Here we use yield which
// pauses the execution of the current coroutine until the promise resolves. Amp will automatically continue the
// coroutine then.
/** @var Response $response */
$response = yield $promise;

// Output the results
\printf(
"HTTP/%s %d %s\r\n%s\r\n\r\n",
$response->getProtocolVersion(),
$response->getStatus(),
$response->getReason(),
(string) $response->getRequest()->getUri()
);

foreach ($response->getHeaders() as $field => $values) {
foreach ($values as $value) {
print "$field: $value\r\n";
}
}
try {
$start = getCurrentTime();

print "\n";
// Instantiate the HTTP client
$client = HttpClientBuilder::buildDefault();

$path = \tempnam(\sys_get_temp_dir(), "artax-streaming-");
$request = new Request('https://1906714720.rsc.cdn77.org/img/cdn77-test-14mb.jpg');
$request->setBodySizeLimit(128 * 1024 * 1024); // 128 MB
$request->setTransferTimeout(120 * 1000); // 120 seconds

/** @var File $file */
$file = yield Amp\File\open($path, "w");
// Make an asynchronous HTTP request
$response = $client->request($request);

$bytes = 0;
// Output the results
\printf(
"HTTP/%s %d %s\r\n%s\r\n\r\n",
$response->getProtocolVersion(),
$response->getStatus(),
$response->getReason(),
(string) $response->getRequest()->getUri()
);

// The response body is an instance of Payload, which allows buffering or streaming by the consumers choice.
// We could also use Amp\ByteStream\pipe() here, but we want to show some progress.
while (null !== $chunk = yield $response->getBody()->read()) {
yield $file->write($chunk);
$bytes += \strlen($chunk);
foreach ($response->getHeaders() as $field => $values) {
foreach ($values as $value) {
print "$field: $value\r\n";
}
}

yield delay(100);
print "\n";

printf("\33[2K\r%s with peak memory usage of %.2fMB.", formatBytes($bytes), (float) \memory_get_peak_usage(true) / 1024 / 1024);
}
$path = \tempnam(\sys_get_temp_dir(), "artax-streaming-");

$file = Amp\File\openFile($path, "w");

yield $file->close();
$bytes = 0;

print \sprintf(
"\rDone in %.2f seconds with peak memory usage of %.2fMB.\n",
(getCurrentTime() - $start) / 1000,
(float) \memory_get_peak_usage(true) / 1024 / 1024
);
// The response body is an instance of Payload, which allows buffering or streaming by the consumers choice.
// We could also use Amp\ByteStream\pipe() here, but we want to show some progress.
while (null !== $chunk = $response->getBody()->read()) {
$file->write($chunk);
$bytes += \strlen($chunk);

// We need to clear the stat cache, as we have just written to the file
StatCache::clear($path);
$size = yield Amp\File\size($path);
delay(100);

print \sprintf("%s has a size of %.2fMB\r\n", $path, (float) $size / 1024 / 1024);
} catch (HttpException $error) {
// If something goes wrong Amp will throw the exception where the promise was yielded.
// The HttpClient::request() method itself will never throw directly, but returns a promise.
echo $error;
printf("\33[2K\r%s with peak memory usage of %.2fMB.", formatBytes($bytes),
(float) \memory_get_peak_usage(true) / 1024 / 1024);
}
});

$file->close();

print \sprintf(
"\rDone in %.2f seconds with peak memory usage of %.2fMB.\n",
(getCurrentTime() - $start) / 1000,
(float) \memory_get_peak_usage(true) / 1024 / 1024
);

$size = Amp\File\getSize($path);

print \sprintf("%s has a size of %.2fMB\r\n", $path, (float) $size / 1024 / 1024);
} catch (HttpException $error) {
// If something goes wrong Amp will throw the exception where the promise was yielded.
// The HttpClient::request() method itself will never throw directly, but returns a promise.
echo $error;
}

0 comments on commit 3739788

Please sign in to comment.