-
Notifications
You must be signed in to change notification settings - Fork 12
/
xqueue.lua
1789 lines (1598 loc) · 48.5 KB
/
xqueue.lua
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
local M = {}
local ffi = require 'ffi'
local log = require 'log'
local fiber = require 'fiber'
local clock = require 'clock'
local tuple_ctype = ffi.typeof(box.tuple.new())
local monotonic_max_age = 10*365*86400;
local function table_clear(t)
if type(t) ~= 'table' then
error("bad argument #1 to 'clear' (table expected, got "..(t ~= nil and type(t) or 'no value')..")",2)
end
local count = #t
for i=0, count do t[i]=nil end
return
end
local function is_array(t)
local gen,param,state = ipairs(t)
-- print(gen,param,state)
local v = gen(param,state)
-- print(v)
return v ~= nil
end
local peers = {}
rawset(_G,"\0xq.on_connect",box.session.on_connect(function()
local sid = box.session.id()
local peer = box.session.peer()
box.session.storage.peer = box.session.peer()
peers[ sid ] = peer
log.debug("connected %s, sid=%s, fid=%s", peer, sid, fiber.id() )
end,rawget(_G,"\0xq.on_connect")))
rawset(_G,"\0xq.on_disconnect",box.session.on_disconnect(function()
local sid = box.session.id()
local peer = peers[ sid ]
peers[ sid ] = nil
log.debug("disconnected %s, sid=%s, fid=%s", peer, sid, fiber.id() )
end,rawget(_G,"\0xq.on_disconnect")))
--[[
Field sets:
1. id, status (minimal required configuration)
2. id, status, priority
3. id, status, runat
4. id, status, priority, runat
Primary index variants:
1. index(status, [ id ])
2. index(status, priority, [ id ])
Format:
local format = box.space._space.index.name:get(space_name)[ 7 ]
Status:
R - ready - task is ready to be taken
created by put without delay
turned on by release/kick without delay
turned on from W when delay passed
deleted after ttl if ttl is enabled
T - taken - task is taken by consumer. may not be taken by other.
turned into R after ttr if ttr is enabled
W - waiting - task is not ready to be taken. waiting for its `delay`
requires `runat`
`delay` may be set during put, release, kick
turned into R after delay
B - buried - task was temporary discarded from queue by consumer
may be revived using kick by administrator
use it in unpredicted conditions, when man intervention is required
Without mandatory monitoring (stats.buried) usage of buried is useless and awry
Z - zombie - task was processed and ack'ed and *temporary* kept for delay
D - done - task was processed and ack'ed and permanently left in database
enabled when keep feature is set
X - reserved for statistics
(TODO: reload/upgrade and feature switch)
Interface:
# Creator methods:
M.upgrade(space, {
format = {
-- space format. applied to space.format() if passed
},
fields = {
-- id is always taken from pk
status = 'status_field_name' | status_field_no,
runat = 'runat_field_name' | runat_field_no,
priority = 'priority_field_name' | priority_field_no,
},
features = {
id = 'auto_increment' | 'uuid' | 'required' | function
-- auto_increment - if pk is number, then use it for auto_increment
-- uuid - if pk is string, then use uuid for id
-- required - primary key MUST be present in tuple during put
-- function - funciton will be called to aquire id for task
buried = true, -- if true, support bury/kick
delayed = true, -- if true, support delayed tasks, requires `runat`
keep = true, -- if true, keep ack'ed tasks in [D]one state, instead of deleting
-- mutually exclusive with zombie
zombie = true|number, -- requires `runat` field
-- if number, then with default zombie delay, otherwise only if set delay during ack
-- mutually exclusive with keep
ttl = true|number, -- requires `runat` field
-- if number, then with default ttl, otherwise only if set during put/release
ttr = true|number, -- requires `runat` field
-- if number, then with default ttl, otherwise only if set
},
})
Producer methods:
sp:put({...}, [ attr ]) (array or table (if have format) or tuple)
Consumer methods:
* id:
- array of keyfields of pk
- table of named keyields
- tuple
sp:take(timeout) -> tuple
sp:ack(id, [ attr ])
attr.update (only if support zombie)
sp:release(id, [ attr ])
attr.ttr (only if support ttr)
attr.ttl (only if support ttl)
attr.update
sp:bury(id, [ attr ])
attr.ttl (only if support ttl)
attr.update
Admin methods:
sp:queue_stats()
sp:kick(N | id, [attr]) -- put buried task id or N oldest buried tasks to [R]eady
]]
local json = require 'json'
json.cfg{ encode_invalid_as_nil = true }
local function typeeq(src, ref)
if ref == 'str' then
return src == 'STR' or src == 'str' or src == 'string'
elseif ref == 'num' then
return src == 'NUM' or src == 'num' or src == 'number' or src == 'unsigned'
else
return src == ref
end
end
local function is_eq(a, b, depth)
local t = type(a)
if t ~= type(b) then return false end
if t == 'table' then
for k,v in pairs(a) do
if b[k] == nil then return end
if not is_eq(v,b[k]) then return false end
end
for k,v in pairs(b) do
if a[k] == nil then return end
if not is_eq(v,a[k]) then return false end
end
return true
elseif t == 'string' or t == 'number' then
return a == b
elseif t == 'cdata' then
return ffi.typeof(a) == ffi.typeof(b) and a == b
else
error("Wrong types for equality", depth or 2)
end
end
local function _tuple2table ( qformat )
local rows = {}
for k,v in ipairs(qformat) do
table.insert(rows,"\t['"..v.name.."'] = t["..tostring(k).."];\n")
end
local fun = "return function(t,...) "..
"if select('#',...) > 0 then error('excess args',2) end "..
"return t and {\n"..table.concat(rows, "").."} or nil end\n"
return dostring(fun)
end
local function _table2tuple ( qformat )
local rows = {}
for _,v in ipairs(qformat) do
table.insert(rows,"\tt['"..v.name.."'] == nil and NULL or t['"..v.name.."'];\n")
end
local fun = "local NULL = require'msgpack'.NULL return function(t) return "..
"t and box.tuple.new({\n"..table.concat(rows, "").."}) or nil end\n"
-- print(fun)
return dostring(fun)
end
local pretty_st = {
R = "Ready",
T = "Taken",
W = "Waiting",
B = "Buried",
Z = "Zombie",
D = "Done",
}
---@class xqueue.space
local methods = {}
---@class PrimaryKeyField:table
---@field no number position in tuple
---@field name string name of the field
---@field type "uuid"|"string"|"number"|"unsigned"|"integer"|"boolean" type of the field
---@class xqFeatures: table
---@field id "auto_increment"|"time64"|"uuid"| fun(): scalar (Default: uuid)
---@field retval "tuple" | "table"
---@field buried boolean
---@field delayed boolean
---@field keep boolean
---@field tube boolean
---@field zombie boolean|number
---@field zombie_delay number
---@field ttl boolean|number
---@field ttr boolean|number
---@field ttl_default number?
---@field ttr_default number?
---@class xq:table
---@field NEVER integer (Default: 0)
---@field atomic fun(self: xq, key: scalar, fun: fun(...:any): ...?): ...
---@field bysid table<number,table<string,string>> mapping sid => {key => key}
---@field taken table<string,number> mapping key => sid
---@field _lock table<string,boolean> locks key => boolean (in atomic)
---@field put_wait table<string,{cond:fiber.cond,task:box.tuple?,processed: boolean?}> mapping key => fiber.cond for producer
---@field take_wait fiber.channel
---@field take_chans table<string,fiber.channel> mapping tube => fiber.channel
---@field debug boolean
---@field have_runat boolean
---@field gen_id? fun(): scalar
---@field getkey fun(self: xq, arg: table|scalar|box.tuple): scalar
---@field packkey fun(self: xq, key: any): string
---@field tube_index? boxIndex
---@field index boxIndex
---@field key PrimaryKeyField
---@field fieldmap table<string,number>
---@field timeoffset fun(delta: number): number
---@field features xqFeatures
---@field fields table<string, string|number>
---@field tuple fun(tbl: table): box.tuple
---@field table fun(tuple: box.tuple): table
---@field retwrap fun(t: box.tuple|table): table|box.tuple
---@field wakeup fun(self: xq, t: box.tuple|table)
---@field runat_chan fiber.channel
---@field check_owner fun(self: xq, key: tuple_type|box.tuple): box.tuple
---@field put_back fun(key: table|box.tuple)
---@field _stat { counts: table, transition: table }
---@field putback fun(self: xq, task: table|box.tuple)
---@field _default_truncate fun(space: boxSpaceObject)
---@field _on_repl replaceTrigger
---@field _on_dis fun()
---@field ready? fiber.channel channel appears when xq is not ready
---@class xqueue.space: boxSpaceObject
---@field xq xq xqueue specific storage
---@class xqueue.fields
---@field status? string|number Xqueue name for the Status field
---@field runat? string|number Xqueue name for the RunAt field
---@field priority? string|number Xqueue name for Task priority field
---@field tube? string|number Xqueue name for Tube field
---@class xqueue.features
---@field id 'uuid' | 'auto_increment' | 'required' | 'time64' | (fun(): number|string) Mandatory Field for TaskID generation
---@field retval? 'table'|'tuple' Type of return Value of the task in xqueue methods.
---(Default: table when space with format, tuple when space is without format)
---@field buried? boolean should xqueue allow buring of the tasks (by default: true)
---@field keep? boolean should xqueue keep :ack'ed tasks in the Space or not
---@field delayed? boolean should xqueue allow delay tasks (requires runat field and index) (defauled: false)
---@field zombie? boolean|number should xqueue temporarily keep :ack'ed tasks in the Space (default: false). Mutually exclusive with keep
---when zombie is configured with number, then this value is treated as zombie_delay (requires runat to be present)
---@field ttl? boolean|number should xqueue allow Time-To-Live on tasks. When specified with number, this value used for ttl_default.
---Requires runat field and index.
---@field ttr? boolean|number should xqueue allow Time-To-Release on tasks. When specified with number, this value used for ttl_default.
---Requires runat field and index.
---@class xqueue.upgrade.options
---@field format? boxSpaceFormat
---@field fields xqueue.fields
---@field debug? boolean
---@field tube_stats? string[] List of tube names for per-tube statistics
---@field features xqueue.features
---@field worker? fun(task: box.tuple|table) simple ad-hoc worker callback
---@field workers? number (number of workers to spawn)
---Upgrades given space to xqueue instance
---@param space xqueue.space
---@param opts xqueue.upgrade.options
---@param depth? number
function M.upgrade(space,opts,depth)
depth = depth or 0
log.info("xqueue upgrade(%s,%s)", space.name, json.encode(opts))
if not opts.fields then error("opts.fields required",2) end
if opts.format then
-- todo: check if already have such format
local format_av = box.space._space.index.name:get(space.name)[ 7 ]
if not is_eq(format_av, opts.format) then
space:format(opts.format)
else
print("formats are equal")
end
end
-- This variable will be defined later
local taken_mt
local self = {}
if space.xq then
self.taken = space.xq.taken
self._stat = space.xq._stat
self.bysid = space.xq.bysid
self._lock = space.xq._lock
self.take_wait = space.xq.take_wait
self.take_chans = space.xq.take_chans or setmetatable({}, { __mode = 'v' })
self.put_wait = space.xq.put_wait or setmetatable({}, { __mode = 'v' })
self._on_repl = space.xq._on_repl
self._on_dis = space.xq._on_dis
else
self.taken = {}
self.bysid = {}
-- byfid = {};
self._lock = {}
self.put_wait = setmetatable({}, { __mode = 'v' })
self.take_wait = fiber.channel(0)
self.take_chans = setmetatable({}, { __mode = 'v' })
end
setmetatable(self.bysid, {
__serialize='map',
__newindex = function(t, key, val)
if type(val) == 'table' then
rawset(t, key, setmetatable(val, taken_mt))
else
rawset(t, key, val)
end
end
})
self.debug = not not opts.debug
if not self._default_truncate then
self._default_truncate = space.truncate
end
local format_av = box.space._space.index.name:get(space.name)[ 7 ]
local format = {}
local have_format = false
local have_runat = false
for no,f in pairs(format_av) do
format[ f.name ] = {
name = f.name;
type = f.type;
no = no;
}
format[ no ] = format[ f.name ];
have_format = true
self.have_format = true
end
for _,idx in pairs(space.index) do
for _,part in pairs(idx.parts) do
format[ part.fieldno ] = format[ part.fieldno ] or { no = part.fieldno }
format[ part.fieldno ].type = part.type
end
end
-- dd(format)
-- 1. fields check
local fields = {}
local fieldmap = {}
for _,f in pairs({{"status","str"},{"runat","num"},{"priority","num"},{"tube","str"}}) do
local fname,ftype = f[1], f[2]
local num = opts.fields[fname]
if num then
if type(num) == 'string' then
if format[num] then
fields[fname] = format[num].no;
else
error(string.format("unknown field %s for %s", num, fname),2 + depth)
end
elseif type(num) == 'number' then
if format[num] then
fields[fname] = num
else
error(string.format("unknown field %s for %s", num, fname),2 + depth)
end
else
error(string.format("wrong type %s for field %s, number or string required",type(num),fname),2 + depth)
end
-- check type
if format[num] then
if not typeeq(format[num].type, ftype) then
error(string.format("type mismatch for field %s, required %s, got %s",fname, ftype, format[fname].type),2+depth)
end
end
fieldmap[fname] = format[num].name
end
end
-- dd(fields)
-- 2. index check
local pk = space.index[0]
if #pk.parts ~= 1 then
error("Composite primary keys are not supported yet")
end
local pktype
if typeeq( format[pk.parts[1].fieldno].type, 'str' ) then
pktype = 'string'
taken_mt = { __serialize = 'map' }
elseif typeeq( format[pk.parts[1].fieldno].type, 'num' ) then
pktype = 'number'
taken_mt = {
__serialize = 'map',
__newindex = function(t, key, val)
return rawset(t, tostring(ffi.cast("uint64_t", key)), val)
end,
__index = function(t, key)
return rawget(t, tostring(ffi.cast("uint64_t", key)))
end
}
else
error("Unknown key type "..format[pk.parts[1].fieldno].type)
end
setmetatable(self.taken, taken_mt)
local pkf = {
no = pk.parts[1].fieldno;
name = format[pk.parts[1].fieldno].name;
['type'] = pktype;
}
self.key = pkf
self.fields = fields
self.fieldmap = fieldmap
function self:getkey(arg)
local _type = type(arg)
if _type == 'table' then
if is_array(arg) then
return arg[ self.key.no ]
else
return arg[ self.key.name ]
-- pass
end
elseif _type == 'cdata' and ffi.typeof(arg) == tuple_ctype then
return arg[ self.key.no ]
elseif _type == self.key.type then
return arg
else
error("Wrong key/task argument. Expected table or tuple or key", 3)
end
end
function self.packkey(_, key)
if type(key) == 'cdata' then
return tostring(ffi.cast("uint64_t", key))
else
return key
end
end
do
local filter
if fields.priority then
filter = function(index)
return #index.parts >= 3
and index.parts[1].fieldno == fields.status
and index.parts[2].fieldno == fields.priority
and index.parts[3].fieldno == self.key.no
end
else
filter = function(index)
return #index.parts >= 2
and index.parts[1].fieldno == fields.status
and index.parts[2].fieldno == self.key.no
end
end
for i,index in pairs(space.index) do
if type(i) == 'number' and filter(index) then
self.index = index
break
end
end
if not self.index then
if fields.priority then
error("not found index by status + priority + id",2+depth)
else
error("not found index by status + id",2+depth)
end
end
if fields.tube then
for n,index in pairs(space.index) do
if type(n) == 'number' and index.parts[1].fieldno == fields.tube then
local not_match = false
for i = 2, #index.parts do
if index.parts[i].fieldno ~= self.index.parts[i-1].fieldno then
not_match = true
break
end
end
if not not_match then
self.tube_index = index
break
end
end
end
if not self.tube_index then
if fields.priority then
error("not found index by tube + status + priority + id",2+depth)
else
error("not found index by tube + status + id",2+depth)
end
end
end
end
---@type boxIndex
local runat_index
if fields.runat then
for _,index in pairs(space.index) do
if type(_) == 'number' then
if index.parts[1].fieldno == fields.runat then
-- print("found",index.name)
runat_index = index
break
end
end
end
if not runat_index then
error(string.format("fields.runat requires tree index with this first field in it"),2+depth)
else
local t = runat_index:pairs({0},{iterator = box.index.GT}):nth(1)
if t then
if t[ self.fields.runat ] < monotonic_max_age then
error("!!! Queue contains monotonic runat. Consider updating tasks (https://github.com/moonlibs/xqueue/issues/2)")
end
end
have_runat = true
end
end
self.have_runat = have_runat
---@type table<string, { counts: {}, transition: {} }>
local stat_tube = {}
if self.fields.tube and type(opts.tube_stats) == 'table' then
for _, tube_name in ipairs(opts.tube_stats) do
if type(tube_name) == 'string' then
stat_tube[tube_name] = {
counts = {},
transition = {},
}
end
end
end
if not self._stat then
self._stat = {
counts = {};
transition = {};
tube = stat_tube;
}
if self.fields.tube then
for status in pairs(pretty_st) do
self._stat.counts[status] = 0LL+self.index:count(status)
end
for tube in pairs(stat_tube) do
for status in pairs(pretty_st) do
stat_tube[tube].counts[status] = 0LL+self.tube_index:count({ tube, status })
end
end
else
for status in pairs(pretty_st) do
self._stat.counts[status] = 0LL+self.index:count(status)
end
end
else
self._stat = { counts = {}, transition = {}, tube = stat_tube }
end
-- 3. features check
local features = {}
local gen_id
opts.features = opts.features or {}
if not opts.features.id then
opts.features.id = 'uuid'
end
-- 'auto_increment' | 'time64' | 'uuid' | 'required' | function
if opts.features.id == 'auto_increment' then
if not (#pk.parts == 1 and typeeq( pk.parts[1].type, 'num')) then
error("For auto_increment numeric pk is mandatory",2+depth)
end
local pk_fno = pk.parts[1].fieldno
gen_id = function()
local max = pk:max()
if max then
return max[pk_fno] + 1
else
return 1
end
end
elseif opts.features.id == 'time64' then
if not (#pk.parts == 1 and typeeq( pk.parts[1].type, 'num')) then
error("For time64 numeric pk is mandatory",2+depth)
end
gen_id = function()
local key = clock.realtime64()
while true do
local exists = pk:get(key)
if not exists then
return key
end
key = key + 1
end
end
elseif opts.features.id == 'uuid' then
if not (#pk.parts == 1 and typeeq( pk.parts[1].type, 'str')) then
error("For uuid string pk is mandatory",2+depth)
end
local uuid = require'uuid'
gen_id = function()
while true do
local key = uuid.str()
local exists = pk:get(key)
if not exists then
return key
end
end
end
elseif opts.features.id == 'required' then
-- gen_id = function()
-- -- ???
-- error("TODO")
-- end
elseif type(opts.features.id) == 'function'
or (debug.getmetatable(opts.features.id)
and debug.getmetatable(opts.features.id).__call)
then
gen_id = opts.features.id
else
error(string.format(
"Wrong type for features.id %s, may be 'auto_increment' | 'time64' | 'uuid' | 'required' | function",
opts.features.id
), 2+depth)
end
if not opts.features.retval then
opts.features.retval = have_format and 'table' or 'tuple'
end
if format then
self.tuple = _table2tuple(format)
self.table = _tuple2table(format)
end
if opts.features.retval == 'table' then
self.retwrap = self.table
else
self.retwrap = function(t) return t end
end
features.buried = not not opts.features.buried
features.keep = not not opts.features.keep
if opts.features.delayed then
if not have_runat then
error(string.format("Delayed feature requires runat field and index" ),2+depth)
end
features.delayed = true
else
features.delayed = false
end
if opts.features.zombie then
if features.keep then
error(string.format("features keep and zombie are mutually exclusive" ),2+depth)
end
if not have_runat then
error(string.format("feature zombie requires runat field and index" ),2+depth)
end
features.zombie = true
if type(opts.features.zombie) == 'number' then
features.zombie_delay = opts.features.zombie
end
else
features.zombie = false
end
if opts.features.ttl then
if not have_runat then
error(string.format("feature ttl requires runat field and index" ),2+depth)
end
features.ttl = true
if type(opts.features.ttl) == 'number' then
features.ttl_default = opts.features.ttl
end
else
features.ttl = false
end
if opts.features.ttr then
if not have_runat then
error(string.format("feature ttr requires runat field and index" ),2+depth)
end
features.ttr = true
if type(opts.features.ttr) == 'number' then
features.ttr_default = opts.features.ttr
end
else
features.ttr = false
end
if fields.tube then
features.tube = true
end
self.gen_id = gen_id
self.features = features
self.space = space.id
function self.timeoffset(delta)
delta = tonumber(delta) or 0
return clock.realtime() + delta
end
function self.timeready(time)
return time < clock.realtime()
end
function self.timeremaining(time)
return time - clock.realtime()
end
-- self.NEVER = -1ULL
self.NEVER = 0
function self.keyfield(_,t)
return t[pkf.no]
end
function self.keypack(_,t)
return t[pkf.no]
end
-- Notify producer if it is still waiting us.
-- Producer waits only for successfully processed task
-- or for task which would never be processed.
-- Discarding to process task depends on consumer's logic.
-- Also task can be deleted from space by exceeding TTL.
-- Producer should not be notified if queue is able to process task in future.
local function notify_producer(key, task)
local pkey = self:packkey(key)
local wait = self.put_wait[pkey]
if not wait then
-- no producer
return
end
if task.status == 'Z' or task.status == 'D' then
-- task was processed
wait.task = task
wait.processed = true
wait.cond:broadcast()
return
end
if not space:get{key} then
-- task is not present in space
-- it could be TTL or :ack
if task.status == 'T' then
-- task was acked:
wait.task = task
wait.processed = true
wait.cond:broadcast()
elseif task.status == 'R' then
-- task was killed by TTL
wait.task = task
wait.processed = false
wait.cond:broadcast()
end
else
-- task is still in space
if task.status == 'B' then
-- task was buried
wait.task = task
wait.processed = false
wait.cond:broadcast()
end
end
end
self.ready = fiber.channel(0)
local function rw_fiber_f(func, ...)
local xq = self
repeat
if box.info.ro then
log.verbose("awaiting rw")
repeat
if box.ctl.wait_rw then
pcall(box.ctl.wait_rw, 1)
else
fiber.sleep(0.001)
end
until not box.info.ro
end
local ok, err = pcall(func, ...)
if not ok then
log.error("%s%s",
err, xq.ready and ': (xq is not ready yet)' or '')
end
fiber.testcancel()
until (not box.space[space.name]) or space.xq ~= xq
end
if opts.worker then
local workers = opts.workers or 1
local worker = opts.worker
for i = 1,workers do
fiber.create(rw_fiber_f, function(space,xq)
local fname = space.name .. '.xq.wrk' .. tostring(i)
---@diagnostic disable-next-line: undefined-field
if package.reload then fname = fname .. '.' .. package.reload.count end
fiber.name(string.sub(fname,1,32))
repeat fiber.sleep(0.001) until space.xq
if xq.ready then xq.ready:get() end
log.info("I am worker %s",i)
while box.space[space.name] and space.xq == xq and not box.info.ro do
if xq.ready then xq.ready:get() end
local task = space:take(1)
if task then
local key = xq:getkey(task)
local r,e = pcall(worker,task)
if not r then
log.error("Worker for {%s} has error: %s", key, e)
else
if xq.taken[ key ] then
space:ack(task)
end
end
if xq.taken[ key ] then
log.error("Worker for {%s} not released task", key)
space:release(task)
end
end
fiber.yield()
end
if box.info.ro then
log.info("Shutting down on ro instance")
return
end
log.info("worker %s ended", i)
end,space,self)
end
end
if have_runat then
self.runat_chan = fiber.channel(0)
self.runat = fiber.create(rw_fiber_f, function(space,xq,runat_index)
local fname = space.name .. '.xq'
if package.reload then fname = fname .. '.' .. package.reload.count end
fiber.name(string.sub(fname,1,32))
repeat fiber.sleep(0.001) until space.xq
if xq.ready then xq.ready:get() end
local chan = xq.runat_chan
log.info("Runat started")
local maxrun = 1000
local curwait
local collect = {}
while box.space[space.name] and space.xq == xq and not box.info.ro do
local r,e = pcall(function()
-- print("runat loop 2 ",box.time64())
local remaining
for _,t in runat_index:pairs({0},{iterator = box.index.GT}) do
-- print("checking ",t)
if xq.timeready( t[ xq.fields.runat ] ) then
table.insert(collect,t)
else
remaining = xq.timeremaining(t[ xq.fields.runat ])
break
end
if #collect >= maxrun then remaining = 0 break end
end
for _,t in ipairs(collect) do
-- log.info("Runat: %s, %s", _, t)
if t[xq.fields.status] == 'W' then
log.info("Runat: W->R %s",xq:keyfield(t))
-- TODO: default ttl?
local u = space:update({ xq:keyfield(t) },{
{ '=',xq.fields.status,'R' },
{ '=',xq.fields.runat, xq.NEVER }
})
xq:wakeup(u)
elseif t[xq.fields.status] == 'R' and xq.features.ttl then
local key = xq:keyfield(t)
log.info("Runat: Kill R by ttl %s (%+0.2fs)", key, fiber.time() - t[ xq.fields.runat ])
t = space:delete{key}
notify_producer(key, t)
elseif t[xq.fields.status] == 'Z' and xq.features.zombie then
log.info("Runat: Kill Zombie %s",xq:keyfield(t))
space:delete{ xq:keyfield(t) }
elseif t[xq.fields.status] == 'T' and xq.features.ttr then
local key = xq:keypack(t)
local sid = xq.taken[ key ]
local peer = peers[sid] or sid
log.info("Runat: autorelease T->R by ttr %s taken by %s",xq:keyfield(t), peer)
local u = space:update({ xq:keyfield(t) },{
{ '=',xq.fields.status,'R' },
{ '=',xq.fields.runat, xq.NEVER }
})
xq.taken[ key ] = nil
if sid then
self.bysid[ sid ][ key ] = nil
end
xq:wakeup(u)
else
log.error("Runat: unsupported status %s for %s",t[xq.fields.status], tostring(t))
space:update({ xq:keyfield(t) },{
{ '=',xq.fields.runat, xq.NEVER }
})
end
end
if remaining then
if remaining >= 0 and remaining < 1 then
return remaining
end
end
return 1
end)
table_clear(collect)
if r then
curwait = e
else
curwait = 1
log.error("Runat/ERR: %s",e)
end
-- log.info("Wait %0.2fs",curwait)
if curwait == 0 then fiber.sleep(0) end
chan:get(curwait)
end
if box.info.ro then
log.info("Shutting down on ro instance")
return
end
log.info("Runat ended")
end,space,self,runat_index)
end
local function atomic_tail(self, key, status, ...)
self._lock[key] = nil
if not status then
error((...), 3)
end
return ...
end
function self:atomic(key, fun, ...)
self._lock[key] = true
return atomic_tail(self, key, pcall(fun, ...))
end
function self:check_owner(key)
local t = space:get(key)
if not t then