-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcppq.hpp
More file actions
1069 lines (915 loc) · 34.2 KB
/
cppq.hpp
File metadata and controls
1069 lines (915 loc) · 34.2 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
#pragma once
#include <hiredis/hiredis.h>
#include <uuid/uuid.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <exception>
#include <functional>
#include <future>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <shared_mutex>
#include <string>
#include <string_view>
#include <thread>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
namespace cppq {
inline constexpr char enqueueScript[] = R"DOC(
local queue = ARGV[1]
local uuid = ARGV[2]
local type = ARGV[3]
local payload = ARGV[4]
local state = ARGV[5]
local maxRetry = ARGV[6]
local retried = ARGV[7]
local dequeuedAtMs = ARGV[8]
local scheduleType = ARGV[9]
local scheduleValue = ARGV[10]
if scheduleType == 'none' then
redis.call('LPUSH', 'cppq:' .. queue .. ':pending', uuid)
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid,
'type', type, 'payload', payload, 'state', state,
'maxRetry', maxRetry, 'retried', retried, 'dequeuedAtMs', dequeuedAtMs)
elseif scheduleType == 'time' then
redis.call('LPUSH', 'cppq:' .. queue .. ':scheduled', uuid)
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid,
'type', type, 'payload', payload, 'state', state,
'maxRetry', maxRetry, 'retried', retried, 'dequeuedAtMs', dequeuedAtMs,
'schedule', scheduleValue)
elseif scheduleType == 'cron' then
redis.call('LPUSH', 'cppq:' .. queue .. ':scheduled', uuid)
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid,
'type', type, 'payload', payload, 'state', state,
'maxRetry', maxRetry, 'retried', retried, 'dequeuedAtMs', dequeuedAtMs,
'cron', scheduleValue)
end
return 'OK'
)DOC";
inline constexpr char dequeueScript[] = R"DOC(
local queue = ARGV[1]
local dequeuedAtMs = ARGV[2]
local pending = redis.call('LRANGE', 'cppq:' .. queue .. ':pending', -1, -1)
if #pending == 0 then
return nil
end
local uuid = pending[1]
redis.call('LREM', 'cppq:' .. queue .. ':pending', 1, uuid)
local task = redis.call('HGETALL', 'cppq:' .. queue .. ':task:' .. uuid)
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid, 'dequeuedAtMs', dequeuedAtMs, 'state', 'Active')
redis.call('LPUSH', 'cppq:' .. queue .. ':active', uuid)
return {uuid, task}
)DOC";
inline constexpr char dequeueScheduledScript[] = R"DOC(
local queue = ARGV[1]
local dequeuedAtMs = ARGV[2]
local getScheduledSHA = ARGV[3]
local uuid = redis.call('EVALSHA', getScheduledSHA, 0, queue)
if not uuid then
return nil
end
redis.call('LREM', 'cppq:' .. queue .. ':scheduled', 1, uuid)
local task = redis.call('HGETALL', 'cppq:' .. queue .. ':task:' .. uuid)
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid, 'dequeuedAtMs', dequeuedAtMs, 'state', 'Active')
redis.call('LPUSH', 'cppq:' .. queue .. ':active', uuid)
return {uuid, task}
)DOC";
inline constexpr char taskSuccessScript[] = R"DOC(
local queue = ARGV[1]
local uuid = ARGV[2]
local result = ARGV[3]
redis.call('LREM', 'cppq:' .. queue .. ':active', 1, uuid)
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid, 'state', 'Completed', 'result', result)
redis.call('LPUSH', 'cppq:' .. queue .. ':completed', uuid)
return 'OK'
)DOC";
inline constexpr char taskFailureScript[] = R"DOC(
local queue = ARGV[1]
local uuid = ARGV[2]
local retried = ARGV[3]
local maxRetry = ARGV[4]
redis.call('LREM', 'cppq:' .. queue .. ':active', 1, uuid)
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid, 'retried', retried)
if tonumber(retried) >= tonumber(maxRetry) then
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid, 'state', 'Failed')
redis.call('LPUSH', 'cppq:' .. queue .. ':failed', uuid)
else
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid, 'state', 'Pending')
redis.call('LPUSH', 'cppq:' .. queue .. ':pending', uuid)
end
return 'OK'
)DOC";
inline constexpr char recoveryScript[] = R"DOC(
local queue = ARGV[1]
local uuid = ARGV[2]
local hasSchedule = ARGV[3]
redis.call('LREM', 'cppq:' .. queue .. ':active', 1, uuid)
redis.call('HSET', 'cppq:' .. queue .. ':task:' .. uuid, 'state', 'Pending')
if hasSchedule == '0' then
redis.call('LPUSH', 'cppq:' .. queue .. ':pending', uuid)
else
redis.call('LPUSH', 'cppq:' .. queue .. ':scheduled', uuid)
end
return 'OK'
)DOC";
inline constexpr char getScheduledScript[] = R"DOC(
local timeCall = redis.call('TIME')
local nowMs = tonumber(timeCall[1]) * 1000 + math.floor(tonumber(timeCall[2]) / 1000)
local scheduled = redis.call('LRANGE', 'cppq:' .. ARGV[1] .. ':scheduled', 0, -1)
-- Iterate from tail to preserve FIFO order for ready scheduled tasks.
for i = #scheduled, 1, -1 do
local uuid = scheduled[i]
local scheduleAt = redis.call('HGET', 'cppq:' .. ARGV[1] .. ':task:' .. uuid, 'schedule')
if scheduleAt then
local scheduleAtMs = tonumber(scheduleAt)
if scheduleAtMs and scheduleAtMs <= nowMs then
return uuid
end
end
end
return nil
)DOC";
using concurrency_t =
std::invoke_result_t<decltype(std::thread::hardware_concurrency)>;
enum class ErrorCode {
Success = 0,
ConnectionFailed,
EnqueueFailed,
DequeueFailed,
InvalidTask,
RedisError,
TaskNotFound,
QueueEmpty
};
class CppqException : public std::exception {
public:
CppqException(ErrorCode code, std::string_view message)
: code_(code), message_(message) {}
const char* what() const noexcept override { return message_.c_str(); }
ErrorCode code() const noexcept { return code_; }
private:
ErrorCode code_;
std::string message_;
};
class UUID {
public:
UUID() { uuid_generate(data_.data()); }
explicit UUID(const uuid_t uuid) {
std::copy(uuid, uuid + 16, data_.begin());
}
explicit UUID(std::string_view uuid_str) {
uuid_t temp;
if (uuid_parse(uuid_str.data(), temp) != 0) {
throw CppqException(ErrorCode::InvalidTask, "Invalid UUID string");
}
std::copy(std::begin(temp), std::end(temp), data_.begin());
}
std::string toString() const {
char uuid_str[37];
uuid_unparse_lower(data_.data(), uuid_str);
return uuid_str;
}
const std::array<unsigned char, 16>& data() const noexcept { return data_; }
private:
std::array<unsigned char, 16> data_;
};
class RedisConnection {
public:
explicit RedisConnection(const redisOptions& options)
: ctx_(redisConnectWithOptions(&options), redisFree) {
if (!ctx_ || ctx_->err) {
throw CppqException(
ErrorCode::ConnectionFailed,
ctx_ ? ctx_->errstr : "Failed to allocate Redis context");
}
}
redisContext* get() noexcept { return ctx_.get(); }
const redisContext* get() const noexcept { return ctx_.get(); }
redisContext* operator->() noexcept { return ctx_.get(); }
const redisContext* operator->() const noexcept { return ctx_.get(); }
bool isConnected() const noexcept { return ctx_ && ctx_->err == 0; }
private:
std::unique_ptr<redisContext, decltype(&redisFree)> ctx_;
};
class RedisConnectionPool {
public:
explicit RedisConnectionPool(const redisOptions& options,
size_t pool_size = 10)
: options_(options), pool_size_(pool_size) {
for (size_t i = 0; i < pool_size_; ++i) {
connections_.emplace_back(std::make_unique<RedisConnection>(options_));
}
}
std::unique_ptr<RedisConnection> acquire() {
std::unique_lock lock(mutex_);
cv_.wait(lock, [this] { return !connections_.empty(); });
auto conn = std::move(connections_.back());
connections_.pop_back();
if (!conn->isConnected()) {
conn = std::make_unique<RedisConnection>(options_);
}
return conn;
}
void release(std::unique_ptr<RedisConnection> conn) {
if (conn && conn->isConnected()) {
std::lock_guard lock(mutex_);
connections_.push_back(std::move(conn));
cv_.notify_one();
}
}
private:
redisOptions options_;
size_t pool_size_;
std::vector<std::unique_ptr<RedisConnection>> connections_;
mutable std::mutex mutex_;
std::condition_variable cv_;
};
class [[nodiscard]] thread_pool {
public:
thread_pool(const concurrency_t thread_count_ = 0)
: thread_count(determine_thread_count(thread_count_)),
threads(std::make_unique<std::thread[]>(
determine_thread_count(thread_count_))) {
create_threads();
}
~thread_pool() {
wait_for_tasks();
destroy_threads();
}
[[nodiscard]] concurrency_t get_thread_count() const { return thread_count; }
template <typename F, typename... A>
void push_task(F&& task, A&&... args) {
std::function<void()> task_function =
std::bind(std::forward<F>(task), std::forward<A>(args)...);
{
const std::scoped_lock tasks_lock(tasks_mutex);
tasks.push(task_function);
}
++tasks_total;
task_available_cv.notify_one();
}
void wait_for_tasks() {
waiting = true;
std::unique_lock<std::mutex> tasks_lock(tasks_mutex);
task_done_cv.wait(tasks_lock, [this] { return (tasks_total == 0); });
waiting = false;
}
private:
void create_threads() {
running = true;
for (concurrency_t i = 0; i < thread_count; ++i) {
threads[i] = std::thread(&thread_pool::worker, this);
}
}
void destroy_threads() {
running = false;
task_available_cv.notify_all();
for (concurrency_t i = 0; i < thread_count; ++i) {
threads[i].join();
}
}
[[nodiscard]] concurrency_t determine_thread_count(
const concurrency_t thread_count_) {
if (thread_count_ > 0)
return thread_count_;
else {
if (std::thread::hardware_concurrency() > 0)
return std::thread::hardware_concurrency();
else
return 1;
}
}
void worker() {
while (running) {
std::function<void()> task;
std::unique_lock<std::mutex> tasks_lock(tasks_mutex);
task_available_cv.wait(tasks_lock,
[this] { return !tasks.empty() || !running; });
if (running) {
task = std::move(tasks.front());
tasks.pop();
tasks_lock.unlock();
try {
task();
} catch (const std::exception& e) {
std::cerr << "thread_pool task exception: " << e.what() << std::endl;
} catch (...) {
std::cerr << "thread_pool task exception: unknown error" << std::endl;
}
tasks_lock.lock();
--tasks_total;
if (waiting && tasks_total == 0) task_done_cv.notify_all();
}
}
}
std::atomic<bool> running = false;
std::condition_variable task_available_cv = {};
std::condition_variable task_done_cv = {};
std::queue<std::function<void()>> tasks = {};
std::atomic<size_t> tasks_total = 0;
mutable std::mutex tasks_mutex = {};
concurrency_t thread_count = 0;
std::unique_ptr<std::thread[]> threads = nullptr;
std::atomic<bool> waiting = false;
};
enum class TaskState { Unknown, Pending, Scheduled, Active, Failed, Completed };
inline const char* stateToString(TaskState state) noexcept {
switch (state) {
case TaskState::Unknown:
return "Unknown";
case TaskState::Pending:
return "Pending";
case TaskState::Scheduled:
return "Scheduled";
case TaskState::Active:
return "Active";
case TaskState::Failed:
return "Failed";
case TaskState::Completed:
return "Completed";
}
return "Unknown";
}
inline TaskState stringToState(std::string_view state) noexcept {
if (state == "Unknown") return TaskState::Unknown;
if (state == "Pending") return TaskState::Pending;
if (state == "Scheduled") return TaskState::Scheduled;
if (state == "Active") return TaskState::Active;
if (state == "Failed") return TaskState::Failed;
if (state == "Completed") return TaskState::Completed;
return TaskState::Unknown;
}
class Task {
public:
Task(std::string type, std::string payload, uint64_t maxRetry)
: uuid_(),
type(std::move(type)),
payload(std::move(payload)),
state(TaskState::Unknown),
maxRetry(maxRetry),
retried(0),
dequeuedAtMs(0),
schedule(0) {}
Task(std::string_view uuid_str, std::string type, std::string payload,
std::string_view state_str, uint64_t maxRetry, uint64_t retried,
uint64_t dequeuedAtMs, uint64_t schedule = 0, std::string cron = "")
: uuid_(uuid_str),
type(std::move(type)),
payload(std::move(payload)),
state(stringToState(state_str)),
maxRetry(maxRetry),
retried(retried),
dequeuedAtMs(dequeuedAtMs),
schedule(schedule),
cron(std::move(cron)) {}
Task(const Task&) = default;
Task(Task&&) = default;
Task& operator=(const Task&) = default;
Task& operator=(Task&&) = default;
const UUID& getUuid() const noexcept { return uuid_; }
std::string getUuidString() const { return uuid_.toString(); }
UUID uuid_;
std::string type;
std::string payload;
TaskState state;
uint64_t maxRetry;
uint64_t retried;
uint64_t dequeuedAtMs;
uint64_t schedule;
std::string cron;
std::string result;
};
using Handler = void (*)(Task&);
namespace detail {
struct RedisReplyDeleter {
void operator()(redisReply* reply) const noexcept {
if (reply) freeReplyObject(reply);
}
};
using RedisReplyPtr = std::unique_ptr<redisReply, RedisReplyDeleter>;
struct ScriptCache {
std::mutex mutex;
std::string sha;
};
struct HandlerRegistry {
std::unordered_map<std::string, Handler> handlers;
std::shared_mutex mutex;
};
inline HandlerRegistry& handlerRegistry() {
static HandlerRegistry instance;
return instance;
}
inline std::optional<Handler> getHandler(std::string_view type) {
auto& registry = handlerRegistry();
std::shared_lock<std::shared_mutex> lock(registry.mutex);
auto it = registry.handlers.find(std::string(type));
if (it == registry.handlers.end()) return std::nullopt;
return it->second;
}
inline std::string ensureScriptLoaded(redisContext* c, const char* script,
ScriptCache& cache, ErrorCode code,
std::string_view context) {
{
std::lock_guard<std::mutex> lock(cache.mutex);
if (!cache.sha.empty()) {
return cache.sha;
}
}
RedisReplyPtr reply(
static_cast<redisReply*>(redisCommand(c, "SCRIPT LOAD %s", script)));
if (!reply || reply->type != REDIS_REPLY_STRING) {
std::string error_msg(context);
if (reply && reply->str) {
error_msg.append(": ").append(reply->str);
}
throw CppqException(code, error_msg);
}
{
std::lock_guard<std::mutex> lock(cache.mutex);
cache.sha = reply->str ? reply->str : "";
if (cache.sha.empty()) {
throw CppqException(code, std::string(context));
}
return cache.sha;
}
}
inline void invalidateScriptCache(ScriptCache& cache) {
std::lock_guard<std::mutex> lock(cache.mutex);
cache.sha.clear();
}
inline bool isNoScriptError(const redisReply* reply) noexcept {
if (!reply || reply->type != REDIS_REPLY_ERROR || !reply->str) {
return false;
}
return std::string_view(reply->str).find("NOSCRIPT") !=
std::string_view::npos;
}
template <typename CommandFn>
inline RedisReplyPtr executeScript(redisContext* c, const char* script,
ScriptCache& cache, ErrorCode code,
std::string_view context,
CommandFn&& command) {
std::string sha = ensureScriptLoaded(c, script, cache, code, context);
RedisReplyPtr reply(static_cast<redisReply*>(command(sha.c_str())));
if (isNoScriptError(reply.get())) {
invalidateScriptCache(cache);
sha = ensureScriptLoaded(c, script, cache, code, context);
reply.reset(static_cast<redisReply*>(command(sha.c_str())));
}
return reply;
}
inline ScriptCache& enqueueScriptCache() {
static ScriptCache cache;
return cache;
}
inline ScriptCache& dequeueScriptCache() {
static ScriptCache cache;
return cache;
}
inline ScriptCache& dequeueScheduledScriptCache() {
static ScriptCache cache;
return cache;
}
inline ScriptCache& taskSuccessScriptCache() {
static ScriptCache cache;
return cache;
}
inline ScriptCache& taskFailureScriptCache() {
static ScriptCache cache;
return cache;
}
inline ScriptCache& recoveryScriptCache() {
static ScriptCache cache;
return cache;
}
inline ScriptCache& getScheduledScriptCache() {
static ScriptCache cache;
return cache;
}
} // namespace detail
inline void registerHandler(std::string_view type, Handler handler) {
auto& registry = detail::handlerRegistry();
std::unique_lock<std::shared_mutex> lock(registry.mutex);
registry.handlers[std::string(type)] = handler;
}
enum class ScheduleType { None, Cron, TimePoint };
struct ScheduleOptions {
ScheduleType type{ScheduleType::None};
std::optional<std::chrono::system_clock::time_point> timePoint;
std::optional<std::string> cronExpression;
};
inline ScheduleOptions scheduleOptions(
std::chrono::system_clock::time_point t) noexcept {
ScheduleOptions options;
options.type = ScheduleType::TimePoint;
options.timePoint = t;
return options;
}
inline ScheduleOptions scheduleOptions(std::string_view c) {
ScheduleOptions options;
options.type = ScheduleType::Cron;
options.cronExpression = std::string(c);
return options;
}
void enqueue(redisContext* c, Task& task, std::string_view queue,
ScheduleOptions s) {
task.state =
s.type == ScheduleType::None ? TaskState::Pending : TaskState::Scheduled;
std::string uuid_str = task.getUuidString();
const char* state_str = stateToString(task.state);
std::string scheduleType;
std::string scheduleValue;
switch (s.type) {
case ScheduleType::None:
scheduleType = "none";
break;
case ScheduleType::TimePoint: {
if (!s.timePoint.has_value()) {
throw CppqException(
ErrorCode::InvalidTask,
"ScheduleOptions missing time point for time-based schedule");
}
scheduleType = "time";
scheduleValue =
std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(
s.timePoint.value().time_since_epoch())
.count());
break;
}
case ScheduleType::Cron: {
if (!s.cronExpression.has_value()) {
throw CppqException(ErrorCode::InvalidTask,
"ScheduleOptions missing cron expression");
}
scheduleType = "cron";
scheduleValue = s.cronExpression.value();
break;
}
}
const std::string queueStr(queue);
const auto maxRetryStr = std::to_string(task.maxRetry);
const auto retriedStr = std::to_string(task.retried);
const auto dequeuedAtMsStr = std::to_string(task.dequeuedAtMs);
auto& enqueueCache = detail::enqueueScriptCache();
detail::RedisReplyPtr reply = detail::executeScript(
c, enqueueScript, enqueueCache, ErrorCode::EnqueueFailed,
"Failed to load enqueue script", [&](const char* scriptSHA) {
return redisCommand(c, "EVALSHA %s 0 %s %s %s %s %s %s %s %s %s %s",
scriptSHA, queueStr.c_str(), uuid_str.c_str(),
task.type.c_str(), task.payload.c_str(), state_str,
maxRetryStr.c_str(), retriedStr.c_str(),
dequeuedAtMsStr.c_str(), scheduleType.c_str(),
scheduleValue.c_str());
});
if (!reply || reply->type == REDIS_REPLY_ERROR) {
std::string error_msg =
reply && reply->str ? reply->str : "Failed to execute Redis command";
throw CppqException(ErrorCode::EnqueueFailed, error_msg);
}
}
void enqueue(redisContext* c, Task& task, std::string_view queue) {
return enqueue(c, task, queue, ScheduleOptions{});
}
void enqueueBatch(redisContext* c,
std::vector<std::reference_wrapper<Task>>& tasks,
std::string_view queue,
ScheduleOptions s = ScheduleOptions{}) {
if (tasks.empty()) return;
const std::string queueStr(queue);
auto& enqueueCache = detail::enqueueScriptCache();
for (auto& task_ref : tasks) {
Task& task = task_ref.get();
task.state = s.type == ScheduleType::None ? TaskState::Pending
: TaskState::Scheduled;
std::string uuid_str = task.getUuidString();
const char* state_str = stateToString(task.state);
std::string scheduleType;
std::string scheduleValue;
switch (s.type) {
case ScheduleType::None:
scheduleType = "none";
break;
case ScheduleType::TimePoint: {
if (!s.timePoint.has_value()) {
throw CppqException(
ErrorCode::InvalidTask,
"ScheduleOptions missing time point for time-based schedule");
}
scheduleType = "time";
scheduleValue = std::to_string(
std::chrono::duration_cast<std::chrono::milliseconds>(
s.timePoint.value().time_since_epoch())
.count());
break;
}
case ScheduleType::Cron: {
if (!s.cronExpression.has_value()) {
throw CppqException(ErrorCode::InvalidTask,
"ScheduleOptions missing cron expression");
}
scheduleType = "cron";
scheduleValue = s.cronExpression.value();
break;
}
}
const auto maxRetryStr = std::to_string(task.maxRetry);
const auto retriedStr = std::to_string(task.retried);
const auto dequeuedAtMsStr = std::to_string(task.dequeuedAtMs);
detail::RedisReplyPtr reply = detail::executeScript(
c, enqueueScript, enqueueCache, ErrorCode::EnqueueFailed,
"Failed to load enqueue script", [&](const char* scriptSHA) {
return redisCommand(c, "EVALSHA %s 0 %s %s %s %s %s %s %s %s %s %s",
scriptSHA, queueStr.c_str(), uuid_str.c_str(),
task.type.c_str(), task.payload.c_str(),
state_str, maxRetryStr.c_str(),
retriedStr.c_str(), dequeuedAtMsStr.c_str(),
scheduleType.c_str(), scheduleValue.c_str());
});
if (!reply || reply->type == REDIS_REPLY_ERROR) {
std::string error_msg =
reply && reply->str ? reply->str : "Failed to execute Redis command";
throw CppqException(ErrorCode::EnqueueFailed, error_msg);
}
}
}
std::optional<Task> dequeue(redisContext* c, std::string_view queue) {
uint64_t dequeuedAtMs =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
const std::string queueStr(queue);
const auto dequeuedAtMsStr = std::to_string(dequeuedAtMs);
auto& dequeueCache = detail::dequeueScriptCache();
detail::RedisReplyPtr reply = detail::executeScript(
c, dequeueScript, dequeueCache, ErrorCode::DequeueFailed,
"Failed to load dequeue script", [&](const char* scriptSHA) {
return redisCommand(c, "EVALSHA %s 0 %s %s", scriptSHA,
queueStr.c_str(), dequeuedAtMsStr.c_str());
});
if (!reply || reply->type == REDIS_REPLY_NIL) {
return {};
}
if (reply->type != REDIS_REPLY_ARRAY || reply->elements != 2) {
return {};
}
std::string uuid_str = reply->element[0]->str;
redisReply* taskData = reply->element[1];
if (taskData->type != REDIS_REPLY_ARRAY || taskData->elements < 12) {
return {};
}
std::unordered_map<std::string, std::string> taskMap;
for (size_t i = 0; i < taskData->elements; i += 2) {
if (i + 1 < taskData->elements) {
taskMap[taskData->element[i]->str] = taskData->element[i + 1]->str;
}
}
Task task(uuid_str, taskMap["type"], taskMap["payload"], "Active",
strtoull(taskMap["maxRetry"].c_str(), NULL, 0),
strtoull(taskMap["retried"].c_str(), NULL, 0), dequeuedAtMs);
return task;
}
std::optional<Task> dequeueScheduled(redisContext* c, std::string_view queue) {
uint64_t dequeuedAtMs =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
const std::string queueStr(queue);
auto& dequeueScheduledCache = detail::dequeueScheduledScriptCache();
auto& getScheduledCache = detail::getScheduledScriptCache();
const auto dequeuedAtMsStr = std::to_string(dequeuedAtMs);
std::string getScheduledScriptSHA = detail::ensureScriptLoaded(
c, getScheduledScript, getScheduledCache, ErrorCode::DequeueFailed,
"Failed to load getScheduled script");
auto execute = [&](const char* scheduledScriptSHA) {
return redisCommand(c, "EVALSHA %s 0 %s %s %s", scheduledScriptSHA,
queueStr.c_str(), dequeuedAtMsStr.c_str(),
getScheduledScriptSHA.c_str());
};
detail::RedisReplyPtr reply =
detail::executeScript(c, dequeueScheduledScript, dequeueScheduledCache,
ErrorCode::DequeueFailed,
"Failed to load dequeueScheduled script", execute);
// Nested EVALSHA inside dequeueScheduledScript can fail independently.
if (detail::isNoScriptError(reply.get())) {
detail::invalidateScriptCache(getScheduledCache);
getScheduledScriptSHA = detail::ensureScriptLoaded(
c, getScheduledScript, getScheduledCache, ErrorCode::DequeueFailed,
"Failed to load getScheduled script");
reply = detail::executeScript(
c, dequeueScheduledScript, dequeueScheduledCache,
ErrorCode::DequeueFailed, "Failed to load dequeueScheduled script",
execute);
}
if (!reply || reply->type == REDIS_REPLY_NIL) {
return {};
}
if (reply->type != REDIS_REPLY_ARRAY || reply->elements != 2) {
return {};
}
std::string uuid_str = reply->element[0]->str;
redisReply* taskData = reply->element[1];
if (taskData->type != REDIS_REPLY_ARRAY || taskData->elements < 12) {
return {};
}
std::unordered_map<std::string, std::string> taskMap;
for (size_t i = 0; i < taskData->elements; i += 2) {
if (i + 1 < taskData->elements) {
taskMap[taskData->element[i]->str] = taskData->element[i + 1]->str;
}
}
uint64_t schedule = 0;
if (taskMap.find("schedule") != taskMap.end()) {
schedule = strtoull(taskMap["schedule"].c_str(), NULL, 0);
}
Task task(uuid_str, taskMap["type"], taskMap["payload"], "Active",
strtoull(taskMap["maxRetry"].c_str(), NULL, 0),
strtoull(taskMap["retried"].c_str(), NULL, 0), dequeuedAtMs,
schedule);
return task;
}
void taskRunner(redisOptions redisOpts, Task task, std::string queue) {
try {
RedisConnection conn(redisOpts);
auto handlerOpt = detail::getHandler(task.type);
if (!handlerOpt) {
throw CppqException(ErrorCode::TaskNotFound,
"No handler registered for task type");
}
Handler handler = *handlerOpt;
std::string uuid_str = task.getUuidString();
try {
handler(task);
} catch (const std::exception&) {
task.retried++;
const auto retriedStr = std::to_string(task.retried);
const auto maxRetryStr = std::to_string(task.maxRetry);
auto& taskFailureCache = detail::taskFailureScriptCache();
detail::RedisReplyPtr reply = detail::executeScript(
conn.get(), taskFailureScript, taskFailureCache,
ErrorCode::RedisError, "Failed to load task failure script",
[&](const char* scriptSHA) {
return redisCommand(conn.get(), "EVALSHA %s 0 %s %s %s %s",
scriptSHA, queue.c_str(), uuid_str.c_str(),
retriedStr.c_str(), maxRetryStr.c_str());
});
if (reply && reply->type == REDIS_REPLY_ERROR) {
throw CppqException(
ErrorCode::RedisError,
reply->str ? reply->str : "Failed to execute task failure script");
}
return;
}
task.state = TaskState::Completed;
auto& taskSuccessCache = detail::taskSuccessScriptCache();
detail::RedisReplyPtr reply = detail::executeScript(
conn.get(), taskSuccessScript, taskSuccessCache, ErrorCode::RedisError,
"Failed to load task success script", [&](const char* scriptSHA) {
return redisCommand(conn.get(), "EVALSHA %s 0 %s %s %s", scriptSHA,
queue.c_str(), uuid_str.c_str(),
task.result.c_str());
});
if (reply && reply->type == REDIS_REPLY_ERROR) {
throw CppqException(
ErrorCode::RedisError,
reply->str ? reply->str : "Failed to execute task success script");
}
} catch (const CppqException& e) {
std::cerr << "Task runner error: " << e.what() << std::endl;
}
}
void recovery(redisOptions redisOpts, std::map<std::string, int> queues,
uint64_t timeoutMs, uint64_t checkEveryMs,
std::atomic<bool>* stopFlag = nullptr) {
std::unique_ptr<redisContext, decltype(&redisFree)> ctx(
redisConnectWithOptions(&redisOpts), redisFree);
if (!ctx || ctx->err) {
std::cerr << "Failed to connect to Redis" << std::endl;
return;
}
redisContext* c = ctx.get();
auto& recoveryCache = detail::recoveryScriptCache();
// TODO: Consider incrementing `retried` on recovery
while (!stopFlag || !stopFlag->load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(checkEveryMs));
if (stopFlag && stopFlag->load()) break;
for (std::map<std::string, int>::iterator it = queues.begin();
it != queues.end(); it++) {
detail::RedisReplyPtr reply(static_cast<redisReply*>(
redisCommand(c, "LRANGE cppq:%s:active 0 -1", it->first.c_str())));
if (!reply || reply->type != REDIS_REPLY_ARRAY) {
continue;
}
for (size_t i = 0; i < reply->elements; i++) {
redisReply* uuidReply = reply->element[i];
if (!uuidReply || uuidReply->type != REDIS_REPLY_STRING ||
!uuidReply->str) {
continue;
}
std::string uuid = uuidReply->str;
detail::RedisReplyPtr dequeuedAtMsReply(static_cast<redisReply*>(
redisCommand(c, "HGET cppq:%s:task:%s dequeuedAtMs",
it->first.c_str(), uuid.c_str())));
if (!dequeuedAtMsReply ||
dequeuedAtMsReply->type != REDIS_REPLY_STRING ||
!dequeuedAtMsReply->str) {
continue;
}
detail::RedisReplyPtr scheduleReply(static_cast<redisReply*>(
redisCommand(c, "HGET cppq:%s:task:%s schedule", it->first.c_str(),
uuid.c_str())));
uint64_t dequeuedAtMs = strtoull(dequeuedAtMsReply->str, NULL, 0);
if (dequeuedAtMs + timeoutMs <
static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count())) {
const char* hasScheduleStr =
(scheduleReply && scheduleReply->type == REDIS_REPLY_STRING &&
scheduleReply->str)
? "1"
: "0";
detail::RedisReplyPtr execReply = detail::executeScript(
c, recoveryScript, recoveryCache, ErrorCode::RedisError,
"Failed to load recovery script", [&](const char* scriptSHA) {
return redisCommand(c, "EVALSHA %s 0 %s %s %s", scriptSHA,
it->first.c_str(), uuid.c_str(),
hasScheduleStr);
});
if (!execReply || execReply->type == REDIS_REPLY_ERROR) {
std::cerr << "Recovery script error: "
<< (execReply && execReply->str ? execReply->str
: "unknown error")
<< std::endl;
}
}
}