-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
amqp10_client_session.erl
1328 lines (1182 loc) · 53.8 KB
/
amqp10_client_session.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(amqp10_client_session).
-behaviour(gen_statem).
-include("amqp10_client.hrl").
-include_lib("amqp10_common/include/amqp10_framing.hrl").
-include_lib("amqp10_common/include/amqp10_types.hrl").
%% Public API.
-export(['begin'/1,
begin_sync/1,
begin_sync/2,
'end'/1,
attach/2,
detach/2,
transfer/3,
flow/4,
disposition/5
]).
%% Private API
-export([start_link/4,
socket_ready/2
]).
%% gen_statem callbacks
-export([
init/1,
terminate/3,
code_change/4,
callback_mode/0,
format_status/1
]).
%% gen_statem state callbacks
%% see figure 2.30
-export([
unmapped/3,
begin_sent/3,
mapped/3,
end_sent/3
]).
-import(serial_number,
[add/2,
diff/2]).
-define(MAX_SESSION_WINDOW_SIZE, 65535).
-define(DEFAULT_TIMEOUT, 5000).
-define(UINT_OUTGOING_WINDOW, {uint, ?UINT_MAX}).
-define(INITIAL_OUTGOING_DELIVERY_ID, ?UINT_MAX).
%% "The next-outgoing-id MAY be initialized to an arbitrary value" [2.5.6]
-define(INITIAL_OUTGOING_TRANSFER_ID, ?UINT_MAX - 1).
%% "Note that, despite its name, the delivery-count is not a count but a
%% sequence number initialized at an arbitrary point by the sender." [2.6.7]
-define(INITIAL_DELIVERY_COUNT, ?UINT_MAX - 2).
-type link_name() :: binary().
-type link_address() :: binary().
-type link_role() :: sender | receiver.
-type link_target() :: {pid, pid()} | binary() | undefined.
%% "The locally chosen handle is referred to as the output handle." [2.6.2]
-type output_handle() :: link_handle().
%% "The remotely chosen handle is referred to as the input handle." [2.6.2]
-type input_handle() :: link_handle().
-type snd_settle_mode() :: unsettled | settled | mixed.
-type rcv_settle_mode() :: first | second.
-type terminus_durability() :: none | configuration | unsettled_state.
-type target_def() :: #{address => link_address(),
durable => terminus_durability()}.
-type source_def() :: #{address => link_address(),
durable => terminus_durability()}.
-type attach_role() :: {sender, target_def()} | {receiver, source_def(), pid()}.
% http://www.amqp.org/specification/1.0/filters
-type filter() :: #{binary() => binary() | map() | list(binary())}.
-type max_message_size() :: undefined | non_neg_integer().
-type attach_args() :: #{name => binary(),
role => attach_role(),
snd_settle_mode => snd_settle_mode(),
rcv_settle_mode => rcv_settle_mode(),
filter => filter(),
properties => amqp10_client_types:properties(),
max_message_size => max_message_size(),
handle => output_handle()
}.
-type transfer_error() :: {error,
insufficient_credit |
remote_incoming_window_exceeded |
message_size_exceeded |
link_not_found |
half_attached}.
-type link_ref() :: #link_ref{}.
-export_type([snd_settle_mode/0,
rcv_settle_mode/0,
terminus_durability/0,
attach_args/0,
attach_role/0,
target_def/0,
source_def/0,
filter/0,
max_message_size/0,
transfer_error/0]).
-record(link,
{name :: link_name(),
ref :: link_ref(),
state = detached :: detached | attach_sent | attached | detach_sent,
notify :: pid(),
output_handle :: output_handle(),
input_handle :: input_handle() | undefined,
role :: link_role(),
target :: link_target(),
max_message_size :: non_neg_integer() | Unlimited :: undefined,
delivery_count :: sequence_no() | undefined,
link_credit = 0 :: non_neg_integer(),
available = 0 :: non_neg_integer(),
drain = false :: boolean(),
partial_transfers :: undefined | {#'v1_0.transfer'{}, [binary()]},
auto_flow :: never | {auto, RenewWhenBelow :: pos_integer(), Credit :: pos_integer()},
incoming_unsettled = #{} :: #{delivery_number() => ok}
}).
-record(state,
{channel :: pos_integer(),
remote_channel :: pos_integer() | undefined,
%% session flow control, see section 2.5.6
next_incoming_id :: transfer_number() | undefined,
incoming_window = ?MAX_SESSION_WINDOW_SIZE :: non_neg_integer(),
next_outgoing_id = ?INITIAL_OUTGOING_TRANSFER_ID :: transfer_number(),
remote_incoming_window = 0 :: non_neg_integer(),
remote_outgoing_window = 0 :: non_neg_integer(),
reader :: pid(),
socket :: amqp10_client_connection:amqp10_socket() | undefined,
links = #{} :: #{output_handle() => #link{}},
link_index = #{} :: #{link_name() => output_handle()},
link_handle_index = #{} :: #{input_handle() => output_handle()},
next_link_handle = 0 :: output_handle(),
early_attach_requests :: [term()],
connection_config :: amqp10_client_connection:connection_config(),
outgoing_delivery_id = ?INITIAL_OUTGOING_DELIVERY_ID :: delivery_number(),
outgoing_unsettled = #{} :: #{delivery_number() => {amqp10_msg:delivery_tag(), Notify :: pid()}},
notify :: pid()
}).
%% -------------------------------------------------------------------
%% Public API.
%% -------------------------------------------------------------------
-spec 'begin'(pid()) -> supervisor:startchild_ret().
'begin'(Connection) ->
%% The connection process is responsible for allocating a channel
%% number and contact the sessions supervisor to start a new session
%% process.
amqp10_client_connection:begin_session(Connection).
-spec begin_sync(pid()) -> supervisor:startchild_ret().
begin_sync(Connection) ->
begin_sync(Connection, ?DEFAULT_TIMEOUT).
-spec begin_sync(pid(), non_neg_integer()) ->
supervisor:startchild_ret() | session_timeout.
begin_sync(Connection, Timeout) ->
{ok, Session} = amqp10_client_connection:begin_session(Connection),
receive
{session_begin, Session} -> {ok, Session}
after Timeout -> session_timeout
end.
-spec 'end'(pid()) -> ok.
'end'(Pid) ->
gen_statem:cast(Pid, 'end').
-spec attach(pid(), attach_args()) -> {ok, link_ref()}.
attach(Session, Args) ->
gen_statem:call(Session, {attach, Args}, ?TIMEOUT).
-spec detach(pid(), output_handle()) -> ok | {error, link_not_found | half_attached}.
detach(Session, Handle) ->
gen_statem:call(Session, {detach, Handle}, ?TIMEOUT).
-spec transfer(pid(), amqp10_msg:amqp10_msg(), timeout()) ->
ok | transfer_error().
transfer(Session, Amqp10Msg, Timeout) ->
[Transfer | Records] = amqp10_msg:to_amqp_records(Amqp10Msg),
gen_statem:call(Session, {transfer, Transfer, Records}, Timeout).
flow(Session, Handle, Flow, RenewWhenBelow) ->
gen_statem:cast(Session, {flow_link, Handle, Flow, RenewWhenBelow}).
%% Sending a disposition on a sender link (with receiver-settle-mode = second)
%% is currently unsupported.
-spec disposition(link_ref(), delivery_number(), delivery_number(), boolean(),
amqp10_client_types:delivery_state()) -> ok.
disposition(#link_ref{role = receiver,
session = Session,
link_handle = Handle},
First, Last, Settled, DeliveryState) ->
gen_statem:call(Session, {disposition, Handle, First, Last, Settled,
DeliveryState}, ?TIMEOUT).
%% -------------------------------------------------------------------
%% Private API.
%% -------------------------------------------------------------------
start_link(From, Channel, Reader, ConnConfig) ->
gen_statem:start_link(?MODULE, [From, Channel, Reader, ConnConfig], []).
-spec socket_ready(pid(), amqp10_client_connection:amqp10_socket()) -> ok.
socket_ready(Pid, Socket) ->
gen_statem:cast(Pid, {socket_ready, Socket}).
%% -------------------------------------------------------------------
%% gen_statem callbacks.
%% -------------------------------------------------------------------
callback_mode() -> [state_functions].
init([FromPid, Channel, Reader, ConnConfig]) ->
process_flag(trap_exit, true),
amqp10_client_frame_reader:register_session(Reader, self(), Channel),
State = #state{notify = FromPid,
channel = Channel,
reader = Reader,
connection_config = ConnConfig,
early_attach_requests = []},
{ok, unmapped, State}.
unmapped(cast, {socket_ready, Socket}, State) ->
State1 = State#state{socket = Socket},
ok = send_begin(State1),
{next_state, begin_sent, State1};
unmapped({call, From}, {attach, Attach},
#state{early_attach_requests = EARs} = State) ->
{keep_state,
State#state{early_attach_requests = [{From, Attach} | EARs]}}.
begin_sent(cast, #'v1_0.begin'{remote_channel = {ushort, RemoteChannel},
next_outgoing_id = {uint, NOI},
incoming_window = {uint, InWindow},
outgoing_window = {uint, OutWindow}},
#state{early_attach_requests = EARs} = State) ->
State1 = State#state{remote_channel = RemoteChannel},
State2 = lists:foldr(fun({From, Attach}, S) ->
{S2, H} = send_attach(fun send/2, Attach, From, S),
gen_statem:reply(From, {ok, H}),
S2
end, State1, EARs),
ok = notify_session_begun(State2),
{next_state, mapped, State2#state{early_attach_requests = [],
next_incoming_id = NOI,
remote_incoming_window = InWindow,
remote_outgoing_window = OutWindow}};
begin_sent({call, From}, {attach, Attach},
#state{early_attach_requests = EARs} = State) ->
{keep_state,
State#state{early_attach_requests = [{From, Attach} | EARs]}}.
mapped(cast, 'end', State) ->
%% We send the first end frame and wait for the reply.
send_end(State),
{next_state, end_sent, State};
mapped(cast, {flow_link, OutHandle, Flow0, RenewWhenBelow}, State0) ->
State = send_flow_link(OutHandle, Flow0, RenewWhenBelow, State0),
{keep_state, State};
mapped(cast, {flow_session, Flow0 = #'v1_0.flow'{incoming_window = {uint, IncomingWindow}}},
#state{next_incoming_id = NII,
next_outgoing_id = NOI} = State) ->
Flow = Flow0#'v1_0.flow'{
next_incoming_id = maybe_uint(NII),
next_outgoing_id = uint(NOI),
outgoing_window = ?UINT_OUTGOING_WINDOW},
ok = send(Flow, State),
{keep_state, State#state{incoming_window = IncomingWindow}};
mapped(cast, #'v1_0.end'{error = Err}, State) ->
%% We receive the first end frame, reply and terminate.
_ = send_end(State),
% TODO: send notifications for links?
Reason = reason(Err),
ok = notify_session_ended(State, Reason),
{stop, normal, State};
mapped(cast, #'v1_0.attach'{name = {utf8, Name},
initial_delivery_count = IDC,
handle = {uint, InHandle},
max_message_size = MaybeMaxMessageSize},
#state{links = Links, link_index = LinkIndex,
link_handle_index = LHI} = State0) ->
#{Name := OutHandle} = LinkIndex,
#{OutHandle := Link0} = Links,
ok = notify_link_attached(Link0),
{DeliveryCount, MaxMessageSize} =
case Link0 of
#link{role = sender,
delivery_count = DC} ->
MSS = case MaybeMaxMessageSize of
{ulong, S} when S > 0 -> S;
_ -> undefined
end,
{DC, MSS};
#link{role = receiver,
max_message_size = MSS} ->
{unpack(IDC), MSS}
end,
Link = Link0#link{state = attached,
input_handle = InHandle,
delivery_count = DeliveryCount,
max_message_size = MaxMessageSize},
State = State0#state{links = Links#{OutHandle => Link},
link_index = maps:remove(Name, LinkIndex),
link_handle_index = LHI#{InHandle => OutHandle}},
{keep_state, State};
mapped(cast, #'v1_0.detach'{handle = {uint, InHandle},
error = Err},
#state{links = Links, link_handle_index = LHI} = State0) ->
with_link(InHandle, State0,
fun (#link{output_handle = OutHandle} = Link, State) ->
Reason = reason(Err),
ok = notify_link_detached(Link, Reason),
{keep_state,
State#state{links = maps:remove(OutHandle, Links),
link_handle_index = maps:remove(InHandle, LHI)}}
end);
mapped(cast, #'v1_0.flow'{handle = undefined} = Flow, State0) ->
State = handle_session_flow(Flow, State0),
{keep_state, State};
mapped(cast, #'v1_0.flow'{handle = {uint, InHandle}} = Flow,
#state{links = Links} = State0) ->
State = handle_session_flow(Flow, State0),
{ok, #link{output_handle = OutHandle} = Link0} =
find_link_by_input_handle(InHandle, State),
% TODO: handle `send_flow` return tag
{ok, Link} = handle_link_flow(Flow, Link0),
ok = maybe_notify_link_credit(Link0, Link),
Links1 = Links#{OutHandle := Link},
State1 = State#state{links = Links1},
{keep_state, State1};
mapped(cast, {#'v1_0.transfer'{handle = {uint, InHandle},
more = true} = Transfer, Payload},
#state{links = Links} = State0) ->
{ok, #link{output_handle = OutHandle} = Link} =
find_link_by_input_handle(InHandle, State0),
Link1 = append_partial_transfer(Transfer, Payload, Link),
State = book_partial_transfer_received(
State0#state{links = Links#{OutHandle => Link1}}),
{keep_state, State};
mapped(cast, {Transfer0 = #'v1_0.transfer'{handle = {uint, InHandle}},
Payload0}, State0) ->
{ok, #link{target = {pid, TargetPid},
ref = LinkRef,
incoming_unsettled = Unsettled
} = Link0} = find_link_by_input_handle(InHandle, State0),
{Transfer = #'v1_0.transfer'{settled = Settled,
delivery_id = {uint, DeliveryId}},
Payload, Link1} = complete_partial_transfer(Transfer0, Payload0, Link0),
Msg = decode_as_msg(Transfer, Payload),
Link2 = case Settled of
true ->
Link1;
_ ->
%% "If not set on the first (or only) transfer for a (multi-transfer) delivery,
%% then the settled flag MUST be interpreted as being false." [2.7.5]
Link1#link{incoming_unsettled = Unsettled#{DeliveryId => ok}}
end,
% link bookkeeping
% notify when credit is exhausted (link_credit = 0)
% detach the Link with a transfer-limit-exceeded error code if further
% transfers are received
case book_transfer_received(State0, Link2) of
{ok, Link3, State1} ->
% deliver
TargetPid ! {amqp10_msg, LinkRef, Msg},
State = auto_flow(Link3, State1),
{keep_state, State};
{credit_exhausted, Link3, State} ->
TargetPid ! {amqp10_msg, LinkRef, Msg},
notify_credit_exhausted(Link3),
{keep_state, State};
{transfer_limit_exceeded, Link3, State} ->
logger:warning("transfer_limit_exceeded for link ~tp", [Link3]),
Link = detach_with_error_cond(Link3, State,
?V_1_0_LINK_ERROR_TRANSFER_LIMIT_EXCEEDED),
{keep_state, update_link(Link, State)}
end;
% role=true indicates the disposition is from a `receiver`. i.e. from the
% clients point of view these are dispositions relating to `sender`links
mapped(cast, #'v1_0.disposition'{role = true,
settled = true,
first = {uint, First},
last = Last0,
state = DeliveryState},
#state{outgoing_unsettled = Unsettled0} = State) ->
Last = case Last0 of
undefined -> First;
{uint, L} -> L
end,
% TODO: no good if the range becomes very large!! refactor
Unsettled = serial_number:foldl(
fun(Id, Acc0) ->
case maps:take(Id, Acc0) of
{{DeliveryTag, Pid}, Acc} ->
%% TODO: currently all modified delivery states
%% will be translated to the old, `modified` atom.
%% At some point we should translate into the
%% full {modified, bool, bool, map) tuple.
S = translate_delivery_state(DeliveryState),
ok = notify_disposition(Pid, {S, DeliveryTag}),
Acc;
error ->
Acc0
end
end, Unsettled0, First, Last),
{keep_state, State#state{outgoing_unsettled = Unsettled}};
mapped(cast, Frame, State) ->
logger:warning("Unhandled session frame ~tp in state ~tp",
[Frame, State]),
{keep_state, State};
mapped({call, From},
{transfer, _Transfer, _Parts},
#state{remote_incoming_window = Window})
when Window =< 0 ->
{keep_state_and_data, {reply, From, {error, remote_incoming_window_exceeded}}};
mapped({call, From},
{transfer, _Transfer, _Parts},
#state{remote_incoming_window = Window})
when Window =< 0 ->
{keep_state_and_data, {reply, From, {error, remote_incoming_window_exceeded}}};
mapped({call, From = {Pid, _}},
{transfer, #'v1_0.transfer'{handle = {uint, OutHandle},
delivery_tag = {binary, DeliveryTag},
settled = false} = Transfer0, Parts},
#state{outgoing_delivery_id = DeliveryId, links = Links,
outgoing_unsettled = Unsettled} = State) ->
case Links of
#{OutHandle := #link{input_handle = undefined}} ->
{keep_state_and_data, {reply, From, {error, half_attached}}};
#{OutHandle := #link{link_credit = LC}} when LC =< 0 ->
{keep_state_and_data, {reply, From, {error, insufficient_credit}}};
#{OutHandle := Link = #link{max_message_size = MaxMessageSize}} ->
Transfer = Transfer0#'v1_0.transfer'{delivery_id = uint(DeliveryId)},
case send_transfer(Transfer, Parts, MaxMessageSize, State) of
{ok, NumFrames} ->
State1 = State#state{outgoing_unsettled = Unsettled#{DeliveryId => {DeliveryTag, Pid}}},
{keep_state, book_transfer_send(NumFrames, Link, State1), {reply, From, ok}};
Error ->
{keep_state_and_data, {reply, From, Error}}
end;
_ ->
{keep_state_and_data, {reply, From, {error, link_not_found}}}
end;
mapped({call, From},
{transfer, #'v1_0.transfer'{handle = {uint, OutHandle}} = Transfer0,
Parts}, #state{outgoing_delivery_id = DeliveryId,
links = Links} = State) ->
case Links of
#{OutHandle := #link{input_handle = undefined}} ->
{keep_state_and_data, {reply, From, {error, half_attached}}};
#{OutHandle := #link{link_credit = LC}} when LC =< 0 ->
{keep_state_and_data, {reply, From, {error, insufficient_credit}}};
#{OutHandle := Link = #link{max_message_size = MaxMessageSize}} ->
Transfer = Transfer0#'v1_0.transfer'{delivery_id = uint(DeliveryId)},
case send_transfer(Transfer, Parts, MaxMessageSize, State) of
{ok, NumFrames} ->
{keep_state, book_transfer_send(NumFrames, Link, State), {reply, From, ok}};
Error ->
{keep_state_and_data, {reply, From, Error}}
end;
_ ->
{keep_state_and_data, {reply, From, {error, link_not_found}}}
end;
mapped({call, From},
{disposition, OutputHandle, First, Last, Settled0, DeliveryState},
#state{links = Links} = State0) ->
#{OutputHandle := Link0 = #link{incoming_unsettled = Unsettled0}} = Links,
Unsettled = serial_number:foldl(fun maps:remove/2, Unsettled0, First, Last),
Link = Link0#link{incoming_unsettled = Unsettled},
State1 = State0#state{links = Links#{OutputHandle := Link}},
State = auto_flow(Link, State1),
Disposition = #'v1_0.disposition'{
role = translate_role(receiver),
first = {uint, First},
last = {uint, Last},
settled = Settled0,
state = translate_delivery_state(DeliveryState)},
Res = send(Disposition, State),
{keep_state, State, {reply, From, Res}};
mapped({call, From}, {attach, Attach}, State) ->
{State1, LinkRef} = send_attach(fun send/2, Attach, From, State),
{keep_state, State1, {reply, From, {ok, LinkRef}}};
mapped({call, From}, Msg, State) ->
{Reply, State1} = send_detach(fun send/2, Msg, From, State),
{keep_state, State1, {reply, From, Reply}};
mapped(_EvtType, Msg, _State) ->
logger:warning("amqp10_session: unhandled msg in mapped state ~W",
[Msg, 10]),
keep_state_and_data.
end_sent(_EvtType, #'v1_0.end'{error = Err}, State) ->
Reason = reason(Err),
ok = notify_session_ended(State, Reason),
{stop, normal, State};
end_sent(_EvtType, _Frame, _State) ->
% just drop frames here
keep_state_and_data.
terminate(Reason, _StateName, #state{channel = Channel,
remote_channel = RemoteChannel,
reader = Reader}) ->
case Reason of
normal -> amqp10_client_frame_reader:unregister_session(
Reader, self(), Channel, RemoteChannel);
_ -> ok
end,
ok.
code_change(_OldVsn, StateName, State, _Extra) ->
{ok, StateName, State}.
%% -------------------------------------------------------------------
%% Internal functions.
%% -------------------------------------------------------------------
send_begin(#state{socket = Socket,
next_outgoing_id = NextOutId,
incoming_window = InWin} = State) ->
Begin = #'v1_0.begin'{next_outgoing_id = uint(NextOutId),
incoming_window = uint(InWin),
outgoing_window = ?UINT_OUTGOING_WINDOW},
Frame = encode_frame(Begin, State),
socket_send(Socket, Frame).
send_end(State) ->
send_end(State, undefined).
send_end(#state{socket = Socket} = State, Cond) ->
Err = #'v1_0.error'{condition = Cond},
End = #'v1_0.end'{error = Err},
Frame = encode_frame(End, State),
socket_send(Socket, Frame).
encode_frame(Record, #state{channel = Channel}) ->
Encoded = amqp10_framing:encode_bin(Record),
amqp10_binary_generator:build_frame(Channel, Encoded).
send(Record, #state{socket = Socket} = State) ->
Frame = encode_frame(Record, State),
socket_send(Socket, Frame).
send_transfer(Transfer0, Parts0, MaxMessageSize, #state{socket = Socket,
channel = Channel,
connection_config = Config}) ->
OutMaxFrameSize = maps:get(outgoing_max_frame_size, Config),
Transfer = amqp10_framing:encode_bin(Transfer0),
TransferSize = iolist_size(Transfer),
Parts = [amqp10_framing:encode_bin(P) || P <- Parts0],
PartsBin = iolist_to_binary(Parts),
if is_integer(MaxMessageSize) andalso
MaxMessageSize > 0 andalso
byte_size(PartsBin) > MaxMessageSize ->
{error, message_size_exceeded};
true ->
% TODO: this does not take the extended header into account
% see: 2.3
MaxPayloadSize = OutMaxFrameSize - TransferSize - ?FRAME_HEADER_SIZE,
Frames = build_frames(Channel, Transfer0, PartsBin, MaxPayloadSize, []),
ok = socket_send(Socket, Frames),
{ok, length(Frames)}
end.
send_flow_link(OutHandle,
#'v1_0.flow'{link_credit = {uint, Credit}} = Flow0, RenewWhenBelow,
#state{links = Links,
next_incoming_id = NII,
next_outgoing_id = NOI,
incoming_window = InWin} = State) ->
AutoFlow = case RenewWhenBelow of
never -> never;
Limit -> {auto, Limit, Credit}
end,
#{OutHandle := #link{output_handle = H,
role = receiver,
delivery_count = DeliveryCount,
available = Available} = Link} = Links,
Flow = Flow0#'v1_0.flow'{
handle = uint(H),
%% "This value MUST be set if the peer has received the begin
%% frame for the session, and MUST NOT be set if it has not." [2.7.4]
next_incoming_id = maybe_uint(NII),
next_outgoing_id = uint(NOI),
outgoing_window = ?UINT_OUTGOING_WINDOW,
incoming_window = uint(InWin),
%% "In the event that the receiving link endpoint has not yet seen the
%% initial attach frame from the sender this field MUST NOT be set." [2.7.4]
delivery_count = maybe_uint(DeliveryCount),
available = uint(Available)},
ok = send(Flow, State),
State#state{links = Links#{OutHandle =>
Link#link{link_credit = Credit,
auto_flow = AutoFlow}}}.
build_frames(Channel, Trf, Bin, MaxPayloadSize, Acc)
when byte_size(Bin) =< MaxPayloadSize ->
T = amqp10_framing:encode_bin(Trf#'v1_0.transfer'{more = false}),
Frame = amqp10_binary_generator:build_frame(Channel, [T, Bin]),
lists:reverse([Frame | Acc]);
build_frames(Channel, Trf, Payload, MaxPayloadSize, Acc) ->
<<Bin:MaxPayloadSize/binary, Rest/binary>> = Payload,
T = amqp10_framing:encode_bin(Trf#'v1_0.transfer'{more = true}),
Frame = amqp10_binary_generator:build_frame(Channel, [T, Bin]),
build_frames(Channel, Trf, Rest, MaxPayloadSize, [Frame | Acc]).
make_source(#{role := {sender, _}}) ->
#'v1_0.source'{};
make_source(#{role := {receiver, #{address := Address} = Target, _Pid}, filter := Filter}) ->
Durable = translate_terminus_durability(maps:get(durable, Target, none)),
TranslatedFilter = translate_filters(Filter),
#'v1_0.source'{address = {utf8, Address},
durable = {uint, Durable},
filter = TranslatedFilter}.
make_target(#{role := {receiver, _Source, _Pid}}) ->
#'v1_0.target'{};
make_target(#{role := {sender, #{address := Address} = Target}}) ->
Durable = translate_terminus_durability(maps:get(durable, Target, none)),
#'v1_0.target'{address = {utf8, Address},
durable = {uint, Durable}}.
max_message_size(#{max_message_size := Size})
when is_integer(Size) andalso
Size > 0 ->
{ulong, Size};
max_message_size(_) ->
undefined.
translate_terminus_durability(none) -> 0;
translate_terminus_durability(configuration) -> 1;
translate_terminus_durability(unsettled_state) -> 2.
translate_filters(Filters)
when is_map(Filters) andalso
map_size(Filters) == 0 ->
undefined;
translate_filters(Filters)
when is_map(Filters) ->
{map,
maps:fold(
fun
(<<"apache.org:legacy-amqp-headers-binding:map">> = K, V, Acc) when is_map(V) ->
%% special case conversion
Key = sym(K),
[{Key, {described, Key, translate_legacy_amqp_headers_binding(V)}} | Acc];
(K, V, Acc) when is_binary(K) ->
%% try treat any filter value generically
Key = sym(K),
Value = filter_value_type(V),
[{Key, {described, Key, Value}} | Acc]
end, [], Filters)}.
filter_value_type(V) when is_binary(V) ->
%% this is clearly not always correct
{utf8, V};
filter_value_type(V)
when is_integer(V) andalso V >= 0 ->
{uint, V};
filter_value_type(VList) when is_list(VList) ->
{list, [filter_value_type(V) || V <- VList]};
filter_value_type({T, _} = V) when is_atom(T) ->
%% looks like an already tagged type, just pass it through
V.
% https://people.apache.org/~rgodfrey/amqp-1.0/apache-filters.html
translate_legacy_amqp_headers_binding(LegacyHeaders) ->
{map,
maps:fold(
fun(<<"x-match">> = K, <<"any">> = V, Acc) ->
[{{utf8, K}, {utf8, V}} | Acc];
(<<"x-match">> = K, <<"all">> = V, Acc) ->
[{{utf8, K}, {utf8, V}} | Acc];
(<<"x-", _/binary>>, _, Acc) ->
Acc;
(K, V, Acc) ->
[{{utf8, K}, filter_value_type(V)} | Acc]
end, [], LegacyHeaders)}.
send_detach(Send, {detach, OutHandle}, _From, State = #state{links = Links}) ->
case Links of
#{OutHandle := #link{input_handle = undefined}} ->
% Link = stash_link_request(Link0, From, Msg),
% not fully attached yet - stash the request for later processing
{{error, half_attached}, State};
#{OutHandle := Link} ->
Detach = #'v1_0.detach'{handle = uint(OutHandle),
closed = true},
ok = Send(Detach, State),
Links1 = Links#{OutHandle => Link#link{state = detach_sent}},
{ok, State#state{links = Links1}};
_ ->
{{error, link_not_found}, State}
end.
detach_with_error_cond(Link = #link{output_handle = OutHandle}, State, Cond) ->
Err = #'v1_0.error'{condition = Cond},
Detach = #'v1_0.detach'{handle = uint(OutHandle),
closed = true,
error = Err},
ok = send(Detach, State),
Link#link{state = detach_sent}.
send_attach(Send, #{name := Name, role := Role} = Args, {FromPid, _},
#state{next_link_handle = OutHandle0, links = Links,
link_index = LinkIndex} = State) ->
Source = make_source(Args),
Target = make_target(Args),
Properties = amqp10_client_types:make_properties(Args),
{LinkTarget, RoleAsBool, InitialDeliveryCount, MaxMessageSize} =
case Role of
{receiver, _, Pid} ->
{{pid, Pid}, true, undefined, max_message_size(Args)};
{sender, #{address := TargetAddr}} ->
{TargetAddr, false, uint(?INITIAL_DELIVERY_COUNT), undefined}
end,
{OutHandle, NextLinkHandle} =
case Args of
#{handle := Handle} ->
%% Client app provided link handle.
%% Really only meant for integration tests.
{Handle, OutHandle0};
_ ->
{OutHandle0, OutHandle0 + 1}
end,
% create attach performative
Attach = #'v1_0.attach'{name = {utf8, Name},
role = RoleAsBool,
handle = {uint, OutHandle},
source = Source,
properties = Properties,
initial_delivery_count = InitialDeliveryCount,
snd_settle_mode = snd_settle_mode(Args),
rcv_settle_mode = rcv_settle_mode(Args),
target = Target,
max_message_size = MaxMessageSize},
ok = Send(Attach, State),
LinkRef = make_link_ref(element(1, Role), self(), OutHandle),
Link = #link{name = Name,
ref = LinkRef,
output_handle = OutHandle,
state = attach_sent,
role = element(1, Role),
notify = FromPid,
auto_flow = never,
target = LinkTarget,
delivery_count = unpack(InitialDeliveryCount),
max_message_size = unpack(MaxMessageSize)},
{State#state{links = Links#{OutHandle => Link},
next_link_handle = NextLinkHandle,
link_index = LinkIndex#{Name => OutHandle}}, LinkRef}.
-spec handle_session_flow(#'v1_0.flow'{}, #state{}) -> #state{}.
handle_session_flow(#'v1_0.flow'{next_incoming_id = MaybeNII,
next_outgoing_id = {uint, NOI},
incoming_window = {uint, InWin},
outgoing_window = {uint, OutWin}},
#state{next_outgoing_id = OurNOI} = State) ->
NII = case MaybeNII of
{uint, N} -> N;
undefined -> ?INITIAL_OUTGOING_TRANSFER_ID
end,
RemoteIncomingWindow = diff(add(NII, InWin), OurNOI), % see: 2.5.6
State#state{next_incoming_id = NOI,
remote_incoming_window = RemoteIncomingWindow,
remote_outgoing_window = OutWin}.
-spec handle_link_flow(#'v1_0.flow'{}, #link{}) -> {ok | send_flow, #link{}}.
handle_link_flow(#'v1_0.flow'{drain = true,
link_credit = {uint, TheirCredit}},
Link = #link{role = sender,
delivery_count = OurDC,
available = 0}) ->
{send_flow, Link#link{link_credit = 0,
delivery_count = add(OurDC, TheirCredit)}};
handle_link_flow(#'v1_0.flow'{delivery_count = MaybeTheirDC,
link_credit = {uint, TheirCredit}},
Link = #link{role = sender,
delivery_count = OurDC}) ->
TheirDC = case MaybeTheirDC of
{uint, DC} -> DC;
undefined -> ?INITIAL_DELIVERY_COUNT
end,
LinkCredit = diff(add(TheirDC, TheirCredit), OurDC),
{ok, Link#link{link_credit = LinkCredit}};
handle_link_flow(#'v1_0.flow'{delivery_count = TheirDC,
link_credit = {uint, TheirCredit},
available = Available,
drain = Drain},
Link0 = #link{role = receiver}) ->
Link = case Drain andalso TheirCredit =< 0 of
true ->
notify_credit_exhausted(Link0),
Link0#link{delivery_count = unpack(TheirDC),
link_credit = 0,
available = unpack(Available),
drain = Drain};
false ->
Link0#link{delivery_count = unpack(TheirDC),
available = unpack(Available),
drain = Drain}
end,
{ok, Link}.
-spec find_link_by_input_handle(input_handle(), #state{}) ->
{ok, #link{}} | not_found.
find_link_by_input_handle(InHandle, #state{link_handle_index = LHI,
links = Links}) ->
case LHI of
#{InHandle := OutHandle} ->
case Links of
#{OutHandle := Link} ->
{ok, Link};
_ -> not_found
end;
_ -> not_found
end.
with_link(InHandle, State, Fun) ->
case find_link_by_input_handle(InHandle, State) of
{ok, Link} ->
Fun(Link, State);
not_found ->
% end session with errant-link
ok = send_end(State, ?V_1_0_SESSION_ERROR_ERRANT_LINK),
{next_state, end_sent, State}
end.
maybe_uint(undefined) -> undefined;
maybe_uint(Int) -> uint(Int).
uint(Int) -> {uint, Int}.
unpack(X) -> amqp10_client_types:unpack(X).
snd_settle_mode(#{snd_settle_mode := unsettled}) -> {ubyte, 0};
snd_settle_mode(#{snd_settle_mode := settled}) -> {ubyte, 1};
snd_settle_mode(#{snd_settle_mode := mixed}) -> {ubyte, 2};
snd_settle_mode(_) -> undefined.
rcv_settle_mode(#{rcv_settle_mode := first}) -> {ubyte, 0};
rcv_settle_mode(#{rcv_settle_mode := second}) -> {ubyte, 1};
rcv_settle_mode(_) -> undefined.
% certain amqp10 brokers (IBM MQ) return an undefined delivery state
% when the link is detached before settlement is sent
% TODO: work out if we can assume accepted
translate_delivery_state(undefined) -> undefined;
translate_delivery_state(#'v1_0.accepted'{}) -> accepted;
translate_delivery_state(#'v1_0.rejected'{}) -> rejected;
translate_delivery_state(#'v1_0.modified'{}) -> modified;
translate_delivery_state(#'v1_0.released'{}) -> released;
translate_delivery_state(#'v1_0.received'{}) -> received;
translate_delivery_state(accepted) -> #'v1_0.accepted'{};
translate_delivery_state(rejected) -> #'v1_0.rejected'{};
translate_delivery_state(modified) -> #'v1_0.modified'{};
translate_delivery_state({modified,
DeliveryFailed,
UndeliverableHere,
MessageAnnotations}) ->
MA = translate_message_annotations(MessageAnnotations),
#'v1_0.modified'{delivery_failed = DeliveryFailed,
undeliverable_here = UndeliverableHere,
message_annotations = MA};
translate_delivery_state(released) -> #'v1_0.released'{};
translate_delivery_state(received) -> #'v1_0.received'{}.
translate_role(receiver) -> true.
maybe_notify_link_credit(#link{role = sender,
link_credit = 0},
#link{role = sender,
link_credit = NewCredit} = NewLink)
when NewCredit > 0 ->
notify_link(NewLink, credited);
maybe_notify_link_credit(_Old, _New) ->
ok.
notify_link_attached(Link) ->
notify_link(Link, attached).
notify_link_detached(Link, Reason) ->
notify_link(Link, {detached, Reason}).
notify_link(#link{notify = Pid, ref = Ref}, What) ->
Evt = {amqp10_event, {link, Ref, What}},
Pid ! Evt,
ok.
notify_session_begun(#state{notify = Pid}) ->
Pid ! amqp10_session_event(begun),
ok.
notify_session_ended(#state{notify = Pid}, Reason) ->
Pid ! amqp10_session_event({ended, Reason}),
ok.
notify_disposition(Pid, DeliveryStateDeliveryTag) ->
Pid ! {amqp10_disposition, DeliveryStateDeliveryTag},
ok.
book_transfer_send(Num, #link{output_handle = Handle} = Link,
#state{next_outgoing_id = NextOutgoingId,
outgoing_delivery_id = DeliveryId,
remote_incoming_window = RIW,
links = Links} = State) ->
State#state{next_outgoing_id = add(NextOutgoingId, Num),
outgoing_delivery_id = add(DeliveryId, 1),
remote_incoming_window = RIW-Num,
links = Links#{Handle => book_link_transfer_send(Link)}}.
book_partial_transfer_received(#state{next_incoming_id = NID,
remote_outgoing_window = ROW} = State) ->
State#state{next_incoming_id = add(NID, 1),
remote_outgoing_window = ROW - 1}.
book_transfer_received(State = #state{connection_config =
#{transfer_limit_margin := Margin}},
#link{link_credit = Margin} = Link) ->
{transfer_limit_exceeded, Link, State};
book_transfer_received(#state{next_incoming_id = NID,
remote_outgoing_window = ROW,
links = Links} = State,
#link{output_handle = OutHandle,
delivery_count = DC,
link_credit = LC,
available = Avail} = Link) ->
Link1 = Link#link{delivery_count = add(DC, 1),
link_credit = LC - 1,
%% "the receiver MUST maintain a floor of zero in its
%% calculation of the value of available" [2.6.7]
available = max(0, Avail - 1)},
State1 = State#state{links = Links#{OutHandle => Link1},
next_incoming_id = add(NID, 1),
remote_outgoing_window = ROW - 1},
case Link1 of
#link{link_credit = 0,
auto_flow = never} ->
{credit_exhausted, Link1, State1};
_ ->
{ok, Link1, State1}
end.
auto_flow(#link{link_credit = LC,
auto_flow = {auto, RenewWhenBelow, Credit},
output_handle = OutHandle,
incoming_unsettled = Unsettled},
State)
when LC + map_size(Unsettled) < RenewWhenBelow ->
send_flow_link(OutHandle,
#'v1_0.flow'{link_credit = {uint, Credit}},