summaryrefslogtreecommitdiffstats
path: root/lib/private/Http
diff options
context:
space:
mode:
authorJoas Schilling <coding@schilljs.com>2023-06-02 16:05:35 +0200
committerJoas Schilling <coding@schilljs.com>2023-08-07 15:38:09 +0200
commit32bfd43d2921d65198b2302a3084077eb154ecb6 (patch)
tree91773a648859b49ef91a2d4f7647f74776bf8c81 /lib/private/Http
parentcc66e3bcd1afc305c121358d38be4bce03e35053 (diff)
downloadnextcloud-server-32bfd43d2921d65198b2302a3084077eb154ecb6.tar.gz
nextcloud-server-32bfd43d2921d65198b2302a3084077eb154ecb6.zip
feat(HTTPClient): Provide wrapped access to Guzzle's asyncRequest()
Signed-off-by: Joas Schilling <coding@schilljs.com>
Diffstat (limited to 'lib/private/Http')
-rw-r--r--lib/private/Http/Client/Client.php231
-rw-r--r--lib/private/Http/Client/ClientService.php3
-rw-r--r--lib/private/Http/Client/GuzzlePromiseAdapter.php139
3 files changed, 365 insertions, 8 deletions
diff --git a/lib/private/Http/Client/Client.php b/lib/private/Http/Client/Client.php
index 298749d52e1..3bf43e6c07e 100644
--- a/lib/private/Http/Client/Client.php
+++ b/lib/private/Http/Client/Client.php
@@ -34,13 +34,16 @@ declare(strict_types=1);
namespace OC\Http\Client;
use GuzzleHttp\Client as GuzzleClient;
+use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\RequestOptions;
use OCP\Http\Client\IClient;
+use OCP\Http\Client\IPromise;
use OCP\Http\Client\IResponse;
use OCP\Http\Client\LocalServerException;
use OCP\ICertificateManager;
use OCP\IConfig;
use OCP\Security\IRemoteHostValidator;
+use Psr\Log\LoggerInterface;
use function parse_url;
/**
@@ -61,7 +64,8 @@ class Client implements IClient {
IConfig $config,
ICertificateManager $certificateManager,
GuzzleClient $client,
- IRemoteHostValidator $remoteHostValidator
+ IRemoteHostValidator $remoteHostValidator,
+ protected LoggerInterface $logger,
) {
$this->config = $config;
$this->client = $client;
@@ -205,7 +209,7 @@ class Client implements IClient {
* 'headers' => [
* 'foo' => 'bar',
* ],
- * 'cookies' => ['
+ * 'cookies' => [
* 'foo' => 'bar',
* ],
* 'allow_redirects' => [
@@ -236,7 +240,7 @@ class Client implements IClient {
* 'headers' => [
* 'foo' => 'bar',
* ],
- * 'cookies' => ['
+ * 'cookies' => [
* 'foo' => 'bar',
* ],
* 'allow_redirects' => [
@@ -271,7 +275,7 @@ class Client implements IClient {
* 'headers' => [
* 'foo' => 'bar',
* ],
- * 'cookies' => ['
+ * 'cookies' => [
* 'foo' => 'bar',
* ],
* 'allow_redirects' => [
@@ -312,7 +316,7 @@ class Client implements IClient {
* 'headers' => [
* 'foo' => 'bar',
* ],
- * 'cookies' => ['
+ * 'cookies' => [
* 'foo' => 'bar',
* ],
* 'allow_redirects' => [
@@ -347,7 +351,7 @@ class Client implements IClient {
* 'headers' => [
* 'foo' => 'bar',
* ],
- * 'cookies' => ['
+ * 'cookies' => [
* 'foo' => 'bar',
* ],
* 'allow_redirects' => [
@@ -370,7 +374,7 @@ class Client implements IClient {
}
/**
- * Sends a options request
+ * Sends an OPTIONS request
*
* @param string $uri
* @param array $options Array such as
@@ -382,7 +386,7 @@ class Client implements IClient {
* 'headers' => [
* 'foo' => 'bar',
* ],
- * 'cookies' => ['
+ * 'cookies' => [
* 'foo' => 'bar',
* ],
* 'allow_redirects' => [
@@ -403,4 +407,215 @@ class Client implements IClient {
$response = $this->client->request('options', $uri, $this->buildRequestOptions($options));
return new Response($response);
}
+
+ protected function wrapGuzzlePromise(PromiseInterface $promise): IPromise {
+ return new GuzzlePromiseAdapter(
+ $promise,
+ $this->logger
+ );
+ }
+
+ /**
+ * Sends an asynchronous GET request
+ *
+ * @param string $uri
+ * @param array $options Array such as
+ * 'query' => [
+ * 'field' => 'abc',
+ * 'other_field' => '123',
+ * 'file_name' => fopen('/path/to/file', 'r'),
+ * ],
+ * 'headers' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'cookies' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'allow_redirects' => [
+ * 'max' => 10, // allow at most 10 redirects.
+ * 'strict' => true, // use "strict" RFC compliant redirects.
+ * 'referer' => true, // add a Referer header
+ * 'protocols' => ['https'] // only allow https URLs
+ * ],
+ * 'sink' => '/path/to/file', // save to a file or a stream
+ * 'verify' => true, // bool or string to CA file
+ * 'debug' => true,
+ * 'timeout' => 5,
+ * @return IPromise
+ */
+ public function getAsync(string $uri, array $options = []): IPromise {
+ $this->preventLocalAddress($uri, $options);
+ $response = $this->client->requestAsync('get', $uri, $this->buildRequestOptions($options));
+ return $this->wrapGuzzlePromise($response);
+ }
+
+ /**
+ * Sends an asynchronous HEAD request
+ *
+ * @param string $uri
+ * @param array $options Array such as
+ * 'headers' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'cookies' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'allow_redirects' => [
+ * 'max' => 10, // allow at most 10 redirects.
+ * 'strict' => true, // use "strict" RFC compliant redirects.
+ * 'referer' => true, // add a Referer header
+ * 'protocols' => ['https'] // only allow https URLs
+ * ],
+ * 'sink' => '/path/to/file', // save to a file or a stream
+ * 'verify' => true, // bool or string to CA file
+ * 'debug' => true,
+ * 'timeout' => 5,
+ * @return IPromise
+ */
+ public function headAsync(string $uri, array $options = []): IPromise {
+ $this->preventLocalAddress($uri, $options);
+ $response = $this->client->requestAsync('head', $uri, $this->buildRequestOptions($options));
+ return $this->wrapGuzzlePromise($response);
+ }
+
+ /**
+ * Sends an asynchronous POST request
+ *
+ * @param string $uri
+ * @param array $options Array such as
+ * 'body' => [
+ * 'field' => 'abc',
+ * 'other_field' => '123',
+ * 'file_name' => fopen('/path/to/file', 'r'),
+ * ],
+ * 'headers' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'cookies' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'allow_redirects' => [
+ * 'max' => 10, // allow at most 10 redirects.
+ * 'strict' => true, // use "strict" RFC compliant redirects.
+ * 'referer' => true, // add a Referer header
+ * 'protocols' => ['https'] // only allow https URLs
+ * ],
+ * 'sink' => '/path/to/file', // save to a file or a stream
+ * 'verify' => true, // bool or string to CA file
+ * 'debug' => true,
+ * 'timeout' => 5,
+ * @return IPromise
+ */
+ public function postAsync(string $uri, array $options = []): IPromise {
+ $this->preventLocalAddress($uri, $options);
+
+ if (isset($options['body']) && is_array($options['body'])) {
+ $options['form_params'] = $options['body'];
+ unset($options['body']);
+ }
+
+ return $this->wrapGuzzlePromise($this->client->requestAsync('post', $uri, $this->buildRequestOptions($options)));
+ }
+
+ /**
+ * Sends an asynchronous PUT request
+ *
+ * @param string $uri
+ * @param array $options Array such as
+ * 'body' => [
+ * 'field' => 'abc',
+ * 'other_field' => '123',
+ * 'file_name' => fopen('/path/to/file', 'r'),
+ * ],
+ * 'headers' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'cookies' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'allow_redirects' => [
+ * 'max' => 10, // allow at most 10 redirects.
+ * 'strict' => true, // use "strict" RFC compliant redirects.
+ * 'referer' => true, // add a Referer header
+ * 'protocols' => ['https'] // only allow https URLs
+ * ],
+ * 'sink' => '/path/to/file', // save to a file or a stream
+ * 'verify' => true, // bool or string to CA file
+ * 'debug' => true,
+ * 'timeout' => 5,
+ * @return IPromise
+ */
+ public function putAsync(string $uri, array $options = []): IPromise {
+ $this->preventLocalAddress($uri, $options);
+ $response = $this->client->requestAsync('put', $uri, $this->buildRequestOptions($options));
+ return $this->wrapGuzzlePromise($response);
+ }
+
+ /**
+ * Sends an asynchronous DELETE request
+ *
+ * @param string $uri
+ * @param array $options Array such as
+ * 'body' => [
+ * 'field' => 'abc',
+ * 'other_field' => '123',
+ * 'file_name' => fopen('/path/to/file', 'r'),
+ * ],
+ * 'headers' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'cookies' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'allow_redirects' => [
+ * 'max' => 10, // allow at most 10 redirects.
+ * 'strict' => true, // use "strict" RFC compliant redirects.
+ * 'referer' => true, // add a Referer header
+ * 'protocols' => ['https'] // only allow https URLs
+ * ],
+ * 'sink' => '/path/to/file', // save to a file or a stream
+ * 'verify' => true, // bool or string to CA file
+ * 'debug' => true,
+ * 'timeout' => 5,
+ * @return IPromise
+ */
+ public function deleteAsync(string $uri, array $options = []): IPromise {
+ $this->preventLocalAddress($uri, $options);
+ $response = $this->client->requestAsync('delete', $uri, $this->buildRequestOptions($options));
+ return $this->wrapGuzzlePromise($response);
+ }
+
+ /**
+ * Sends an asynchronous OPTIONS request
+ *
+ * @param string $uri
+ * @param array $options Array such as
+ * 'body' => [
+ * 'field' => 'abc',
+ * 'other_field' => '123',
+ * 'file_name' => fopen('/path/to/file', 'r'),
+ * ],
+ * 'headers' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'cookies' => [
+ * 'foo' => 'bar',
+ * ],
+ * 'allow_redirects' => [
+ * 'max' => 10, // allow at most 10 redirects.
+ * 'strict' => true, // use "strict" RFC compliant redirects.
+ * 'referer' => true, // add a Referer header
+ * 'protocols' => ['https'] // only allow https URLs
+ * ],
+ * 'sink' => '/path/to/file', // save to a file or a stream
+ * 'verify' => true, // bool or string to CA file
+ * 'debug' => true,
+ * 'timeout' => 5,
+ * @return IPromise
+ */
+ public function optionsAsync(string $uri, array $options = []): IPromise {
+ $this->preventLocalAddress($uri, $options);
+ $response = $this->client->requestAsync('options', $uri, $this->buildRequestOptions($options));
+ return $this->wrapGuzzlePromise($response);
+ }
}
diff --git a/lib/private/Http/Client/ClientService.php b/lib/private/Http/Client/ClientService.php
index d0640680124..532aa7f566a 100644
--- a/lib/private/Http/Client/ClientService.php
+++ b/lib/private/Http/Client/ClientService.php
@@ -37,6 +37,7 @@ use OCP\ICertificateManager;
use OCP\IConfig;
use OCP\Security\IRemoteHostValidator;
use Psr\Http\Message\RequestInterface;
+use Psr\Log\LoggerInterface;
/**
* Class ClientService
@@ -59,6 +60,7 @@ class ClientService implements IClientService {
DnsPinMiddleware $dnsPinMiddleware,
IRemoteHostValidator $remoteHostValidator,
IEventLogger $eventLogger,
+ protected LoggerInterface $logger,
) {
$this->config = $config;
$this->certificateManager = $certificateManager;
@@ -87,6 +89,7 @@ class ClientService implements IClientService {
$this->certificateManager,
$client,
$this->remoteHostValidator,
+ $this->logger,
);
}
}
diff --git a/lib/private/Http/Client/GuzzlePromiseAdapter.php b/lib/private/Http/Client/GuzzlePromiseAdapter.php
new file mode 100644
index 00000000000..9d0b89bfd17
--- /dev/null
+++ b/lib/private/Http/Client/GuzzlePromiseAdapter.php
@@ -0,0 +1,139 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * @copyright Copyright (c) 2023, Joas Schilling <coding@schilljs.com>
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace OC\Http\Client;
+
+use Exception;
+use GuzzleHttp\Exception\RequestException;
+use GuzzleHttp\Promise\PromiseInterface;
+use LogicException;
+use OCP\Http\Client\IPromise;
+use OCP\Http\Client\IResponse;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Log\LoggerInterface;
+
+/**
+ * A wrapper around Guzzle's PromiseInterface
+ *
+ * @see \GuzzleHttp\Promise\PromiseInterface
+ * @since 28.0.0
+ */
+class GuzzlePromiseAdapter implements IPromise {
+ public function __construct(
+ protected PromiseInterface $promise,
+ protected LoggerInterface $logger,
+ ) {
+ }
+
+ /**
+ * Appends fulfillment and rejection handlers to the promise, and returns
+ * a new promise resolving to the return value of the called handler.
+ *
+ * @param ?callable(IResponse): void $onFulfilled Invoked when the promise fulfills. Gets an \OCP\Http\Client\IResponse passed in as argument
+ * @param ?callable(Exception): void $onRejected Invoked when the promise is rejected. Gets an \Exception passed in as argument
+ *
+ * @return IPromise
+ * @since 28.0.0
+ */
+ public function then(
+ ?callable $onFulfilled = null,
+ ?callable $onRejected = null,
+ ): IPromise {
+ if ($onFulfilled !== null) {
+ $wrappedOnFulfilled = static function (ResponseInterface $response) use ($onFulfilled) {
+ $onFulfilled(new Response($response));
+ };
+ } else {
+ $wrappedOnFulfilled = null;
+ }
+
+ if ($onRejected !== null) {
+ $wrappedOnRejected = static function (RequestException $e) use ($onRejected) {
+ $onRejected($e);
+ };
+ } else {
+ $wrappedOnRejected = null;
+ }
+
+ $this->promise->then($wrappedOnFulfilled, $wrappedOnRejected);
+ return $this;
+ }
+
+ /**
+ * Get the state of the promise ("pending", "rejected", or "fulfilled").
+ *
+ * The three states can be checked against the constants defined:
+ * STATE_PENDING, STATE_FULFILLED, and STATE_REJECTED.
+ *
+ * @return IPromise::STATE_*
+ * @since 28.0.0
+ */
+ public function getState(): string {
+ $state = $this->promise->getState();
+ if ($state === PromiseInterface::FULFILLED) {
+ return self::STATE_FULFILLED;
+ }
+ if ($state === PromiseInterface::REJECTED) {
+ return self::STATE_REJECTED;
+ }
+ if ($state === PromiseInterface::PENDING) {
+ return self::STATE_PENDING;
+ }
+
+ $this->logger->error('Unexpected promise state "{state}" returned by Guzzle', [
+ 'state' => $state,
+ ]);
+ return self::STATE_PENDING;
+ }
+
+ /**
+ * Cancels the promise if possible.
+ *
+ * @link https://github.com/promises-aplus/cancellation-spec/issues/7
+ * @since 28.0.0
+ */
+ public function cancel(): void {
+ $this->promise->cancel();
+ }
+
+ /**
+ * Waits until the promise completes if possible.
+ *
+ * Pass $unwrap as true to unwrap the result of the promise, either
+ * returning the resolved value or throwing the rejected exception.
+ *
+ * If the promise cannot be waited on, then the promise will be rejected.
+ *
+ * @param bool $unwrap
+ *
+ * @return mixed
+ *
+ * @throws LogicException if the promise has no wait function or if the
+ * promise does not settle after waiting.
+ * @since 28.0.0
+ */
+ public function wait(bool $unwrap = true): mixed {
+ return $this->promise->wait($unwrap);
+ }
+}