bfe8c27e4da46dacbcb9f558615a21a7a1ee02ad
3 namespace seekat\API\Call
;
5 use http\
{Client
, Client\Request
, Client\Response
};
6 use Psr\Log\LoggerInterface
;
11 * The response importer
32 * @var LoggerInterface
37 * The executed request
44 * The promised response
66 * Create a deferred promise for the response of $request
68 * @param API $api The endpoint of the request
69 * @param Request $request The request to execute
70 * @param Cache\Service $cache
72 function __construct(API
$api, Request
$request, Cache\Service
$cache = null) {
73 $this->request
= $request;
74 $this->client
= $api->getClient();
75 $this->logger
= $api->getLogger();
76 $this->result
= new Result($api);
77 $this->cache
= new Cache($cache);
79 $future = $api->getFuture();
80 $context = $future->createContext(function() {
81 if ($this->response
) {
82 /* we did finish in the meantime */
85 $this->client
->dequeue($this->request
);
86 ($this->reject
)("Cancelled");
89 $this->promise
= $future->getPromise($context);
90 $this->resolve
= API\Future\resolver
($future, $context);
91 $this->reject
= API\Future\rejecter
($future, $context);
95 if (!$this->cached($cached)) {
96 $this->refresh($cached);
99 return $this->promise
;
105 * @param Response $cached
108 private function cached(Response
&$cached = null) : bool {
109 $fresh = $this->cache
->load($this->request
, $cachedResponse);
111 if (!$cachedResponse) {
114 $cached = $cachedResponse;
116 $this->logger
->info("deferred -> cached", [
117 "method" => $this->request
->getRequestMethod(),
118 "url" => $this->request
->getRequestUrl(),
123 $this->logger
->info("cached -> stale", [
124 "method" => $this->request
->getRequestMethod(),
125 "url" => $this->request
->getRequestUrl(),
131 $this->response
= $cached;
132 $this->complete("cached");
139 * @param Response|null $cached
141 private function refresh(Response
$cached = null) {
142 $this->client
->enqueue($this->request
, function(Response
$response) use($cached) {
143 $this->response
= $response;
148 $this->logger
->info(($cached ?
"stale" : "deferred") . " -> enqueued", [
149 "method" => $this->request
->getRequestMethod(),
150 "url" => $this->request
->getRequestUrl(),
154 $this->client
->once();
158 * Completion callback
160 private function complete(string $by = "enqueued") {
161 if ($this->response
) {
162 $this->logger
->info("$by -> response", [
163 "url" => $this->request
->getRequestUrl(),
164 "info" => $this->response
->getInfo(),
168 $this->cache
->update($this->request
, $this->response
);
169 ($this->resolve
)(($this->result
)($this->response
));
170 } catch (\Throwable
$e) {
174 $info = $this->client
->getTransferInfo($this->request
);
176 $this->logger
->warning("$by -> no response", [
177 "url" => $this->request
->getRequestUrl(),
181 ($this->reject
)($info->error
);