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

Implement provider-includes #281

Merged
merged 3 commits into from
Sep 23, 2020
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
2 changes: 2 additions & 0 deletions src/Command/ProxySyncMetadataCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ protected function execute(InputInterface $input, OutputInterface $output)
$this->register->all()->forEach(function (Proxy $proxy) use ($lock): void {
$proxy->syncMetadata();
$lock->refresh();
$proxy->updateLatestProviders();
$lock->refresh();
});
} finally {
$lock->release();
Expand Down
82 changes: 78 additions & 4 deletions src/Controller/ProxyController.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,18 @@ public function __construct(ProxyRegister $register)
}

/**
* @Route("/packages.json", host="repo.{domain}", name="packages", methods={"GET"}, defaults={"domain"="%domain%"}, requirements={"domain"="%domain%"})
* @Route(
* "/packages.json",
* host="repo.{domain}",
* name="packages",
* methods={"GET"},
* defaults={"domain"="%domain%"},
* requirements={"domain"="%domain%"}
* )
*/
public function packages(Request $request): JsonResponse
{
$providerHash = $this->register->getByHost('packagist.org')->latestProviderHash();
$response = (new JsonResponse([
'notify-batch' => $this->generateUrl('package_downloads', [], RouterInterface::ABSOLUTE_URL),
'providers-url' => '/p/%package%$%hash%.json',
Expand All @@ -46,6 +54,7 @@ public function packages(Request $request): JsonResponse
],
],
'providers-lazy-url' => '/p/%package%',
'provider-includes' => $providerHash !== null ? ['p/provider-latest$%hash%.json' => ['sha256' => $providerHash]] : [],
]))
->setPublic()
->setTtl(86400)
Expand All @@ -57,14 +66,46 @@ public function packages(Request $request): JsonResponse
}

/**
* @Route("/p/{package}",
* @Route("/p/{package}${hash}.json",
* name="package_legacy_metadata",
* host="repo.{domain}",
* defaults={"domain"="%domain%"},
* requirements={"package"="%package_name_pattern%","domain"="%domain%"},
* methods={"GET"})
*/
public function legacyMetadata(string $package, Request $request): Response
public function legacyMetadata(string $package, string $hash, Request $request): Response
{
/** @var Metadata $metadata */
$metadata = $this->register->all()
->map(fn (Proxy $proxy) => $proxy->legacyMetadata($package, $hash))
->find(fn (Option $option) => !$option->isEmpty())
->map(fn (Option $option) => $option->get())
->getOrElseThrow(new NotFoundHttpException('Provider not found'));

$response = (new StreamedResponse(ResponseCallback::fromStream($metadata->stream()), 200, [
'Accept-Ranges' => 'bytes',
'Content-Type' => 'application/json',
/* @phpstan-ignore-next-line */
'Content-Length' => fstat($metadata->stream())['size'],
]))
->setPublic()
->setLastModified((new \DateTime())->setTimestamp($metadata->timestamp()))
;

$response->isNotModified($request);

return $response;
}

/**
* @Route("/p/{package}",
* name="package_legacy_metadata_lazy",
* host="repo.{domain}",
* defaults={"domain"="%domain%"},
* requirements={"package"="%package_name_pattern%","domain"="%domain%"},
* methods={"GET"})
*/
public function legacyMetadataLazy(string $package, Request $request): Response
{
/** @var Metadata $metadata */
$metadata = $this->register->all()
Expand All @@ -88,6 +129,39 @@ public function legacyMetadata(string $package, Request $request): Response
return $response;
}

/**
* @Route(
* "/p/provider-{version}${hash}.json",
* host="repo.{domain}",
* name="providers",
* methods={"GET"},
* defaults={"domain"="%domain%"}, requirements={"domain"="%domain%"}
* )
*/
public function providers(string $version, string $hash, Request $request): Response
{
/** @var Metadata $metadata */
$metadata = $this->register->all()
->map(fn (Proxy $proxy) => $proxy->providers($version, $hash))
->find(fn (Option $option) => !$option->isEmpty())
->map(fn (Option $option) => $option->get())
->getOrElseThrow(new NotFoundHttpException('Provider not found'));

$response = (new StreamedResponse(ResponseCallback::fromStream($metadata->stream()), 200, [
'Accept-Ranges' => 'bytes',
'Content-Type' => 'application/json',
/* @phpstan-ignore-next-line */
'Content-Length' => fstat($metadata->stream())['size'],
]))
->setPublic()
->setLastModified((new \DateTime())->setTimestamp($metadata->timestamp()))
;

$response->isNotModified($request);

return $response;
}

/**
* @Route("/p2/{package}.json",
* name="package_metadata",
Expand All @@ -103,7 +177,7 @@ public function metadata(string $package, Request $request): Response
->map(fn (Proxy $proxy) => $proxy->metadata($package))
->find(fn (Option $option) => !$option->isEmpty())
->map(fn (Option $option) => $option->get())
->getOrElseThrow(new NotFoundHttpException());
->getOrElseThrow(new NotFoundHttpException('Metadata not found'));

$response = (new StreamedResponse(ResponseCallback::fromStream($metadata->stream()), 200, [
'Accept-Ranges' => 'bytes',
Expand Down
128 changes: 117 additions & 11 deletions src/Service/Proxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function __construct(
*/
public function metadata(string $package): Option
{
return $this->fetchMetadata(sprintf('%s/p2/%s.json', $this->url, $package));
return $this->fetchMetadataLazy(sprintf('%s/p2/%s.json', $this->url, $package));
}

/**
Expand Down Expand Up @@ -66,9 +66,32 @@ public function distribution(string $package, string $version, string $ref, stri
/**
* @return Option<Metadata>
*/
public function legacyMetadata(string $package): Option
public function legacyMetadata(string $package, ?string $hash = null): Option
{
return $this->fetchMetadata(sprintf('%s/p/%s.json', $this->url, $package));
return $hash === null ?
$this->fetchMetadataLazy(sprintf('%s/p/%s.json', $this->url, $package)) :
$this->fetchMetadata(sprintf('%s/p/%s$%s.json', $this->url, $package, $hash));
}

/**
* @return Option<Metadata>
*/
public function providers(string $version, string $hash): Option
{
return $this->fetchMetadata(sprintf('%s/provider/provider-%s$%s.json', $this->url, $version, $hash));
}

public function latestProviderHash(): ?string
{
foreach ($this->filesystem->listContents($this->name.'/provider') as $file) {
if ($file['type'] === 'file' && $file['extension'] === 'json') {
preg_match('/\$(?<hash>.+)$/', $file['filename'], $matches);

return $matches['hash'];
}
}

return null;
}

/**
Expand Down Expand Up @@ -120,12 +143,20 @@ public function syncMetadata(): void

$this->syncPackagesMetadata(array_filter(
$this->filesystem->listContents($dir['path'], true),
fn (array $file) => $file['type'] === 'file' && $file['extension'] === 'json')
fn (array $file) => $file['type'] === 'file' && $file['extension'] === 'json' && strpos($file['filename'], '$') === false)
);
}
$this->downloader->run();
}

public function updateLatestProviders(): void
{
$this->updateLatestProvider(array_filter(
$this->filesystem->listContents($this->name.'/p', true),
fn (array $file) => $file['type'] === 'file' && $file['extension'] === 'json' && strpos($file['filename'], '$') !== false)
);
}

public function url(): string
{
return $this->url;
Expand All @@ -138,17 +169,71 @@ private function syncPackagesMetadata(array $files): void
{
foreach ($files as $file) {
$url = sprintf('%s://%s', parse_url($this->url, PHP_URL_SCHEME), $file['path']);
// todo: what if proxy do not return `Last-Modified` header?
$this->downloader->getLastModified($url, function (int $timestamp) use ($url, $file): void {
if ($timestamp > ($file['timestamp'] ?? time())) {
$this->downloader->getAsyncContents($url, [], function ($stream) use ($file): void {
$this->filesystem->putStream($file['path'], $stream);
});
}
$this->downloader->getAsyncContents($url, [], function ($stream) use ($file): void {
$path = $file['path'];
$contents = (string) stream_get_contents($stream);

$this->filesystem->putStream($path, $stream);
$this->filesystem->put(
(string) preg_replace(
'/(.+?)(\$\w+|)(\.json)$/',
'${1}\$'.hash('sha256', $contents).'.json',
$path,
1
),
$contents
);
});
}
}

/**
* @param mixed[] $files
*/
private function updateLatestProvider(array $files): void
{
$latest = [];
foreach ($files as $file) {
preg_match('/(?<name>.+)\$/', $file['filename'], $matches);
$key = $file['dirname'].'/'.$matches['name'];
if (!isset($latest[$key])) {
$latest[$key] = $file;
continue;
}

if ($file['timestamp'] >= $latest[$key]['timestamp']) {
$latest[$key] = $file;
}
}

$providers = [];
foreach ($latest as $file) {
$path = $file['path'];
preg_match('/'.$this->name.'\/p\/(?<name>.+)\$/', $path, $matches);
$providers[$matches['name']] = [
'sha256' => hash('sha256', (string) $this->filesystem->read($path)),
];
}

$contents = json_encode([
'providers' => $providers,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
$basePath = sprintf('%s/provider', $this->name);

foreach ($this->filesystem->listContents($basePath) as $file) {
if ($file['type'] !== 'file' || $file['extension'] !== 'json') {
continue;
}

$this->filesystem->delete($file['path']);
}

$this->filesystem->put(
sprintf('%s/provider-latest$%s.json', $basePath, hash('sha256', $contents)),
$contents
);
}

/**
* @return mixed[]
*/
Expand All @@ -165,6 +250,27 @@ private function decodeMetadata(string $package): array
* @return Option<Metadata>
*/
private function fetchMetadata(string $url): Option
{
$path = $this->metadataPath($url);
if (!$this->filesystem->has($path)) {
return Option::none();
}

$stream = $this->filesystem->readStream($path);
if ($stream === false) {
return Option::none();
}

return Option::some(new Metadata(
(int) $this->filesystem->getTimestamp($path),
$stream
));
}

/**
* @return Option<Metadata>
*/
private function fetchMetadataLazy(string $url): Option
{
$path = $this->metadataPath($url);
if (!$this->filesystem->has($path)) {
Expand Down
63 changes: 60 additions & 3 deletions tests/Functional/Controller/ProxyControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,17 @@ public function testPackagesAction(): void
"preferred": true
}
],
"providers-lazy-url": "/p/%package%"
"providers-lazy-url": "/p/%package%",
"provider-includes": {
"p/provider-latest$%hash%.json": {
"sha256": "bf7274d469c9a2c4b4d0babeeb112b40a3afd19a9887adb342671818360ae326"
}
}
}
', $this->client->getResponse()->getContent());
}

public function testProviderAction(): void
public function testProviderLazyAction(): void
{
$response = $this->contentFromStream(fn () => $this->client->request('GET', '/p/buddy-works/repman', [], [], [
'HTTP_HOST' => 'repo.repman.wip',
Expand All @@ -50,7 +55,7 @@ public function testProviderAction(): void
self::assertTrue($this->client->getResponse()->isCacheable());
}

public function testProviderActionEmptyPackagesWhenNotExist(): void
public function testProviderLazyActionEmptyPackagesWhenNotExist(): void
{
$response = $this->contentFromStream(fn () => $this->client->request('GET', '/p/buddy-works/example-app', [], [], [
'HTTP_HOST' => 'repo.repman.wip',
Expand Down Expand Up @@ -85,6 +90,58 @@ public function testProviderV2ActionWhenPackageNotExist(): void
$this->client->request('GET', '/p2/buddy-works/example-app.json', [], [], [
'HTTP_HOST' => 'repo.repman.wip',
]);
self::assertTrue($this->client->getResponse()->isNotFound());
}

public function testProviderAction(): void
{
$response = $this->contentFromStream(fn () => $this->client->request('GET', '/p/buddy-works/repman$985a77691ad57c77f96e5b97ae30828c75e4030b65e6211a0a20c54f594c5ea9.json', [], [], [
'HTTP_HOST' => 'repo.repman.wip',
]));

self::assertMatchesPattern('
{
"packages":
{
"buddy-works/repman": "@array@"
}
}
', $response);
self::assertTrue($this->client->getResponse()->isCacheable());
}

public function testProviderNotFoundWhenNotExist(): void
{
$this->contentFromStream(fn () => $this->client->request('GET', '/p/buddy-works/repman$ee203d24e9722116c133153095cd65f7d94d8261bed4bd77da698dda07e8c98d.json', [], [], [
'HTTP_HOST' => 'repo.repman.wip',
]));

self::assertTrue($this->client->getResponse()->isNotFound());
}

public function testProvidersAction(): void
{
$response = $this->contentFromStream(fn () => $this->client->request('GET', '/p/provider-latest$bf7274d469c9a2c4b4d0babeeb112b40a3afd19a9887adb342671818360ae326.json', [], [], [
'HTTP_HOST' => 'repo.repman.wip',
]));

self::assertMatchesPattern('
{
"providers": {
"buddy-works/repman": {
"sha256": "d5d2c9708c1240da3913ee9fba51759b14b8443826a93b84fa0fa95d70cd3703"
}
}
}
', $response);
self::assertTrue($this->client->getResponse()->isCacheable());
}

public function testProvidersNotFoundWhenNotExist(): void
{
$this->contentFromStream(fn () => $this->client->request('GET', 'provider-latest$e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.json', [], [], [
'HTTP_HOST' => 'repo.repman.wip',
]));

self::assertTrue($this->client->getResponse()->isNotFound());
}
Expand Down
Loading