ProcessCallAPI.php
3.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace App\Jobs;
use App\Service\API\API;
use App\Service\Contract\APIRequest;
use App\Service\Handlers\AdsHandler;
use App\Service\HeaderLimits;
use App\Service\Limits;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class ProcessCallAPI implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $api;
private $limitId;
public $tries = 1;
public $timeout = 1500;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(int $limitId, APIRequest $api)
{
$this->limitId = $limitId;
$this->api = $api;
}
/**
* Execute the job.
*
* @return void
* @throws \Throwable
*/
public function handle()
{
$limits = Limits::getInstance($this->api->getToken());
try {
$api = API::getInstance($this->api);
//считаем на сколько объектов зарезервировано получение данных
//только их и запрашиваем
$limit = \App\Models\Limits::find($this->limitId);
$maxObjects = $limits::NAN;
if ($limit->spent) {
$limits = Limits::getInstance($this->api->getToken());
$maxObjects = $limits->countObjectsLimitReserve($this->api, $limit);
}
if (
($maxObjects && $maxObjects !== $limits::NAN && $this->api->getObjectsCount() > $maxObjects)
||
(($maxObjects = $this->api->getMaxCount()) && $maxObjects !== $limits::NAN && $this->api->getObjectsCount() > $maxObjects)
) {
//те на которые не хватило баллов помещаем в очередь
if ($apiR = $this->api->slice($maxObjects)) {
dispatch(new ProcessCallLimitedAPI($apiR))->onQueue('limits');
}
}
$response = $api->execute();
$handler = AdsHandler::getInstance($this->api);
$handler->checkError($response);
$limits->acceptRezerv($this->limitId, new HeaderLimits($response->headers()));
$handler->handle($response);
} catch (\Exception $e) {
Log::debug('');
Log::debug("Exception in ProcessCallAPI, удаляем резервирование баллов. token_id {$this->api->getToken()->getKey()}, объектов {$this->api->getObjectsCount()} {$this->api->getService()} {$this->api->getMethod()}");
if (isset($response)) {
$headerLimit = new HeaderLimits($response->headers());
}
try {
$limits->removeRezerv($this->limitId, $headerLimit ?? null);
} catch (\Throwable $e) {
Log::error($e);
}
throw $e;
}
}
public function failed()
{
$this->api->failed();
}
}