34
35:- module(stomp,
36 [ stomp_connection/5, 37 38 stomp_connection/6, 39 40 stomp_connection_property/2, 41 stomp_destroy_connection/1, 42 stomp_connect/1, 43 stomp_connect/2, 44 stomp_teardown/1, 45 stomp_reconnect/1, 46 stomp_send/4, 47 stomp_send_json/4, 48 stomp_subscribe/4, 49 stomp_unsubscribe/2, 50 stomp_ack/2, 51 stomp_nack/2, 52 stomp_ack/3, 53 stomp_nack/3, 54 stomp_transaction/2, 55 stomp_disconnect/2, 56 57 stomp_begin/2, 58 stomp_commit/2, 59 stomp_abort/2, 60 stomp_setup/2 61 ]). 62
113
114:- meta_predicate
115 stomp_connection(+, +, +, 4, -),
116 stomp_connection(+, +, +, 4, -, +),
117 stomp_transaction(+, 0). 118
119:- use_module(library(apply)). 120:- use_module(library(debug)). 121:- use_module(library(error)). 122:- use_module(library(gensym)). 123:- use_module(library(http/http_stream)). 124:- use_module(library(json)). 125:- use_module(library(readutil)). 126:- use_module(library(socket)). 127:- use_module(library(uuid)). 128:- use_module(library(lists)). 129:- use_module(library(option)). 130:- use_module(library(time)). 131
132:- dynamic
133 connection_property/3. 134
209
210stomp_connection(Address, Host, Headers, Callback, Connection) :-
211 stomp_connection(Address, Host, Headers, Callback, Connection, []).
212
213stomp_connection(Address, Host, Headers, Callback, Connection, Options) :-
214 option(reconnect(Reconnect), Options, false),
215 option(connect_timeout(Timeout), Options, 600),
216 option(json_options(JSONOptions), Options, []),
217 option(max_header_size(MaxHeader), Options, 1048576),
218 option(max_body_size(MaxBody), Options, 104857600),
219 must_be(oneof_or_nonneg(infinite), MaxHeader),
220 must_be(oneof_or_nonneg(infinite), MaxBody),
221 valid_address(Address),
222 must_be(atom, Host),
223 must_be(dict, Headers),
224 must_be(callable, Callback),
225 uuid(Connection),
226 retractall(connection_property(Connection, _, _)),
227 update_connection_mapping(
228 Connection,
229 _{ address: Address,
230 callback: Callback,
231 host: Host,
232 headers: Headers,
233 reconnect: Reconnect,
234 connect_timeout: Timeout,
235 json_options: JSONOptions,
236 max_header_size: MaxHeader,
237 max_body_size: MaxBody
238 }).
239
240:- multifile error:has_type/2. 241error:has_type(oneof_or_nonneg(Atom), X) :-
242 ( X == Atom
243 -> true
244 ; integer(X),
245 X >= 0
246 ).
247
248valid_address(Host:Port) :-
249 !,
250 must_be(atom, Host),
251 must_be(integer, Port).
252valid_address(Address) :-
253 type_error(stom_address, Address).
254
255connection_property(address).
256connection_property(callback).
257connection_property(host).
258connection_property(headers).
259connection_property(reconnect).
260connection_property(connect_timeout).
261connection_property(json_options).
262connection_property(max_header_size).
263connection_property(max_body_size).
264
286
287stomp_connection_property(Connection, Property) :-
288 var(Property),
289 !,
290 connection_property(Connection, Name, Value),
291 Property =.. [Name,Value].
292stomp_connection_property(Connection, Property) :-
293 must_be(compound, Property),
294 Property =.. [Name,Value],
295 query_connection_property(Connection, Name, Value).
296
301
302stomp_destroy_connection(Connection) :-
303 must_be(ground, Connection),
304 ( query_connection_property(Connection, address, _)
305 -> stomp_teardown(Connection),
306 retractall(connection_property(Connection, _, _))
307 ; existence_error(stomp_connection, Connection)
308 ).
309
319
320stomp_setup(Connection, Options) :-
321 stomp_setup(Connection, _New, Options).
322
323stomp_setup(Connection, false, _) :-
324 query_connection_property(Connection, stream, _Stream),
325 !.
326stomp_setup(Connection, New, Options) :-
327 with_mutex(stomp, stomp_setup_guarded(Connection, New, Options)).
328
329stomp_setup_guarded(Connection, false, _) :-
330 query_connection_property(Connection, stream, _Stream),
331 !.
332stomp_setup_guarded(Connection, true, Options) :-
333 query_connection_property(Connection, address, Address),
334 connect(Connection, Address, Stream, Options),
335 set_stream(Stream, encoding(utf8)),
336 gensym(stomp_receive, Alias),
337 thread_create(receive(Connection, Stream), ReceiverThreadId, [alias(Alias)]),
338 debug(stomp(connection), 'Handling input on thread ~p', [ReceiverThreadId]),
339 update_connection_mapping(Connection,
340 _{ receiver_thread_id: ReceiverThreadId,
341 stream:Stream
342 }).
343
348
349connect(Connection, Address, Stream, Options) :-
350 stomp_deadline(Connection, Deadline, Options),
351 connect_with_deadline(Connection, Address, Stream, Deadline, Options).
352
353connect_with_deadline(_Connection, Address, Stream, once, Options) :-
354 !,
355 tcp_connect(Address, Stream, Options).
356connect_with_deadline(Connection, Address, Stream, Deadline, Options) :-
357 number(Deadline),
358 !,
359 between(0, infinite, Retry),
360 get_time(Now),
361 Timeout is Deadline-Now,
362 ( Timeout > 0
363 -> ( catch(call_with_time_limit(
364 Timeout,
365 tcp_connect(Address, Stream, Options)),
366 Error,
367 true)
368 -> ( var(Error)
369 -> !
370 ; ( debugging(stomp(connection))
371 -> print_message(warning, Error)
372 ; true
373 ),
374 wait_retry(Connection, Error, Retry, Deadline)
375 )
376 ; wait_retry(Connection, failed, Retry, Deadline)
377 )
378 ; throw(error(stomp_error(connect, Connection, timeout), _))
379 ).
380connect_with_deadline(Connection, Address, Stream, Deadline, Options) :-
381 between(0, infinite, Retry),
382 Error = error(Formal, _),
383 ( catch(tcp_connect(Address, Stream, Options),
384 Error,
385 true)
386 -> ( var(Formal)
387 -> !
388 ; ( debugging(stomp(connection))
389 -> print_message(warning, Error)
390 ; true
391 ),
392 wait_retry(Connection, Formal, Retry, Deadline)
393 )
394 ; wait_retry(Connection, failed, Retry, Deadline)
395 ).
396
397wait_retry(Connection, Why, _Retry, _Deadline) :-
398 Why = error(stomp_error(connect, Connection, error(_)), _),
399 !,
400 throw(Why).
401wait_retry(Connection, _Why, Retry, Deadline) :-
402 Wait0 is min(10, 0.1 * (1<<Retry)),
403 ( number(Deadline)
404 -> get_time(Now),
405 Wait is min(Deadline-Now, Wait0)
406 ; Wait = Wait0
407 ),
408 ( Wait > 0
409 -> sleep(Wait),
410 fail
411 ; throw(error(stomp_error(connect, Connection, timeout), _))
412 ).
413
414
421
422stomp_teardown(Connection) :-
423 terminate_helper(Connection, receiver_thread_id),
424 terminate_helper(Connection, heartbeat_thread_id),
425 forall(query_connection_property(Connection, stream, Stream),
426 close(Stream, [force(true)])),
427 debug(stomp(connection), 'retract connection mapping for ~p', [Connection]),
428 reset_connection_properties(Connection).
429
430terminate_helper(Connection, Helper) :-
431 retract(connection_property(Connection, Helper, Thread)),
432 \+ thread_self(Thread),
433 catch(thread_signal(Thread, abort), error(_,_), fail),
434 !,
435 thread_join(Thread, _Status).
436terminate_helper(_, _).
437
438reset_connection_properties(Connection) :-
439 findall(P,
440 ( query_connection_property(Connection, P, _),
441 \+ connection_property(P)
442 ), Ps),
443 forall(member(P, Ps),
444 retractall(connection_property(Connection, P, _))).
445
449
450stomp_reconnect(Connection) :-
451 stomp_teardown(Connection),
452 stomp_connect(Connection).
453
471
472stomp_connect(Connection) :-
473 stomp_connect(Connection, []).
474
475stomp_connect(Connection, Options) :-
476 update_reconnect_property(Connection),
477 stomp_deadline(Connection, Deadline, Options),
478 stomp_deadline_connect(Connection, Deadline, Options).
479
480update_reconnect_property(Connection) :-
481 query_connection_property(Connection, reconnect, disconnected),
482 !,
483 update_connection_property(Connection, reconnect, true).
484update_reconnect_property(_).
485
486stomp_deadline_connect(Connection, Deadline, Options) :-
487 between(0, infinite, Retry),
488 stomp_setup(Connection, New, [deadline(Deadline)|Options]),
489 ( New == true
490 -> Error = error(Formal, _),
491 catch(connect_handshake(Connection), Error, true),
492 ( var(Formal)
493 -> !
494 ; stomp_teardown(Connection),
495 wait_retry(Connection, Error, Retry, Deadline)
496 )
497 ; query_connection_property(Connection, connected, _)
498 -> true
499 ; wait_connected(Connection)
500 -> true
501 ; stomp_teardown(Connection),
502 wait_retry(Connection, failed, Retry, Deadline)
503 ).
504
508
509connect_handshake(Connection) :-
510 query_connection_property(Connection, headers, Headers),
511 query_connection_property(Connection, host, Host),
512 ( Heartbeat = Headers.get('heart-beat')
513 -> update_connection_property(Connection, 'heart-beat', Heartbeat)
514 ; true
515 ),
516 thread_self(Self),
517 update_connection_property(Connection, waiting_thread, Self),
518 send_frame(Connection,
519 connect,
520 Headers.put(_{ 'accept-version':'1.0,1.1,1.2',
521 host:Host
522 })),
523 ( thread_get_message(Self, stomp(connected(Connection, Status)),
524 [timeout(10)])
525 -> ( Status == true
526 -> get_time(Now),
527 update_connection_property(Connection, connected, Now)
528 ; throw(error(stomp_error(connect, Connection, Status), _))
529 )
530 ; retractall(connection_property(Connection, waiting_thread, _)),
531 throw(error(stomp_error(connect, Connection, timeout), _))
532 ).
533
534wait_connected(Connection) :-
535 thread_wait(query_connection_property(Connection, connected, _),
536 [ timeout(10),
537 wait_preds([connection_property/3])
538 ]),
539 !.
540wait_connected(Connection) :-
541 throw(error(stomp_error(connect, Connection, timeout), _)).
542
554
555stomp_deadline(_Connection, Deadline, Options) :-
556 option(deadline(Deadline), Options),
557 !.
558stomp_deadline(Connection, Deadline, Options) :-
559 ( option(timeout(Time), Options)
560 ; query_connection_property(Connection, connect_timeout, Time)
561 ),
562 !,
563 ( number(Time)
564 -> get_time(Now),
565 Deadline is Now+Time
566 ; must_be(oneof([inf,infinite]), Time),
567 Deadline = infinite
568 ).
569stomp_deadline(_, once, _).
570
571
579
580stomp_send(Connection, Destination, Headers, Body) :-
581 add_transaction(Headers, Headers1),
582 send_frame(Connection, send, Headers1.put(destination, Destination), Body).
583
591
592stomp_send_json(Connection, Destination, Headers, JSON) :-
593 add_transaction(Headers, Headers1),
594 atom_json_term(Body, JSON,
595 [ as(string),
596 width(0) 597 ]),
598 send_frame(Connection, send,
599 Headers1.put(_{ destination:Destination,
600 'content-type':'application/json'
601 }),
602 Body).
603
609
610stomp_subscribe(Connection, Destination, Id, Headers) :-
611 send_frame(Connection, subscribe,
612 Headers.put(_{destination:Destination, id:Id})).
613
619
620stomp_unsubscribe(Connection, Id) :-
621 send_frame(Connection, unsubscribe, _{id:Id}).
622
629
630stomp_ack(Connection, MessageId, Headers) :-
631 send_frame(Connection, ack, Headers.put('message-id', MessageId)).
632
639
640stomp_nack(Connection, MessageId, Headers) :-
641 send_frame(Connection, nack, Headers.put('message-id', MessageId)).
642
650
651stomp_ack(Connection, Header) :-
652 stomp_ack_nack(Connection, ack, Header).
653
654stomp_nack(Connection, Header) :-
655 stomp_ack_nack(Connection, nack, Header).
656
657stomp_ack_nack(Connection, Type, Header) :-
658 ( Id = Header.get(ack)
659 -> send_frame(Connection, Type, _{id: Id})
660 ; Pass = _{'message-id':_, subscription:_},
661 Pass :< Header
662 -> send_frame(Connection, Type, Pass)
663 ).
664
665
670
671stomp_begin(Connection, Transaction) :-
672 send_frame(Connection, begin, _{transaction:Transaction}).
673
679
680stomp_commit(Connection, Transaction) :-
681 send_frame(Connection, commit, _{transaction:Transaction}).
682
688
689stomp_abort(Connection, Transaction) :-
690 send_frame(Connection, abort, _{transaction:Transaction}).
691
699
700stomp_transaction(Connection, Goal) :-
701 uuid(TransactionID),
702 stomp_transaction(Connection, Goal, TransactionID).
703
704stomp_transaction(Connection, Goal, TransactionID) :-
705 stomp_begin(Connection, TransactionID),
706 ( catch(once(Goal), Error, true)
707 -> ( var(Error)
708 -> stomp_commit(Connection, TransactionID)
709 ; stomp_abort(Connection, TransactionID),
710 throw(Error)
711 )
712 ; stomp_abort(Connection, TransactionID),
713 fail
714 ).
715
716in_transaction(TransactionID) :-
717 prolog_current_frame(Frame),
718 prolog_frame_attribute(
719 Frame, parent_goal,
720 stomp_transaction(_Connection, _Goal, TransactionID)).
721
722add_transaction(Headers, Headers1) :-
723 in_transaction(TransactionID),
724 !,
725 Headers1 = Headers.put(transaction, TransactionID).
726add_transaction(Headers, Headers).
727
728
737
738stomp_disconnect(Connection, Headers) :-
739 ( query_connection_property(Connection, reconnect, true)
740 -> update_connection_property(Connection, reconnect, disconnected)
741 ; true
742 ),
743 send_frame(Connection, disconnect, Headers).
744
751
752send_frame(Connection, Command, Headers) :-
753 send_frame(Connection, Command, Headers, "").
754
755send_frame(Connection, Command, Headers, Body) :-
756 Error = error(Formal,_),
757 catch(send_frame_guarded(Connection, Command, Headers, Body),
758 Error,
759 true),
760 ( var(Formal)
761 -> true
762 ; query_connection_property(Connection, reconnect, true)
763 -> notify(Connection, disconnected),
764 stomp_teardown(Connection),
765 debug(stomp(connection), 'Sending thread reconnects', []),
766 send_frame(Connection, Command, Headers, Body)
767 ; notify(Connection, disconnected),
768 throw(Error)
769 ).
770
771send_frame_guarded(Connection, Command, Headers, Body) :-
772 has_body(Command),
773 !,
774 connection_stream(Connection, Stream),
775 default_content_type('text/plain', Headers, Headers1),
776 body_bytes(Body, ContentLength),
777 Headers2 = Headers1.put('content-length', ContentLength),
778 with_output_to(Stream,
779 ( send_command(Stream, Command),
780 send_header(Stream, Headers2),
781 format(Stream, '~w\u0000\n', [Body]),
782 flush_output(Stream))).
783send_frame_guarded(Connection, heartbeat, _Headers, _Body) :-
784 !,
785 connection_stream(Connection, Stream),
786 nl(Stream),
787 flush_output(Stream).
788send_frame_guarded(Connection, Command, Headers, _Body) :-
789 connection_stream(Connection, Stream),
790 with_output_to(Stream,
791 ( send_command(Stream, Command),
792 send_header(Stream, Headers),
793 format(Stream, '\u0000\n', []),
794 flush_output(Stream))).
795
797
798connection_stream(Connection, Stream) :-
799 query_connection_property(Connection, stream, Stream),
800 !.
801connection_stream(Connection, Stream) :-
802 stomp_connect(Connection),
803 query_connection_property(Connection, stream, Stream).
804
805send_command(Stream, Command) :-
806 string_upper(Command, Upper),
807 format(Stream, '~w\n', [Upper]).
808
(Stream, Headers) :-
810 dict_pairs(Headers, _, Pairs),
811 maplist(send_header_line(Stream), Pairs),
812 nl(Stream).
813
(Stream, Name-Value) :-
815 escape_value(Name, NameString),
816 ( number(Value)
817 -> format(Stream, '~w:~w\n', [NameString,Value])
818 ; escape_value(Value, String),
819 format(Stream, '~w:~w\n', [NameString,String])
820 ).
821
822escape_value(Value, String) :-
823 split_string(Value, "\r\n:\\", "", [_]),
824 !,
825 String = Value.
826escape_value(Value, String) :-
827 string_codes(Value, Codes),
828 phrase(escape(Codes), Encoded),
829 string_codes(String, Encoded).
830
831escape([]) --> [].
832escape([H|T]) --> esc(H), escape(T).
833
834esc(0'\r) --> !, "\\r".
835esc(0'\n) --> !, "\\n".
836esc(0':) --> !, "\\c".
837esc(0'\\) --> !, "\\\\".
838esc(C) --> [C].
839
840default_content_type(ContentType, Header0, Header) :-
841 ( get_dict('content-type', Header0, _)
842 -> Header = Header0
843 ; put_dict('content-type', Header0, ContentType, Header)
844 ).
845
846body_bytes(String, Bytes) :-
847 setup_call_cleanup(
848 open_null_stream(Out),
849 ( write(Out, String),
850 byte_count(Out, Bytes)
851 ),
852 close(Out)).
853
854
855 858
865
866read_frame(Connection, Stream, Frame) :-
867 query_connection_property(Connection, max_header_size, MaxHeader),
868 limit(MaxHeader, Limit),
869 read_command(Stream, Command, Limit, Left),
870 ( Command == end_of_file
871 -> Frame = end_of_file
872 ; Command == heartbeat
873 -> Frame = stomp_frame{cmd:heartbeat}
874 ; read_header(Stream, Header, Left),
875 read_content(Connection, Stream, Header, Content),
876 ( Content == skipped
877 -> Frame = skipped
878 ; has_body(Command)
879 -> ( get_dict('content-type', Header, Type)
880 -> true
881 ; Type = "text/plain"
882 ),
883 convert_content(Connection, Type, Content, Body),
884 Frame = stomp_frame{cmd:Command, headers:Header, body:Body}
885 ; Frame = stomp_frame{cmd:Command, headers:Header}
886 )
887 ).
888
889has_body(send).
890has_body(message).
891has_body(error).
892
893read_command(Stream, Command, Left0, Left) :-
894 read_line_limited(Stream, String, Left0, Left),
895 debug(stomp(command), 'Got line ~p', [String]),
896 ( String == end_of_file
897 -> Command = end_of_file
898 ; String == ""
899 -> Command = heartbeat
900 ; string_lower(String, Lwr),
901 atom_string(Command, Lwr)
902 ).
903
(Stream, Header, Left) :-
905 read_header_lines(Stream, Pairs, [], Left),
906 dict_pairs(Header, stomp_header, Pairs).
907
(Stream, Header, Seen, Left0) :-
909 read_line_limited(Stream, Line, Left0, Left),
910 ( Line == ""
911 -> Header = []
912 ; sub_string(Line, Before, _, After, ":")
913 -> sub_atom(Line, 0, Before, _, Name),
914 ( memberchk(Name, Seen)
915 -> read_header_lines(Stream, Header, Seen, Left)
916 ; sub_string(Line, _, After, 0, Value0),
917 convert_value(Name, Value0, Value),
918 Header = [Name-Value|More],
919 read_header_lines(Stream, More, [Name|Seen], Left)
920 )
921 ).
922
928
929read_line_limited(Stream, Line, Left0, Left) :-
930 get_code(Stream, C0),
931 ( C0 == -1
932 -> Line = end_of_file,
933 Left = Left0
934 ; read_line_codes(C0, Stream, Codes, Left0, Left),
935 ( append(Codes1, [0'\r], Codes)
936 -> true
937 ; Codes1 = Codes
938 ),
939 string_codes(Line, Codes1)
940 ).
941
942read_line_codes(0'\n, _, [], Left, Left) :- !.
943read_line_codes(-1, _, [], Left, Left) :- !.
944read_line_codes(C, Stream, [C|T], Left0, Left) :-
945 Left0 > 0,
946 !,
947 Left1 is Left0 - 1,
948 get_code(Stream, C1),
949 read_line_codes(C1, Stream, T, Left1, Left).
950read_line_codes(_, _, _, _, _) :-
951 resource_error(stomp(max_header_size)).
952
956
957limit(infinite, Limit) :-
958 !,
959 Limit = 0x3fffffffffffffff. 960limit(Limit, Limit).
961
962convert_value('content-length', String, Bytes) :-
963 !,
964 ( nonneg_integer_string(String, Bytes)
965 -> true
966 ; syntax_error(stomp_content_length(String))
967 ).
968convert_value(_, String, Value) :-
969 unescape_header_value(String, Value).
970
974
975nonneg_integer_string(String, Int) :-
976 string_codes(String, Codes),
977 Codes \== [],
978 forall(member(C, Codes), code_type(C, digit(_))),
979 number_codes(Int, Codes).
980
(String, Value) :-
982 sub_atom(String, _, _, _, "\\"),
983 !,
984 string_codes(String, Codes),
985 phrase(unescape(Plain), Codes),
986 string_codes(Value, Plain).
987unescape_header_value(String, String).
988
989unescape([H|T]) --> "\\", !, unesc(H), unescape(T).
990unescape([H|T]) --> [H], !, unescape(T).
991unescape([]) --> [].
992
993unesc(0'\r) --> "r", !.
994unesc(0'\n) --> "n", !.
995unesc(0':) --> "c", !.
996unesc(0'\\) --> "\\", !.
997unesc(_) --> [C], { syntax_error(invalid_stomp_escape(C)) }.
998
1009
1010read_content(Connection, Stream, Header, Content) :-
1011 query_connection_property(Connection, max_body_size, MaxBody),
1012 ( get_dict('content-length', Header, Bytes)
1013 -> ( MaxBody \== infinite,
1014 Bytes > MaxBody
1015 -> skip_content(Stream, Bytes),
1016 print_message(warning,
1017 stomp(frame_skipped(Connection, Header, MaxBody))),
1018 Content = skipped
1019 ; setup_call_cleanup(
1020 stream_range_open(Stream, DataStream, [size(Bytes)]),
1021 read_string(DataStream, _, Content),
1022 close(DataStream))
1023 ),
1024 get_char(Stream, End),
1025 ( End == '\u0000'
1026 -> true
1027 ; syntax_error(stomp_frame_not_terminated)
1028 )
1029 ; limit(MaxBody, Limit),
1030 read_to_nul(Stream, Codes, Limit),
1031 string_codes(Content, Codes)
1032 ).
1033
1034skip_content(Stream, Bytes) :-
1035 setup_call_cleanup(
1036 open_null_stream(Null),
1037 setup_call_cleanup(
1038 stream_range_open(Stream, DataStream, [size(Bytes)]),
1039 copy_stream_data(DataStream, Null),
1040 close(DataStream)),
1041 close(Null)).
1042
1043read_to_nul(Stream, Codes, Left) :-
1044 get_code(Stream, C),
1045 read_to_nul(C, Stream, Codes, Left).
1046
1047read_to_nul(0, _, [], _) :- !.
1048read_to_nul(-1, _, _, _) :- !,
1049 syntax_error(stomp_frame_not_terminated).
1050read_to_nul(C, Stream, [C|T], Left0) :-
1051 Left0 > 0,
1052 !,
1053 Left is Left0 - 1,
1054 get_code(Stream, C1),
1055 read_to_nul(C1, Stream, T, Left).
1056read_to_nul(_, _, _, _) :-
1057 resource_error(stomp(max_body_size)).
1058
1064
1065convert_content(Connection, Type, String, Content) :-
1066 json_content_type(Type),
1067 !,
1068 query_connection_property(Connection, json_options, Options),
1069 catch(setup_call_cleanup(
1070 open_string(String, In),
1071 ( json_read_dict(In, Content, Options),
1072 json_read_dict(In, End, [end_of_file(end_of_file)]),
1073 ( End == end_of_file
1074 -> true
1075 ; syntax_error(json(trailing_data))
1076 )
1077 ),
1078 close(In)),
1079 Error,
1080 ( print_message(warning, Error),
1081 Content = String
1082 )).
1083convert_content(_Connection, _Type, String, String).
1084
1085json_content_type(Type) :-
1086 split_string(Type, ";", " \t", [Main|_]),
1087 string_lower(Main, "application/json").
1088
1089
1093
1094receive(Connection, Stream) :-
1095 E = error(Formal, _),
1096 catch(read_frame(Connection, Stream, Frame), E, true),
1097 !,
1098 ( var(Formal)
1099 -> debug(stomp(receive), 'received frame ~p', [Frame]),
1100 ( Frame == end_of_file
1101 -> receive_done(Connection, end_of_file)
1102 ; Frame == skipped
1103 -> receive(Connection, Stream)
1104 ; catch_with_backtrace(process_frame(Connection, Frame),
1105 PE, print_message(warning, PE)),
1106 receive(Connection, Stream)
1107 )
1108 ; receive_done(Connection, E)
1109 ).
1110receive(Connection, _Stream) :-
1111 receive_done(Connection, "failed to read frame").
1112
1120
1121receive_done(Connection, Why) :-
1122 ( Why = error(_,_)
1123 -> print_message(warning, Why)
1124 ; true
1125 ),
1126 notify(Connection, disconnected),
1127 stomp_teardown(Connection),
1128 ( query_connection_property(Connection, reconnect, true)
1129 -> debug(stomp(connection), 'Receiver thread reconnects (~p)', [Why]),
1130 stomp_connect(Connection)
1131 ; debug(stomp(connection), 'Receiver thread terminates (~p)', [Why])
1132 ),
1133 thread_self(Me),
1134 thread_detach(Me).
1135
1139
1140process_frame(Connection, Frame) :-
1141 Frame.cmd = heartbeat, !,
1142 get_time(Now),
1143 debug(stomp(heartbeat), 'received heartbeat at ~w', [Now]),
1144 update_connection_property(Connection, received_heartbeat, Now),
1145 notify(Connection, heartbeat, _{}, "").
1146process_frame(Connection, Frame) :-
1147 _{cmd:FrameType, headers:Headers, body:Body} :< Frame,
1148 !,
1149 process_connect(FrameType, Connection, Frame),
1150 notify(Connection, FrameType, Headers, Body).
1151process_frame(Connection, Frame) :-
1152 _{cmd:FrameType, headers:Headers} :< Frame,
1153 process_connect(FrameType, Connection, Frame),
1154 notify(Connection, FrameType, Headers).
1155
1156process_connect(connected, Connection, Frame) :-
1157 retract(connection_property(Connection, waiting_thread, Waiting)),
1158 !,
1159 thread_send_message(Waiting, stomp(connected(Connection, true))),
1160 start_heartbeat_if_required(Connection, Frame.headers).
1161process_connect(error, Connection, Frame) :-
1162 retract(connection_property(Connection, waiting_thread, Waiting)),
1163 !,
1164 thread_send_message(
1165 Waiting,
1166 stomp(connected(Connection, error(Frame.body)))).
1167process_connect(_, _, _).
1168
1169start_heartbeat_if_required(Connection, Headers) :-
1170 ( query_connection_property(Connection, 'heart-beat', CHB),
1171 SHB = Headers.get('heart-beat')
1172 -> start_heartbeat(Connection, CHB, SHB)
1173 ; true
1174 ).
1175
1176start_heartbeat(Connection, CHB, SHB) :-
1177 extract_heartbeats(CHB, CX, CY),
1178 extract_heartbeats(SHB, SX, SY),
1179 calculate_heartbeats(CX-CY, SX-SY, X-Y),
1180 \+ (X =:= 0, Y =:= 0),
1181 !,
1182 debug(stomp(heartbeat), 'calculated heartbeats are ~p,~p', [X, Y]),
1183 SendSleep is X / 1000,
1184 ReceiveSleep is Y / 1000 + 2,
1185 ( X =:= 0
1186 -> SleepTime = ReceiveSleep
1187 ; ( Y =:= 0
1188 -> SleepTime = SendSleep
1189 ; SleepTime is gcd(X, Y) / 2000
1190 )
1191 ),
1192 get_time(Now),
1193 gensym(stomp_heartbeat, Alias),
1194 debug(stomp(heartbeat), 'Creating heartbeat thread (~p ~p ~p)',
1195 [SendSleep, ReceiveSleep, SleepTime]),
1196 thread_create(heartbeat_loop(Connection, SendSleep, ReceiveSleep,
1197 SleepTime, Now, Now),
1198 HeartbeatThreadId, [alias(Alias)]),
1199 update_connection_mapping(Connection,
1200 _{ heartbeat_thread_id:HeartbeatThreadId,
1201 received_heartbeat:Now
1202 }).
1203start_heartbeat(_, _, _).
1204
(Heartbeat, X, Y) :-
1206 split_string(Heartbeat, ",", " ", [XS, YS]),
1207 nonneg_integer_string(XS, X),
1208 nonneg_integer_string(YS, Y).
1209
1210calculate_heartbeats(CX-CY, SX-SY, X-Y) :-
1211 ( CX =\= 0, SY =\= 0
1212 -> X is max(CX, SY)
1213 ; X = 0
1214 ),
1215 ( CY =\= 0, SX =\= 0
1216 -> Y is max(CY, SX)
1217 ; Y = 0
1218 ).
1219
1220heartbeat_loop(Connection, SendSleep, ReceiveSleep, SleepTime,
1221 SendTime, ReceiveTime) :-
1222 sleep(SleepTime),
1223 get_time(Now),
1224 ( Now - SendTime > SendSleep
1225 -> SendTime1 = Now,
1226 debug(stomp(heartbeat), 'sending a heartbeat message at ~p', [Now]),
1227 send_frame(Connection, heartbeat, _{})
1228 ; SendTime1 = SendTime
1229 ),
1230 ( Now - ReceiveTime > ReceiveSleep
1231 -> ReceiveTime1 = Now,
1232 check_receive_heartbeat(Connection, Now, ReceiveSleep)
1233 ; ReceiveTime1 = ReceiveTime
1234 ),
1235 heartbeat_loop(Connection, SendSleep, ReceiveSleep, SleepTime,
1236 SendTime1, ReceiveTime1).
1237
1238check_receive_heartbeat(Connection, Now, ReceiveSleep) :-
1239 query_connection_property(Connection, received_heartbeat, ReceivedHeartbeat),
1240 DiffReceive is Now - ReceivedHeartbeat,
1241 ( DiffReceive > ReceiveSleep
1242 -> debug(stomp(heartbeat),
1243 'Heartbeat timeout: diff_receive=~p, time=~p, lastrec=~p',
1244 [DiffReceive, Now, ReceivedHeartbeat]),
1245 notify(Connection, heartbeat_timeout)
1246 ; true
1247 ).
1248
1254
1255notify(Connection, FrameType) :-
1256 notify(Connection, FrameType, stomp_header{cmd:FrameType}, "").
1257
1258notify(Connection, FrameType, Header) :-
1259 notify(Connection, FrameType, Header, "").
1260
1261notify(Connection, FrameType, Header, Body) :-
1262 query_connection_property(Connection, callback, Callback),
1263 Error = error(Formal,_),
1264 ( catch_with_backtrace(
1265 call(Callback, FrameType, Connection, Header, Body),
1266 Error, true)
1267 -> ( var(Formal)
1268 -> true
1269 ; print_message(warning, Error)
1270 )
1271 ; true
1272 ).
1273
1274update_connection_mapping(Connection, Dict) :-
1275 dict_pairs(Dict, _, Pairs),
1276 maplist(update_connection_property(Connection), Pairs).
1277
1278update_connection_property(Connection, Name-Value) :-
1279 update_connection_property(Connection, Name, Value).
1280
1281update_connection_property(Connection, Name, Value) :-
1282 transaction(update_connection_property_(Connection, Name, Value)).
1283
1284update_connection_property_(Connection, Name, Value) :-
1285 retractall(connection_property(Connection, Name, _)),
1286 asserta(connection_property(Connection, Name, Value)).
1287
1288query_connection_property(Connection, Name, Value) :-
1289 ( nonvar(Name),
1290 nonvar(Connection)
1291 -> connection_property(Connection, Name, Value),
1292 !
1293 ; connection_property(Connection, Name, Value)
1294 ).
1295
1296
1297 1300
1301:- multifile prolog:error_message//1,
1302 prolog:message//1. 1303
1304prolog:message(stomp(frame_skipped(Connection, Header, MaxBody))) -->
1305 { connection_property(Connection, address, Address) },
1306 [ 'STOMP: ~w: skipped frame with ~D bytes body (max_body_size: ~D)'-
1307 [Address, Header.'content-length', MaxBody] ].
1308
1309prolog:error_message(stomp_error(connect, Connection, error(Message))) -->
1310 { connection_property(Connection, address, Address) },
1311 [ 'STOMPL: Failed to connect to ~p: ~p'-[Address, Message] ].
1312prolog:error_message(stomp_error(connect, Connection, Detail)) -->
1313 { connection_property(Connection, address, Address) },
1314 [ 'STOMPL: Failed to connect to ~p: ~p'-[Address, Detail] ]