-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathCloudTasksQueue.php
264 lines (221 loc) · 7.57 KB
/
CloudTasksQueue.php
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<?php
namespace Stackkit\LaravelGoogleCloudTasksQueue;
use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\HttpMethod;
use Google\Cloud\Tasks\V2\HttpRequest;
use Google\Cloud\Tasks\V2\OidcToken;
use Google\Cloud\Tasks\V2\Task;
use Google\Protobuf\Duration;
use Google\Protobuf\Timestamp;
use Illuminate\Contracts\Queue\Queue as QueueContract;
use Illuminate\Queue\Queue as LaravelQueue;
use Illuminate\Support\Str;
use Stackkit\LaravelGoogleCloudTasksQueue\Events\TaskCreated;
use function Safe\json_decode;
use function Safe\json_encode;
class CloudTasksQueue extends LaravelQueue implements QueueContract
{
/**
* @var CloudTasksClient
*/
private $client;
public array $config;
public function __construct(array $config, CloudTasksClient $client, $dispatchAfterCommit = false)
{
$this->client = $client;
$this->config = $config;
$this->dispatchAfterCommit = $dispatchAfterCommit;
}
/**
* Get the size of the queue.
*
* @param string|null $queue
* @return int
*/
public function size($queue = null)
{
// It is not possible to know the number of tasks in the queue.
return 0;
}
/**
* Fallback method for Laravel 6x and 7x
*
* @param \Closure|string|object $job
* @param string $payload
* @param string $queue
* @param \DateTimeInterface|\DateInterval|int|null $delay
* @param callable $callback
* @return mixed
*/
protected function enqueueUsing($job, $payload, $queue, $delay, $callback)
{
if (method_exists(parent::class, 'enqueueUsing')) {
return parent::enqueueUsing($job, $payload, $queue, $delay, $callback);
}
return $callback($payload, $queue, $delay);
}
/**
* Push a new job onto the queue.
*
* @param string|object $job
* @param mixed $data
* @param string|null $queue
* @return void
*/
public function push($job, $data = '', $queue = null)
{
return $this->enqueueUsing(
$job,
$this->createPayload($job, $this->getQueue($queue), $data),
$queue,
null,
function ($payload, $queue) {
return $this->pushRaw($payload, $queue);
}
);
}
/**
* Push a raw payload onto the queue.
*
* @param string $payload
* @param string|null $queue
* @param array $options
* @return string
*/
public function pushRaw($payload, $queue = null, array $options = [])
{
$delay = ! empty($options['delay']) ? $options['delay'] : 0;
$this->pushToCloudTasks($queue, $payload, $delay);
}
/**
* Push a new job onto the queue after a delay.
*
* @param \DateTimeInterface|\DateInterval|int $delay
* @param string|object $job
* @param mixed $data
* @param string|null $queue
* @return void
*/
public function later($delay, $job, $data = '', $queue = null)
{
return $this->enqueueUsing(
$job,
$this->createPayload($job, $this->getQueue($queue), $data),
$queue,
$delay,
function ($payload, $queue, $delay) {
return $this->pushToCloudTasks($queue, $payload, $delay);
}
);
}
/**
* Push a job to Cloud Tasks.
*
* @param string|null $queue
* @param string $payload
* @param \DateTimeInterface|\DateInterval|int $delay
* @return string
*/
protected function pushToCloudTasks($queue, $payload, $delay = 0)
{
$queue = $this->getQueue($queue);
$queueName = $this->client->queueName($this->config['project'], $this->config['location'], $queue);
$availableAt = $this->availableAt($delay);
$httpRequest = $this->createHttpRequest();
$httpRequest->setUrl($this->getHandler());
$httpRequest->setHttpMethod(HttpMethod::POST);
// Laravel 7+ jobs have a uuid, but Laravel 6 doesn't have it.
// Since we are using and expecting the uuid in some places
// we will add it manually here if it's not present yet.
[$payload, $uuid] = $this->withUuid($payload);
// Since 3.x tasks are released back onto the queue after an exception has
// been thrown. This means we lose the native [X-CloudTasks-TaskRetryCount] header
// value and need to manually set and update the number of times a task has been attempted.
$payload = $this->withAttempts($payload);
$httpRequest->setBody($payload);
$task = $this->createTask();
$task->setHttpRequest($httpRequest);
// The deadline for requests sent to the app. If the app does not respond by
// this deadline then the request is cancelled and the attempt is marked as
// a failure. Cloud Tasks will retry the task according to the RetryConfig.
if (!empty($this->config['dispatch_deadline'])) {
$task->setDispatchDeadline(new Duration(['seconds' => $this->config['dispatch_deadline']]));
}
$token = new OidcToken;
$token->setServiceAccountEmail($this->config['service_account_email']);
$token->setAudience(hash_hmac('sha256', $this->getHandler(), config('app.key')));
$httpRequest->setOidcToken($token);
if ($availableAt > time()) {
$task->setScheduleTime(new Timestamp(['seconds' => $availableAt]));
}
$createdTask = CloudTasksApi::createTask($queueName, $task);
event((new TaskCreated)->queue($queue)->task($task));
return $uuid;
}
private function withUuid(string $payload): array
{
/** @var array $decoded */
$decoded = json_decode($payload, true);
if (!isset($decoded['uuid'])) {
$decoded['uuid'] = (string) Str::uuid();
}
return [
json_encode($decoded),
$decoded['uuid'],
];
}
private function withAttempts(string $payload): string
{
/** @var array $decoded */
$decoded = json_decode($payload, true);
if (!isset($decoded['internal']['attempts'])) {
$decoded['internal']['attempts'] = 0;
}
return json_encode($decoded);
}
/**
* Pop the next job off of the queue.
*
* @param string|null $queue
* @return \Illuminate\Contracts\Queue\Job|null
*/
public function pop($queue = null)
{
// TODO: Implement pop() method.
}
private function getQueue(?string $queue = null): string
{
return $queue ?: $this->config['queue'];
}
private function createHttpRequest(): HttpRequest
{
return app(HttpRequest::class);
}
public function delete(CloudTasksJob $job): void
{
$config = $this->config;
$queue = $job->getQueue() ?: $this->config['queue']; // @todo: make this a helper method somewhere.
$taskName = $this->client->taskName(
$config['project'],
$config['location'],
$queue,
(string) request()->headers->get('X-Cloudtasks-Taskname')
);
CloudTasksApi::deleteTask($taskName);
}
public function release(CloudTasksJob $job, int $delay = 0): void
{
$job->delete();
$payload = $job->getRawBody();
$options = ['delay' => $delay];
$this->pushRaw($payload, $job->getQueue(), $options);
}
private function createTask(): Task
{
return app(Task::class);
}
public function getHandler(): string
{
return Config::getHandler($this->config['handler']);
}
}