Skip to content

Commit

Permalink
perf(app): optimize download performance
Browse files Browse the repository at this point in the history
- Move the download logic inside a timebox to limit execution time
- Use a progress callback to track the download progress
- Display progress information during  the download
- Finish the progress when the download is complete
  • Loading branch information
guanguans committed Oct 17, 2024
1 parent eb9ffc6 commit 9630046
Showing 1 changed file with 25 additions and 20 deletions.
45 changes: 25 additions & 20 deletions app/Music.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Traits\Tappable;
use Laravel\Prompts\Progress;
use Psr\Http\Message\ResponseInterface;
use function Laravel\Prompts\progress;

final class Music implements Contracts\HttpClientFactory, Contracts\Music
Expand Down Expand Up @@ -80,30 +81,34 @@ public function search(string $keyword, array $sources = []): Collection
/**
* @psalm-suppress UnusedVariable
*
* @throws \Throwable
* @throws GuzzleException
*/
public function download(string $url, string $savedPath): void
{
$this->createHttpClient()->get($url, [
'sink' => $savedPath,
'progress' => static function (int $totalDownload, int $downloaded) use (&$progress, $savedPath): void {
if (0 === $totalDownload || 0 === $downloaded || 'submit' === $progress?->state) {
return;
}

if (!$progress instanceof Progress) {
/** @noinspection PhpVoidFunctionResultUsedInspection */
$progress = tap(progress($savedPath, $totalDownload))->start();
}

if ($totalDownload === $downloaded) {
$progress->finish();
}

$progress->progress = $downloaded;
$progress->render();
},
]);
$this->timebox->call(
fn (): ResponseInterface => $this->createHttpClient()->get($url, [
'sink' => $savedPath,
'progress' => static function (int $totalDownload, int $downloaded) use (&$progress, $savedPath): void {
if (0 === $totalDownload || 0 === $downloaded || 'submit' === $progress?->state) {
return;
}

if (!$progress instanceof Progress) {
/** @noinspection PhpVoidFunctionResultUsedInspection */
$progress = tap(progress($savedPath, $totalDownload))->start();
}

if ($totalDownload === $downloaded) {
$progress->finish();
}

$progress->progress = $downloaded;
$progress->render();
},
]),
$this->minCallMicroseconds
);
}

public function setMeting(Meting $meting): self
Expand Down

0 comments on commit 9630046

Please sign in to comment.