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

Issue 140 #167

Draft
wants to merge 3 commits into
base: dev
Choose a base branch
from
Draft
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
24 changes: 24 additions & 0 deletions app/HttpClient/Exceptions/NotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace App\HttpClient\Exceptions;

use GuzzleHttp\Exception\ClientException;
use Throwable;

class NotFoundException extends RuntimeException
{
public function __construct(
Throwable $previous = null
) {
parent::__construct(
previous: $previous,
);
}

public static function fromClientException(ClientException $exception): static
{
return new static(
previous: $exception,
);
}
}
38 changes: 38 additions & 0 deletions app/HttpClient/Exceptions/RateLimitExceededException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace App\HttpClient\Exceptions;

use Carbon\Carbon;
use DateTimeInterface;
use GuzzleHttp\Exception\ClientException;
use Throwable;

class RateLimitExceededException extends RuntimeException
{
public function __construct(
public int $limit,
public int $remaining,
public int $used,
public string $resource,
public DateTimeInterface $reset,
Throwable $previous = null
) {
parent::__construct(
previous: $previous,
);
}

public static function fromClientException(ClientException $exception): static
{
return new static(
limit: (int) $exception->getResponse()->getHeader('X-RateLimit-Limit')[0],
remaining: (int) $exception->getResponse()->getHeader('X-RateLimit-Remaining')[0],
used: (int) $exception->getResponse()->getHeader('X-RateLimit-Used')[0],
resource: $exception->getResponse()->getHeader('X-RateLimit-Resource')[0],
reset: Carbon::createFromTimestampUTC(
$exception->getResponse()->getHeader('X-RateLimit-Reset')[0]
),
previous: $exception,
);
}
}
9 changes: 9 additions & 0 deletions app/HttpClient/Exceptions/RuntimeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace App\HttpClient\Exceptions;

use RuntimeException as BaseRuntimeException;

abstract class RuntimeException extends BaseRuntimeException
{
}
28 changes: 28 additions & 0 deletions app/HttpClient/Exceptions/SsoRequiredException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace App\HttpClient\Exceptions;

use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Str;
use Throwable;

class SsoRequiredException extends RuntimeException
{
public function __construct(
public string $url,
Throwable $previous = null
) {
parent::__construct(
message: 'Resource protected by organization SAML enforcement. You must grant your personal token access to this organization.',
previous: $previous,
);
}

public static function fromClientException(ClientException $exception): static
{
return new static(
url: Str::after($exception->getResponse()->getHeader('x-github-sso')[0], 'url='),
previous: $exception,
);
}
}
29 changes: 29 additions & 0 deletions app/HttpClient/Exceptions/UnauthorizedException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\HttpClient\Exceptions;

use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Str;
use Throwable;

class UnauthorizedException extends RuntimeException
{
public function __construct(
public string $token,
Throwable $previous = null
) {
parent::__construct(
previous: $previous,
);
}

public static function fromClientException(ClientException $exception): static
{
return new static(
token: (string) Str::of($exception->getRequest()->getHeader('Authorization')[0])
->after('Bearer')
->trim(),
previous: $exception,
);
}
}
16 changes: 16 additions & 0 deletions app/HttpClient/Factory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace App\HttpClient;

use Illuminate\Http\Client\Factory as HttpFactory;

class Factory extends HttpFactory
{
public function github(): GithubPendingRequest
{
$request = new GithubPendingRequest($this);
$request->stub($this->stubCallbacks);

return $request;
}
}
104 changes: 104 additions & 0 deletions app/HttpClient/GithubPendingRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?php

namespace App\HttpClient;

use App\HttpClient\Exceptions\NotFoundException;
use App\HttpClient\Exceptions\RateLimitExceededException;
use App\HttpClient\Exceptions\SsoRequiredException;
use App\HttpClient\Exceptions\UnauthorizedException;
use App\Models\User;
use Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use Illuminate\Http\Client\Factory;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Traits\Conditionable;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class GithubPendingRequest extends PendingRequest
{
use Conditionable;

public function __construct(Factory $factory = null)
{
parent::__construct($factory);

$this
->baseUrl('https://api.github.com')
->accept('application/vnd.github.v3+json')
->withUserAgent(config('app.name').' '.config('app.url'))
->withOptions(['http_errors' => true])
->when(
User::whereIsRegistered()->inRandomOrder()->first()?->github_access_token,
fn (PendingRequest $request, $token) => $request->withToken($token)
)
->retry(
3,
500,
static function (Exception $exception): bool {
if (
$exception instanceof ServerException
&& $exception->hasResponse()
&& $exception->getResponse()->getStatusCode() === SymfonyResponse::HTTP_BAD_GATEWAY
) {
return true;
}

return false;
}
);
}

public function graphql(string $query, array $variables = []): Response
{
return $this
->asJson()
->accept('application/vnd.github.v4+json')
->post('/graphql', [
'query' => $query,
'variables' => $variables,
]);
}

public function send(string $method, string $url, array $options = []): Response
{
try {
$response = parent::send($method, $url, $options);
} catch (ClientException $exception) {
if (! $exception->hasResponse()) {
throw $exception;
}

$response = $exception->getResponse();

if ($response->getStatusCode() === SymfonyResponse::HTTP_NOT_FOUND) {
throw NotFoundException::fromClientException($exception);
}

if ($response->getStatusCode() === SymfonyResponse::HTTP_UNAUTHORIZED) {
throw UnauthorizedException::fromClientException($exception);
}

if (
$response->getStatusCode() === SymfonyResponse::HTTP_FORBIDDEN
&& $response->hasHeader('X-RateLimit-Remaining')
&& (int) $response->getHeader('X-RateLimit-Remaining')[0] <= 0
) {
throw RateLimitExceededException::fromClientException($exception);
}

if (
$response->getStatusCode() === SymfonyResponse::HTTP_FORBIDDEN
&& $response->hasHeader('x-github-sso')
&& str_contains($response->getHeader('x-github-sso')[0], 'required;')
) {
throw SsoRequiredException::fromClientException($exception);
}

throw $exception;
}

return $response;
}
}
1 change: 1 addition & 0 deletions app/Jobs/Concerns/RateLimited.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public function rateLimit(ClientException $exception): bool
$exception->hasResponse()
&& $exception->getResponse()->getStatusCode() === Response::HTTP_FORBIDDEN
&& $exception->getResponse()->hasHeader('X-RateLimit-Reset')
&& ! $exception->getResponse()->hasHeader('x-github-sso')
) {
$reset = Carbon::createFromTimestampUTC(
Arr::first($exception->getResponse()->getHeader('X-RateLimit-Reset'))
Expand Down
2 changes: 1 addition & 1 deletion app/Jobs/GithubJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function handle(): ?bool

if (
$exception->hasResponse()
&& in_array($exception->getResponse()->getStatusCode(), [Response::HTTP_NOT_FOUND, Response::HTTP_FORBIDDEN])
&& in_array($exception->getResponse()->getStatusCode(), [Response::HTTP_NOT_FOUND])
) {
$this->entity()->update([
'block_reason' => BlockReason::DELETED(),
Expand Down
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"extra": {
"composer-normalize": {
Expand Down