-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkislayphp_queue.cpp
More file actions
2383 lines (2131 loc) · 86.7 KB
/
kislayphp_queue.cpp
File metadata and controls
2383 lines (2131 loc) · 86.7 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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
extern "C" {
#include "php.h"
#include "ext/standard/info.h"
#include "Zend/zend_API.h"
#include "Zend/zend_interfaces.h"
#include "Zend/zend_exceptions.h"
}
#include "php_kislayphp_queue.h"
#include <algorithm>
#include <chrono>
#include <cctype>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "Zend/zend_smart_str.h"
#include "ext/standard/php_var.h"
#ifndef zend_call_method_with_0_params
static inline void kislayphp_call_method_with_0_params(
zend_object *obj,
zend_class_entry *obj_ce,
zend_function **fn_proxy,
const char *function_name,
zval *retval) {
zend_call_method(obj, obj_ce, fn_proxy, function_name, std::strlen(function_name), retval, 0, nullptr, nullptr);
}
#define zend_call_method_with_0_params(obj, obj_ce, fn_proxy, function_name, retval) \
kislayphp_call_method_with_0_params(obj, obj_ce, fn_proxy, function_name, retval)
#endif
#ifndef zend_call_method_with_1_params
static inline void kislayphp_call_method_with_1_params(
zend_object *obj,
zend_class_entry *obj_ce,
zend_function **fn_proxy,
const char *function_name,
zval *retval,
zval *param1) {
zend_call_method(obj, obj_ce, fn_proxy, function_name, std::strlen(function_name), retval, 1, param1, nullptr);
}
#define zend_call_method_with_1_params(obj, obj_ce, fn_proxy, function_name, retval, param1) \
kislayphp_call_method_with_1_params(obj, obj_ce, fn_proxy, function_name, retval, param1)
#endif
#ifndef zend_call_method_with_2_params
static inline void kislayphp_call_method_with_2_params(
zend_object *obj,
zend_class_entry *obj_ce,
zend_function **fn_proxy,
const char *function_name,
zval *retval,
zval *param1,
zval *param2) {
zend_call_method(obj, obj_ce, fn_proxy, function_name, std::strlen(function_name), retval, 2, param1, param2);
}
#define zend_call_method_with_2_params(obj, obj_ce, fn_proxy, function_name, retval, param1, param2) \
kislayphp_call_method_with_2_params(obj, obj_ce, fn_proxy, function_name, retval, param1, param2)
#endif
static zend_class_entry *kislayphp_queue_ce;
static zend_class_entry *kislayphp_queue_client_interface_ce;
static zend_class_entry *kislayphp_queue_server_ce;
static zend_class_entry *kislayphp_queue_client_ce;
static zend_class_entry *kislayphp_queue_worker_ce;
static zend_class_entry *kislayphp_queue_job_ce;
static zend_object_handlers kislayphp_queue_handlers;
static zend_object_handlers kislayphp_queue_server_handlers;
static zend_object_handlers kislayphp_queue_client_handlers;
static zend_object_handlers kislayphp_queue_worker_handlers;
static zend_object_handlers kislayphp_queue_job_handlers;
struct kislay_http_request_t {
std::string method;
std::string uri;
std::string path;
std::string query;
std::string body;
std::map<std::string, std::string> headers;
};
struct kislay_http_url_t {
std::string host;
int port;
std::string path;
};
struct kislay_queue_config_t {
zend_long visibility_timeout_ms;
zend_long max_attempts;
zend_long retry_backoff_ms;
std::string dead_letter_queue;
kislay_queue_config_t()
: visibility_timeout_ms(30000),
max_attempts(3),
retry_backoff_ms(1000),
dead_letter_queue() {}
};
struct kislay_queue_stats_t {
std::uint64_t pushed_total;
std::uint64_t fetched_total;
std::uint64_t acked_total;
std::uint64_t nacked_total;
std::uint64_t retried_total;
std::uint64_t dead_lettered_total;
std::uint64_t purged_total;
kislay_queue_stats_t()
: pushed_total(0),
fetched_total(0),
acked_total(0),
nacked_total(0),
retried_total(0),
dead_lettered_total(0),
purged_total(0) {}
};
struct kislay_queue_job_record_t {
std::string id;
std::string queue;
std::string payload_bytes;
std::string headers_bytes;
zend_long attempts;
zend_long max_attempts;
std::uint64_t created_at_ms;
std::uint64_t available_at_ms;
std::uint64_t lease_until_ms;
std::string status;
std::string worker_id;
kislay_queue_job_record_t()
: attempts(0),
max_attempts(3),
created_at_ms(0),
available_at_ms(0),
lease_until_ms(0),
status("ready") {}
};
struct kislay_queue_fetch_result_t {
bool found;
std::string id;
std::string queue;
std::string payload_bytes;
std::string headers_bytes;
zend_long attempts;
zend_long max_attempts;
std::uint64_t available_at_ms;
kislay_queue_fetch_result_t()
: found(false), attempts(0), max_attempts(0), available_at_ms(0) {}
};
typedef struct _php_kislayphp_queue_t {
std::unordered_map<std::string, std::vector<zval>> queues;
pthread_mutex_t lock;
zval client;
bool has_client;
zend_object std;
} php_kislayphp_queue_t;
typedef struct _php_kislayphp_queue_server_t {
std::unordered_map<std::string, kislay_queue_config_t> configs;
std::unordered_map<std::string, std::vector<std::string>> queue_jobs;
std::unordered_map<std::string, kislay_queue_job_record_t> jobs;
std::unordered_map<std::string, kislay_queue_stats_t> stats;
std::string host;
zend_long port;
int listen_fd;
bool running;
std::uint64_t next_job_id;
pthread_mutex_t lock;
zend_object std;
} php_kislayphp_queue_server_t;
typedef struct _php_kislayphp_queue_client_t {
std::string base_url;
zend_object std;
} php_kislayphp_queue_client_t;
typedef struct _php_kislayphp_queue_worker_t {
std::string base_url;
bool stop_requested;
zend_object std;
} php_kislayphp_queue_worker_t;
typedef struct _php_kislayphp_queue_job_t {
std::string base_url;
std::string id;
std::string queue;
zval payload;
zval headers;
zend_long attempts;
zend_long max_attempts;
std::uint64_t available_at_ms;
bool finished;
zend_object std;
} php_kislayphp_queue_job_t;
struct kislay_scoped_lock_t {
pthread_mutex_t *lock;
explicit kislay_scoped_lock_t(pthread_mutex_t *target) : lock(target) {
pthread_mutex_lock(lock);
}
~kislay_scoped_lock_t() {
pthread_mutex_unlock(lock);
}
};
static inline php_kislayphp_queue_t *php_kislayphp_queue_from_obj(zend_object *obj) {
return reinterpret_cast<php_kislayphp_queue_t *>(reinterpret_cast<char *>(obj) - XtOffsetOf(php_kislayphp_queue_t, std));
}
static inline php_kislayphp_queue_server_t *php_kislayphp_queue_server_from_obj(zend_object *obj) {
return reinterpret_cast<php_kislayphp_queue_server_t *>(reinterpret_cast<char *>(obj) - XtOffsetOf(php_kislayphp_queue_server_t, std));
}
static inline php_kislayphp_queue_client_t *php_kislayphp_queue_client_from_obj(zend_object *obj) {
return reinterpret_cast<php_kislayphp_queue_client_t *>(reinterpret_cast<char *>(obj) - XtOffsetOf(php_kislayphp_queue_client_t, std));
}
static inline php_kislayphp_queue_worker_t *php_kislayphp_queue_worker_from_obj(zend_object *obj) {
return reinterpret_cast<php_kislayphp_queue_worker_t *>(reinterpret_cast<char *>(obj) - XtOffsetOf(php_kislayphp_queue_worker_t, std));
}
static inline php_kislayphp_queue_job_t *php_kislayphp_queue_job_from_obj(zend_object *obj) {
return reinterpret_cast<php_kislayphp_queue_job_t *>(reinterpret_cast<char *>(obj) - XtOffsetOf(php_kislayphp_queue_job_t, std));
}
static std::uint64_t kislay_now_ms() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count());
}
static void kislay_sleep_ms(zend_long value) {
if (value <= 0) {
value = 1;
}
usleep(static_cast<useconds_t>(value * 1000));
}
static bool kislay_call_function(const char *name, zval *retval, uint32_t param_count, zval params[]) {
zval function_name;
ZVAL_STRING(&function_name, name);
int result = call_user_function(EG(function_table), nullptr, &function_name, retval, param_count, params);
zval_ptr_dtor(&function_name);
return result == SUCCESS;
}
static bool kislay_json_encode_zval(zval *value, std::string *out) {
zval retval;
zval params[1];
ZVAL_COPY(¶ms[0], value);
ZVAL_UNDEF(&retval);
bool ok = kislay_call_function("json_encode", &retval, 1, params);
zval_ptr_dtor(¶ms[0]);
if (!ok || Z_TYPE(retval) != IS_STRING) {
if (!Z_ISUNDEF(retval)) {
zval_ptr_dtor(&retval);
}
return false;
}
*out = std::string(Z_STRVAL(retval), Z_STRLEN(retval));
zval_ptr_dtor(&retval);
return true;
}
static bool kislay_json_decode_assoc(const std::string &json, zval *return_value) {
zval retval;
zval params[2];
ZVAL_STRINGL(¶ms[0], json.c_str(), json.size());
ZVAL_TRUE(¶ms[1]);
ZVAL_UNDEF(&retval);
bool ok = kislay_call_function("json_decode", &retval, 2, params);
zval_ptr_dtor(¶ms[0]);
zval_ptr_dtor(¶ms[1]);
if (!ok || Z_ISUNDEF(retval)) {
if (!Z_ISUNDEF(retval)) {
zval_ptr_dtor(&retval);
}
return false;
}
ZVAL_COPY_VALUE(return_value, &retval);
return true;
}
static std::string kislay_trim(const std::string &value) {
std::size_t start = 0;
while (start < value.size() && std::isspace(static_cast<unsigned char>(value[start]))) {
start++;
}
std::size_t end = value.size();
while (end > start && std::isspace(static_cast<unsigned char>(value[end - 1]))) {
end--;
}
return value.substr(start, end - start);
}
static std::string kislay_to_lower(std::string value) {
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char ch) {
return static_cast<char>(std::tolower(ch));
});
return value;
}
static std::string kislay_url_decode(const std::string &value) {
std::string result;
result.reserve(value.size());
for (std::size_t i = 0; i < value.size(); ++i) {
if (value[i] == '%' && i + 2 < value.size()) {
char hex[3] = {value[i + 1], value[i + 2], '\0'};
char *endptr = nullptr;
long decoded = std::strtol(hex, &endptr, 16);
if (endptr != nullptr && *endptr == '\0') {
result.push_back(static_cast<char>(decoded));
i += 2;
continue;
}
}
if (value[i] == '+') {
result.push_back(' ');
} else {
result.push_back(value[i]);
}
}
return result;
}
static std::vector<std::string> kislay_split(const std::string &value, char delimiter) {
std::vector<std::string> parts;
std::stringstream stream(value);
std::string item;
while (std::getline(stream, item, delimiter)) {
parts.push_back(item);
}
return parts;
}
static std::map<std::string, std::string> kislay_parse_query(const std::string &query) {
std::map<std::string, std::string> out;
std::vector<std::string> pairs = kislay_split(query, '&');
for (std::size_t i = 0; i < pairs.size(); ++i) {
if (pairs[i].empty()) {
continue;
}
std::size_t eq = pairs[i].find('=');
if (eq == std::string::npos) {
out[kislay_url_decode(pairs[i])] = "";
} else {
out[kislay_url_decode(pairs[i].substr(0, eq))] = kislay_url_decode(pairs[i].substr(eq + 1));
}
}
return out;
}
static bool kislay_parse_http_url(const std::string &url, kislay_http_url_t *parsed) {
std::string work = url;
const std::string http_prefix("http://");
if (work.compare(0, http_prefix.size(), http_prefix) == 0) {
work = work.substr(http_prefix.size());
}
std::size_t slash = work.find('/');
std::string authority = slash == std::string::npos ? work : work.substr(0, slash);
parsed->path = slash == std::string::npos ? "/" : work.substr(slash);
std::size_t colon = authority.rfind(':');
if (colon == std::string::npos) {
parsed->host = authority;
parsed->port = 80;
} else {
parsed->host = authority.substr(0, colon);
parsed->port = std::atoi(authority.substr(colon + 1).c_str());
if (parsed->port <= 0) {
parsed->port = 80;
}
}
return !parsed->host.empty();
}
static bool kislay_http_request(const std::string &method, const std::string &url, const std::string &body, int *status_code, std::string *response_body, std::string *error) {
kislay_http_url_t parsed;
if (!kislay_parse_http_url(url, &parsed)) {
if (error != nullptr) {
*error = "Invalid URL";
}
return false;
}
struct addrinfo hints;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo *result = nullptr;
std::string port = std::to_string(parsed.port);
if (getaddrinfo(parsed.host.c_str(), port.c_str(), &hints, &result) != 0) {
if (error != nullptr) {
*error = "getaddrinfo failed";
}
return false;
}
int fd = -1;
for (struct addrinfo *rp = result; rp != nullptr; rp = rp->ai_next) {
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (fd == -1) {
continue;
}
if (connect(fd, rp->ai_addr, rp->ai_addrlen) == 0) {
break;
}
close(fd);
fd = -1;
}
freeaddrinfo(result);
if (fd == -1) {
if (error != nullptr) {
*error = "connect failed";
}
return false;
}
std::ostringstream request;
request << method << " " << parsed.path << " HTTP/1.1\r\n";
request << "Host: " << parsed.host << "\r\n";
request << "Connection: close\r\n";
if (!body.empty()) {
request << "Content-Type: application/json\r\n";
request << "Content-Length: " << body.size() << "\r\n";
}
request << "\r\n";
request << body;
const std::string wire = request.str();
std::size_t sent = 0;
while (sent < wire.size()) {
ssize_t wrote = send(fd, wire.data() + sent, wire.size() - sent, 0);
if (wrote <= 0) {
if (error != nullptr) {
*error = "send failed";
}
close(fd);
return false;
}
sent += static_cast<std::size_t>(wrote);
}
std::string response;
char buffer[4096];
for (;;) {
ssize_t received = recv(fd, buffer, sizeof(buffer), 0);
if (received == 0) {
break;
}
if (received < 0) {
if (error != nullptr) {
*error = "recv failed";
}
close(fd);
return false;
}
response.append(buffer, static_cast<std::size_t>(received));
}
close(fd);
std::size_t header_end = response.find("\r\n\r\n");
if (header_end == std::string::npos) {
if (error != nullptr) {
*error = "Invalid HTTP response";
}
return false;
}
std::string headers = response.substr(0, header_end);
if (response_body != nullptr) {
*response_body = response.substr(header_end + 4);
}
std::size_t first_space = headers.find(' ');
if (first_space == std::string::npos) {
if (error != nullptr) {
*error = "Invalid status line";
}
return false;
}
std::size_t second_space = headers.find(' ', first_space + 1);
std::string code = headers.substr(first_space + 1, second_space == std::string::npos ? std::string::npos : (second_space - first_space - 1));
if (status_code != nullptr) {
*status_code = std::atoi(code.c_str());
}
return true;
}
static bool kislay_http_read_request(int fd, kislay_http_request_t *request) {
std::string incoming;
char buffer[4096];
std::size_t header_end = std::string::npos;
while ((header_end = incoming.find("\r\n\r\n")) == std::string::npos) {
ssize_t received = recv(fd, buffer, sizeof(buffer), 0);
if (received <= 0) {
return false;
}
incoming.append(buffer, static_cast<std::size_t>(received));
if (incoming.size() > 1024 * 1024) {
return false;
}
}
std::string header_block = incoming.substr(0, header_end);
std::string body = incoming.substr(header_end + 4);
std::istringstream stream(header_block);
std::string request_line;
if (!std::getline(stream, request_line)) {
return false;
}
if (!request_line.empty() && request_line[request_line.size() - 1] == '\r') {
request_line.erase(request_line.size() - 1);
}
std::istringstream line_stream(request_line);
line_stream >> request->method >> request->uri;
std::string header_line;
std::size_t content_length = 0;
while (std::getline(stream, header_line)) {
if (!header_line.empty() && header_line[header_line.size() - 1] == '\r') {
header_line.erase(header_line.size() - 1);
}
std::size_t colon = header_line.find(':');
if (colon == std::string::npos) {
continue;
}
std::string key = kislay_to_lower(kislay_trim(header_line.substr(0, colon)));
std::string value = kislay_trim(header_line.substr(colon + 1));
request->headers[key] = value;
if (key == "content-length") {
content_length = static_cast<std::size_t>(std::strtoull(value.c_str(), nullptr, 10));
}
}
while (body.size() < content_length) {
ssize_t received = recv(fd, buffer, sizeof(buffer), 0);
if (received <= 0) {
return false;
}
body.append(buffer, static_cast<std::size_t>(received));
}
request->body = body.substr(0, content_length);
std::size_t q = request->uri.find('?');
request->path = q == std::string::npos ? request->uri : request->uri.substr(0, q);
request->query = q == std::string::npos ? std::string() : request->uri.substr(q + 1);
return true;
}
static void kislay_http_send_response(int fd, int status_code, const std::string &content_type, const std::string &body) {
std::ostringstream response;
const char *status_text = "OK";
if (status_code == 201) status_text = "Created";
if (status_code == 400) status_text = "Bad Request";
if (status_code == 404) status_text = "Not Found";
if (status_code == 405) status_text = "Method Not Allowed";
if (status_code == 500) status_text = "Internal Server Error";
response << "HTTP/1.1 " << status_code << ' ' << status_text << "\r\n";
response << "Content-Type: " << content_type << "\r\n";
response << "Content-Length: " << body.size() << "\r\n";
response << "Connection: close\r\n\r\n";
response << body;
const std::string wire = response.str();
send(fd, wire.data(), wire.size(), 0);
}
static std::string kislay_hex_encode(const std::string &input) {
static const char *digits = "0123456789abcdef";
std::string out;
out.reserve(input.size() * 2);
for (std::size_t i = 0; i < input.size(); ++i) {
unsigned char ch = static_cast<unsigned char>(input[i]);
out.push_back(digits[(ch >> 4) & 0x0F]);
out.push_back(digits[ch & 0x0F]);
}
return out;
}
static int kislay_hex_value(char ch) {
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'a' && ch <= 'f') return 10 + (ch - 'a');
if (ch >= 'A' && ch <= 'F') return 10 + (ch - 'A');
return -1;
}
static bool kislay_hex_decode(const std::string &input, std::string *out) {
if ((input.size() % 2) != 0) {
return false;
}
out->clear();
out->reserve(input.size() / 2);
for (std::size_t i = 0; i < input.size(); i += 2) {
int high = kislay_hex_value(input[i]);
int low = kislay_hex_value(input[i + 1]);
if (high < 0 || low < 0) {
return false;
}
out->push_back(static_cast<char>((high << 4) | low));
}
return true;
}
static bool kislay_serialize_payload(zval *payload, std::string *out) {
zval retval;
zval params[1];
ZVAL_COPY(¶ms[0], payload);
ZVAL_UNDEF(&retval);
bool ok = kislay_call_function("serialize", &retval, 1, params);
zval_ptr_dtor(¶ms[0]);
if (!ok || Z_TYPE(retval) != IS_STRING) {
if (!Z_ISUNDEF(retval)) {
zval_ptr_dtor(&retval);
}
return false;
}
out->assign(Z_STRVAL(retval), Z_STRLEN(retval));
zval_ptr_dtor(&retval);
return true;
}
static bool kislay_unserialize_payload(const std::string &data, zval *out) {
zval retval;
zval params[1];
ZVAL_STRINGL(¶ms[0], data.c_str(), data.size());
ZVAL_UNDEF(&retval);
bool ok = kislay_call_function("unserialize", &retval, 1, params);
zval_ptr_dtor(¶ms[0]);
if (!ok || Z_ISUNDEF(retval)) {
if (!Z_ISUNDEF(retval)) {
zval_ptr_dtor(&retval);
}
return false;
}
ZVAL_COPY_VALUE(out, &retval);
return true;
}
static bool kislay_hash_find_string(HashTable *ht, const char *key, std::string *out) {
zval *value = zend_hash_str_find(ht, key, std::strlen(key));
if (value == nullptr || Z_TYPE_P(value) == IS_NULL) {
return false;
}
zend_string *str = zval_get_string(value);
*out = std::string(ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
return true;
}
static zend_long kislay_hash_find_long(HashTable *ht, const char *key, zend_long fallback) {
zval *value = zend_hash_str_find(ht, key, std::strlen(key));
if (value == nullptr || Z_TYPE_P(value) == IS_NULL) {
return fallback;
}
return zval_get_long(value);
}
static bool kislay_hash_find_bool(HashTable *ht, const char *key, bool fallback) {
zval *value = zend_hash_str_find(ht, key, std::strlen(key));
if (value == nullptr || Z_TYPE_P(value) == IS_NULL) {
return fallback;
}
return zend_is_true(value);
}
static zval *kislay_hash_find(HashTable *ht, const char *key) {
return zend_hash_str_find(ht, key, std::strlen(key));
}
static bool kislay_queue_is_dlq_name(const std::string &queue) {
return queue.size() >= 4 && queue.compare(queue.size() - 4, 4, ".dlq") == 0;
}
static kislay_queue_config_t kislay_queue_default_config(const std::string &queue) {
kislay_queue_config_t config;
if (!kislay_queue_is_dlq_name(queue)) {
config.dead_letter_queue = queue + ".dlq";
}
return config;
}
static std::string kislay_queue_make_job_id(php_kislayphp_queue_server_t *server) {
server->next_job_id++;
std::ostringstream oss;
oss << "job_" << static_cast<unsigned long long>(kislay_now_ms()) << '_' << static_cast<unsigned long long>(server->next_job_id);
return oss.str();
}
static kislay_queue_config_t &kislay_queue_ensure_config_locked(php_kislayphp_queue_server_t *server, const std::string &queue) {
std::unordered_map<std::string, kislay_queue_config_t>::iterator it = server->configs.find(queue);
if (it == server->configs.end()) {
it = server->configs.insert(std::make_pair(queue, kislay_queue_default_config(queue))).first;
}
return it->second;
}
static kislay_queue_stats_t &kislay_queue_ensure_stats_locked(php_kislayphp_queue_server_t *server, const std::string &queue) {
return server->stats[queue];
}
static void kislay_queue_remove_job_id(std::vector<std::string> *ids, const std::string &job_id) {
ids->erase(std::remove(ids->begin(), ids->end(), job_id), ids->end());
}
static void kislay_queue_move_to_dlq_locked(php_kislayphp_queue_server_t *server, kislay_queue_job_record_t *job) {
kislay_queue_config_t &source_config = kislay_queue_ensure_config_locked(server, job->queue);
std::string source_queue = job->queue;
kislay_queue_ensure_stats_locked(server, source_queue).dead_lettered_total++;
if (source_config.dead_letter_queue.empty()) {
std::vector<std::string> &source_ids = server->queue_jobs[source_queue];
kislay_queue_remove_job_id(&source_ids, job->id);
server->jobs.erase(job->id);
return;
}
std::string dlq_name = source_config.dead_letter_queue;
kislay_queue_ensure_config_locked(server, dlq_name);
std::vector<std::string> &source_ids = server->queue_jobs[source_queue];
kislay_queue_remove_job_id(&source_ids, job->id);
job->queue = dlq_name;
job->status = "ready";
job->lease_until_ms = 0;
job->available_at_ms = kislay_now_ms();
job->worker_id.clear();
server->queue_jobs[dlq_name].push_back(job->id);
}
static bool kislay_queue_job_ack_locked(php_kislayphp_queue_server_t *server, const std::string &job_id) {
std::unordered_map<std::string, kislay_queue_job_record_t>::iterator it = server->jobs.find(job_id);
if (it == server->jobs.end()) {
return false;
}
std::string queue = it->second.queue;
std::vector<std::string> &ids = server->queue_jobs[queue];
kislay_queue_remove_job_id(&ids, job_id);
kislay_queue_ensure_stats_locked(server, queue).acked_total++;
server->jobs.erase(it);
return true;
}
static bool kislay_queue_job_nack_locked(php_kislayphp_queue_server_t *server, const std::string &job_id, bool requeue, zend_long delay_ms) {
std::unordered_map<std::string, kislay_queue_job_record_t>::iterator it = server->jobs.find(job_id);
if (it == server->jobs.end()) {
return false;
}
kislay_queue_job_record_t &job = it->second;
kislay_queue_stats_t &stats = kislay_queue_ensure_stats_locked(server, job.queue);
stats.nacked_total++;
kislay_queue_config_t &config = kislay_queue_ensure_config_locked(server, job.queue);
if (!requeue || job.attempts >= job.max_attempts) {
kislay_queue_move_to_dlq_locked(server, &job);
return true;
}
zend_long actual_delay = delay_ms >= 0 ? delay_ms : config.retry_backoff_ms;
if (actual_delay < 0) {
actual_delay = 0;
}
job.worker_id.clear();
job.lease_until_ms = 0;
job.available_at_ms = kislay_now_ms() + static_cast<std::uint64_t>(actual_delay);
job.status = actual_delay > 0 ? "delayed" : "ready";
stats.retried_total++;
return true;
}
static void kislay_queue_reconcile_job_locked(php_kislayphp_queue_server_t *server, kislay_queue_job_record_t *job, std::uint64_t now_ms) {
if (job->status == "delayed" && job->available_at_ms <= now_ms) {
job->status = "ready";
return;
}
if (job->status == "leased" && job->lease_until_ms <= now_ms) {
kislay_queue_config_t &config = kislay_queue_ensure_config_locked(server, job->queue);
if (job->attempts >= job->max_attempts) {
kislay_queue_move_to_dlq_locked(server, job);
return;
}
job->worker_id.clear();
job->lease_until_ms = 0;
job->available_at_ms = now_ms + static_cast<std::uint64_t>(config.retry_backoff_ms > 0 ? config.retry_backoff_ms : 0);
job->status = config.retry_backoff_ms > 0 ? "delayed" : "ready";
kislay_queue_ensure_stats_locked(server, job->queue).retried_total++;
}
}
static std::string kislay_queue_push_locked(php_kislayphp_queue_server_t *server, const std::string &queue, const std::string &payload_bytes, const std::string &headers_bytes, zend_long delay_ms, zend_long max_attempts) {
kislay_queue_config_t &config = kislay_queue_ensure_config_locked(server, queue);
kislay_queue_stats_t &stats = kislay_queue_ensure_stats_locked(server, queue);
kislay_queue_job_record_t job;
job.id = kislay_queue_make_job_id(server);
job.queue = queue;
job.payload_bytes = payload_bytes;
job.headers_bytes = headers_bytes;
job.created_at_ms = kislay_now_ms();
if (delay_ms < 0) {
delay_ms = 0;
}
job.available_at_ms = job.created_at_ms + static_cast<std::uint64_t>(delay_ms);
job.max_attempts = max_attempts > 0 ? max_attempts : config.max_attempts;
job.status = delay_ms > 0 ? "delayed" : "ready";
server->jobs[job.id] = job;
server->queue_jobs[queue].push_back(job.id);
stats.pushed_total++;
return job.id;
}
static bool kislay_queue_fetch_locked(php_kislayphp_queue_server_t *server, const std::string &queue, zend_long lease_ms, const std::string &worker_id, kislay_queue_fetch_result_t *result) {
kislay_queue_ensure_config_locked(server, queue);
std::vector<std::string> &ids = server->queue_jobs[queue];
std::uint64_t now_ms = kislay_now_ms();
if (lease_ms <= 0) {
lease_ms = kislay_queue_ensure_config_locked(server, queue).visibility_timeout_ms;
}
if (lease_ms <= 0) {
lease_ms = 30000;
}
for (std::size_t i = 0; i < ids.size(); ++i) {
std::unordered_map<std::string, kislay_queue_job_record_t>::iterator it = server->jobs.find(ids[i]);
if (it == server->jobs.end()) {
ids.erase(ids.begin() + i);
i--;
continue;
}
kislay_queue_job_record_t &job = it->second;
std::string original_queue = job.queue;
kislay_queue_reconcile_job_locked(server, &job, now_ms);
if (job.queue != original_queue) {
i--;
continue;
}
if (job.status == "ready" && job.available_at_ms <= now_ms) {
job.status = "leased";
job.lease_until_ms = now_ms + static_cast<std::uint64_t>(lease_ms);
job.worker_id = worker_id;
job.attempts++;
kislay_queue_ensure_stats_locked(server, queue).fetched_total++;
result->found = true;
result->id = job.id;
result->queue = job.queue;
result->payload_bytes = job.payload_bytes;
result->headers_bytes = job.headers_bytes;
result->attempts = job.attempts;
result->max_attempts = job.max_attempts;
result->available_at_ms = job.available_at_ms;
return true;
}
}
result->found = false;
return true;
}
static void kislay_queue_collect_counts_locked(php_kislayphp_queue_server_t *server, const std::string &queue, std::uint64_t *ready, std::uint64_t *delayed, std::uint64_t *leased) {
*ready = 0;
*delayed = 0;
*leased = 0;
std::vector<std::string> &ids = server->queue_jobs[queue];
std::uint64_t now_ms = kislay_now_ms();
for (std::size_t i = 0; i < ids.size(); ++i) {
std::unordered_map<std::string, kislay_queue_job_record_t>::iterator it = server->jobs.find(ids[i]);
if (it == server->jobs.end()) {
ids.erase(ids.begin() + i);
i--;
continue;
}
kislay_queue_job_record_t &job = it->second;
std::string original_queue = job.queue;
kislay_queue_reconcile_job_locked(server, &job, now_ms);
if (job.queue != original_queue) {
i--;
continue;
}
if (job.status == "ready") {
(*ready)++;
} else if (job.status == "delayed") {
(*delayed)++;
} else if (job.status == "leased") {
(*leased)++;
}
}
}
static void kislay_queue_stats_to_zval(php_kislayphp_queue_server_t *server, const std::string &queue, zval *return_value) {
kislay_queue_stats_t &stats = kislay_queue_ensure_stats_locked(server, queue);
std::uint64_t ready = 0;
std::uint64_t delayed = 0;
std::uint64_t leased = 0;
kislay_queue_collect_counts_locked(server, queue, &ready, &delayed, &leased);
array_init(return_value);
add_assoc_string(return_value, "queue", const_cast<char *>(queue.c_str()));
add_assoc_long(return_value, "ready", static_cast<zend_long>(ready));
add_assoc_long(return_value, "delayed", static_cast<zend_long>(delayed));
add_assoc_long(return_value, "leased", static_cast<zend_long>(leased));
add_assoc_long(return_value, "pushed_total", static_cast<zend_long>(stats.pushed_total));
add_assoc_long(return_value, "fetched_total", static_cast<zend_long>(stats.fetched_total));
add_assoc_long(return_value, "acked_total", static_cast<zend_long>(stats.acked_total));
add_assoc_long(return_value, "nacked_total", static_cast<zend_long>(stats.nacked_total));
add_assoc_long(return_value, "retried_total", static_cast<zend_long>(stats.retried_total));
add_assoc_long(return_value, "dead_lettered_total", static_cast<zend_long>(stats.dead_lettered_total));
add_assoc_long(return_value, "purged_total", static_cast<zend_long>(stats.purged_total));
}
static zend_long kislay_queue_purge_locked(php_kislayphp_queue_server_t *server, const std::string &queue) {
zend_long removed = 0;
std::vector<std::string> &ids = server->queue_jobs[queue];
for (std::size_t i = 0; i < ids.size(); ++i) {
removed++;
server->jobs.erase(ids[i]);
}
ids.clear();
kislay_queue_ensure_stats_locked(server, queue).purged_total += static_cast<std::uint64_t>(removed);
return removed;
}
static bool kislay_queue_build_json_body(zval *root, std::string *json, std::string *error) {
if (kislay_json_encode_zval(root, json)) {
return true;
}
if (error != nullptr) {
*error = "Failed to encode JSON";
}
return false;
}
static bool kislay_queue_path_extract(const std::string &path, const std::string &prefix, const std::string &suffix, std::string *value) {
if (path.size() < prefix.size() + suffix.size()) {
return false;
}
if (path.compare(0, prefix.size(), prefix) != 0) {
return false;
}
if (path.compare(path.size() - suffix.size(), suffix.size(), suffix) != 0) {
return false;
}
*value = kislay_url_decode(path.substr(prefix.size(), path.size() - prefix.size() - suffix.size()));
return true;
}
static bool kislay_queue_client_request_json(const std::string &method, const std::string &url, const std::string &body, zval *decoded, std::string *error) {
int status = 0;
std::string response_body;
if (!kislay_http_request(method, url, body, &status, &response_body, error)) {
return false;
}
if (status < 200 || status >= 300) {
if (error != nullptr) {
*error = "Queue server responded with HTTP " + std::to_string(status);
}
return false;
}
if (response_body.empty()) {
array_init(decoded);
return true;
}
if (!kislay_json_decode_assoc(response_body, decoded) || Z_TYPE_P(decoded) != IS_ARRAY) {
if (!Z_ISUNDEF_P(decoded)) {
zval_ptr_dtor(decoded);
}
if (error != nullptr) {
*error = "Invalid JSON response";
}
return false;
}