View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2014-2020, VU University Amsterdam
    7                              CWI Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(hub,
   37          [ hub_create/3,               % +HubName, -Hub, +Options
   38            hub_add/3,                  % +HubName, +Websocket, ?Id
   39            hub_member/2,               % +HubName, ?Id
   40            hub_send/2,                 % +ClientId, +Message
   41            hub_broadcast/2,            % +HubName, +Message
   42            hub_broadcast/3,            % +HubName, +Message, +Condition
   43            current_hub/2               % ?HubName, ?Hub
   44          ]).   45:- use_module(library(debug)).   46:- use_module(library(error)).   47:- autoload(library(option), [option/3]).   48:- use_module(library(apply)).   49:- use_module(library(gensym)).   50:- if(exists_source(library(uuid))).   51:- use_module(library(uuid)).   52:- endif.   53:- use_module(library(ordsets)).   54:- use_module(library(http/websocket)).   55
   56:- meta_predicate
   57    hub_broadcast(+,+,1).

Manage a hub for websockets

This library manages a hub that consists of clients that are connected using a websocket. Messages arriving at any of the websockets are sent to the event queue of the hub. In addition, the hub provides a broadcast interface. A typical usage scenario for a hub is a chat server A scenario for realizing an chat server is:

  1. Create a new hub using hub_create/3.
  2. Create one or more threads that listen to Hub.queues.event from the created hub. These threads can update the shared view of the world. A message is a dict as returned by ws_receive/2 or a hub control message. Currently, the following control messages are defined:
    hub{error:Error, left:ClientId, reason:Reason}
    A client left us because of an I/O error. Reason is read or write and Error is the Prolog I/O exception.
    hub{joined:ClientId}
    A new client has joined the chatroom.

    The thread(s) can talk to clients using two predicates:

A hub consists of (currently) four message queues and a simple dynamic fact. Threads that are needed for the communication tasks are created on demand and die if no more work needs to be done.

To be done
- The current design does not use threads to perform tasks for multiple hubs. This implies that the design scales rather poorly for hosting many hubs with few users.
   96:- dynamic
   97    hub/2,                          % Hub, Queues ...
   98    websocket/5.                    % Hub, Socket, Queue, Lock, Id
   99
  100:- volatile hub/2, websocket/5.
 hub_create(+Name, -Hub, +Options) is det
Create a new hub. Hub is a dict containing the following public information:
Hub.name
The name of the hub (the Name argument)
queues.event
Message queue to which the hub thread(s) can listen.

Options:

read_timeout(+Seconds)
Maximum time to wait for the remainder of a message after the first data of the message has arrived. If a client exceeds this time, it is disconnected. Default is 60. Use infinite to wait forever.

After creating a hub, the application normally creates a thread that listens to Hub.queues.event and exposes some mechanisms to establish websockets and add them to the hub using hub_add/3.

See also
- http_upgrade_to_websocket/3 establishes a websocket from the SWI-Prolog webserver.
  127hub_create(HubName, Hub, Options) :-
  128    must_be(atom, HubName),
  129    option(read_timeout(ReadTimeout), Options, 60),
  130    (   ReadTimeout == infinite
  131    ->  true
  132    ;   must_be(number, ReadTimeout)
  133    ),
  134    message_queue_create(WaitQueue),
  135    message_queue_create(ReadyQueue),
  136    message_queue_create(EventQueue),
  137    message_queue_create(BroadcastQueue),
  138    Hub = hub{name:HubName,
  139              read_timeout:ReadTimeout,
  140              queues:_{wait:WaitQueue,
  141                       ready:ReadyQueue,
  142                       event:EventQueue,
  143                       broadcast:BroadcastQueue
  144                      }},
  145    assertz(hub(HubName, Hub)).
 current_hub(?Name, ?Hub) is nondet
True when there exists a hub Hub with Name.
  152current_hub(HubName, Hub) :-
  153    hub(HubName, Hub).
  154
  155
  156                 /*******************************
  157                 *            WAITERS           *
  158                 *******************************/
  159
  160/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  161The task of this layer is to wait   for  (a potentially large number of)
  162websockets. Whenever there is data on one   of these sockets, the socket
  163is handed to Hub.queues.ready. This is realised using wait_for_input/3,
  164which allows a single thread  to  wait   for  many  sockets.  But ... on
  165Windows it allows to wait for at most  64 sockets. In addition, there is
  166no way to add an additional input   for control messages because Windows
  167select() can only wait for sockets. On Unix   we could use pipe/2 to add
  168the control channel. On Windows  we   would  need  an additional network
  169service, giving rise its own  problems   with  allocation, firewalls and
  170security.
  171
  172So, instead we keep a queue of websockets   that  need to be waited for.
  173Whenever we add a  websocket,  we  create   a  waiter  thread  that will
  174typically start waiting for this socket.   In  addition, we schedule any
  175waiting thread that has less  than  the   maximum  number  of sockets to
  176timeout at as good as we can the same   time.  All of them will hunt for
  177the same set of queues,  but  they  have   to  wait  for  each other and
  178therefore most of the time one thread will walk away with all websockets
  179and the others commit suicide because there is nothing to wait for.
  180- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  181
  182:- meta_predicate
  183    hub_thread(0, +, +).
 hub_add(+Hub, +WebSocket, ?Id) is det
Add a WebSocket to the hub. Id is used to identify this user. It may be provided (as a ground term) or is generated as a UUID.
  190hub_add(HubName, WebSocket, Id) :-
  191    must_be(atom, HubName),
  192    hub(HubName, Hub),
  193    (   var(Id)
  194    ->  uuid(Id)
  195    ;   true
  196    ),
  197    (   Timeout = Hub.get(read_timeout),
  198        Timeout \== infinite
  199    ->  set_stream(WebSocket, timeout(Timeout))
  200    ;   true
  201    ),
  202    message_queue_create(OutputQueue),
  203    mutex_create(Lock),
  204                                         % asserta/1 allows for reuse of Id
  205    asserta(websocket(HubName, WebSocket, OutputQueue, Lock, Id)),
  206    thread_send_message(Hub.queues.wait, WebSocket),
  207    thread_send_message(Hub.queues.event,
  208                        hub{joined:Id}),
  209    debug(hub(gate), 'Joined ~w: ~w', [HubName, Id]),
  210    create_wait_thread(Hub).
 hub_member(?HubName, ?Id) is nondet
True when Id is a member of the hub HubName.
  216hub_member(HubName, Id) :-
  217    websocket(HubName, _WebSocket, _OutputQueue, _Lock, Id).
  218
  219:- if(\+current_predicate(uuid/1)).  220% FIXME: Proper pure Prolog random UUID implementation
  221uuid(UUID) :-
  222    A is random(1<<63),
  223    format(atom(UUID), '~d', [A]).
  224:- endif.  225
  226create_wait_thread(Hub) :-
  227    hub_thread(wait_for_sockets(Hub), Hub, hub_wait_).
  228
  229wait_for_sockets(Hub) :-
  230    wait_for_sockets(Hub, 64).
  231
  232wait_for_sockets(Hub, Max) :-
  233    Queues = Hub.queues,
  234    repeat,
  235      get_messages(Queues.wait, Max, List),
  236      (   List \== []
  237      ->  create_new_waiter_if_needed(Hub),
  238          sort(List, Set),
  239          (   debugging(hub(wait))
  240          ->  length(Set, Len),
  241              debug(hub(wait), 'Waiting for ~d queues', [Len])
  242          ;   true
  243          ),
  244          wait_for_set(Set, Left, ReadySet, Max),
  245          (   ReadySet \== []
  246          ->  debug(hub(ready), 'Data on ~p', [ReadySet]),
  247              Ready = Queues.ready,
  248              maplist(thread_send_message(Ready), ReadySet),
  249              create_reader_threads(Hub),
  250              ord_subtract(Set, ReadySet, NotReadySet)
  251          ;   NotReadySet = Left             % timeout
  252          ),
  253          (   NotReadySet \== []
  254          ->  debug(hub(wait), 'Re-scheduling: ~p', [NotReadySet]),
  255              Wait = Queues.wait,
  256              maplist(thread_send_message(Wait), NotReadySet),
  257              fail
  258          ;   true
  259          )
  260      ;   !
  261      ).
  262
  263create_new_waiter_if_needed(Hub) :-
  264    message_queue_property(Hub.queues.wait, size(0)),
  265    !.
  266create_new_waiter_if_needed(Hub) :-
  267    create_wait_thread(Hub).
 wait_for_set(+Set0, -Left, -Ready, +Max) is det
Wait for input from Set0. Note that Set0 may contain closed websockets.
  274wait_for_set([], [], [], _) :-
  275    !.
  276wait_for_set(Set0, Set, ReadySet, Max) :-
  277    wait_timeout(Set0, Max, Timeout),
  278    catch(wait_for_input(Set0, ReadySet, Timeout),
  279          error(existence_error(stream, S), _), true),
  280    (   var(S)
  281    ->  Set = Set0
  282    ;   delete(Set0, S, Set1),
  283        wait_for_set(Set1, Set, ReadySet, Max)
  284    ).
 wait_timeout(+WaitForList, +Max, -TimeOut) is det
Determine the timeout, such that multiple threads waiting for less than the maximum number of sockets time out at the same moment and we can combine them on a single thread.
  293:- dynamic
  294    scheduled_timeout/1.  295
  296wait_timeout(List, Max, Timeout) :-
  297    length(List, Max),
  298    !,
  299    Timeout = infinite.
  300wait_timeout(_, _, Timeout) :-
  301    get_time(Now),
  302    (   scheduled_timeout(SchedAt)
  303    ->  (   SchedAt > Now
  304        ->  At = SchedAt
  305        ;   retractall(scheduled_timeout(_)),
  306            At is ceiling(Now) + 1,
  307            asserta(scheduled_timeout(At))
  308        )
  309    ;   At is ceiling(Now) + 1,
  310        asserta(scheduled_timeout(At))
  311    ),
  312    Timeout is At - Now.
 get_messages(+Queue, +Max, -List) is det
Get the next Max messages from Queue or as many as there are available without blocking very long. This routine is designed such that if multiple threads are running for messages, one gets all of them and the others nothing.
  322get_messages(Q, N, List) :-
  323    with_mutex(hub_wait,
  324               get_messages_sync(Q, N, List)).
  325
  326get_messages_sync(Q, N, [H|T]) :-
  327    succ(N2, N),
  328    thread_get_message(Q, H, [timeout(0.01)]),
  329    !,
  330    get_messages_sync(Q, N2, T).
  331get_messages_sync(_, _, []).
  332
  333
  334                 /*******************************
  335                 *            READERS           *
  336                 *******************************/
  337
  338/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  339The next layer consists of `readers'.   Whenever  one or more websockets
  340have   data,   the   socket   is    added   to   Hub.queues.ready   and
  341create_reader_threads/1 is called. This  examines   the  number of ready
  342sockets and fires a number  of  threads   to  handle  the read requests.
  343Multiple threads are mainly needed for the case that a client signals to
  344be  ready,  but  only  provides  an   incomplete  message,  causing  the
  345ws_receive/2 to block.
  346
  347Each  of  the  threads  reads  the  next   message  and  sends  this  to
  348Hub.queues.event. The websocket is then rescheduled   to listen for new
  349events. This read either fires a thread   to  listen for the new waiting
  350socket using create_wait_thread/1 or, if there   are no more websockets,
  351does this job itself. This  deals  with   the  common  scenario that one
  352client wakes up, starts a thread to  read   its  event and waits for new
  353messages on the same websockets.
  354- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  355
  356create_reader_threads(Hub) :-
  357    message_queue_property(Hub.queues.ready, size(Ready)),
  358    Threads is ceiling(sqrt(Ready)),
  359    forall(between(1, Threads, _),
  360           create_reader_thread(Hub)).
  361
  362create_reader_thread(Hub) :-
  363    hub_thread(read_message(Hub), Hub, hub_read_ws_).
  364
  365read_message(Hub) :-
  366    Queues = Hub.queues,
  367    thread_get_message(Queues.ready, WS, [timeout(0)]),
  368    !,
  369    catch(ws_receive(WS, Message), Error, true),
  370    (   var(Error),
  371        websocket(HubName, WS, _, _, Id)
  372    ->  (   Message.get(opcode) == close
  373        ->  close_client(WS, Message)
  374        ;   Event = Message.put(_{client:Id, hub:HubName}),
  375            debug(hub(event), 'Event: ~p', [Event]),
  376            thread_send_message(Queues.event, Event),
  377            (   Message.get(opcode) == close
  378            ->  CloseError = error(_,_),
  379                catch(ws_close(WS, 1000, ""), CloseError,
  380                      ws_warning(CloseError))
  381            ;   thread_send_message(Queues.wait, WS)
  382            ),
  383            (   message_queue_property(Queues.ready, size(0))
  384            ->  !,
  385                wait_for_sockets(Hub)
  386            ;   create_wait_thread(Hub),
  387                read_message(Hub)
  388            )
  389        )
  390    ;   websocket(_, WS, _, _, _)
  391    ->  io_read_error(WS, Error),
  392        read_message(Hub)
  393    ;   read_message(Hub)                   % already destroyed
  394    ).
  395read_message(_).
  396
  397ws_warning(error(Formal, _)) :-
  398    silent(Formal),
  399    !.
  400ws_warning(Error) :-
  401    print_message(warning, Error).
  402
  403silent(socket_error(epipe, _)).
 io_read_error(+WebSocket, +Error)
Called on a read error from WebSocket. We close the websocket and send the hub an event that we lost the connection to the specified client. Note that we leave destruction of the anonymous message queue and mutex to the Prolog garbage collector.
  412io_read_error(WebSocket, Error) :-
  413    debug(hub(gate), 'Got read error on ~w: ~p',
  414          [WebSocket, Error]),
  415    retract(websocket(HubName, WebSocket, _Queue, _Lock, Id)),
  416    !,
  417    E = error(_,_),
  418    catch(ws_close(WebSocket, 1011, Error), E,
  419          ws_warning(E)),
  420    hub(HubName, Hub),
  421    thread_send_message(Hub.queues.event,
  422                        hub{left:Id,
  423                            hub:HubName,
  424                            reason:read,
  425                            error:Error}).
  426io_read_error(_, _).                      % already considered gone
  427
  428close_client(WebSocket, Message) :-
  429    Message.get(data) == end_of_file,
  430    !,
  431    io_read_error(WebSocket, end_of_file).
  432close_client(WebSocket, Message) :-
  433    retract(websocket(HubName, WebSocket, _Queue, _Lock, Id)),
  434    !,
  435    E = error(_,_),
  436    catch(ws_close(WebSocket, 1000, "Bye"), E,
  437          ws_warning(E)),
  438    hub(HubName, Hub),
  439    thread_send_message(Hub.queues.event,
  440                        hub{left:Id,
  441                            hub:HubName,
  442                            reason:close,
  443                            data:Message.data
  444                           }).
 io_write_error(+WebSocket, +Message, +Error)
Failed to write Message to WebSocket due to Error. Note that this may be a pending but closed WebSocket. We first check whether there is a new one and if not send a left message and pass the error such that the client can re-send it when appropriate.
  453io_write_error(WebSocket, Message, Error) :-
  454    debug(hub(gate), 'Got write error on ~w: ~p',
  455          [WebSocket, Error]),
  456    retract(websocket(HubName, WebSocket, _Queue, _Lock, Id)),
  457    !,
  458    catch(ws_close(WebSocket, 1011, Error), _, true),
  459    (   websocket(_, _, _, _, Id)
  460    ->  true
  461    ;   hub(HubName, Hub),
  462        thread_send_message(Hub.queues.event,
  463                            hub{left:Id,
  464                                hub:HubName,
  465                                reason:write(Message),
  466                                error:Error})
  467    ).
  468io_write_error(_, _, _).                      % already considered gone
  469
  470
  471                 /*******************************
  472                 *        SENDING MESSAGES      *
  473                 *******************************/
  474
  475/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  476My  initial  thought  about  sending  messages    was  to  add  a  tuple
  477WebSocket-Message to an output  queue  and   have  a  dynamic  number of
  478threads sending these messages to the   websockets. But, it is desirable
  479that, if multiple messages are sent to  a particular client, they arrive
  480in this order. As multiple threads are performing this task, this is not
  481easy to guarantee. Therefore, we create an  output queue and a mutex for
  482each client. An output thread will   walk  along the websockets, looking
  483for one that has pending messages.  It   then  grabs the lock associated
  484with the client and sends all waiting output messages.
  485
  486The price is that we might peek   a significant number of message queues
  487before we find one that  contains  messages.   If  this  proves  to be a
  488significant problem, we  could  maintain  a   queue  of  queues  holding
  489messages.
  490- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
 hub_send(+ClientId, +Message) is semidet
Send message to the indicated ClientId. Fails silently if ClientId does not exist.
Arguments:
Message- is either a single message (as accepted by ws_send/2) or a list of such messages.
  500hub_send(ClientId, Message) :-
  501    websocket(HubName, _WS, ClientQueue, _Lock, ClientId),
  502    hub(HubName, Hub),
  503    (   is_list(Message)
  504    ->  maplist(queue_output(ClientQueue), Message)
  505    ;   queue_output(ClientQueue, Message)
  506    ),
  507    create_output_thread(Hub, ClientQueue).
  508
  509create_output_thread(Hub, Queue) :-
  510    hub_thread(broadcast_from_queue(Queue, [timeout(0)]),
  511               Hub, hub_out_q_).
 hub_broadcast(+Hub, +Message) is det
 hub_broadcast(+Hub, +Message, :Condition) is det
Send Message to all websockets associated with Hub for which call(Condition, Id) succeeds. Note that this process is asynchronous: this predicate returns immediately after putting all requests in a broadcast queue. If a message cannot be delivered due to a network error, the hub is informed through io_error/3.
  523hub_broadcast(HubName, Message) :-
  524    hub_broadcast(HubName, Message, all).
  525
  526all(_).
  527
  528hub_broadcast(HubName, Message, Condition) :-
  529    must_be(atom, HubName),
  530    hub(HubName, Hub),
  531    State = count(0),
  532    forall(( websocket(HubName, _WS, ClientQueue, _Lock, Id),
  533             call(Condition, Id)
  534           ),
  535           ( queue_output(ClientQueue, Message),
  536             inc_count(State)
  537           )),
  538    State = count(Count),
  539    create_broadcast_threads(Hub, Count).
  540
  541queue_output(Queue, Message) :-
  542    thread_send_message(Queue, Message).
  543
  544inc_count(State) :-
  545    arg(1, State, C0),
  546    C1 is C0+1,
  547    nb_setarg(1, State, C1).
  548
  549create_broadcast_threads(Hub, Count) :-
  550    Threads is ceiling(sqrt(Count)),
  551    forall(between(1, Threads, _),
  552           create_broadcast_thread(Hub)).
  553
  554create_broadcast_thread(Hub) :-
  555    current_prolog_flag(threads, true),
  556    !,
  557    hub_thread(broadcast_from_queues(Hub, [timeout(0)]),
  558                    Hub, hub_out_all_).
  559create_broadcast_thread(_).                   % we are shutting down
 broadcast_from_queues(+Hub, +Options) is det
Broadcast from over all known queues.
  565broadcast_from_queues(Hub, Options) :-
  566    forall(websocket(Hub.name, _WebSocket, Queue, _Lock, _Id),
  567           broadcast_from_queue(Queue, Options)).
 broadcast_from_queue(+Queue, +Options) is det
Send all messages pending for Queue. Note that this predicate locks the mutex associated with the Queue, such that other workers cannot start sending messages to this client. Concurrent sending would lead to out-of-order arrival of broadcast messages. If the mutex is already held, someone else is processing this message queue, so we don't have to worry.
  579broadcast_from_queue(Queue, _Options) :-
  580    message_queue_property(Queue, size(0)),
  581    !.
  582broadcast_from_queue(Queue, Options) :-
  583    websocket(_Hub, _WebSocket, Queue, Lock, _Id),
  584    !,
  585    (   setup_call_cleanup(
  586            mutex_trylock(Lock),
  587            broadcast_from_queue_sync(Queue, Options),
  588            mutex_unlock(Lock))
  589    ->  true
  590    ;   true
  591    ).
  592broadcast_from_queue(_, _).
  593
  594% Note that we re-fetch websocket/5, such that we terminate if something
  595% closed the websocket.
  596
  597broadcast_from_queue_sync(Queue, Options) :-
  598    repeat,
  599      (   websocket(_Hub, WebSocket, Queue, _Lock, _Id),
  600          thread_get_message(Queue, Message, Options)
  601      ->  debug(hub(broadcast),
  602                'To: ~p messages: ~p', [WebSocket, Message]),
  603          catch(ws_send(WebSocket, Message), E,
  604                io_write_error(WebSocket, Message, E)),
  605          fail
  606      ;   !
  607      ).
 hub_thread(:Goal, +Hub, +Task) is det
Create a (temporary) thread for the hub to perform Task. We created named threads if debugging hub(thread) is enabled.
  614hub_thread(Goal, _, Task) :-
  615    debugging(hub(thread)),
  616    !,
  617    gensym(Task, Alias),
  618    thread_create(Goal, _, [detached(true), alias(Alias)]).
  619hub_thread(Goal, _, _) :-
  620    thread_create(Goal, _, [detached(true)])