-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathServer.php
More file actions
671 lines (594 loc) · 22.5 KB
/
Copy pathServer.php
File metadata and controls
671 lines (594 loc) · 22.5 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
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
<?php
namespace Utopia\Queue;
use Exception;
use Throwable;
use Utopia\DI\Container;
use Utopia\Queue\Consumer\Bounded;
use Utopia\Queue\Consumer\Exclusive;
use Utopia\Queue\Publisher\Synchronous;
use Utopia\Servers\Hook;
use Utopia\Telemetry\Adapter as Telemetry;
use Utopia\Telemetry\Adapter\None as NoTelemetry;
use Utopia\Telemetry\Histogram;
use Utopia\Validator;
class Server
{
/**
* Bucket boundaries for the duration histograms, in seconds.
*
* A queue spans a wider range than a web request: a job can be picked up
* in milliseconds or sit behind an hour of backlog. The OpenTelemetry
* defaults stop at 10 seconds, which puts every observation of a slow
* queue in the overflow bucket and makes every quantile read exactly 10.
*
* @var list<float|int>
*/
private const array DURATION_BUCKETS = [
0.005,
0.01,
0.025,
0.05,
0.075,
0.1,
0.25,
0.5,
0.75,
1,
2.5,
5,
7.5,
10,
20,
30,
60,
120,
300,
600,
1200,
1800,
3600,
7200,
];
/**
* Job
*/
protected Job $job;
/**
* Named jobs keyed by queue name.
*
* @var array<string, Job>
*/
protected array $jobs = [];
/**
* Per-queue coroutine caps. Defaults to 1 (safe).
*
* @var array<string, int>
*/
protected array $coroutines = [];
/**
* @var (callable(string): Consumer)|null
*/
protected $consumer;
/**
* Hooks that will run when error occur
*
* @var array<Hook>
*/
protected array $errorHooks = [];
/**
* Hooks that will run before running job
*
* @var array<Hook>
*/
protected array $initHooks = [];
/**
* Hooks that will run after running job
*
* @var array<Hook>
*/
protected array $shutdownHooks = [];
/**
* Hooks that will run when worker starts
*
* @var array<Hook>
*/
protected array $workerStartHooks = [];
/**
* Hooks that will run when worker stops
*
* @var array<Hook>
*/
protected array $workerStopHooks = [];
/**
* Messages one receive may claim at once, per queue.
*
* @var array<string, int>
*/
protected array $prefetches = [];
private Histogram $jobWaitTime;
private Histogram $processDuration;
/**
* Creates an instance of a Queue server.
*/
public function __construct(protected Adapter $adapter)
{
$this->job = new Job();
$this->setTelemetry(new NoTelemetry());
}
/**
* Register a job for a queue. Queue name and concurrency live only here —
* the adapter is transport (processes, namespace, consumer).
*
* $coroutines limits running handlers. $prefetch limits all unacknowledged
* messages: waiting, running, and awaiting confirmation. It defaults to
* $coroutines and must be at least that value.
*/
public function job(string $queue, int $coroutines = 1, ?int $prefetch = null): Job
{
if ($queue === '') {
throw new Exception('Queue name is required');
}
$coroutines = max(1, $coroutines);
$prefetch ??= $coroutines;
if ($prefetch < $coroutines) {
throw new \InvalidArgumentException('Prefetch must be at least the number of coroutines');
}
$job = new Job();
$this->job = $job;
$this->jobs[$queue] = $job;
$this->coroutines[$queue] = $coroutines;
$this->prefetches[$queue] = $prefetch;
return $job;
}
/**
* Optional override of the adapter's consumer factory. Prefer passing the
* factory to the Adapter constructor; use this to replace it at runtime.
*
* @param callable(string): Consumer $factory
*/
public function consumer(callable $factory): self
{
$this->consumer = $factory(...);
return $this;
}
/**
* @return array<string, Job>
*/
public function jobs(): array
{
return $this->jobs;
}
public function coroutines(string $queue): int
{
return $this->coroutines[$queue] ?? 1;
}
public function prefetch(string $queue): int
{
return $this->prefetches[$queue] ?? 1;
}
protected function jobFor(Message $message): Job
{
return $this->jobs[$message->getQueue()] ?? $this->job;
}
/**
* Static resources container.
*
* Shortcut for the underlying adapter's {@see Adapter::resources()}. Use
* `$server->resources()->set(...)` to register app-wide services that are
* shared across every message for the lifetime of the server.
*/
public function resources(): Container
{
return $this->adapter->resources();
}
/**
* Per-message context container.
*
* Shortcut for the underlying adapter's {@see Adapter::context()}. Use
* `$server->context()->set(...)` to register message-scoped resources and
* `$server->context()->get(...)` to read them. Lookups fall through to the
* static resources container, so app-wide services remain accessible.
*/
public function context(): Container
{
return $this->adapter->context();
}
public function setTelemetry(Telemetry $telemetry): void
{
$this->jobWaitTime = $telemetry->createHistogram(
'messaging.process.wait.duration',
's',
null,
['ExplicitBucketBoundaries' => self::DURATION_BUCKETS],
);
// https://opentelemetry.io/docs/specs/semconv/messaging/messaging-metrics/#metric-messagingprocessduration
$this->processDuration = $telemetry->createHistogram(
'messaging.process.duration',
's',
null,
['ExplicitBucketBoundaries' => self::DURATION_BUCKETS],
);
$this->createDepthGauge(
$telemetry,
'messaging.queue.depth',
'Number of pending messages in the queue.',
failedJobs: false,
);
$this->createDepthGauge(
$telemetry,
'messaging.queue.failed.depth',
'Number of messages in the failed queue.',
failedJobs: true,
);
}
private function createDepthGauge(
Telemetry $telemetry,
string $name,
string $description,
bool $failedJobs,
): void {
$gauge = $telemetry->createObservableGauge($name, '{message}', $description);
$gauge->observe(function (callable $observe) use ($failedJobs): void {
if (!$this->adapter->consumer instanceof Synchronous) {
return;
}
$queues = array_keys($this->jobs);
foreach ($queues as $queueName) {
$queue = new Queue($queueName, $this->adapter->namespace);
try {
$size = $this->adapter->consumer->getQueueSize($queue, $failedJobs);
} catch (Throwable) {
continue;
}
$observe($size, [
'messaging.destination.name' => $queue->name,
'messaging.destination.namespace' => $queue->namespace,
]);
}
});
}
/**
* Shutdown Hooks
*/
public function shutdown(): Hook
{
$hook = new Hook();
$hook->groups(['*']);
$this->shutdownHooks[] = $hook;
return $hook;
}
/**
* Stops the Queue server.
*/
public function stop(): self
{
try {
$this->adapter->stop();
} catch (Throwable $error) {
$this->resources()->set('error', fn (): \Throwable => $error);
foreach ($this->errorHooks as $hook) {
$hook->getAction()(...$this->getArguments($this->resources(), $hook));
}
}
return $this;
}
/**
* Init Hooks
*/
public function init(): Hook
{
$hook = new Hook();
$hook->groups(['*']);
$this->initHooks[] = $hook;
return $hook;
}
/**
* Starts the Queue Server
*/
public function start(): self
{
try {
$this->adapter->workerStart(function (string $workerId): void {
$this->resources()->set('workerId', fn (): string => $workerId);
foreach ($this->workerStartHooks as $hook) {
$hook->getAction()(...$this->getArguments($this->resources(), $hook));
}
$messageCallback = function (Message $message) {
$receivedAtTimestamp = microtime(true);
$job = $this->jobFor($message);
try {
// The enqueue timestamp comes from the publisher's
// clock and this from the consumer's, so on an idle
// queue a few milliseconds of skew between the two
// hosts yields a negative duration. Recording it
// decrements a cumulative histogram sum, which every
// Prometheus reader takes for a counter reset and
// re-attributes the process's whole lifetime sum to
// one interval — one -20ms sample paged a two-hour
// queue wait on a queue that was empty throughout.
$waitDuration = max(
0.0,
microtime(true) - $message->getTimestamp(),
);
$this->jobWaitTime->record($waitDuration);
$this->context()->set('message', fn (): \Utopia\Queue\Message => $message);
if ($job->getHook()) {
foreach ($this->initHooks as $hook) {
if (\in_array('*', $hook->getGroups())) {
$arguments = $this->getArguments(
$this->context(),
$hook,
$message->getPayload(),
);
$hook->getAction()(...$arguments);
}
}
}
foreach ($job->getGroups() as $group) {
foreach ($this->initHooks as $hook) {
if (\in_array($group, $hook->getGroups())) {
$arguments = $this->getArguments(
$this->context(),
$hook,
$message->getPayload(),
);
$hook->getAction()(...$arguments);
}
}
}
return \call_user_func_array(
$job->getAction(),
$this->getArguments(
$this->context(),
$job,
$message->getPayload(),
),
);
} finally {
$this->processDuration->record(microtime(true) - $receivedAtTimestamp);
}
};
$successCallback = function (Message $message): void {
$job = $this->jobFor($message);
$this->context()->set('message', fn (): \Utopia\Queue\Message => $message);
if ($job->getHook()) {
foreach ($this->shutdownHooks as $hook) {
if (\in_array('*', $hook->getGroups())) {
$arguments = $this->getArguments(
$this->context(),
$hook,
$message->getPayload(),
);
$hook->getAction()(...$arguments);
}
}
}
foreach ($job->getGroups() as $group) {
foreach ($this->shutdownHooks as $hook) {
if (\in_array($group, $hook->getGroups())) {
$arguments = $this->getArguments(
$this->context(),
$hook,
$message->getPayload(),
);
$hook->getAction()(...$arguments);
}
}
}
};
$errorCallback = function (?Message $message, Throwable $th): void {
$this->context()->set('error', fn (): \Throwable => $th);
if ($message instanceof \Utopia\Queue\Message) {
$this->context()->set('message', fn (): \Utopia\Queue\Message => $message);
}
foreach ($this->errorHooks as $hook) {
$hook->getAction()(...$this->getArguments($this->context(), $hook));
}
};
// Jobs own queue identity and concurrency. The adapter only
// runs the consume loops those jobs describe.
if ($this->jobs === []) {
throw new Exception('At least one job() must be registered before start()');
}
// Concurrent receive loops must not share a Redis/NATS receive
// connection — protocol responses and acks would miscorrelate.
if (
\count($this->jobs) > 1
&& !\is_callable($this->consumer)
&& $this->adapter->sharesConsumer()
) {
throw new Exception(
'Multi-queue workers must pass a callable factory to the Adapter constructor (or Server::consumer()) — a shared Consumer cannot be used across concurrent receive loops',
);
}
$queues = [];
foreach (array_keys($this->jobs) as $queueName) {
$coroutines = $this->coroutines[$queueName] ?? 1;
$prefetch = $this->prefetches[$queueName] ?? 1;
$consumer = \is_callable($this->consumer)
? ($this->consumer)($queueName)
: $this->adapter->createConsumer($queueName);
// An exclusive consumer owns a single socket and does not serialise
// access to it. Above one coroutine the receive loop is parked in a
// read on it while the handlers that are still running commit, reject
// or extend on the same socket, and Swoole aborts the worker on the
// first overlap. Refuse here so a concurrency that a serialising
// consumer -- Broker\Redis and Broker\Nats both are -- carries safely
// cannot reach production as a crash loop on one that is not.
if ($prefetch > 1 && $consumer instanceof Exclusive) {
throw new Exception(\sprintf(
"Queue '%s' is registered with job('%s', %d), but its consumer %s drives a single socket that only one coroutine may read at a time. Use one coroutine with prefetch 1 and add replicas for throughput.",
$queueName,
$queueName,
$coroutines,
$consumer::class,
));
}
// A bounded consumer hands out at most N messages before it waits for
// an acknowledgment, and a message parked in redelivery backoff is one
// of those N -- asleep rather than being worked, holding a slot the
// whole time. So a ceiling at or below the coroutine cap is filled by
// as many failures as there are handlers, after which the queue is not
// delivered into at all: the wedge looks like a backlog with idle
// workers in front of it. Refuse it here, the way an exclusive
// consumer's cap is refused, rather than let it be found in a graph.
$ceiling = $consumer instanceof Bounded ? $consumer->inFlightCeiling() : null;
if ($ceiling !== null && $ceiling <= $prefetch) {
throw new Exception(\sprintf(
"Queue '%s' is registered with job('%s', %d), but its consumer %s holds at most %d message(s) in flight. Waiting retries also count toward this ceiling, so filling it with local deliveries can stop further delivery. Raise the in-flight ceiling (Broker\\Nats: maxAckPending) above %d, or lower the prefetch limit.",
$queueName,
$queueName,
$coroutines,
$consumer::class,
$ceiling,
$prefetch,
));
}
$queues[] = [
'queue' => new Queue($queueName, $this->adapter->namespace),
'coroutines' => $coroutines,
'prefetch' => $prefetch,
'consumer' => $consumer,
];
}
$this->adapter->consume($messageCallback, $successCallback, $errorCallback, $queues);
});
$this->adapter->workerStop(function (string $workerId): void {
$this->resources()->set('workerId', fn (): string => $workerId);
try {
// Call user-defined workerStop hooks
foreach ($this->workerStopHooks as $hook) {
try {
$hook->getAction()(...$this->getArguments($this->resources(), $hook));
} catch (Throwable) {
}
}
} finally {
// Always close consumer connection, even if hooks throw
$this->adapter->consumer->close();
}
});
$this->adapter->start();
} catch (Throwable $error) {
$this->resources()->set('error', fn (): \Throwable => $error);
foreach ($this->errorHooks as $hook) {
$hook->getAction()(...$this->getArguments($this->resources(), $hook));
}
throw $error;
}
return $this;
}
/**
* Is called when a Worker starts.
*/
public function workerStart(): Hook
{
$hook = new Hook();
$hook->groups(['*']);
$this->workerStartHooks[] = $hook;
return $hook;
}
/**
* Returns Worker starts hooks.
*/
public function getWorkerStart(): array
{
return $this->workerStartHooks;
}
/**
* Is called when a Worker stops.
*/
public function workerStop(): Hook
{
$hook = new Hook();
$hook->groups(['*']);
$this->workerStopHooks[] = $hook;
return $hook;
}
/**
* Returns Worker stops hooks.
*/
public function getWorkerStop(): array
{
return $this->workerStopHooks;
}
/**
* Get Arguments
*/
protected function getArguments(Container $context, Hook $hook, array $payload = []): array
{
$arguments = [];
foreach ($hook->getParams() as $key => $param) {
$payloadKey = $key;
if (!\array_key_exists($key, $payload) && !empty($param['aliases'])) {
foreach ($param['aliases'] as $alias) {
if (\array_key_exists($alias, $payload)) {
$payloadKey = $alias;
break;
}
}
}
// Get value from route or request object
$value = $payload[$payloadKey] ?? $param['default'];
$value
= $value === '' || $value === null ? $param['default'] : $value;
$this->validate($key, $param, $value, $context);
$hook->setParamValue($key, $value);
$arguments[$param['order']] = $value;
}
foreach ($hook->getInjections() as $injection) {
$arguments[$injection['order']] = $context->get(
$injection['name'],
);
}
// call_user_func_array passes integer keys in iteration order, not key
// order, so sort the two-pass (params, then injections) array by key.
ksort($arguments);
return $arguments;
}
/**
* Validate Param
*
* Creates an validator instance and validate given value with given rules.
*
*
* @throws Exception
*
*/
protected function validate(string $key, array $param, mixed $value, Container $context): void
{
if ('' !== $value && $value !== null) {
$validator = $param['validator']; // checking whether the class exists
if (\is_callable($validator)) {
$validatorKey = '_validator:' . $key;
$context->set($validatorKey, $validator, $param['injections']);
$validator = $context->get($validatorKey);
}
if (!$validator instanceof Validator) {
// is the validator object an instance of the Validator class
throw new Exception(
'Validator object is not an instance of the Validator class',
500,
);
}
if (!$validator->isValid($value)) {
throw new Exception(
'Invalid ' . $key . ': ' . $validator->getDescription(),
400,
);
}
} elseif (!$param['optional']) {
throw new Exception("Param $key is not optional.", 400);
}
}
/**
* Register hook. Will be executed when error occurs.
*/
public function error(): Hook
{
$hook = new Hook();
$hook->groups(['*']);
$this->errorHooks[] = $hook;
return $hook;
}
}