-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
rabbit_fifo.erl
2618 lines (2445 loc) · 116 KB
/
rabbit_fifo.erl
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
%% This Source Code Form is subject to the terms of the Mozilla Public
%% License, v. 2.0. If a copy of the MPL was not distributed with this
%% file, You can obtain one at https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2007-2024 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
-module(rabbit_fifo).
-behaviour(ra_machine).
-compile(inline_list_funcs).
-compile(inline).
-compile({no_auto_import, [apply/3]}).
-dialyzer(no_improper_lists).
-include("rabbit_fifo.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
-export([
%% ra_machine callbacks
init/1,
apply/3,
state_enter/2,
tick/2,
overview/1,
get_checked_out/4,
%% versioning
version/0,
which_module/1,
%% aux
init_aux/1,
handle_aux/6,
% queries
query_messages_ready/1,
query_messages_checked_out/1,
query_messages_total/1,
query_processes/1,
query_ra_indexes/1,
query_waiting_consumers/1,
query_consumer_count/1,
query_consumers/1,
query_stat/1,
query_stat_dlx/1,
query_single_active_consumer/1,
query_in_memory_usage/1,
query_peek/2,
query_notify_decorators_info/1,
usage/1,
%% misc
dehydrate_state/1,
normalize/1,
get_msg_header/1,
get_header/2,
get_msg/1,
%% protocol helpers
make_enqueue/3,
make_register_enqueuer/1,
make_checkout/3,
make_settle/2,
make_return/2,
make_discard/2,
make_credit/4,
make_purge/0,
make_purge_nodes/1,
make_update_config/1,
make_garbage_collection/0
]).
-ifdef(TEST).
-export([update_header/4,
chunk_disk_msgs/3]).
-endif.
-import(serial_number, [add/2, diff/2]).
%% command records representing all the protocol actions that are supported
-record(enqueue, {pid :: option(pid()),
seq :: option(msg_seqno()),
msg :: raw_msg()}).
-record(requeue, {consumer_id :: consumer_id(),
msg_id :: msg_id(),
index :: ra:index(),
header :: msg_header(),
msg :: raw_msg()}).
-record(register_enqueuer, {pid :: pid()}).
-record(checkout, {consumer_id :: consumer_id(),
spec :: checkout_spec(),
meta :: consumer_meta()}).
-record(settle, {consumer_id :: consumer_id(),
msg_ids :: [msg_id()]}).
-record(return, {consumer_id :: consumer_id(),
msg_ids :: [msg_id()]}).
-record(discard, {consumer_id :: consumer_id(),
msg_ids :: [msg_id()]}).
-record(credit, {consumer_id :: consumer_id(),
credit :: non_neg_integer(),
delivery_count :: rabbit_queue_type:delivery_count(),
drain :: boolean()}).
-record(purge, {}).
-record(purge_nodes, {nodes :: [node()]}).
-record(update_config, {config :: config()}).
-record(garbage_collection, {}).
-opaque protocol() ::
#enqueue{} |
#requeue{} |
#register_enqueuer{} |
#checkout{} |
#settle{} |
#return{} |
#discard{} |
#credit{} |
#purge{} |
#purge_nodes{} |
#update_config{} |
#garbage_collection{}.
-type command() :: protocol() |
rabbit_fifo_dlx:protocol() |
ra_machine:builtin_command().
%% all the command types supported by ra fifo
-type client_msg() :: delivery().
%% the messages `rabbit_fifo' can send to consumers.
-opaque state() :: #?MODULE{}.
-export_type([protocol/0,
delivery/0,
command/0,
credit_mode/0,
consumer_meta/0,
consumer_id/0,
client_msg/0,
msg/0,
msg_id/0,
msg_seqno/0,
delivery_msg/0,
state/0,
config/0]).
%% This function is never called since only rabbit_fifo_v0:init/1 is called.
%% See https://github.com/rabbitmq/ra/blob/e0d1e6315a45f5d3c19875d66f9d7bfaf83a46e3/src/ra_machine.erl#L258-L265
-spec init(config()) -> state().
init(#{name := Name,
queue_resource := Resource} = Conf) ->
update_config(Conf, #?MODULE{cfg = #cfg{name = Name,
resource = Resource}}).
update_config(Conf, State) ->
DLH = maps:get(dead_letter_handler, Conf, undefined),
BLH = maps:get(become_leader_handler, Conf, undefined),
RCI = maps:get(release_cursor_interval, Conf, ?RELEASE_CURSOR_EVERY),
Overflow = maps:get(overflow_strategy, Conf, drop_head),
MaxLength = maps:get(max_length, Conf, undefined),
MaxBytes = maps:get(max_bytes, Conf, undefined),
DeliveryLimit = maps:get(delivery_limit, Conf, undefined),
Expires = maps:get(expires, Conf, undefined),
MsgTTL = maps:get(msg_ttl, Conf, undefined),
ConsumerStrategy = case maps:get(single_active_consumer_on, Conf, false) of
true ->
single_active;
false ->
competing
end,
Cfg = State#?MODULE.cfg,
RCISpec = {RCI, RCI},
LastActive = maps:get(created, Conf, undefined),
State#?MODULE{cfg = Cfg#cfg{release_cursor_interval = RCISpec,
dead_letter_handler = DLH,
become_leader_handler = BLH,
overflow_strategy = Overflow,
max_length = MaxLength,
max_bytes = MaxBytes,
consumer_strategy = ConsumerStrategy,
delivery_limit = DeliveryLimit,
expires = Expires,
msg_ttl = MsgTTL},
last_active = LastActive}.
% msg_ids are scoped per consumer
% ra_indexes holds all raft indexes for enqueues currently on queue
-spec apply(ra_machine:command_meta_data(), command(), state()) ->
{state(), ra_machine:reply(), ra_machine:effects() | ra_machine:effect()} |
{state(), ra_machine:reply()}.
apply(Meta, #enqueue{pid = From, seq = Seq,
msg = RawMsg}, State00) ->
apply_enqueue(Meta, From, Seq, RawMsg, State00);
apply(_Meta, #register_enqueuer{pid = Pid},
#?MODULE{enqueuers = Enqueuers0,
cfg = #cfg{overflow_strategy = Overflow}} = State0) ->
State = case maps:is_key(Pid, Enqueuers0) of
true ->
%% if the enqueuer exits just echo the overflow state
State0;
false ->
State0#?MODULE{enqueuers = Enqueuers0#{Pid => #enqueuer{}}}
end,
Res = case is_over_limit(State) of
true when Overflow == reject_publish ->
reject_publish;
_ ->
ok
end,
{State, Res, [{monitor, process, Pid}]};
apply(Meta,
#settle{msg_ids = MsgIds, consumer_id = ConsumerId},
#?MODULE{consumers = Cons0} = State) ->
case Cons0 of
#{ConsumerId := Con0} ->
complete_and_checkout(Meta, MsgIds, ConsumerId,
Con0, [], State);
_ ->
{State, ok}
end;
apply(Meta, #discard{msg_ids = MsgIds, consumer_id = ConsumerId},
#?MODULE{consumers = Cons,
dlx = DlxState0,
cfg = #cfg{dead_letter_handler = DLH}} = State0) ->
case Cons of
#{ConsumerId := #consumer{checked_out = Checked} = Con} ->
% Publishing to dead-letter exchange must maintain same order as messages got rejected.
DiscardMsgs = lists:filtermap(fun(Id) ->
case maps:get(Id, Checked, undefined) of
undefined ->
false;
Msg ->
{true, Msg}
end
end, MsgIds),
{DlxState, Effects} = rabbit_fifo_dlx:discard(DiscardMsgs, rejected, DLH, DlxState0),
State = State0#?MODULE{dlx = DlxState},
complete_and_checkout(Meta, MsgIds, ConsumerId, Con, Effects, State);
_ ->
{State0, ok}
end;
apply(Meta, #return{msg_ids = MsgIds, consumer_id = ConsumerId},
#?MODULE{consumers = Cons0} = State) ->
case Cons0 of
#{ConsumerId := #consumer{checked_out = Checked0}} ->
Returned = maps:with(MsgIds, Checked0),
return(Meta, ConsumerId, Returned, [], State);
_ ->
{State, ok}
end;
apply(#{index := Idx} = Meta,
#requeue{consumer_id = ConsumerId,
msg_id = MsgId,
index = OldIdx,
header = Header0,
msg = _Msg},
#?MODULE{consumers = Cons0,
messages = Messages,
ra_indexes = Indexes0,
enqueue_count = EnqCount} = State00) ->
case Cons0 of
#{ConsumerId := #consumer{checked_out = Checked0} = Con0}
when is_map_key(MsgId, Checked0) ->
%% construct a message with the current raft index
%% and update delivery count before adding it to the message queue
Header = update_header(delivery_count, fun incr/1, 1, Header0),
State0 = add_bytes_return(Header, State00),
Con = Con0#consumer{checked_out = maps:remove(MsgId, Checked0),
credit = increase_credit(Meta, Con0, 1)},
State1 = State0#?MODULE{ra_indexes = rabbit_fifo_index:delete(OldIdx, Indexes0),
messages = lqueue:in(?MSG(Idx, Header), Messages),
enqueue_count = EnqCount + 1},
State2 = update_or_remove_sub(Meta, ConsumerId, Con, State1),
{State, Ret, Effs} = checkout(Meta, State0, State2, []),
update_smallest_raft_index(Idx, Ret,
maybe_store_release_cursor(Idx, State),
Effs);
_ ->
{State00, ok, []}
end;
apply(Meta, #credit{credit = LinkCreditRcv, delivery_count = DeliveryCountRcv,
drain = Drain, consumer_id = ConsumerId = {CTag, CPid}},
#?MODULE{consumers = Cons0,
service_queue = ServiceQueue0,
waiting_consumers = Waiting0} = State0) ->
case Cons0 of
#{ConsumerId := #consumer{delivery_count = DeliveryCountSnd,
cfg = Cfg} = Con0} ->
LinkCreditSnd = link_credit_snd(DeliveryCountRcv, LinkCreditRcv, DeliveryCountSnd, Cfg),
%% grant the credit
Con1 = Con0#consumer{credit = LinkCreditSnd},
ServiceQueue = maybe_queue_consumer(ConsumerId, Con1, ServiceQueue0),
State1 = State0#?MODULE{service_queue = ServiceQueue,
consumers = maps:update(ConsumerId, Con1, Cons0)},
{State2, ok, Effects} = checkout(Meta, State0, State1, []),
#?MODULE{consumers = Cons1 = #{ConsumerId := Con2}} = State2,
#consumer{credit = PostCred,
delivery_count = PostDeliveryCount} = Con2,
Available = messages_ready(State2),
case credit_api_v2(Cfg) of
true ->
{Credit, DeliveryCount, State} =
case Drain andalso PostCred > 0 of
true ->
AdvancedDeliveryCount = add(PostDeliveryCount, PostCred),
ZeroCredit = 0,
Con = Con2#consumer{delivery_count = AdvancedDeliveryCount,
credit = ZeroCredit},
Cons = maps:update(ConsumerId, Con, Cons1),
State3 = State2#?MODULE{consumers = Cons},
{ZeroCredit, AdvancedDeliveryCount, State3};
false ->
{PostCred, PostDeliveryCount, State2}
end,
%% We must send to queue client delivery effects before credit_reply such
%% that session process can send to AMQP 1.0 client TRANSFERs before FLOW.
{State, ok, Effects ++ [{send_msg, CPid,
{credit_reply, CTag, DeliveryCount, Credit, Available, Drain},
?DELIVERY_SEND_MSG_OPTS}]};
false ->
%% We must always send a send_credit_reply because basic.credit is synchronous.
%% Additionally, we keep the bug of credit API v1 that we send to queue client the
%% send_drained reply before the delivery effects (resulting in the wrong behaviour
%% that the session process sends to AMQP 1.0 client the FLOW before the TRANSFERs).
%% We have to keep this bug because old rabbit_fifo_client implementations expect
%% a send_drained Ra reply (they can't handle such a Ra effect).
CreditReply = {send_credit_reply, Available},
case Drain of
true ->
AdvancedDeliveryCount = PostDeliveryCount + PostCred,
Con = Con2#consumer{delivery_count = AdvancedDeliveryCount,
credit = 0},
Cons = maps:update(ConsumerId, Con, Cons1),
State = State2#?MODULE{consumers = Cons},
Reply = {multi, [CreditReply, {send_drained, {CTag, PostCred}}]},
{State, Reply, Effects};
false ->
{State2, CreditReply, Effects}
end
end;
_ when Waiting0 /= [] ->
%%TODO next time when we bump the machine version:
%% 1. Do not put consumer at head of waiting_consumers if NewCredit == 0
%% to reduce likelihood of activating a 0 credit consumer.
%% 2. Support Drain == true, i.e. advance delivery-count, consuming all link-credit since there
%% are no messages available for an inactive consumer and send credit_reply with Drain=true.
case lists:keytake(ConsumerId, 1, Waiting0) of
{value, {_, Con0 = #consumer{delivery_count = DeliveryCountSnd,
cfg = Cfg}}, Waiting} ->
LinkCreditSnd = link_credit_snd(DeliveryCountRcv, LinkCreditRcv, DeliveryCountSnd, Cfg),
%% grant the credit
Con = Con0#consumer{credit = LinkCreditSnd},
State = State0#?MODULE{waiting_consumers =
[{ConsumerId, Con} | Waiting]},
%% No messages are available for inactive consumers.
Available = 0,
case credit_api_v2(Cfg) of
true ->
{State, ok,
{send_msg, CPid,
{credit_reply, CTag, DeliveryCountSnd, LinkCreditSnd, Available, false},
?DELIVERY_SEND_MSG_OPTS}};
false ->
{State, {send_credit_reply, Available}}
end;
false ->
{State0, ok}
end;
_ ->
%% credit for unknown consumer - just ignore
{State0, ok}
end;
apply(_, #checkout{spec = {dequeue, _}},
#?MODULE{cfg = #cfg{consumer_strategy = single_active}} = State0) ->
{State0, {error, {unsupported, single_active_consumer}}};
apply(#{index := Index,
system_time := Ts,
from := From} = Meta, #checkout{spec = {dequeue, Settlement},
meta = ConsumerMeta,
consumer_id = ConsumerId},
#?MODULE{consumers = Consumers} = State00) ->
%% dequeue always updates last_active
State0 = State00#?MODULE{last_active = Ts},
%% all dequeue operations result in keeping the queue from expiring
Exists = maps:is_key(ConsumerId, Consumers),
case messages_ready(State0) of
0 ->
update_smallest_raft_index(Index, {dequeue, empty}, State0, []);
_ when Exists ->
%% a dequeue using the same consumer_id isn't possible at this point
{State0, {dequeue, empty}};
_ ->
{_, State1} = update_consumer(Meta, ConsumerId, ConsumerMeta,
{once, 1, simple_prefetch}, 0,
State0),
case checkout_one(Meta, false, State1, []) of
{success, _, MsgId, ?MSG(RaftIdx, Header), ExpiredMsg, State2, Effects0} ->
{State4, Effects1} = case Settlement of
unsettled ->
{_, Pid} = ConsumerId,
{State2, [{monitor, process, Pid} | Effects0]};
settled ->
%% immediately settle the checkout
{State3, _, SettleEffects} =
apply(Meta, make_settle(ConsumerId, [MsgId]),
State2),
{State3, SettleEffects ++ Effects0}
end,
Effects2 = [reply_log_effect(RaftIdx, MsgId, Header, messages_ready(State4), From) | Effects1],
{State, DroppedMsg, Effects} = evaluate_limit(Index, false, State0, State4,
Effects2),
Reply = '$ra_no_reply',
case {DroppedMsg, ExpiredMsg} of
{false, false} ->
{State, Reply, Effects};
_ ->
update_smallest_raft_index(Index, Reply, State, Effects)
end;
{nochange, _ExpiredMsg = true, State2, Effects0} ->
%% All ready messages expired.
State3 = State2#?MODULE{consumers = maps:remove(ConsumerId, State2#?MODULE.consumers)},
{State, _, Effects} = evaluate_limit(Index, false, State0, State3, Effects0),
update_smallest_raft_index(Index, {dequeue, empty}, State, Effects)
end
end;
apply(#{index := Idx} = Meta,
#checkout{spec = cancel,
consumer_id = ConsumerId}, State0) ->
{State1, Effects1} = cancel_consumer(Meta, ConsumerId, State0, [],
consumer_cancel),
{State, Reply, Effects} = checkout(Meta, State0, State1, Effects1),
update_smallest_raft_index(Idx, Reply, State, Effects);
apply(Meta, #checkout{spec = Spec, meta = ConsumerMeta,
consumer_id = {_, Pid} = ConsumerId}, State0) ->
Priority = get_priority_from_args(ConsumerMeta),
{Consumer, State1} = update_consumer(Meta, ConsumerId, ConsumerMeta,
Spec, Priority, State0),
{State2, Effs} = activate_next_consumer(State1, []),
#consumer{checked_out = Checked,
credit = Credit,
delivery_count = DeliveryCount,
next_msg_id = NextMsgId} = Consumer,
%% reply with a consumer summary
Reply = {ok, #{next_msg_id => NextMsgId,
credit => Credit,
delivery_count => DeliveryCount,
num_checked_out => map_size(Checked)}},
checkout(Meta, State0, State2, [{monitor, process, Pid} | Effs], Reply);
apply(#{index := Index}, #purge{},
#?MODULE{messages_total = Total,
returns = Returns,
ra_indexes = Indexes0
} = State0) ->
NumReady = messages_ready(State0),
Indexes = case Total of
NumReady ->
%% All messages are either in 'messages' queue or 'returns' queue.
%% No message is awaiting acknowledgement.
%% Optimization: empty all 'ra_indexes'.
rabbit_fifo_index:empty();
_ ->
%% Some messages are checked out to consumers awaiting acknowledgement.
%% Therefore we cannot empty all 'ra_indexes'.
%% We only need to delete the indexes from the 'returns' queue because
%% messages of the 'messages' queue are not part of the 'ra_indexes'.
lqueue:fold(fun(?MSG(I, _), Acc) ->
rabbit_fifo_index:delete(I, Acc)
end, Indexes0, Returns)
end,
State1 = State0#?MODULE{ra_indexes = Indexes,
messages = lqueue:new(),
messages_total = Total - NumReady,
returns = lqueue:new(),
msg_bytes_enqueue = 0
},
Effects0 = [garbage_collection],
Reply = {purge, NumReady},
{State, _, Effects} = evaluate_limit(Index, false, State0,
State1, Effects0),
update_smallest_raft_index(Index, Reply, State, Effects);
apply(#{index := Idx}, #garbage_collection{}, State) ->
update_smallest_raft_index(Idx, ok, State, [{aux, garbage_collection}]);
apply(Meta, {timeout, expire_msgs}, State) ->
checkout(Meta, State, State, []);
apply(#{system_time := Ts, machine_version := MachineVersion} = Meta,
{down, Pid, noconnection},
#?MODULE{consumers = Cons0,
cfg = #cfg{consumer_strategy = single_active},
waiting_consumers = Waiting0,
enqueuers = Enqs0} = State0) ->
Node = node(Pid),
%% if the pid refers to an active or cancelled consumer,
%% mark it as suspected and return it to the waiting queue
{State1, Effects0} =
maps:fold(fun({_, P} = Cid, C0, {S0, E0})
when node(P) =:= Node ->
%% the consumer should be returned to waiting
%% and checked out messages should be returned
Effs = consumer_update_active_effects(
S0, Cid, C0, false, suspected_down, E0),
C1 = case MachineVersion of
V when V >= 3 ->
C0;
2 ->
Checked = C0#consumer.checked_out,
Credit = increase_credit(Meta, C0, maps:size(Checked)),
C0#consumer{credit = Credit}
end,
{St, Effs1} = return_all(Meta, S0, Effs, Cid, C1),
%% if the consumer was cancelled there is a chance it got
%% removed when returning hence we need to be defensive here
Waiting = case St#?MODULE.consumers of
#{Cid := C} ->
Waiting0 ++ [{Cid, C}];
_ ->
Waiting0
end,
{St#?MODULE{consumers = maps:remove(Cid, St#?MODULE.consumers),
waiting_consumers = Waiting,
last_active = Ts},
Effs1};
(_, _, S) ->
S
end, {State0, []}, Cons0),
WaitingConsumers = update_waiting_consumer_status(Node, State1,
suspected_down),
%% select a new consumer from the waiting queue and run a checkout
State2 = State1#?MODULE{waiting_consumers = WaitingConsumers},
{State, Effects1} = activate_next_consumer(State2, Effects0),
%% mark any enquers as suspected
Enqs = maps:map(fun(P, E) when node(P) =:= Node ->
E#enqueuer{status = suspected_down};
(_, E) -> E
end, Enqs0),
Effects = [{monitor, node, Node} | Effects1],
checkout(Meta, State0, State#?MODULE{enqueuers = Enqs}, Effects);
apply(#{system_time := Ts, machine_version := MachineVersion} = Meta,
{down, Pid, noconnection},
#?MODULE{consumers = Cons0,
enqueuers = Enqs0} = State0) ->
%% A node has been disconnected. This doesn't necessarily mean that
%% any processes on this node are down, they _may_ come back so here
%% we just mark them as suspected (effectively deactivated)
%% and return all checked out messages to the main queue for delivery to any
%% live consumers
%%
%% all pids for the disconnected node will be marked as suspected not just
%% the one we got the `down' command for
Node = node(Pid),
{State, Effects1} =
maps:fold(
fun({_, P} = Cid, #consumer{checked_out = Checked0,
status = up} = C0,
{St0, Eff}) when node(P) =:= Node ->
C = case MachineVersion of
V when V >= 3 ->
C0#consumer{status = suspected_down};
2 ->
Credit = increase_credit(Meta, C0, map_size(Checked0)),
C0#consumer{status = suspected_down,
credit = Credit}
end,
{St, Eff0} = return_all(Meta, St0, Eff, Cid, C),
Eff1 = consumer_update_active_effects(St, Cid, C, false,
suspected_down, Eff0),
{St, Eff1};
(_, _, {St, Eff}) ->
{St, Eff}
end, {State0, []}, Cons0),
Enqs = maps:map(fun(P, E) when node(P) =:= Node ->
E#enqueuer{status = suspected_down};
(_, E) -> E
end, Enqs0),
% Monitor the node so that we can "unsuspect" these processes when the node
% comes back, then re-issue all monitors and discover the final fate of
% these processes
Effects = [{monitor, node, Node} | Effects1],
checkout(Meta, State0, State#?MODULE{enqueuers = Enqs,
last_active = Ts}, Effects);
apply(#{index := Idx} = Meta, {down, Pid, _Info}, State0) ->
{State1, Effects1} = handle_down(Meta, Pid, State0),
{State, Reply, Effects} = checkout(Meta, State0, State1, Effects1),
update_smallest_raft_index(Idx, Reply, State, Effects);
apply(Meta, {nodeup, Node}, #?MODULE{consumers = Cons0,
enqueuers = Enqs0,
service_queue = _SQ0} = State0) ->
%% A node we are monitoring has come back.
%% If we have suspected any processes of being
%% down we should now re-issue the monitors for them to detect if they're
%% actually down or not
Monitors = [{monitor, process, P}
|| P <- suspected_pids_for(Node, State0)],
Enqs1 = maps:map(fun(P, E) when node(P) =:= Node ->
E#enqueuer{status = up};
(_, E) -> E
end, Enqs0),
ConsumerUpdateActiveFun = consumer_active_flag_update_function(State0),
%% mark all consumers as up
{State1, Effects1} =
maps:fold(fun({_, P} = ConsumerId, C, {SAcc, EAcc})
when (node(P) =:= Node) and
(C#consumer.status =/= cancelled) ->
EAcc1 = ConsumerUpdateActiveFun(SAcc, ConsumerId,
C, true, up, EAcc),
{update_or_remove_sub(Meta, ConsumerId,
C#consumer{status = up},
SAcc), EAcc1};
(_, _, Acc) ->
Acc
end, {State0, Monitors}, Cons0),
Waiting = update_waiting_consumer_status(Node, State1, up),
State2 = State1#?MODULE{enqueuers = Enqs1,
waiting_consumers = Waiting},
{State, Effects} = activate_next_consumer(State2, Effects1),
checkout(Meta, State0, State, Effects);
apply(_, {nodedown, _Node}, State) ->
{State, ok};
apply(#{index := Idx} = Meta, #purge_nodes{nodes = Nodes}, State0) ->
{State, Effects} = lists:foldl(fun(Node, {S, E}) ->
purge_node(Meta, Node, S, E)
end, {State0, []}, Nodes),
update_smallest_raft_index(Idx, ok, State, Effects);
apply(#{index := Idx} = Meta,
#update_config{config = #{dead_letter_handler := NewDLH} = Conf},
#?MODULE{cfg = #cfg{dead_letter_handler = OldDLH,
resource = QRes},
dlx = DlxState0} = State0) ->
{DlxState, Effects0} = rabbit_fifo_dlx:update_config(OldDLH, NewDLH, QRes, DlxState0),
State1 = update_config(Conf, State0#?MODULE{dlx = DlxState}),
{State, Reply, Effects} = checkout(Meta, State0, State1, Effects0),
update_smallest_raft_index(Idx, Reply, State, Effects);
apply(_Meta, {machine_version, FromVersion, ToVersion}, V0State) ->
State = convert(FromVersion, ToVersion, V0State),
{State, ok, [{aux, {dlx, setup}}]};
apply(#{index := IncomingRaftIdx} = Meta, {dlx, _} = Cmd,
#?MODULE{cfg = #cfg{dead_letter_handler = DLH},
dlx = DlxState0} = State0) ->
{DlxState, Effects0} = rabbit_fifo_dlx:apply(Meta, Cmd, DLH, DlxState0),
State1 = State0#?MODULE{dlx = DlxState},
{State, ok, Effects} = checkout(Meta, State0, State1, Effects0),
update_smallest_raft_index(IncomingRaftIdx, State, Effects);
apply(_Meta, Cmd, State) ->
%% handle unhandled commands gracefully
rabbit_log:debug("rabbit_fifo: unhandled command ~W", [Cmd, 10]),
{State, ok, []}.
convert_msg({RaftIdx, {Header, empty}}) when is_integer(RaftIdx) ->
?MSG(RaftIdx, Header);
convert_msg({RaftIdx, {Header, _Msg}}) when is_integer(RaftIdx) ->
?MSG(RaftIdx, Header);
convert_msg({'$empty_msg', Header}) ->
%% dummy index
?MSG(undefined, Header);
convert_msg({'$prefix_msg', Header}) ->
%% dummy index
?MSG(undefined, Header);
convert_msg({Header, empty}) ->
convert_msg(Header);
convert_msg(Header) when ?IS_HEADER(Header) ->
?MSG(undefined, Header).
convert_consumer_v1_to_v2({ConsumerTag, Pid}, CV1) ->
Meta = element(2, CV1),
CheckedOut = element(3, CV1),
NextMsgId = element(4, CV1),
Credit = element(5, CV1),
DeliveryCount = element(6, CV1),
CreditMode = element(7, CV1),
LifeTime = element(8, CV1),
Status = element(9, CV1),
Priority = element(10, CV1),
#consumer{cfg = #consumer_cfg{tag = ConsumerTag,
pid = Pid,
meta = Meta,
credit_mode = CreditMode,
lifetime = LifeTime,
priority = Priority},
credit = Credit,
status = Status,
delivery_count = DeliveryCount,
next_msg_id = NextMsgId,
checked_out = maps:map(
fun (_, {Tag, _} = Msg) when is_atom(Tag) ->
convert_msg(Msg);
(_, {_Seq, Msg}) ->
convert_msg(Msg)
end, CheckedOut)
}.
convert_v1_to_v2(V1State0) ->
V1State = rabbit_fifo_v1:enqueue_all_pending(V1State0),
IndexesV1 = rabbit_fifo_v1:get_field(ra_indexes, V1State),
ReturnsV1 = rabbit_fifo_v1:get_field(returns, V1State),
MessagesV1 = rabbit_fifo_v1:get_field(messages, V1State),
ConsumersV1 = rabbit_fifo_v1:get_field(consumers, V1State),
WaitingConsumersV1 = rabbit_fifo_v1:get_field(waiting_consumers, V1State),
%% remove all raft idx in messages from index
{_, PrefReturns, _, PrefMsgs} = rabbit_fifo_v1:get_field(prefix_msgs, V1State),
V2PrefMsgs = lists:foldl(fun(Hdr, Acc) ->
lqueue:in(convert_msg(Hdr), Acc)
end, lqueue:new(), PrefMsgs),
V2PrefReturns = lists:foldl(fun(Hdr, Acc) ->
lqueue:in(convert_msg(Hdr), Acc)
end, lqueue:new(), PrefReturns),
MessagesV2 = lqueue:fold(fun ({_, Msg}, Acc) ->
lqueue:in(convert_msg(Msg), Acc)
end, V2PrefMsgs, MessagesV1),
ReturnsV2 = lqueue:fold(fun ({_SeqId, Msg}, Acc) ->
lqueue:in(convert_msg(Msg), Acc)
end, V2PrefReturns, ReturnsV1),
ConsumersV2 = maps:map(
fun (ConsumerId, CV1) ->
convert_consumer_v1_to_v2(ConsumerId, CV1)
end, ConsumersV1),
WaitingConsumersV2 = lists:map(
fun ({ConsumerId, CV1}) ->
{ConsumerId, convert_consumer_v1_to_v2(ConsumerId, CV1)}
end, WaitingConsumersV1),
EnqueuersV1 = rabbit_fifo_v1:get_field(enqueuers, V1State),
EnqueuersV2 = maps:map(fun (_EnqPid, Enq) ->
Enq#enqueuer{unused = undefined}
end, EnqueuersV1),
%% do after state conversion
%% The (old) format of dead_letter_handler in RMQ < v3.10 is:
%% {Module, Function, Args}
%% The (new) format of dead_letter_handler in RMQ >= v3.10 is:
%% undefined | {at_most_once, {Module, Function, Args}} | at_least_once
%%
%% Note that the conversion must convert both from old format to new format
%% as well as from new format to new format. The latter is because quorum queues
%% created in RMQ >= v3.10 are still initialised with rabbit_fifo_v0 as described in
%% https://github.com/rabbitmq/ra/blob/e0d1e6315a45f5d3c19875d66f9d7bfaf83a46e3/src/ra_machine.erl#L258-L265
DLH = case rabbit_fifo_v1:get_cfg_field(dead_letter_handler, V1State) of
{_M, _F, _A = [_DLX = undefined|_]} ->
%% queue was declared in RMQ < v3.10 and no DLX configured
undefined;
{_M, _F, _A} = MFA ->
%% queue was declared in RMQ < v3.10 and DLX configured
{at_most_once, MFA};
Other ->
Other
end,
Cfg = #cfg{name = rabbit_fifo_v1:get_cfg_field(name, V1State),
resource = rabbit_fifo_v1:get_cfg_field(resource, V1State),
release_cursor_interval = rabbit_fifo_v1:get_cfg_field(release_cursor_interval, V1State),
dead_letter_handler = DLH,
become_leader_handler = rabbit_fifo_v1:get_cfg_field(become_leader_handler, V1State),
%% TODO: what if policy enabling reject_publish was applied before conversion?
overflow_strategy = rabbit_fifo_v1:get_cfg_field(overflow_strategy, V1State),
max_length = rabbit_fifo_v1:get_cfg_field(max_length, V1State),
max_bytes = rabbit_fifo_v1:get_cfg_field(max_bytes, V1State),
consumer_strategy = rabbit_fifo_v1:get_cfg_field(consumer_strategy, V1State),
delivery_limit = rabbit_fifo_v1:get_cfg_field(delivery_limit, V1State),
expires = rabbit_fifo_v1:get_cfg_field(expires, V1State)
},
MessagesConsumersV2 = maps:fold(fun(_ConsumerId, #consumer{checked_out = Checked}, Acc) ->
Acc + maps:size(Checked)
end, 0, ConsumersV2),
MessagesWaitingConsumersV2 = lists:foldl(fun({_ConsumerId, #consumer{checked_out = Checked}}, Acc) ->
Acc + maps:size(Checked)
end, 0, WaitingConsumersV2),
MessagesTotal = lqueue:len(MessagesV2) +
lqueue:len(ReturnsV2) +
MessagesConsumersV2 +
MessagesWaitingConsumersV2,
#?MODULE{cfg = Cfg,
messages = MessagesV2,
messages_total = MessagesTotal,
returns = ReturnsV2,
enqueue_count = rabbit_fifo_v1:get_field(enqueue_count, V1State),
enqueuers = EnqueuersV2,
ra_indexes = IndexesV1,
release_cursors = rabbit_fifo_v1:get_field(release_cursors, V1State),
consumers = ConsumersV2,
service_queue = rabbit_fifo_v1:get_field(service_queue, V1State),
msg_bytes_enqueue = rabbit_fifo_v1:get_field(msg_bytes_enqueue, V1State),
msg_bytes_checkout = rabbit_fifo_v1:get_field(msg_bytes_checkout, V1State),
waiting_consumers = WaitingConsumersV2,
last_active = rabbit_fifo_v1:get_field(last_active, V1State)
}.
convert_v2_to_v3(#rabbit_fifo{consumers = ConsumersV2} = StateV2) ->
ConsumersV3 = maps:map(fun(_, C) ->
convert_consumer_v2_to_v3(C)
end, ConsumersV2),
StateV2#rabbit_fifo{consumers = ConsumersV3}.
convert_consumer_v2_to_v3(C = #consumer{cfg = Cfg = #consumer_cfg{credit_mode = simple_prefetch,
meta = #{prefetch := Prefetch}}}) ->
C#consumer{cfg = Cfg#consumer_cfg{credit_mode = {simple_prefetch, Prefetch}}};
convert_consumer_v2_to_v3(C) ->
C.
purge_node(Meta, Node, State, Effects) ->
lists:foldl(fun(Pid, {S0, E0}) ->
{S, E} = handle_down(Meta, Pid, S0),
{S, E0 ++ E}
end, {State, Effects}, all_pids_for(Node, State)).
%% any downs that re not noconnection
handle_down(Meta, Pid, #?MODULE{consumers = Cons0,
enqueuers = Enqs0} = State0) ->
% Remove any enqueuer for the down pid
State1 = State0#?MODULE{enqueuers = maps:remove(Pid, Enqs0)},
{Effects1, State2} = handle_waiting_consumer_down(Pid, State1),
% return checked out messages to main queue
% Find the consumers for the down pid
DownConsumers = maps:keys(
maps:filter(fun({_, P}, _) -> P =:= Pid end, Cons0)),
lists:foldl(fun(ConsumerId, {S, E}) ->
cancel_consumer(Meta, ConsumerId, S, E, down)
end, {State2, Effects1}, DownConsumers).
consumer_active_flag_update_function(
#?MODULE{cfg = #cfg{consumer_strategy = competing}}) ->
fun(State, ConsumerId, Consumer, Active, ActivityStatus, Effects) ->
consumer_update_active_effects(State, ConsumerId, Consumer, Active,
ActivityStatus, Effects)
end;
consumer_active_flag_update_function(
#?MODULE{cfg = #cfg{consumer_strategy = single_active}}) ->
fun(_, _, _, _, _, Effects) ->
Effects
end.
handle_waiting_consumer_down(_Pid,
#?MODULE{cfg = #cfg{consumer_strategy = competing}} = State) ->
{[], State};
handle_waiting_consumer_down(_Pid,
#?MODULE{cfg = #cfg{consumer_strategy = single_active},
waiting_consumers = []} = State) ->
{[], State};
handle_waiting_consumer_down(Pid,
#?MODULE{cfg = #cfg{consumer_strategy = single_active},
waiting_consumers = WaitingConsumers0} = State0) ->
% get cancel effects for down waiting consumers
Down = lists:filter(fun({{_, P}, _}) -> P =:= Pid end,
WaitingConsumers0),
Effects = lists:foldl(fun ({ConsumerId, _}, Effects) ->
cancel_consumer_effects(ConsumerId, State0,
Effects)
end, [], Down),
% update state to have only up waiting consumers
StillUp = lists:filter(fun({{_, P}, _}) -> P =/= Pid end,
WaitingConsumers0),
State = State0#?MODULE{waiting_consumers = StillUp},
{Effects, State}.
update_waiting_consumer_status(Node,
#?MODULE{waiting_consumers = WaitingConsumers},
Status) ->
[begin
case node(Pid) of
Node ->
{ConsumerId, Consumer#consumer{status = Status}};
_ ->
{ConsumerId, Consumer}
end
end || {{_, Pid} = ConsumerId, Consumer} <- WaitingConsumers,
Consumer#consumer.status =/= cancelled].
-spec state_enter(ra_server:ra_state() | eol, state()) ->
ra_machine:effects().
state_enter(RaState, #?MODULE{cfg = #cfg{dead_letter_handler = DLH,
resource = QRes},
dlx = DlxState} = State) ->
Effects = rabbit_fifo_dlx:state_enter(RaState, QRes, DLH, DlxState),
state_enter0(RaState, State, Effects).
state_enter0(leader, #?MODULE{consumers = Cons,
enqueuers = Enqs,
waiting_consumers = WaitingConsumers,
cfg = #cfg{name = Name,
resource = Resource,
become_leader_handler = BLH}
} = State,
Effects0) ->
TimerEffs = timer_effect(erlang:system_time(millisecond), State, Effects0),
% return effects to monitor all current consumers and enqueuers
Pids = lists:usort(maps:keys(Enqs)
++ [P || {_, P} <- maps:keys(Cons)]
++ [P || {{_, P}, _} <- WaitingConsumers]),
Mons = [{monitor, process, P} || P <- Pids],
Nots = [{send_msg, P, leader_change, ra_event} || P <- Pids],
NodeMons = lists:usort([{monitor, node, node(P)} || P <- Pids]),
FHReservation = [{mod_call, rabbit_quorum_queue,
file_handle_leader_reservation, [Resource]}],
NotifyDecs = notify_decorators_startup(Resource),
Effects = TimerEffs ++ Mons ++ Nots ++ NodeMons ++ FHReservation ++ [NotifyDecs],
case BLH of
undefined ->
Effects;
{Mod, Fun, Args} ->
[{mod_call, Mod, Fun, Args ++ [Name]} | Effects]
end;
state_enter0(eol, #?MODULE{enqueuers = Enqs,
consumers = Custs0,
waiting_consumers = WaitingConsumers0},
Effects) ->
Custs = maps:fold(fun({_, P}, V, S) -> S#{P => V} end, #{}, Custs0),
WaitingConsumers1 = lists:foldl(fun({{_, P}, V}, Acc) -> Acc#{P => V} end,
#{}, WaitingConsumers0),
AllConsumers = maps:merge(Custs, WaitingConsumers1),
[{send_msg, P, eol, ra_event}
|| P <- maps:keys(maps:merge(Enqs, AllConsumers))] ++
[{aux, eol},
{mod_call, rabbit_quorum_queue, file_handle_release_reservation, []} | Effects];
state_enter0(State, #?MODULE{cfg = #cfg{resource = _Resource}}, Effects)
when State =/= leader ->
FHReservation = {mod_call, rabbit_quorum_queue, file_handle_other_reservation, []},
[FHReservation | Effects];
state_enter0(_, _, Effects) ->
%% catch all as not handling all states
Effects.
-spec tick(non_neg_integer(), state()) -> ra_machine:effects().
tick(Ts, #?MODULE{cfg = #cfg{name = _Name,
resource = QName}} = State) ->
case is_expired(Ts, State) of
true ->
[{mod_call, rabbit_quorum_queue, spawn_deleter, [QName]}];
false ->
[{aux, {handle_tick, [QName, overview(State), all_nodes(State)]}}]
end.
-spec overview(state()) -> map().
overview(#?MODULE{consumers = Cons,
enqueuers = Enqs,
release_cursors = Cursors,
enqueue_count = EnqCount,
msg_bytes_enqueue = EnqueueBytes,
msg_bytes_checkout = CheckoutBytes,
cfg = Cfg,
dlx = DlxState,
waiting_consumers = WaitingConsumers} = State) ->
Conf = #{name => Cfg#cfg.name,
resource => Cfg#cfg.resource,
release_cursor_interval => Cfg#cfg.release_cursor_interval,
dead_lettering_enabled => undefined =/= Cfg#cfg.dead_letter_handler,
max_length => Cfg#cfg.max_length,
max_bytes => Cfg#cfg.max_bytes,
consumer_strategy => Cfg#cfg.consumer_strategy,
expires => Cfg#cfg.expires,
msg_ttl => Cfg#cfg.msg_ttl,
delivery_limit => Cfg#cfg.delivery_limit
},
SacOverview = case active_consumer(Cons) of
{SacConsumerId, _} ->
NumWaiting = length(WaitingConsumers),
#{single_active_consumer_id => SacConsumerId,
single_active_num_waiting_consumers => NumWaiting};
_ ->
#{}
end,
Overview = #{type => ?MODULE,
config => Conf,
num_consumers => map_size(Cons),
num_active_consumers => query_consumer_count(State),
num_checked_out => num_checked_out(State),
num_enqueuers => maps:size(Enqs),
num_ready_messages => messages_ready(State),
num_in_memory_ready_messages => 0, %% backwards compat
num_messages => messages_total(State),
num_release_cursors => lqueue:len(Cursors),
release_cursors => [I || {_, I, _} <- lqueue:to_list(Cursors)],
release_cursor_enqueue_counter => EnqCount,
enqueue_message_bytes => EnqueueBytes,
checkout_message_bytes => CheckoutBytes,
in_memory_message_bytes => 0, %% backwards compat
smallest_raft_index => smallest_raft_index(State)
},
DlxOverview = rabbit_fifo_dlx:overview(DlxState),
maps:merge(maps:merge(Overview, DlxOverview), SacOverview).
-spec get_checked_out(consumer_id(), msg_id(), msg_id(), state()) ->
[delivery_msg()].
get_checked_out(Cid, From, To, #?MODULE{consumers = Consumers}) ->
case Consumers of
#{Cid := #consumer{checked_out = Checked}} ->
[begin
?MSG(I, H) = maps:get(K, Checked),
{K, {I, H}}
end || K <- lists:seq(From, To), maps:is_key(K, Checked)];
_ ->
[]
end.
-spec version() -> pos_integer().
version() -> 3.