Skip to content
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

Install notification to packagist #45

Merged
merged 3 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Command/InstallCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
use Php\Pie\DependencyResolver\DependencyResolver;
use Php\Pie\Downloading\DownloadAndExtract;
use Php\Pie\Installing\Install;
use Php\Pie\Installing\InstallNotification\FailedToSendInstallNotification;
use Php\Pie\Installing\InstallNotification\InstallNotification;
use Php\Pie\Platform\TargetPlatform;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
Expand All @@ -25,6 +27,7 @@ public function __construct(
private readonly DownloadAndExtract $downloadAndExtract,
private readonly Build $build,
private readonly Install $install,
private readonly InstallNotification $installNotification,
) {
parent::__construct();
}
Expand Down Expand Up @@ -62,6 +65,17 @@ public function execute(InputInterface $input, OutputInterface $output): int

($this->install)($downloadedPackage, $targetPlatform, $output);

try {
$this->installNotification->send($targetPlatform, $downloadedPackage);
} catch (FailedToSendInstallNotification $failedToSendInstallNotification) {
if ($output->isVeryVerbose()) {
$output->writeln('Install notification did not send.');
if ($output->isDebug()) {
$output->writeln($failedToSendInstallNotification->__toString());
}
}
}

return Command::SUCCESS;
}
}
4 changes: 4 additions & 0 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
use Php\Pie\Downloading\UnixDownloadAndExtract;
use Php\Pie\Downloading\WindowsDownloadAndExtract;
use Php\Pie\Installing\Install;
use Php\Pie\Installing\InstallNotification\InstallNotification;
use Php\Pie\Installing\InstallNotification\SendInstallNotificationUsingGuzzle;
use Php\Pie\Installing\UnixInstall;
use Php\Pie\Installing\WindowsInstall;
use Php\Pie\Platform\TargetPhp\ResolveTargetPhpToPlatformRepository;
Expand Down Expand Up @@ -138,6 +140,8 @@ static function (ContainerInterface $container): Install {
},
);

$container->alias(SendInstallNotificationUsingGuzzle::class, InstallNotification::class);

return $container;
}
}
4 changes: 4 additions & 0 deletions src/DependencyResolver/Package.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public function __construct(
public readonly string $version,
public readonly string|null $downloadUrl,
public readonly array $configureOptions,
public readonly string|null $notificationUrl,
public readonly string $notificationVersion,
) {
}

Expand All @@ -48,6 +50,8 @@ public static function fromComposerCompletePackage(CompletePackageInterface $com
$completePackage->getPrettyVersion(),
$completePackage->getDistUrl(),
$configureOptions,
$completePackage->getNotificationUrl(),
$completePackage->getVersion(),
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace Php\Pie\Installing\InstallNotification;

use Php\Pie\Downloading\DownloadedPackage;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;

use function sprintf;

class FailedToSendInstallNotification extends RuntimeException
{
public static function fromFailedResponse(
DownloadedPackage $package,
RequestInterface $request,
ResponseInterface $response,
): self {
return new self(sprintf(
"Failed to notify package %s installation to %s [%d]:\n\n"
. "Request: %s\n\n"
. 'Response: %s',
$package->package->prettyNameAndVersion(),
$request->getUri(),
$response->getStatusCode(),
$request->getBody()->__toString(),
$response->getBody()->__toString(),
));
}
}
23 changes: 23 additions & 0 deletions src/Installing/InstallNotification/InstallNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Php\Pie\Installing\InstallNotification;

use Php\Pie\Downloading\DownloadedPackage;
use Php\Pie\Platform\TargetPlatform;

/**
* Send a notification to Packagist that the package was installed. This is
* used for package analytics (i.e. download counts)
*
* @internal This is not public API for PIE, so should not be depended upon unless you accept the risk of BC breaks
*/
interface InstallNotification
{
/** @throws FailedToSendInstallNotification */
public function send(
TargetPlatform $targetPlatform,
DownloadedPackage $package,
): void;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

declare(strict_types=1);

namespace Php\Pie\Installing\InstallNotification;

use Composer\Composer;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use Php\Pie\Downloading\DownloadedPackage;
use Php\Pie\Platform\TargetPlatform;

use function array_key_exists;
use function function_exists;
use function is_array;
use function json_decode;
use function json_encode;
use function php_uname;
use function sprintf;

/** @internal This is not public API for PIE, so should not be depended upon unless you accept the risk of BC breaks */
final class SendInstallNotificationUsingGuzzle implements InstallNotification
{
/** @psalm-suppress PossiblyUnusedMethod no direct reference; used in service locator */
public function __construct(private readonly ClientInterface $client)
{
}

public function send(
TargetPlatform $targetPlatform,
DownloadedPackage $package,
): void {
if ($package->package->notificationUrl === null) {
return;
}

$notificationRequest = new Request(
'POST',
$package->package->notificationUrl,
[
'Content-Type' => 'application/json',
/**
* User agent format is important! If it isn't right, Packagist
* silently discards the payload.
*
* @link https://github.com/composer/packagist/blob/fb75c17d75bc032cc88b997275d40077511d0cd9/src/Controller/ApiController.php#L296
* @link https://github.com/composer/packagist/blob/fb75c17d75bc032cc88b997275d40077511d0cd9/src/Util/UserAgentParser.php#L28-L38
*/
'User-Agent' => sprintf(
'Composer/%s (%s; %s; %s; %s)',
Composer::getVersion(),
function_exists('php_uname') ? php_uname('s') : 'Unknown',
function_exists('php_uname') ? php_uname('r') : 'Unknown',
'PHP ' . $targetPlatform->phpBinaryPath->version(),
'cURL ' . TargetPlatform::getCurlVersion(),
),
],
/**
* @link https://github.com/composer/packagist/blob/main/src/Controller/ApiController.php#L248
* @see \Composer\Installer\InstallationManager::notifyInstalls()
*/
json_encode([
'downloads' => [
[
'name' => $package->package->name,
'version' => $package->package->notificationVersion,
'downloaded' => false,
],
],
]),
);

$notificationResponse = $this->client->send(
$notificationRequest,
[RequestOptions::HTTP_ERRORS => false],
);

/** @var mixed $responseBody */
$responseBody = json_decode($notificationResponse->getBody()->__toString(), true);

if (
! is_array($responseBody)
|| ! array_key_exists('status', $responseBody)
|| $responseBody['status'] !== 'success'
) {
throw FailedToSendInstallNotification::fromFailedResponse(
$package,
$notificationRequest,
$notificationResponse,
);
}
}
}
16 changes: 16 additions & 0 deletions src/Platform/TargetPlatform.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
use Php\Pie\Platform\TargetPhp\PhpBinaryPath;

use function array_key_exists;
use function curl_version;
use function explode;
use function function_exists;
use function is_string;
use function posix_getuid;
use function preg_match;
use function trim;
Expand All @@ -29,6 +31,20 @@ public function __construct(
) {
}

public static function getCurlVersion(): string
{
static $curlVersion = null;

if ($curlVersion === null) {
$curlVersionList = curl_version();
$curlVersion = array_key_exists('version', $curlVersionList) && is_string($curlVersionList['version'])
? $curlVersionList['version']
: null;
}

return (string) $curlVersion;
}

public static function isRunningAsRoot(): bool
{
return function_exists('posix_getuid') && posix_getuid() === 0;
Expand Down
2 changes: 2 additions & 0 deletions test/integration/Building/UnixBuildTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public function testUnixBuildCanBuildExtension(): void
'0.1.0',
null,
[ConfigureOption::fromComposerJsonDefinition(['name' => 'enable-pie_test_ext'])],
null,
'0.1.0.0',
),
self::TEST_EXTENSION_PATH,
);
Expand Down
2 changes: 2 additions & 0 deletions test/integration/Installing/UnixInstallTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public function testUnixInstallCanInstallExtension(): void
'0.1.0',
null,
[ConfigureOption::fromComposerJsonDefinition(['name' => 'enable-pie_test_ext'])],
null,
'0.1.0.0',
),
self::TEST_EXTENSION_PATH,
);
Expand Down
2 changes: 2 additions & 0 deletions test/integration/Installing/WindowsInstallTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ public function testWindowsInstallCanInstallExtension(): void
'1.2.3',
null,
[],
null,
'1.2.3.0',
),
self::TEST_EXTENSION_PATH,
);
Expand Down
4 changes: 4 additions & 0 deletions test/unit/Command/CommandHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ public function testDownloadPackage(): void
'1.2.3',
'https://test-uri/',
[],
null,
'1.2.3.0',
));

$downloadAndExtract->expects(self::once())
Expand Down Expand Up @@ -155,6 +157,8 @@ public function testProcessingConfigureOptionsFromInput(): void
]),
ConfigureOption::fromComposerJsonDefinition(['name' => 'enable-thing']),
],
null,
'1.0.0.0',
);
$inputDefinition = new InputDefinition();
$inputDefinition->addOption(new InputOption('with-stuff', null, InputOption::VALUE_REQUIRED));
Expand Down
4 changes: 4 additions & 0 deletions test/unit/Downloading/AddAuthenticationHeaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ public function testAuthorizationHeaderIsAdded(): void
'1.2.3',
$downloadUrl,
[],
null,
'1.2.3.0',
),
$authHelper,
);
Expand All @@ -63,6 +65,8 @@ public function testExceptionIsThrownWhenPackageDoesNotHaveDownloadUrl(): void
'1.2.3',
null,
[],
null,
'1.2.3.0',
);

$this->expectException(RuntimeException::class);
Expand Down
2 changes: 2 additions & 0 deletions test/unit/Downloading/DownloadedPackageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public function testFromPackageAndExtractedPath(): void
'1.2.3',
null,
[],
null,
'1.2.3.0',
);

$extractedSourcePath = uniqid('/path/to/downloaded/package', true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public function testForPackage(): void
'1.2.3',
null,
[],
null,
'1.2.3.0',
);

$exception = CouldNotFindReleaseAsset::forPackage($package, ['something.zip', 'something2.zip']);
Expand All @@ -44,6 +46,8 @@ public function testForPackageWithMissingTag(): void
'1.2.3',
null,
[],
null,
'1.2.3.0',
);

$exception = CouldNotFindReleaseAsset::forPackageWithMissingTag($package);
Expand Down
6 changes: 6 additions & 0 deletions test/unit/Downloading/GithubPackageReleaseAssetsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ public function testUrlIsReturnedWhenFindingWindowsDownloadUrl(): void
'1.2.3',
'https://test-uri/' . uniqid('downloadUrl', true),
[],
null,
'1.2.3.0',
);

$releaseAssets = new GithubPackageReleaseAssets($authHelper, $guzzleMockClient, 'https://test-github-api-base-url.thephp.foundation');
Expand Down Expand Up @@ -126,6 +128,8 @@ public function testUrlIsReturnedWhenFindingWindowsDownloadUrlWithCompilerAndThr
'1.2.3',
'https://test-uri/' . uniqid('downloadUrl', true),
[],
null,
'1.2.3.0',
);

$releaseAssets = new GithubPackageReleaseAssets($authHelper, $guzzleMockClient, 'https://test-github-api-base-url.thephp.foundation');
Expand Down Expand Up @@ -164,6 +168,8 @@ public function testFindWindowsDownloadUrlForPackageThrowsExceptionWhenAssetNotF
'1.2.3',
'https://test-uri/' . uniqid('downloadUrl', true),
[],
null,
'1.2.3.0',
);

$releaseAssets = new GithubPackageReleaseAssets($authHelper, $guzzleMockClient, 'https://test-github-api-base-url.thephp.foundation');
Expand Down
2 changes: 2 additions & 0 deletions test/unit/Downloading/UnixDownloadAndExtractTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ public function testInvoke(): void
'1.2.3',
$downloadUrl,
[],
null,
'1.2.3.0',
);

$downloadedPackage = $unixDownloadAndExtract->__invoke($targetPlatform, $requestedPackage);
Expand Down
2 changes: 2 additions & 0 deletions test/unit/Downloading/WindowsDownloadAndExtractTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ public function testInvoke(): void
'1.2.3',
'https://test-uri/' . uniqid('downloadUrl', true),
[],
null,
'1.2.3.0',
);

$downloadedPackage = $windowsDownloadAndExtract->__invoke($targetPlatform, $requestedPackage);
Expand Down
Loading