Limits.php
7.34 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php
namespace App\Service;
use App\Models\Tokens;
use App\Service\Contract\HeaderLimits;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
class Limits implements \App\Service\Contract\Limits {
CONST NAN = -1;
private $token;
private $limitCosts;
private function __construct(Tokens $token){
$this->token = $token;
$this->limitCosts = new Costs();
}
public static function getInstance(Tokens $token): Limits
{
return new self($token);
}
function current(): int
{
return $this->token->limit;
}
function dayLimit(): int
{
return $this->token->limits()->complited()->firstOrFail()->day;
}
/**
* Если несколько дней не обновляется и дневные лимиты там менялись то будет ошибка
* но мы ей пренебрегаем, т.к. вообще должно каждый час запускаться это дело и толко при каком то сбое может быть иначе
* Еще может быть ошибка когда первый запус в день происходит, если изменилось количетсво балло на день,
* но это после первого же сама будет исправлено, так что тоже ничгео страшнго нет
*/
function refreshCurrentLimit(){
//последние лимиты по баллам из АПИ
$limit = $this->token->limits()->complited()->first();
if (!$limit)
return;
//сколько часов прошло после последнего запуска
$hours = Date::now()->diffInHours($limit->updated_at);
//новый лимит это послдений доступный + по 1/24 дневного лимита за каждый час без запросов.
// Но не блее чем за 23 предыдущих часа
$hours = $hours > 23 ? 23 : $hours;
$current = $limit->current + $hours * $limit->day/24;
$this->token->limit = $current;
$this->token->save();
}
/**
* @param Contract\APIRequest $request
* @return int
* возвращает сколько объектов можем обработать
* если это выборка, то возвращаем максимум 10 000, это максимум что возвращает АПИ, дальше уже пейджинг.
*/
function countObjectsLimit(\App\Service\Contract\APIRequest $request): int
{
$cost = $this->limitCosts->getCostObject($request);
$maxCount = $request->getMaxCount();
if ($cost == 0 || $maxCount === self::NAN){
return self::NAN;
}
$objectsCount = $request->getObjectsCount();
if ($this->token->limits->count() > 0){
if ($this->limitCosts->getCostCall($request) > $this->current()){
return 0;
}
$allowCount = floor(($this->current() - $this->limitCosts->getCostCall($request)) / $cost);
} else {
$allowCount = $objectsCount; //не было еще запросов, считаем что баллов хватает
}
if ($objectsCount > $maxCount) {
$objectsCount = $maxCount;
}
if ($objectsCount > $allowCount){
$objectsCount = $allowCount;
}
return $objectsCount;
}
/**
* @param Contract\APIRequest $request
* @param \App\Models\Limits $limits
*
* @return int
* возвращает сколько объектов можем обработать на резервированные баллы
*/
function countObjectsLimitReserve(\App\Service\Contract\APIRequest $request, \App\Models\Limits $limit): int
{
$cost = $this->limitCosts->getCostObject($request);
return floor(($limit->spent - $this->limitCosts->getCostCall($request)) / $cost);
}
/**
* @param APIRequest $request
* @param int $objects
* @return int
* @throws \Exception
* предполагается что класс работает в очереди.
* Иначе может быть что одновременно будет два резервирования с одним и тем же остатком.
*/
function doRezerv(\App\Service\Contract\APIRequest $request, int $objects): int
{
$limit = $this->getSpent($objects, $request);
if ($this->token->limits->count() > 0 && $this->token->limit < $limit) {
throw new \Exception('Недостаточно баллов');
}
DB::beginTransaction();
try{
$rezerv = new \App\Models\Limits();
$rezerv->token = $this->token->id;
$rezerv->service = $request->getService();
$rezerv->method = $request->getMethod();
$rezerv->spent = $limit;
$rezerv->day = 0;
$rezerv->current = $this->token->limit;
$rezerv->reserved = 1;
$rezerv->save();
$this->token->limit -= $limit;
$this->token->save();
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
}
return $rezerv->id;
}
function removeRezerv(int $id)
{
DB::beginTransaction();
try{
$limit = \App\Models\Limits::findOrFail($id);
$this->token->limit += $limit->spent;
$this->token->save();
$limit->delete();
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
}
}
function acceptRezerv($id, HeaderLimits $limits){
DB::beginTransaction();
try{
$this->token->limit = $limits->getCurrentLimit();
$this->token->save();
$limit = \App\Models\Limits::findOrFail($id);
$limit->spent = $limits->getSpentLimit();
$limit->current = $limits->getCurrentLimit();
$limit->day = $limits->getDayLimit();
$limit->reserved = 0;
$limit->save();
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
}
}
function updateLimits(HeaderLimits $limits)
{
DB::beginTransaction();
try{
$this->token->limit = $limits->getCurrentLimit();
$this->token->save();
$limit = new \App\Models\Limits();
$limit->token = $this->token->id;
$limit->service = '';
$limit->method = '';
$limit->spent = $limits->getSpentLimit();
$limit->current = $limits->getCurrentLimit();
$limit->day = $limits->getDayLimit();
$limit->reserved = 0;
$limit->save();
DB::commit();
}catch(\Exception $e){
DB::rollBack();
throw $e;
}
}
function getSpent($objects, \App\Service\Contract\APIRequest $request): int
{
$cost = $this->limitCosts->getCostObject($request);
if ($objects === Limits::NAN)
return $this->limitCosts->getCostCall($request);
return $objects * $cost + $this->limitCosts->getCostCall($request);
}
}