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)  2002-2024, University of Amsterdam
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9                              SWI-Prolog Solutions b.v.
   10    All rights reserved.
   11
   12    Redistribution and use in source and binary forms, with or without
   13    modification, are permitted provided that the following conditions
   14    are met:
   15
   16    1. Redistributions of source code must retain the above copyright
   17       notice, this list of conditions and the following disclaimer.
   18
   19    2. Redistributions in binary form must reproduce the above copyright
   20       notice, this list of conditions and the following disclaimer in
   21       the documentation and/or other materials provided with the
   22       distribution.
   23
   24    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   25    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   26    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   27    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   28    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   29    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   30    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   31    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   32    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   33    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   34    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   35    POSSIBILITY OF SUCH DAMAGE.
   36*/
   37
   38:- module(thread_httpd,
   39          [ http_current_server/2,      % ?:Goal, ?Port
   40            http_server_property/2,     % ?Port, ?Property
   41            http_server/2,              % :Goal, +Options
   42            http_workers/2,             % +Port, ?WorkerCount
   43            http_add_worker/2,          % +Port, +Options
   44            http_current_worker/2,      % ?Port, ?ThreadID
   45            http_stop_server/2,         % +Port, +Options
   46            http_spawn/2,               % :Goal, +Options
   47
   48            http_requeue/1,             % +Request
   49            http_close_connection/1,    % +Request
   50            http_enough_workers/3       % +Queue, +Why, +Peer
   51          ]).   52:- use_module(library(debug)).   53:- use_module(library(error)).   54:- use_module(library(option)).   55:- use_module(library(socket)).   56:- use_module(library(thread_pool)).   57:- use_module(library(gensym)).   58:- use_module(http_wrapper).   59:- use_module(http_path).   60:- use_module(http_stream).   61:- use_module(library(settings)).   62
   63:- autoload(library(uri), [uri_resolve/3]).   64
   65:- setting(http:max_keep_alive_drain, nonneg, 65_536,
   66           'Max bytes of an unread request body that are skipped to \c
   67            keep the connection alive.  Else the connection is closed.').   68:- autoload(library(aggregate), [aggregate_all/3]).   69
   70:- predicate_options(http_server/2, 2,
   71                     [ port(any),
   72                       unix_socket(atom),
   73                       entry_page(atom),
   74                       tcp_socket(any),
   75                       workers(positive_integer),
   76                       timeout(number),
   77                       keep_alive_timeout(number),
   78                       silent(boolean),
   79                       ssl(list(any)),  % if http/http_ssl_plugin is loaded
   80                       pass_to(system:thread_create/3, 3)
   81                     ]).   82:- predicate_options(http_spawn/2, 2,
   83                     [ pool(atom),
   84                       pass_to(system:thread_create/3, 3),
   85                       pass_to(thread_pool:thread_create_in_pool/4, 4)
   86                     ]).   87:- predicate_options(http_add_worker/2, 2,
   88                     [ timeout(number),
   89                       keep_alive_timeout(number),
   90                       max_idle_time(number),
   91                       pass_to(system:thread_create/3, 3)
   92                     ]).

Threaded HTTP server

Most code doesn't need to use this directly; instead use library(http/http_server), which combines this library with the typical HTTP libraries that most servers need.

This library defines the HTTP server frontend of choice for SWI-Prolog. It is based on the multi-threading capabilities of SWI-Prolog and thus exploits multiple cores to serve requests concurrently. The server scales well and can cooperate with library(thread_pool) to control the number of concurrent requests of a given type. For example, it can be configured to handle 200 file download requests concurrently, 2 requests that potentially uses a lot of memory and 8 requests that use a lot of CPU resources.

On Unix systems, this library can be combined with library(http/http_unix_daemon) to realise a proper Unix service process that creates a web server at port 80, runs under a specific account, optionally detaches from the controlling terminal, etc.

Combined with library(http/http_ssl_plugin) from the SSL package, this library can be used to create an HTTPS server. See <plbase>/doc/packages/examples/ssl/https for an example server using a self-signed SSL certificate.

  120:- meta_predicate
  121    http_server(1, :),
  122    http_current_server(1, ?),
  123    http_spawn(0, +).  124
  125:- dynamic
  126    current_server/6,       % Port, Goal, Thread, Queue, Scheme, StartTime
  127    queue_worker/2,         % Queue, ThreadID
  128    queue_options/2.        % Queue, Options
  129
  130:- multifile
  131    make_socket_hook/3,
  132    accept_hook/2,
  133    close_hook/1,
  134    open_client_hook/6,
  135    discard_client_hook/1,
  136    http:create_pool/1,
  137    http:schedule_workers/1.  138
  139:- meta_predicate
  140    thread_repeat_wait(0).
 http_server(:Goal, :Options) is det
Create a server at Port that calls Goal for each parsed request. Options provide a list of options. Defined options are
port(?Address)
Port to bind to. Address is either a port or a term Host:Port. The port may be a variable, causing the system to select a free port. See tcp_bind/2.
unix_socket(+Path)
Instead of binding to a TCP port, bind to a Unix Domain Socket at Path.
entry_page(+URI)
Affects the message printed while the server is started. Interpreted as a URI relative to the server root.
tcp_socket(+Socket)
If provided, use this socket instead of the creating one and binding it to an address. The socket must be bound to an address. Note that this also allows binding an HTTP server to a Unix domain socket (AF_UNIX). See socket_create/2.
workers(+Count)
Determine the number of worker threads. Default is 5. This is fine for small scale usage. Public servers typically need a higher number.
timeout(+Seconds)
Maximum time of inactivity trying to read the request after a connection has been opened. Default is 60 seconds. See set_stream/1 using the timeout option.
keep_alive_timeout(+Seconds)
Time to keep `Keep alive' connections alive. Default is 2 seconds. If a handler did not read the request body, the connection is only kept alive if at most the setting http:max_keep_alive_drain (64Kb) bytes of the body are left.
stack_limit(+Bytes)
Stack limit to use for the workers. The default is inherited from the main thread. If you need to control resource usage you may consider the spawn option of http_handler/3 and library(thread_pool).
silent(Bool)
If true (default false), do not print an informational message that the server was started.

A typical initialization for an HTTP server that uses http_dispatch/1 to relay requests to predicates is:

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).

start_server(Port) :-
    http_server(http_dispatch, [port(Port)]).

Note that multiple servers can coexist in the same Prolog process. A notable application of this is to have both an HTTP and HTTPS server, where the HTTP server redirects to the HTTPS server for handling sensitive requests.

  208http_server(Goal, M:Options0) :-
  209    server_address(Address, Options0),
  210    !,
  211    make_socket(Address, M:Options0, Options),
  212    create_workers(Options),
  213    create_server(Goal, Address, Options),
  214    (   option(silent(true), Options0)
  215    ->  true
  216    ;   print_message(informational,
  217                      httpd_started_server(Address, Options0))
  218    ).
  219http_server(_Goal, _:Options0) :-
  220    existence_error(server_address, Options0).
  221
  222server_address(Address, Options) :-
  223    (   option(port(Port), Options)
  224    ->  Address = Port
  225    ;   option(unix_socket(Path), Options)
  226    ->  Address = unix_socket(Path)
  227    ).
  228
  229address_port(_IFace:Port, Port) :- !.
  230address_port(unix_socket(Path), Path) :- !.
  231address_port(Address, Address) :- !.
  232
  233tcp_address(Port) :-
  234    var(Port),
  235    !.
  236tcp_address(Port) :-
  237    integer(Port),
  238    !.
  239tcp_address(_Iface:_Port).
  240
  241address_domain(localhost:_Port, Domain) =>
  242    Domain = inet.
  243address_domain(Iface:_Port, Domain) =>
  244    (   catch(ip_name(IP, Iface), error(_,_), fail),
  245        functor(IP, ip, 8)
  246    ->  Domain = inet6
  247    ;   Domain = inet
  248    ).
  249address_domain(_, Domain) =>
  250    Domain = inet.
 make_socket(+Address, :OptionsIn, -OptionsOut) is det
Create the HTTP server socket and worker pool queue. OptionsOut is guaranteed to hold the option queue(QueueId).
Arguments:
OptionsIn- is qualified to allow passing the module-sensitive ssl option argument.
  261make_socket(Address, M:Options0, Options) :-
  262    tcp_address(Address),
  263    make_socket_hook(Address, M:Options0, Options),
  264    !.
  265make_socket(Address, _:Options0, Options) :-
  266    option(tcp_socket(_), Options0),
  267    !,
  268    make_addr_atom('httpd', Address, Queue),
  269    Options = [ queue(Queue)
  270              | Options0
  271              ].
  272make_socket(Address, _:Options0, Options) :-
  273    tcp_address(Address),
  274    !,
  275    address_domain(Address, Domain),
  276    socket_create(Socket, [domain(Domain)]),
  277    tcp_setopt(Socket, reuseaddr),
  278    tcp_bind(Socket, Address),
  279    tcp_listen(Socket, 64),
  280    make_addr_atom('httpd', Address, Queue),
  281    Options = [ queue(Queue),
  282                tcp_socket(Socket)
  283              | Options0
  284              ].
  285:- if(current_predicate(unix_domain_socket/1)).  286make_socket(Address, _:Options0, Options) :-
  287    Address = unix_socket(Path),
  288    !,
  289    unix_domain_socket(Socket),
  290    tcp_bind(Socket, Path),
  291    tcp_listen(Socket, 64),
  292    make_addr_atom('httpd', Address, Queue),
  293    Options = [ queue(Queue),
  294                tcp_socket(Socket)
  295              | Options0
  296              ].
  297:- endif.
 make_addr_atom(+Scheme, +Address, -Atom) is det
Create an atom that identifies the server's queue and thread resources.
  304make_addr_atom(Scheme, Address, Atom) :-
  305    phrase(address_parts(Address), Parts),
  306    atomic_list_concat([Scheme,@|Parts], Atom).
  307
  308address_parts(Var) -->
  309    { var(Var),
  310      !,
  311      instantiation_error(Var)
  312    }.
  313address_parts(Atomic) -->
  314    { atomic(Atomic) },
  315    !,
  316    [Atomic].
  317address_parts(Host:Port) -->
  318    !,
  319    address_parts(Host), [:], address_parts(Port).
  320address_parts(ip(A,B,C,D)) -->
  321    !,
  322    [ A, '.', B, '.', C, '.', D ].
  323address_parts(unix_socket(Path)) -->
  324    [Path].
  325address_parts(Address) -->
  326    { domain_error(http_server_address, Address) }.
 create_server(:Goal, +Address, +Options) is det
Create the main server thread that runs accept_server/2 to listen to new requests.
  334create_server(Goal, Address, Options) :-
  335    get_time(StartTime),
  336    option(queue(Queue), Options),
  337    scheme(Scheme, Options),
  338    autoload_https(Scheme),
  339    address_port(Address, Port),
  340    make_addr_atom(Scheme, Port, Alias),
  341    thread_self(Initiator),
  342    thread_create(accept_server(Goal, Initiator, Options), _,
  343                  [ alias(Alias),
  344                    class(service)
  345                  ]),
  346    thread_get_message(server_started),
  347    assert(current_server(Port, Goal, Alias, Queue, Scheme, StartTime)).
  348
  349scheme(Scheme, Options) :-
  350    option(scheme(Scheme), Options),
  351    !.
  352scheme(Scheme, Options) :-
  353    (   option(ssl(_), Options)
  354    ;   option(ssl_instance(_), Options)
  355    ),
  356    !,
  357    Scheme = https.
  358scheme(http, _).
  359
  360autoload_https(https) :-
  361    \+ clause(accept_hook(_Goal, _Options), _),
  362    exists_source(library(http/http_ssl_plugin)),
  363    !,
  364    use_module(library(http/http_ssl_plugin)).
  365autoload_https(_).
 http_current_server(:Goal, ?Port) is nondet
True if Goal is the goal of a server at Port.
deprecated
- Use http_server_property(Port, goal(Goal))
  373http_current_server(Goal, Port) :-
  374    current_server(Port, Goal, _, _, _, _).
 http_server_property(?Port, ?Property) is nondet
True if Property is a property of the HTTP server running at Port. Defined properties are:
goal(:Goal)
Goal used to start the server. This is often http_dispatch/1.
scheme(-Scheme)
Scheme is one of http or https.
start_time(?Time)
Time-stamp when the server was created.
  390http_server_property(_:Port, Property) :-
  391    integer(Port),
  392    !,
  393    server_property(Property, Port).
  394http_server_property(Port, Property) :-
  395    server_property(Property, Port).
  396
  397server_property(goal(Goal), Port) :-
  398    current_server(Port, Goal, _, _, _, _).
  399server_property(scheme(Scheme), Port) :-
  400    current_server(Port, _, _, _, Scheme, _).
  401server_property(start_time(Time), Port) :-
  402    current_server(Port, _, _, _, _, Time).
 http_workers(?Port, -Workers) is nondet
http_workers(+Port, +Workers:int) is det
Query or set the number of workers for the server at this port. The number of workers is dynamically modified. Setting it to 1 (one) can be used to profile the worker using tprofile/1.
See also
- library(http/http_dyn_workers) implements dynamic management of the worker pool depending on usage.
  415http_workers(Port, Workers) :-
  416    integer(Workers),
  417    !,
  418    must_be(ground, Port),
  419    (   current_server(Port, _, _, Queue, _, _)
  420    ->  resize_pool(Queue, Workers)
  421    ;   existence_error(http_server, Port)
  422    ).
  423http_workers(Port, Workers) :-
  424    current_server(Port, _, _, Queue, _, _),
  425    aggregate_all(count, queue_worker(Queue, _Worker), Workers).
 http_add_worker(+Port, +Options) is det
Add a new worker to the HTTP server for port Port. Options overrule the default queue options. The following additional options are processed:
max_idle_time(+Seconds)
The created worker will automatically terminate if there is no new work within Seconds.
  438http_add_worker(Port, Options) :-
  439    must_be(ground, Port),
  440    current_server(Port, _, _, Queue, _, _),
  441    !,
  442    queue_options(Queue, QueueOptions),
  443    merge_options(Options, QueueOptions, WorkerOptions),
  444    atom_concat(Queue, '_', AliasBase),
  445    create_workers(1, 1, Queue, AliasBase, WorkerOptions).
  446http_add_worker(Port, _) :-
  447    existence_error(http_server, Port).
 http_current_worker(?Port, ?ThreadID) is nondet
True if ThreadID is the identifier of a Prolog thread serving Port. This predicate is motivated to allow for the use of arbitrary interaction with the worker thread for development and statistics.
  457http_current_worker(Port, ThreadID) :-
  458    current_server(Port, _, _, Queue, _, _),
  459    queue_worker(Queue, ThreadID).
 accept_server(:Goal, +Initiator, +Options)
The goal of a small server-thread accepting new requests and posting them to the queue of workers.
  467accept_server(Goal, Initiator, Options) :-
  468    Ex = http_stop(Stopper),
  469    catch(accept_server2(Goal, Initiator, Options), Ex, true),
  470    thread_self(Thread),
  471    debug(http(stop), '[~p]: accept server received ~p', [Thread, Ex]),
  472    retract(current_server(_Port, _, Thread, Queue, _Scheme, _StartTime)),
  473    close_pending_accepts(Queue),
  474    close_server_socket(Options),
  475    thread_send_message(Stopper, http_stopped).
  476
  477accept_server2(Goal, Initiator, Options) :-
  478    thread_send_message(Initiator, server_started),
  479    repeat,
  480      (   catch(accept_server3(Goal, Options), E, true)
  481      ->  (   var(E)
  482          ->  fail
  483          ;   accept_rethrow_error(E)
  484          ->  throw(E)
  485          ;   print_message(error, E),
  486              fail
  487          )
  488      ;   print_message(error,      % internal error
  489                        goal_failed(accept_server3(Goal, Options))),
  490          fail
  491      ).
  492
  493accept_server3(Goal, Options) :-
  494    accept_hook(Goal, Options),
  495    !.
  496accept_server3(Goal, Options) :-
  497    memberchk(tcp_socket(Socket), Options),
  498    memberchk(queue(Queue), Options),
  499    debug(http(connection), 'Waiting for connection', []),
  500    tcp_accept(Socket, Client, Peer),
  501    sig_atomic(send_to_worker(Queue, Client, Goal, Peer)),
  502    http_enough_workers(Queue, accept, Peer).
  503
  504send_to_worker(Queue, Client, Goal, Peer) :-
  505    debug(http(connection), 'New HTTP connection from ~p', [Peer]),
  506    thread_send_message(Queue, tcp_client(Client, Goal, Peer)).
  507
  508accept_rethrow_error(http_stop(_)).
 close_server_socket(+Options)
Close the server socket.
  514close_server_socket(Options) :-
  515    close_hook(Options),
  516    !.
  517close_server_socket(Options) :-
  518    memberchk(tcp_socket(Socket), Options),
  519    !,
  520    tcp_close_socket(Socket).
 close_pending_accepts(+Queue)
  524close_pending_accepts(Queue) :-
  525    (   thread_get_message(Queue, Msg, [timeout(0)])
  526    ->  close_client(Msg),
  527        close_pending_accepts(Queue)
  528    ;   true
  529    ).
  530
  531close_client(tcp_client(Client, _Goal, _0Peer)) =>
  532    debug(http(stop), 'Closing connection from ~p during shut-down', [_0Peer]),
  533    tcp_close_socket(Client).
  534close_client(Msg) =>
  535    (   discard_client_hook(Msg)
  536    ->  true
  537    ;   print_message(warning, http_close_client(Msg))
  538    ).
 http_stop_server(+Port, +Options)
Stop the indicated HTTP server gracefully. First stops all workers, then stops the server.
To be done
- Realise non-graceful stop
  548http_stop_server(Host:Port, Options) :-         % e.g., localhost:4000
  549    ground(Host),
  550    !,
  551    http_stop_server(Port, Options).
  552http_stop_server(Port, _Options) :-
  553    http_workers(Port, 0),                  % checks Port is ground
  554    current_server(Port, _, Thread, Queue, _Scheme, _Start),
  555    retractall(queue_options(Queue, _)),
  556    debug(http(stop), 'Signalling HTTP server thread ~p to stop', [Thread]),
  557    thread_self(Stopper),
  558    thread_signal(Thread, throw(http_stop(Stopper))),
  559    (   thread_get_message(Stopper, http_stopped, [timeout(0.1)])
  560    ->  true
  561    ;   catch(connect(localhost:Port), _, true)
  562    ),
  563    thread_join(Thread, _0Status),
  564    debug(http(stop), 'Joined HTTP server thread ~p (~p)', [Thread, _0Status]),
  565    message_queue_destroy(Queue).
  566
  567connect(Address) :-
  568    setup_call_cleanup(
  569        tcp_socket(Socket),
  570        tcp_connect(Socket, Address),
  571        tcp_close_socket(Socket)).
 http_enough_workers(+Queue, +Why, +Peer) is det
Check that we have enough workers in our queue. If not, call the hook http:schedule_workers/1 to extend the worker pool. This predicate can be used by accept_hook/2.
  579http_enough_workers(Queue, _Why, _Peer) :-
  580    message_queue_property(Queue, waiting(_0)),
  581    !,
  582    debug(http(scheduler), '~D waiting for work; ok', [_0]).
  583http_enough_workers(Queue, Why, Peer) :-
  584    message_queue_property(Queue, size(Size)),
  585    (   enough(Size, Why)
  586    ->  debug(http(scheduler), '~D in queue; ok', [Size])
  587    ;   current_server(Port, _, _, Queue, _, _),
  588        Data = _{ port:Port,
  589                  reason:Why,
  590                  peer:Peer,
  591                  waiting:Size,
  592                  queue:Queue
  593                },
  594        debug(http(scheduler), 'Asking to reschedule: ~p', [Data]),
  595        catch(http:schedule_workers(Data),
  596              error(Formal, Context),
  597              print_message(error, error(Formal, Context)))
  598    ->  true
  599    ;   true
  600    ).
  601
  602enough(0, _).
  603enough(1, keep_alive).                  % I will be ready myself
 http:schedule_workers(+Data:dict) is semidet
Hook called if a new connection or a keep-alive connection cannot be scheduled immediately to a worker. Dict contains the following keys:
port:Port
Port number that identifies the server.
reason:Reason
One of accept for a new connection or keep_alive if a worker tries to reschedule itself.
peer:Peer
Identify the other end of the connection
waiting:Size
Number of messages waiting in the queue.
queue:Queue
Message queue used to dispatch accepted messages.

Note that, when called with reason:accept, we are called in the time critical main accept loop. An implementation of this hook shall typically send the event to thread dedicated to dynamic worker-pool management.

See also
- http_add_worker/2 may be used to create (temporary) extra workers.
  633                 /*******************************
  634                 *    WORKER QUEUE OPERATIONS   *
  635                 *******************************/
 create_workers(+Options)
Create the pool of HTTP worker-threads. Each worker has the alias http_worker_N.
  642create_workers(Options) :-
  643    option(workers(N), Options, 5),
  644    option(queue(Queue), Options),
  645    catch(message_queue_create(Queue), _, true),
  646    atom_concat(Queue, '_', AliasBase),
  647    create_workers(1, N, Queue, AliasBase, Options),
  648    assert(queue_options(Queue, Options)).
  649
  650create_workers(I, N, _, _, _) :-
  651    I > N,
  652    !.
  653create_workers(I, N, Queue, AliasBase, Options) :-
  654    gensym(AliasBase, Alias),
  655    thread_create(http_worker(Options), Id,
  656                  [ alias(Alias),
  657                    class(http)
  658                  | Options
  659                  ]),
  660    assertz(queue_worker(Queue, Id)),
  661    I2 is I + 1,
  662    create_workers(I2, N, Queue, AliasBase, Options).
 resize_pool(+Queue, +Workers) is det
Create or destroy workers. If workers are destroyed, the call waits until the desired number of waiters is reached.
  670resize_pool(Queue, Size) :-
  671    findall(W, queue_worker(Queue, W), Workers),
  672    length(Workers, Now),
  673    (   Now < Size
  674    ->  queue_options(Queue, Options),
  675        atom_concat(Queue, '_', AliasBase),
  676        I0 is Now+1,
  677        create_workers(I0, Size, Queue, AliasBase, Options)
  678    ;   Now == Size
  679    ->  true
  680    ;   Now > Size
  681    ->  Excess is Now - Size,
  682        thread_self(Me),
  683        forall(between(1, Excess, _), thread_send_message(Queue, quit(Me))),
  684        forall(between(1, Excess, _), thread_get_message(quitted(_)))
  685    ).
 http_worker(+Options)
Run HTTP worker main loop. Workers simply wait until they are passed an accepted socket to process a client.

If the message quit(Sender) is read from the queue, the worker stops.

  696http_worker(Options) :-
  697    debug(http(scheduler), 'New worker', []),
  698    prolog_listen(this_thread_exit, done_worker),
  699    option(queue(Queue), Options),
  700    option(max_idle_time(MaxIdle), Options, infinite),
  701    thread_repeat_wait(get_work(Queue, Message, MaxIdle)),
  702      debug(http(worker), 'Waiting for a job ...', []),
  703      debug(http(worker), 'Got job ~p', [Message]),
  704      (   Message = quit(Sender)
  705      ->  !,
  706          thread_self(Self),
  707          thread_detach(Self),
  708          (   Sender == idle
  709          ->  true
  710          ;   retract(queue_worker(Queue, Self)),
  711              thread_send_message(Sender, quitted(Self))
  712          )
  713      ;   open_client(Message, Queue, Goal, In, Out,
  714                      Options, ClientOptions),
  715          (   catch(http_process(Goal, In, Out, ClientOptions),
  716                    Error, true)
  717          ->  true
  718          ;   Error = goal_failed(http_process/4)
  719          ),
  720          debug_reset_from_class,   % Restore debug mode after user nodebug
  721          (   var(Error)
  722          ->  fail
  723          ;   current_message_level(Error, Level),
  724              print_message(Level, Error),
  725              option(peer(Peer), ClientOptions),
  726              close_connection(Peer, In, Out),
  727              fail
  728          )
  729      ).
  730
  731get_work(Queue, Message, infinite) :-
  732    !,
  733    thread_get_message(Queue, Message).
  734get_work(Queue, Message, MaxIdle) :-
  735    (   thread_get_message(Queue, Message, [timeout(MaxIdle)])
  736    ->  true
  737    ;   Message = quit(idle)
  738    ).
 open_client(+Message, +Queue, -Goal, -In, -Out, +Options, -ClientOptions) is semidet
Opens the connection to the client in a worker from the message sent to the queue by accept_server/2.
  747open_client(requeue(In, Out, Goal, ClOpts),
  748            _, Goal, In, Out, Opts, ClOpts) :-
  749    !,
  750    option(peer(Peer), ClOpts),
  751    option(keep_alive_timeout(KeepAliveTMO), Opts, 2),
  752    check_keep_alive_connection(In, KeepAliveTMO, Peer, In, Out).
  753open_client(Message, Queue, Goal, In, Out, Opts,
  754            [ pool(client(Queue, Goal, In, Out)),
  755              timeout(Timeout)
  756            | Options
  757            ]) :-
  758    catch(open_client(Message, Goal, In, Out, Options, Opts),
  759          E, report_error(E)),
  760    option(timeout(Timeout), Opts, 60),
  761    (   debugging(http(connection))
  762    ->  memberchk(peer(Peer), Options),
  763        debug(http(connection), 'Opened connection from ~p', [Peer])
  764    ;   true
  765    ).
 open_client(+Message, +Goal, -In, -Out, -ClientOptions, +Options) is det
  771open_client(Message, Goal, In, Out, ClientOptions, Options) :-
  772    open_client_hook(Message, Goal, In, Out, ClientOptions, Options),
  773    !.
  774open_client(tcp_client(Socket, Goal, Peer), Goal, In, Out,
  775            [ peer(Peer),
  776              protocol(http)
  777            ], _) :-
  778    tcp_open_socket(Socket, In, Out).
  779
  780report_error(E) :-
  781    print_message(error, E),
  782    fail.
 check_keep_alive_connection(+In, +TimeOut, +Peer, +In, +Out) is semidet
Wait for the client for at most TimeOut seconds. Succeed if the client starts a new request within this time. Otherwise close the connection and fail.
  791check_keep_alive_connection(In, TMO, Peer, In, Out) :-
  792    stream_property(In, timeout(Old)),
  793    set_stream(In, timeout(TMO)),
  794    debug(http(keep_alive), 'Waiting for keep-alive ...', []),
  795    catch(peek_code(In, Code), E, true),
  796    (   var(E),                     % no exception
  797        Code \== -1                 % no end-of-file
  798    ->  set_stream(In, timeout(Old)),
  799        debug(http(keep_alive), '\tre-using keep-alive connection', [])
  800    ;   (   Code == -1
  801        ->  debug(http(keep_alive), '\tRemote closed keep-alive connection', [])
  802        ;   debug(http(keep_alive), '\tTimeout on keep-alive connection', [])
  803        ),
  804        close_connection(Peer, In, Out),
  805        fail
  806    ).
 done_worker
Called when worker is terminated due to http_workers/2 or a (debugging) exception. In the latter case, recreate_worker/2 creates a new worker.
  815done_worker :-
  816    thread_self(Self),
  817    thread_detach(Self),
  818    retract(queue_worker(Queue, Self)),
  819    thread_property(Self, status(Status)),
  820    !,
  821    (   catch(recreate_worker(Status, Queue), _, fail)
  822    ->  print_message(informational,
  823                      httpd_restarted_worker(Self))
  824    ;   done_status_message_level(Status, Level),
  825        print_message(Level,
  826                      httpd_stopped_worker(Self, Status))
  827    ).
  828done_worker :-                                  % received quit(Sender)
  829    thread_self(Self),
  830    thread_property(Self, status(Status)),
  831    done_status_message_level(Status, Level),
  832    print_message(Level,
  833                  httpd_stopped_worker(Self, Status)).
  834
  835done_status_message_level(true, silent) :- !.
  836done_status_message_level(exception('$aborted'), silent) :- !.
  837done_status_message_level(exception(unwind(abort)), silent) :- !.
  838done_status_message_level(exception(unwind(halt(_))), silent) :- !.
  839done_status_message_level(_, informational).
 recreate_worker(+Status, +Queue) is semidet
Deal with the possibility that threads are, during development, killed with abort/0. We recreate the worker to avoid that eventually we run out of workers. If we are aborted due to a halt/0 call, thread_create/3 will raise a permission error.

The first clause deals with the possibility that we cannot write to user_error. This is possible when Prolog is started as a service using some service managers. Would be nice if we could write an error, but where?

  854recreate_worker(exception(error(io_error(write,user_error),_)), _Queue) :-
  855    halt(2).
  856recreate_worker(exception(Error), Queue) :-
  857    recreate_on_error(Error),
  858    queue_options(Queue, Options),
  859    atom_concat(Queue, '_', AliasBase),
  860    create_workers(1, 1, Queue, AliasBase, Options).
  861
  862recreate_on_error('$aborted').
  863recreate_on_error(unwind(abort)).
  864recreate_on_error(time_limit_exceeded).
 thread_httpd:message_level(+Exception, -Level)
Determine the message stream used for exceptions that may occur during server_loop/5. Being multifile, clauses can be added by the application to refine error handling. See also message_hook/3 for further programming error handling.
  873:- multifile
  874    message_level/2.  875
  876message_level(error(io_error(read, _), _),               silent).
  877message_level(error(socket_error(epipe,_), _),           silent).
  878message_level(error(http_write_short(_Obj,_Written), _), silent).
  879message_level(error(timeout_error(read, _), _),          informational).
  880message_level(keep_alive_timeout,                        silent).
  881
  882current_message_level(Term, Level) :-
  883    (   message_level(Term, Level)
  884    ->  true
  885    ;   Level = error
  886    ).
 read_remaining_request(+StartBody, +Request) is semidet
If our handler did not read the complete request we must read the remainder if we are dealing with a Keep-alive connection. We only do so if the remainder is at most the setting http:max_keep_alive_drain. Otherwise we fail, which closes the connection: reading a large body that nobody needs would occupy this worker for as long as the client keeps sending.
  897read_remaining_request(StartBody, Request) :-
  898    memberchk(content_length(Len), Request),
  899    !,
  900    memberchk(pool(client(_Queue, _Goal, In, _Out)), Request),
  901    byte_count(In, Here),
  902    Left is StartBody+Len-Here,
  903    read_incomplete(In, Left).
  904read_remaining_request(_, _Request).
  905
  906read_incomplete(_, 0) :-
  907    !.
  908read_incomplete(In, Left) :-
  909    setting(http:max_keep_alive_drain, Max),
  910    Left =< Max,
  911    catch(setup_call_cleanup(
  912              open_null_stream(Null),
  913              copy_stream_data(In, Null, Left),
  914              close(Null)),
  915          error(_,_),
  916          fail).
 http_requeue(+Header)
Re-queue a connection to the worker pool. This deals with processing additional requests on keep-alive connections.
  923http_requeue(Header) :-
  924    requeue_header(Header, ClientOptions),
  925    memberchk(pool(client(Queue, Goal, In, Out)), ClientOptions),
  926    option(peer(Peer), ClientOptions),
  927    http_enough_workers(Queue, keep_alive, Peer),
  928    thread_send_message(Queue, requeue(In, Out, Goal, ClientOptions)),
  929    !.
  930http_requeue(Header) :-
  931    debug(http(error), 'Re-queue failed: ~p', [Header]),
  932    fail.
  933
  934requeue_header([], []).
  935requeue_header([H|T0], [H|T]) :-
  936    requeue_keep(H),
  937    !,
  938    requeue_header(T0, T).
  939requeue_header([_|T0], T) :-
  940    requeue_header(T0, T).
  941
  942requeue_keep(pool(_)).
  943requeue_keep(peer(_)).
  944requeue_keep(protocol(_)).
 http_process(Message, Queue, +Options)
Handle a single client message on the given stream.
  951http_process(Goal, In, Out, Options) :-
  952    debug(http(server), 'Running server goal ~p on ~p -> ~p',
  953          [Goal, In, Out]),
  954    option(timeout(TMO), Options, 60),
  955    set_stream(In, timeout(TMO)),
  956    set_stream(Out, timeout(TMO)),
  957    http_wrapper(Goal, In, Out, Connection,
  958                 [ request(Request),
  959                   byte_count(StartBody)
  960                 | Options
  961                 ]),
  962    next(Connection, StartBody, Request).
  963
  964next(Connection, StartBody, Request) :-
  965    next_(Connection, StartBody, Request), !.
  966next(Connection, StartBody, Request) :-
  967    print_message(warning, goal_failed(next(Connection,StartBody,Request))).
  968
  969next_(switch_protocol(SwitchGoal, _SwitchOptions), _, Request) :-
  970    !,
  971    memberchk(pool(client(_Queue, _Goal, In, Out)), Request),
  972    (   catch(call(SwitchGoal, In, Out), E,
  973              (   print_message(error, E),
  974                  fail))
  975    ->  true
  976    ;   http_close_connection(Request)
  977    ).
  978next_(spawned(ThreadId), _, _) :-
  979    !,
  980    debug(http(spawn), 'Handler spawned to thread ~w', [ThreadId]).
  981next_(Connection, StartBody, Request) :-
  982    downcase_atom(Connection, 'keep-alive'),
  983    read_remaining_request(StartBody, Request),
  984    http_requeue(Request),
  985    !.
  986next_(_, _, Request) :-
  987    http_close_connection(Request).
 http_close_connection(+Request)
Close connection associated to Request. See also http_requeue/1.
  994http_close_connection(Request) :-
  995    memberchk(pool(client(_Queue, _Goal, In, Out)), Request),
  996    memberchk(peer(Peer), Request),
  997    close_connection(Peer, In, Out).
 close_connection(+Peer, +In, +Out)
Closes the connection from the server to the client. Errors are currently silently ignored.
 1004close_connection(Peer, In, Out) :-
 1005    debug(http(connection), 'Closing connection from ~p', [Peer]),
 1006    catch(close(In, [force(true)]), _, true),
 1007    catch(close(Out, [force(true)]), _, true).
 http_spawn(:Goal, +Options) is det
Continue this connection on a new thread. A handler may call http_spawn/2 to start a new thread that continues processing the current request using Goal. The original thread returns to the worker pool for processing new requests. Options are passed to thread_create/3, except for:
pool(+Pool)
Interfaces to library(thread_pool), starting the thread on the given pool.

If a pool does not exist, this predicate calls the multifile hook create_pool/1 to create it. If this predicate succeeds the operation is retried.

 1025http_spawn(Goal, Options) :-
 1026    select_option(pool(Pool), Options, ThreadOptions),
 1027    !,
 1028    current_output(CGI),
 1029    Error = error(Formal, _),
 1030    catch(thread_create_in_pool(Pool,
 1031                                wrap_spawned(CGI, Goal), Id,
 1032                                [ detached(true),
 1033                                  class(http)
 1034                                | ThreadOptions
 1035                                ]),
 1036          Error,
 1037          true),
 1038    (   var(Formal)
 1039    ->  http_spawned(Id)
 1040    ;   Formal = resource_error(threads_in_pool(_))
 1041    ->  throw(http_reply(busy))
 1042    ;   Formal = existence_error(thread_pool, Pool),
 1043        create_pool(Pool)
 1044    ->  http_spawn(Goal, Options)
 1045    ;   throw(Error)
 1046    ).
 1047http_spawn(Goal, Options) :-
 1048    current_output(CGI),
 1049    thread_create(wrap_spawned(CGI, Goal), Id,
 1050                  [ detached(true),
 1051                    class(http)
 1052                  | Options
 1053                  ]),
 1054    http_spawned(Id).
 1055
 1056wrap_spawned(CGI, Goal) :-
 1057    set_output(CGI),
 1058    cgi_property(CGI, request(Request)),
 1059    memberchk(input(Input), Request),
 1060    byte_count(Input, StartBody),
 1061    http_wrap_spawned(Goal, Request, Connection),
 1062    next(Connection, StartBody, Request).
 create_pool(+Pool)
Lazy creation of worker-pools for the HTTP server. This predicate calls the hook create_pool/1. If the hook fails it creates a default pool of size 10. This should suffice most typical usecases. Note that we get a permission error if the pool is already created. We can ignore this.
 1072create_pool(Pool) :-
 1073    E = error(permission_error(create, thread_pool, Pool), _),
 1074    catch(http:create_pool(Pool), E, true).
 1075create_pool(Pool) :-
 1076    print_message(informational, httpd(created_pool(Pool))),
 1077    thread_pool_create(Pool, 10, []).
 1078
 1079
 1080		 /*******************************
 1081		 *         WAIT POLICIES	*
 1082		 *******************************/
 1083
 1084:- meta_predicate
 1085    thread_repeat_wait(0).
 thread_repeat_wait(:Goal) is multi
Acts as repeat, thread_idle(Goal), choosing whether to use a long or short idle time based on the average firing rate.
 1092thread_repeat_wait(Goal) :-
 1093    new_rate_mma(5, 1000, State),
 1094    repeat,
 1095      notrace,
 1096      update_rate_mma(State, MMA),
 1097      long(MMA, IsLong),
 1098      (   IsLong == brief
 1099      ->  call(Goal)
 1100      ;   thread_idle(Goal, IsLong)
 1101      ).
 1102
 1103long(MMA, brief) :-
 1104    MMA < 0.05,
 1105    !.
 1106long(MMA, short) :-
 1107    MMA < 1,
 1108    !.
 1109long(_, long).
 new_rate_mma(+N, +Resolution, -State) is det
 update_rate_mma(!State, -MMA) is det
Implement Modified Moving Average computing the average time between requests as an exponential moving average with alpha=1/N.
Arguments:
Resolution- is the time resolution in 1/Resolution seconds. All storage is done in integers to avoid the need for stack freezing in nb_setarg/3.
See also
- https://en.wikipedia.org/wiki/Moving_average
 1123new_rate_mma(N, Resolution, rstate(Base, 0, MaxI, Resolution, N, 0)) :-
 1124    current_prolog_flag(max_tagged_integer, MaxI),
 1125    get_time(Base).
 1126
 1127update_rate_mma(State, MMAr) :-
 1128    State = rstate(Base, Last, MaxI, Resolution, N, MMA0),
 1129    get_time(Now),
 1130    Stamp is round((Now-Base)*Resolution),
 1131    (   Stamp > MaxI
 1132    ->  nb_setarg(1, State, Now),
 1133        nb_setarg(2, State, 0)
 1134    ;   true
 1135    ),
 1136    Diff is Stamp-Last,
 1137    nb_setarg(2, State, Stamp),
 1138    MMA is round(((N-1)*MMA0+Diff)/N),
 1139    nb_setarg(6, State, MMA),
 1140    MMAr is MMA/float(Resolution).
 1141
 1142
 1143                 /*******************************
 1144                 *            MESSAGES          *
 1145                 *******************************/
 1146
 1147:- multifile
 1148    prolog:message/3. 1149
 1150prolog:message(httpd_started_server(Port, Options)) -->
 1151    [ 'Started server at '-[] ],
 1152    http_root(Port, Options).
 1153prolog:message(httpd_stopped_worker(Self, Status)) -->
 1154    [ 'Stopped worker ~p: ~p'-[Self, Status] ].
 1155prolog:message(httpd_restarted_worker(Self)) -->
 1156    [ 'Replaced aborted worker ~p'-[Self] ].
 1157prolog:message(httpd(created_pool(Pool))) -->
 1158    [ 'Created thread-pool ~p of size 10'-[Pool], nl,
 1159      'Create this pool at startup-time or define the hook ', nl,
 1160      'http:create_pool/1 to avoid this message and create a ', nl,
 1161      'pool that fits the usage-profile.'
 1162    ].
 1163
 1164http_root(Address, Options) -->
 1165    { landing_page(Address, URI, Options) },
 1166    [ url(URI) ].
 1167
 1168landing_page(Host:Port, URI, Options) :-
 1169    !,
 1170    must_be(atom, Host),
 1171    must_be(integer, Port),
 1172    http_server_property(Port, scheme(Scheme)),
 1173    (   default_port(Scheme, Port)
 1174    ->  format(atom(Base), '~w://~w', [Scheme, Host])
 1175    ;   format(atom(Base), '~w://~w:~w', [Scheme, Host, Port])
 1176    ),
 1177    entry_page(Base, URI, Options).
 1178landing_page(unix_socket(Path), URI, _Options) :-
 1179    !,
 1180    format(string(URI), 'Unix domain socket "~w"', [Path]).
 1181landing_page(Port, URI, Options) :-
 1182    landing_page(localhost:Port, URI, Options).
 1183
 1184default_port(http, 80).
 1185default_port(https, 443).
 1186
 1187entry_page(Base, URI, Options) :-
 1188    option(entry_page(Entry), Options),
 1189    !,
 1190    uri_resolve(Entry, Base, URI).
 1191entry_page(Base, URI, _) :-
 1192    http_absolute_location(root(.), Entry, []),
 1193    uri_resolve(Entry, Base, URI)