View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Hongxin Liang and Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2021-2025, SWI-Prolog Solutions b.v.
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(stomp,
   36          [ stomp_connection/5,    % +Address, +Host, +Headers,
   37                                   % :Callback, -Connection
   38            stomp_connection/6,    % +Address, +Host, +Headers,
   39                                   % :Callback, -Connection, +Options
   40            stomp_connection_property/2, % ?Connection, ?Property
   41            stomp_destroy_connection/1, % +Connection
   42            stomp_connect/1,       % +Connection
   43            stomp_connect/2,       % +Connection, +Options
   44            stomp_teardown/1,      % +Connection
   45            stomp_reconnect/1,	   % +Connection
   46            stomp_send/4,          % +Connection, +Destination, +Headers, +Body
   47            stomp_send_json/4,     % +Connection, +Destination, +Headers, +JSON
   48            stomp_subscribe/4,     % +Connection, +Destination, +Id, +Headers
   49            stomp_unsubscribe/2,   % +Connection, +Id
   50            stomp_ack/2,           % +Connection, +MsgHeaders
   51            stomp_nack/2,          % +Connection, +MsgHeaders
   52            stomp_ack/3,           % +Connection, +MessageId, +Headers
   53            stomp_nack/3,          % +Connection, +MessageId, +Headers
   54            stomp_transaction/2,   % +Connection, :Goal
   55            stomp_disconnect/2,    % +Connection, +Headers
   56                                   % Low level predicates
   57            stomp_begin/2,         % +Connection, +Transaction
   58            stomp_commit/2,        % +Connection, +Transaction
   59            stomp_abort/2,         % +Connection, +Transaction
   60            stomp_setup/2          % +Connection, +Options
   61          ]).   62
   63/** <module> STOMP client.
   64
   65This module provides a STOMP  (Simple   (or  Streaming)  Text Orientated
   66Messaging Protocol) client. This client  is   based  on  work by Hongxin
   67Liang. The current version is a major rewrite, both changing the API and
   68the low-level STOMP frame (de)serialization.
   69
   70The predicate stomp_connection/5 is used to   register a connection. The
   71connection is established by  stomp_connect/1,   which  is lazily called
   72from any of the predicates that send   a STOMP frame. After establishing
   73the connection two threads are created.   One  receives STOMP frames and
   74the other manages and watches the _heart beat_.
   75
   76## Threading	{#stomp-threading}
   77
   78Upon receiving a frame the   callback registered with stomp_connection/5
   79is called in  the  context  of   the  receiving  thread.  More demanding
   80applications may decide to send incomming frames to a SWI-Prolog message
   81queue and have one  or  more   _worker  threads_  processing  the input.
   82Alternatively, frames may be  inspected  by   the  receiving  thread and
   83either processed immediately or be dispatched   to either new or running
   84threads.  The best scenario depends on the message rate, processing time
   85and concurrency of the Prolog application.
   86
   87All message sending predicates of this library are _thread safe_. If two
   88threads send a frame to the  same   connection  the library ensures that
   89both frames are properly serialized.
   90
   91## Reconnecting	{#stomp-reconnecting}
   92
   93By default this library tries to establish   the connection and the user
   94gets notified by  means  of  a   `disconnected`  pseudo  frame  that the
   95connection is lost. Using the Options argument of stomp_connection/6 the
   96system can be configured to try and keep connecting if the server is not
   97available and reconnect if  the  connection   is  lost.  See the pong.pl
   98example.
   99
  100## Security	{#stomp-security}
  101
  102The connection is a plain TCP connection.  This implies that the
  103``login`` and ``passcode`` headers as well as all messages are sent
  104unencrypted.  Use a secured network or tunnel when connecting to a
  105broker over an untrusted network.
  106
  107@author Hongxin Liang and Jan Wielemaker
  108@license BSD-2
  109@see http://stomp.github.io/index.html
  110@see https://github.com/jasonrbriggs/stomp.py
  111@tbd TSL support
  112*/
  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
  135%!  stomp_connection(+Address, +Host, +Headers, :Callback,
  136%!                   -Connection) is det.
  137%!  stomp_connection(+Address, +Host, +Headers, :Callback,
  138%!                   -Connection, +Options) is det.
  139%
  140%   Create a connection reference. The connection is   not set up yet by
  141%   this predicate. Callback is called on  any received frame except for
  142%   _heart beat_ frames as below.
  143%
  144%   ```
  145%   call(Callback, Command, Connection, Header, Body)
  146%   ```
  147%
  148%   Where command is one of  the  commands   below.  `Header`  is a dict
  149%   holding the STOMP frame header, where  all values are strings except
  150%   for the `'content-length'` key value which is passed as an integer.
  151%
  152%   Body  is  a   string   or,   if   the    data   is   of   the   type
  153%   ``application/json``, a dict.  If a JSON body cannot be parsed, a
  154%   warning is printed and Body is the string.  Note that message
  155%   headers and body are under control of the sender of the message.
  156%
  157%     - connected
  158%       A connection was established.  Connection and Header are valid.
  159%     - disconnected
  160%       The connection was lost.  Only Connection is valid.
  161%     - message
  162%       A message arrived.  All three arguments are valid.  Body is
  163%       a dict if the ``content-type`` of the message is
  164%       ``application/json`` and a string otherwise.
  165%     - heartbeat
  166%       A heartbeat was received.  Only Connection is valid.  This
  167%       callback is also called for each newline that follows a frame.
  168%       These newlines can be a heartbeat, but can also be additional
  169%       newlines that follow a frame.
  170%     - heartbeat_timeout
  171%       No heartbeat was received.  Only Connection is valid.
  172%     - error
  173%       An error happened.  All three arguments are valid and handled
  174%       as `message`.
  175%
  176%   Note that stomp_teardown/1 causes the receiving and heartbeat thread
  177%   to be signalled with abort/0.
  178%
  179%   Options processed:
  180%
  181%     - reconnect(+Bool)
  182%       Try to reestablish the connection to the server if the
  183%       connection is lost.  Default is `false`
  184%     - connect_timeout(+Seconds)
  185%       Maximum time to try and reestablish a connection.  The
  186%       default is `600` (10 minutes).
  187%     - json_options(+Options)
  188%       Options passed to json_read_dict/3 to translate
  189%       `application/json` content to Prolog.  Default is `[]`.
  190%     - max_header_size(+Size)
  191%       Maximum size in characters of the command and header lines of
  192%       a received frame.  Default is 1Mb (1,048,576).  If the header
  193%       is larger, the connection is closed.
  194%     - max_body_size(+Size)
  195%       Maximum size of the body of a received frame.  Default is 100Mb
  196%       (104,857,600).  If the frame has a ``content-length`` header,
  197%       a larger body is skipped and a warning is printed.  Otherwise
  198%       the connection is closed.
  199%
  200%   Both size limits accept `infinite` to remove the limit.
  201%
  202%   @arg Address is a valid address   for tcp_connect/3. Normally a term
  203%   Host:Port, e.g., `localhost:32772`.
  204%   @arg Host is a path denoting the STOMP host.  Often just `/`.
  205%   @arg Headers is a dict with STOMP headers used for the ``CONNECT``
  206%   request.
  207%   @arg Connection is an opaque ground term that identifies the
  208%   connection.
  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
  265%!  stomp_connection_property(?Connection, ?Property) is nondet.
  266%
  267%   True when Property, is a property  of Connection. Defined properties
  268%   are:
  269%
  270%     - address(Address)
  271%     - callback(Callback)
  272%     - host(Host)
  273%     - headers(Headers)
  274%     - reconnect(Bool)
  275%     - connect_timeout(Seconds)
  276%     - json_options(Options)
  277%     - max_header_size(Size)
  278%     - max_body_size(Size)
  279%       All the above properties result from the stomp_connection/6
  280%       registration.
  281%     - receiver_thread_id(Thread)
  282%     - stream(Stream)
  283%     - heartbeat_thread_id(Thread)
  284%     - received_heartbeat(TimeStamp)
  285%       These describe an active STOMP connection.
  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
  297%!  stomp_destroy_connection(+Connection)
  298%
  299%   Destroy a connection. If it is active, first use stomp_teardown/1 to
  300%   disconnect.
  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
  310%!  stomp_setup(+Connection, +Options) is det.
  311%
  312%   Set up the actual socket connection and start receiving thread. This
  313%   is a no-op if the connection has   already been created. The Options
  314%   processed are below. Other options are passed to tcp_connect/3.
  315%
  316%     - timeout(+Seconds)
  317%       If tcp_connect/3 fails, retry until the timeout is reached.
  318%       If Seconds is `inf` or `infinite`, keep retrying forever.
  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
  344%!  connect(+Connection, +Address, -Stream, +Options) is det.
  345%
  346%   Connect to Address. If the option timeout(Sec) is present, retry the
  347%   connection until the timeout is reached.
  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
  415%!  stomp_teardown(+Connection) is semidet.
  416%
  417%   Tear down the socket connection, stop receiving thread and heartbeat
  418%   thread (if applicable).  The  registration   of  the  connection  as
  419%   created by stomp_connection/5 is preserved and the connection may be
  420%   reconnected using stomp_connect/1.
  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
  446%!  stomp_reconnect(+Connection) is det.
  447%
  448%   Teardown the connection and try to reconnect.
  449
  450stomp_reconnect(Connection) :-
  451    stomp_teardown(Connection),
  452    stomp_connect(Connection).
  453
  454%!  stomp_connect(+Connection) is det.
  455%!  stomp_connect(+Connection, +Options) is det.
  456%
  457%   Setup the connection. First ensures a  socket connection and if this
  458%   is new send a ``CONNECT``  frame.   Protocol  version  and heartbeat
  459%   negotiation will be  handled.  ``STOMP``  frame   is  not  used  for
  460%   backward compatibility.
  461%
  462%   This predicate waits for the connection handshake to have completed.
  463%   Currently it waits for a maximum   of  10 seconds after establishing
  464%   the socket for the server reply.
  465%
  466%   Calling this on an established connection has no effect.
  467%
  468%   @see http://stomp.github.io/stomp-specification-1.2.html#CONNECT_or_STOMP_Frame).
  469%   @error stomp_error(connect, Connection, Detail) if no connection
  470%   could be established.
  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
  505%   The receiver thread may process the CONNECTED reply before
  506%   send_frame/3 returns, so we must register the waiting thread and
  507%   the heart-beat before sending CONNECT.
  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
  543%!  stomp_deadline(+Connection, -Deadline, +Options) is det.
  544%
  545%   True when there is a connection timeout and Deadline is the deadline
  546%   for establishing a connection.  Deadline is one of
  547%
  548%     - Number
  549%       The deadline as a time stamp
  550%     - infinite
  551%       Keep trying
  552%     - once
  553%       Try to connect once.
  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
  572%!  stomp_send(+Connection, +Destination, +Headers, +Body) is det.
  573%
  574%   Send  a  ``SEND``  frame.  If   ``content-type``  is  not  provided,
  575%   ``text/plain`` will be used. ``content-length``   will  be filled in
  576%   automatically.
  577%
  578%   @see http://stomp.github.io/stomp-specification-1.2.html#SEND
  579
  580stomp_send(Connection, Destination, Headers, Body) :-
  581    add_transaction(Headers, Headers1),
  582    send_frame(Connection, send, Headers1.put(destination, Destination), Body).
  583
  584%!  stomp_send_json(+Connection, +Destination, +Headers, +JSON) is det.
  585%
  586%   Send a ``SEND`` frame. ``JSON`` can be either a JSON term or a dict.
  587%   ``content-type`` is filled in  automatically as ``application/json``
  588%   and ``content-length`` will be filled in automatically as well.
  589%
  590%   @see http://stomp.github.io/stomp-specification-1.2.html#SEND
  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)           % No layout for speed
  597                   ]),
  598    send_frame(Connection, send,
  599               Headers1.put(_{ destination:Destination,
  600                               'content-type':'application/json'
  601                             }),
  602               Body).
  603
  604%!  stomp_subscribe(+Connection, +Destination, +Id, +Headers) is det.
  605%
  606%   Send a ``SUBSCRIBE`` frame.
  607%
  608%   @see http://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE
  609
  610stomp_subscribe(Connection, Destination, Id, Headers) :-
  611    send_frame(Connection, subscribe,
  612               Headers.put(_{destination:Destination, id:Id})).
  613
  614%!  stomp_unsubscribe(+Connection, +Id) is det.
  615%
  616%   Send an ``UNSUBSCRIBE`` frame.
  617%
  618%   @see http://stomp.github.io/stomp-specification-1.2.html#UNSUBSCRIBE
  619
  620stomp_unsubscribe(Connection, Id) :-
  621    send_frame(Connection, unsubscribe, _{id:Id}).
  622
  623%!  stomp_ack(+Connection, +MessageId, +Headers) is det.
  624%
  625%   Send an ``ACK`` frame. See stomp_ack/2 for simply passing the header
  626%   received with the message we acknowledge.
  627%
  628%   @see http://stomp.github.io/stomp-specification-1.2.html#ACK
  629
  630stomp_ack(Connection, MessageId, Headers) :-
  631    send_frame(Connection, ack, Headers.put('message-id', MessageId)).
  632
  633%!  stomp_nack(+Connection, +MessageId, +Headers) is det.
  634%
  635%   Send a ``NACK`` frame.  See  stomp_nack/2   for  simply  passing the
  636%   header received with the message we acknowledge.
  637%
  638%   @see http://stomp.github.io/stomp-specification-1.2.html#NACK
  639
  640stomp_nack(Connection, MessageId, Headers) :-
  641    send_frame(Connection, nack, Headers.put('message-id', MessageId)).
  642
  643%!  stomp_ack(+Connection, +MsgHeader) is det.
  644%!  stomp_nack(+Connection, +MsgHeader) is det.
  645%
  646%   Reply with an ACK or NACK based on the received message header. On a
  647%   STOMP 1.1 request we get an `ack` field in the header and reply with
  648%   an  `id`.  For  STOMP  1.2  we   reply  with  the  `message-id`  and
  649%   `subscription` that we received with the message.
  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
  666%!  stomp_begin(+Connection, +Transaction) is det.
  667%
  668%   Send a ``BEGIN`` frame.
  669%   @see http://stomp.github.io/stomp-specification-1.2.html#BEGIN
  670
  671stomp_begin(Connection, Transaction) :-
  672    send_frame(Connection, begin, _{transaction:Transaction}).
  673
  674%!  stomp_commit(+Connection, +Transaction) is det.
  675%
  676%   Send a ``COMMIT`` frame.
  677%
  678%   @see http://stomp.github.io/stomp-specification-1.2.html#COMMIT
  679
  680stomp_commit(Connection, Transaction) :-
  681    send_frame(Connection, commit, _{transaction:Transaction}).
  682
  683%!  stomp_abort(+Connection, +Transaction) is det.
  684%
  685%   Send a ``ABORT`` frame.
  686%
  687%   @see http://stomp.github.io/stomp-specification-1.2.html#ABORT
  688
  689stomp_abort(Connection, Transaction) :-
  690    send_frame(Connection, abort, _{transaction:Transaction}).
  691
  692%!  stomp_transaction(+Connection, :Goal) is semidet.
  693%
  694%   Run Goal as  once/1,  tagging  all   ``SEND``  messages  inside  the
  695%   transaction with the transaction id.  If   Goal  fails  or raises an
  696%   exception the transaction is aborted.   Failure  or exceptions cause
  697%   the transaction to be aborted using   stomp_abort/2, after which the
  698%   result is forwarded.
  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
  729%!  stomp_disconnect(+Connection, +Headers) is det.
  730%
  731%   Send a ``DISCONNECT`` frame. If the   connection has the `reconnect`
  732%   property set to `true`, this  will   be  reset  to `disconnected` to
  733%   avoid  reconnecting.  A  subsequent    stomp_connect/2   resets  the
  734%   reconnect status.
  735%
  736%   @see http://stomp.github.io/stomp-specification-1.2.html#DISCONNECT
  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
  745%!  send_frame(+Connection, +Command, +Headers) is det.
  746%!  send_frame(+Connection, +Command, +Headers, +Body) is det.
  747%
  748%   Send a frame. If no connection is  established connect first. If the
  749%   sending results in an I/O error, disconnect, reconnect and try again
  750%   if the `reconnect` propertys is set.
  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
  796%!  connection_stream(+Connection, -Stream)
  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
  809send_header(Stream, Headers) :-
  810    dict_pairs(Headers, _, Pairs),
  811    maplist(send_header_line(Stream), Pairs),
  812    nl(Stream).
  813
  814send_header_line(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		 /*******************************
  856		 *        INCOMING DATA		*
  857		 *******************************/
  858
  859%!  read_frame(+Connection, +Stream, -Frame) is det.
  860%
  861%   Read a frame from a STOMP stream.   On end-of-file, Frame is unified
  862%   with the atom `end_of_file`. If the  body   is  too  large and could
  863%   be skipped, Frame is unified with `skipped`.  Otherwise  it   is  a
  864%   dict holding the `cmd`, `headers` (another dict) and `body`.
  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
  904read_header(Stream, Header, Left) :-
  905    read_header_lines(Stream, Pairs, [], Left),
  906    dict_pairs(Header, stomp_header, Pairs).
  907
  908read_header_lines(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
  923%!  read_line_limited(+Stream, -Line, +Left0, -Left) is det.
  924%
  925%   Read a line as read_line_to_string/2, but raise a resource error if
  926%   more than Left0 characters are read.  Left is the number of
  927%   characters left.
  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
  953%!  limit(+Option, -Limit) is det.
  954%
  955%   Translate a size limit option into a number we can count down.
  956
  957limit(infinite, Limit) :-
  958    !,
  959    Limit = 0x3fffffffffffffff.         % large, but fast integer
  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
  971%!  nonneg_integer_string(+String, -Int) is semidet.
  972%
  973%   True when String only consists of digits that represent Int.
  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
  981unescape_header_value(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
  999%!  read_content(+Connection, +Stream, +Header, -Content) is det.
 1000%
 1001%   Read the body as a string. If there is a ``content-length`` header,
 1002%   the body has this length in bytes and must be followed by a NUL
 1003%   byte. Otherwise the body ends at the first NUL byte. Note that the
 1004%   body may be followed by an arbitrary number of newlines. We leave
 1005%   them in place to avoid blocking.
 1006%
 1007%   If the body exceeds the `max_body_size` and the length is known,
 1008%   it is skipped and Content is unified with `skipped`.
 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
 1059%!  convert_content(+Connection, +ContentType, +String, -Content) is det.
 1060%
 1061%   Translate a JSON body to a dict.  The body comes from the sender of
 1062%   the message.  If it is not valid JSON, print a warning and pass the
 1063%   body as a string rather than losing the connection.
 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
 1090%!  receive(+Connection, +Stream) is det.
 1091%
 1092%   Read and process incoming messages from Stream.
 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
 1113%!  receive_done(+Connection, +Why)
 1114%
 1115%   The receiver thread needs to  close   the  connection due to reading
 1116%   end-of-file, an I/O error or failure to parse a frame. If connection
 1117%   is configured to be restarted this   thread  will try to reestablish
 1118%   the connection. After reestablishing the   connection  this receiver
 1119%   thread terminates.
 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
 1136%!  process_frame(+Connection, +Frame) is det.
 1137%
 1138%   Process an incoming frame.
 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
 1205extract_heartbeats(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
 1249%!  notify(+Connection, +FrameType) is det.
 1250%!  notify(+Connection, +FrameType, +Header) is det.
 1251%!  notify(+Connection, +FrameType, +Header, +Body) is det.
 1252%
 1253%   Call the callback using  FrameType.
 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		 /*******************************
 1298		 *            MESSAGES		*
 1299		 *******************************/
 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] ]