View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker and Sean Charles
    4    E-mail:        jan@swi-prolog.org and <sean at objitsu dot com>
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2013-2024, Sean Charles
    7                              SWI-Prolog Solutions b.v.
    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    NOTE
   36
   37    The original code was subject to the MIT licence and written by
   38    Sean Charles.  Re-licenced to standard SWI-Prolog BSD-2 with
   39    permission from Sean Charles.
   40*/
   41
   42:- module(redis,
   43          [ redis_server/3,             % +Alias, +Address, +Options
   44            redis_connect/1,            % -Connection
   45            redis_connect/3,            % -Connection, +Host, +Port
   46            redis_disconnect/1,         % +Connection
   47            redis_disconnect/2,         % +Connection, +Options
   48                                        % Queries
   49            redis/1,                    % +Request
   50            redis/2,                    % +Connection, +Request
   51            redis/3,                    % +Connection, +Request, -Reply
   52                                        % High level queries
   53            redis_get_list/3,           % +Redis, +Key, -List
   54            redis_get_list/4,           % +Redis, +Key, +ChunkSize, -List
   55            redis_set_list/3,           % +Redis, +Key, +List
   56            redis_get_hash/3,           % +Redis, +Key, -Data:dict
   57            redis_set_hash/3,           % +Redis, +Key, +Data:dict
   58            redis_scan/3,               % +Redis, -LazyList, +Options
   59            redis_sscan/4,              % +Redis, +Set, -LazyList, +Options
   60            redis_hscan/4,              % +Redis, +Hash, -LazyList, +Options
   61            redis_zscan/4,              % +Redis, +Set, -LazyList, +Options
   62                                        % Publish/Subscribe
   63            redis_subscribe/4,          % +Redis, +Channels, -Id, +Options
   64            redis_subscribe/2,          % +Id, +Channels
   65            redis_unsubscribe/2,        % +Id, +Channels
   66            redis_current_subscription/2, % ?Id,?Channels
   67            redis_write/2,              % +Redis, +Command
   68            redis_read/2,               % +Redis, -Reply
   69                                        % Building blocks
   70            redis_array_dict/3,         % ?Array, ?Tag, ?Dict
   71                                        % Admin stuff
   72            redis_property/2,           % +Reply, ?Property
   73            redis_current_command/2,    % +Redis,?Command
   74            redis_current_command/3,    % +Redis, +Command, -Properties
   75
   76            sentinel_slave/4            % +ServerId, +Pool, -Slave, +Options
   77          ]).   78:- autoload(library(socket), [tcp_connect/3]).   79:- autoload(library(apply), [maplist/2, convlist/3, maplist/3, maplist/5]).   80:- autoload(library(broadcast), [broadcast/1]).   81:- autoload(library(error),
   82            [ must_be/2,
   83	      type_error/2,
   84              instantiation_error/1,
   85              uninstantiation_error/1,
   86              existence_error/2,
   87              existence_error/3
   88            ]).   89:- autoload(library(lazy_lists), [lazy_list/2]).   90:- autoload(library(lists), [append/3, member/2]).   91:- autoload(library(option), [merge_options/3, option/2,
   92			      option/3, select_option/4]).   93:- autoload(library(pairs), [group_pairs_by_key/2]).   94:- autoload(library(time), [call_with_time_limit/2]).   95:- use_module(library(debug), [debug/3, assertion/1]).   96:- use_module(library(settings), [setting/4, setting/2]).   97:- if(exists_source(library(ssl))).   98:- autoload(library(ssl), [ssl_context/3, ssl_negotiate/5]).   99:- endif.  100
  101:- use_foreign_library(foreign(redis4pl)).  102
  103:- setting(max_retry_count, nonneg, 8640, % one day
  104           "Max number of retries").  105:- setting(max_retry_wait, number, 10,
  106           "Max time to wait between recovery attempts").  107:- setting(sentinel_timeout, number, 0.2,
  108	   "Time to wait for a sentinel").  109
  110:- predicate_options(redis_server/3, 3,
  111                     [ pass_to(redis:redis_connect/3, 3)
  112                     ]).  113:- predicate_options(redis_connect/3, 3,
  114                     [ reconnect(boolean),
  115                       user(atom),
  116                       password(atomic),
  117                       version(between(2,3))
  118                     ]).  119:- predicate_options(redis_disconnect/2, 2,
  120                     [ force(boolean)
  121                     ]).  122:- predicate_options(redis_scan/3, 3,
  123                     [ match(atomic),
  124                       count(nonneg),
  125                       type(atom)
  126                     ]).  127% Actually not passing, but the same
  128:- predicate_options(redis_sscan/4, 4, [pass_to(redis:redis_scan/3, 3)]).  129:- predicate_options(redis_hscan/4, 4, [pass_to(redis:redis_scan/3, 3)]).  130:- predicate_options(redis_zscan/4, 4, [pass_to(redis:redis_scan/3, 3)]).  131
  132
  133/** <module> Redis client
  134
  135This library is a client  to   [Redis](https://redis.io),  a popular key
  136value store to  deal  with  caching   and  communication  between  micro
  137services.
  138
  139In the typical use case we register  the   details  of one or more Redis
  140servers using redis_server/3. Subsequenly, redis/2-3   is  used to issue
  141commands on the server.  For example:
  142
  143```
  144?- redis_server(default, redis:6379, [password("secret")]).
  145?- redis(default, set(user, "Bob")).
  146?- redis(default, get(user), User).
  147User = "Bob"
  148```
  149*/
  150
  151:- dynamic server/3.  152
  153:- dynamic ( connection/2,              % ServerName, Stream
  154	     sentinel/2			% Pool, Address
  155           ) as volatile.  156
  157%!  redis_server(+ServerName, +Address, +Options) is det.
  158%
  159%   Register a redis server without  connecting   to  it. The ServerName
  160%   acts as a lazy connection alias.  Initially the ServerName `default`
  161%   points at `localhost:6379` with no   connect  options. The `default`
  162%   server is used for redis/1 and redis/2 and may be changed using this
  163%   predicate.  Options are described with redis_connect/3.
  164%
  165%   Connections  established  this  way  are  by  default  automatically
  166%   reconnected if the connection  is  lost   for  some  reason unless a
  167%   reconnect(false) option is specified.
  168
  169redis_server(Alias, Address, Options) :-
  170    must_be(ground, Alias),
  171    retractall(server(Alias, _, _)),
  172    asserta(server(Alias, Address, Options)).
  173
  174server(default, localhost:6379, []).
  175
  176%!  redis_connect(-Connection) is det.
  177%!  redis_connect(+Address, -Connection, +Options) is det.
  178%!  redis_connect(-Connection, +Host, +Port) is det.
  179%
  180%   Connect to a redis server. The  main mode is redis_connect(+Address,
  181%   -Connection,   +Options).   redis_connect/1   is     equivalent   to
  182%   redis_connect(localhost:6379, Connection, []).  Options:
  183%
  184%     - reconnect(+Boolean)
  185%       If `true`, try to reconnect to the service when the connection
  186%       seems lost.  Default is `true` for connections specified using
  187%       redis_server/3 and `false` for explictly opened connections.
  188%     - user(+User)
  189%       If version(3) and password(Password) are specified, these
  190%       are used to authenticate using the `HELLO` command.
  191%     - password(+Password)
  192%       Authenticate using Password
  193%     - version(+Version)
  194%       Specify the connection protocol version.  Initially this is
  195%       version 2.  Redis 6 also supports version 3.  When specified
  196%       as `3`, the `HELLO` command is used to upgrade the protocol.
  197%     - tls(true)
  198%       When specified, initiate a TLS connection.  If this option is
  199%       specified we must also specify the `cacert`, `key` and `cert`
  200%       options.
  201%     - cacert(+File)
  202%       CA Certificate file to verify with.
  203%     - cert(+File)
  204%       Client certificate to authenticate with.
  205%     - key(+File)
  206%       Private key file to authenticate with.
  207%     - sentinels(+ListOfAddresses)
  208%       Used together with an Address of the form sentinel(MasterName)
  209%       to enable contacting a network of Redis servers guarded by a
  210%       sentinel network.
  211%     - sentinel_user(+User)
  212%     - sentinel_password(+Password)
  213%       Authentication information for the senitels.  When omitted we
  214%       try to connect withour authentication.
  215%
  216%   Instead of using these predicates, redis/2  and redis/3 are normally
  217%   used with a _server name_  argument registered using redis_server/3.
  218%   These  predicates  are  meant  for   creating  a  temporary  paralel
  219%   connection or using a connection with a _blocking_ call.
  220%
  221%   @compat   redis_connect(-Connection,   +Host,     +Port)    provides
  222%   compatibility to the original GNU-Prolog interface and is equivalent
  223%   to redis_connect(Host:Port, Connection, []).
  224%
  225%   @arg Address is a term Host:Port, unix(File) or the name of a server
  226%   registered  using  redis_server/3.  The  latter   realises  a  _new_
  227%   connection that is typically used for   blocking redis commands such
  228%   as listening for published messages, waiting on a list or stream.
  229
  230redis_connect(Conn) :-
  231    redis_connect(default, Conn, []).
  232
  233redis_connect(Conn, Host, Port) :-
  234    var(Conn),
  235    ground(Host), ground(Port),
  236    !,                                  % GNU-Prolog compatibility
  237    redis_connect(Host:Port, Conn, []).
  238redis_connect(Server, Conn, Options) :-
  239    atom(Server),
  240    !,
  241    (   server(Server, Address, DefaultOptions)
  242    ->  merge_options(Options, DefaultOptions, Options2),
  243        do_connect(Server, Address, Conn, [address(Address)|Options2])
  244    ;   existence_error(redis_server, Server)
  245    ).
  246redis_connect(Address, Conn, Options) :-
  247    do_connect(Address, Address, Conn, [address(Address)|Options]).
  248
  249%!  do_connect(+Id, +Address, -Conn, +Options)
  250%
  251%   Open the connection.  A connection is a compound term of the shape
  252%
  253%       redis_connection(Id, Stream, Failures, Options)
  254
  255do_connect(Id, sentinel(Pool), Conn, Options) =>
  256    sentinel_master(Id, Pool, Conn, Options).
  257do_connect(Id, Address0, Conn, Options) =>
  258    tcp_address(Address0, Address),
  259    check_tls(Address, Options),
  260    tcp_connect(Address, Stream0, Options),
  261    tls_upgrade(Address, Stream0, Stream, Options),
  262    Conn = redis_connection(Id, Stream, 0, Options),
  263    hello(Conn, Options).
  264
  265tcp_address(unix(Path), Path) :-
  266    !.                                  % Using an atom is ambiguous
  267tcp_address(Address, Address).
  268
  269%!  check_tls(+Address, +Options) is det.
  270%
  271%   Raise an error if tls(true) is specified but cannot be honoured,
  272%   rather than silently using a plain connection.
  273
  274check_tls(Address, Options) :-
  275    option(tls(true), Options),
  276    !,
  277    (   current_predicate(ssl_context/3)
  278    ->  (   Address = _Host:_Port
  279        ->  true
  280        ;   domain_error(tls_address, Address)
  281        )
  282    ;   existence_error(library, ssl)
  283    ).
  284check_tls(_, _).
  285
  286%!  tls_upgrade(+Address, +Raw, -Stream, +Options) is det.
  287%
  288%   Upgrade to a TLS connection when tls(true) is specified.
  289
  290:- if(current_predicate(ssl_context/3)).  291tls_upgrade(Host:_Port, Raw, Stream, Options) :-
  292    option(tls(true), Options),
  293    !,
  294    must_have_option(cacert(CacertFile), Options),
  295    must_have_option(key(KeyFile), Options),
  296    must_have_option(cert(CertFile), Options),
  297    ssl_context(client, SSL,
  298		[ host(Host),
  299		  certificate_file(CertFile),
  300		  key_file(KeyFile),
  301		  cacerts([file(CacertFile)]),
  302		  cert_verify_hook(tls_verify),
  303		  close_parent(true)
  304		]),
  305    stream_pair(Raw, RawRead, RawWrite),
  306    ssl_negotiate(SSL, RawRead, RawWrite, Read, Write),
  307    stream_pair(Stream, Read, Write).
  308:- endif.  309tls_upgrade(_, Stream, Stream, _).
  310
  311:- if(current_predicate(ssl_context/3)).  312
  313%!  tls_verify(+SSL, +ProblemCert, +AllCerts, +FirstCert, +Status) is semidet.
  314%
  315%   Accept  or reject  the certificate  verification.  Similar  to the
  316%   Redis  command   line  client   (``redis-cli``),  we   accept  the
  317%   certificate as long as it is signed, not verifying the hostname.
  318
  319:- public tls_verify/5.  320tls_verify(_SSL, _ProblemCert, _AllCerts, _FirstCert, verified) :-
  321    !.
  322tls_verify(_SSL, _ProblemCert, _AllCerts, _FirstCert, hostname_mismatch) :-
  323    !.
  324tls_verify(_SSL, _ProblemCert, _AllCerts, _FirstCert, _Error) :-
  325    fail.
  326
  327:- endif.  328
  329%!  sentinel_master(+ServerId, +SentinelPool, -Connection, +Options) is det.
  330%
  331%   Discover the master and connect to it.
  332
  333sentinel_master(Id, Pool, Master, Options) :-
  334    sentinel_connect(Id, Pool, Conn, Options),
  335    setting(sentinel_timeout, TMO),
  336    call_cleanup(
  337	query_sentinel(Pool, Conn, MasterAddr),
  338	redis_disconnect(Conn)),
  339    debug(redis(sentinel), 'Sentinel claims master is at ~p', [MasterAddr]),
  340    do_connect(Id, MasterAddr, Master, Options),
  341    debug(redis(sentinel), 'Connected to claimed master', []),
  342    redis(Master, role, Role),
  343    (   Role = [master|_Slaves]
  344    ->  debug(redis(sentinel), 'Verified role at ~p', [MasterAddr])
  345    ;   redis_disconnect(Master),
  346	debug(redis(sentinel), '~p is not the master: ~p', [MasterAddr, Role]),
  347	sleep(TMO),
  348	sentinel_master(Id, Pool, Master, Options)
  349    ).
  350
  351sentinel_connect(Id, Pool, Conn, Options) :-
  352    must_have_option(sentinels(Sentinels), Options),
  353    sentinel_auth(Options, Options1),
  354    setting(sentinel_timeout, TMO),
  355    (   sentinel(Pool, Sentinel)
  356    ;   member(Sentinel, Sentinels)
  357    ),
  358    catch(call_with_time_limit(
  359	      TMO,
  360	      do_connect(Id, Sentinel, Conn,
  361			 [sentinel(true)|Options1])),
  362	  Error,
  363	  (print_message(warning, Error),fail)),
  364    !,
  365    debug(redis(sentinel), 'Connected to sentinel at ~p', [Sentinel]),
  366    redis(Conn, sentinel(sentinels, Pool), Peers),
  367    transaction(update_known_sentinels(Pool, Sentinel, Peers)).
  368
  369sentinel_auth(Options0, Options) :-
  370    option(sentinel_user(User), Options0),
  371    option(sentinel_password(Passwd), Options0),
  372    !,
  373    merge_options([user(User), password(Passwd)], Options0, Options).
  374sentinel_auth(Options0, Options) :-
  375    select_option(password(_), Options0, Options, _).
  376
  377
  378query_sentinel(Pool, Conn, Host:Port) :-
  379    redis(Conn, sentinel('get-master-addr-by-name', Pool), MasterData),
  380    MasterData = [Host,Port].
  381
  382update_known_sentinels(Pool, Sentinel, Peers) :-
  383    retractall(sentinel(Pool, _)),
  384    maplist(update_peer_sentinel(Pool), Peers),
  385    asserta(sentinel(Pool, Sentinel)).
  386
  387update_peer_sentinel(Pool, Attrs),
  388  memberchk(ip-Host, Attrs),
  389  memberchk(port-Port, Attrs) =>
  390    asserta(sentinel(Pool, Host:Port)).
  391
  392must_have_option(Opt, Options) :-
  393    option(Opt, Options),
  394    !.
  395must_have_option(Opt, Options) :-
  396    existence_error(option, Opt, Options).
  397
  398%!  sentinel_slave(+ServerId, +Pool, -Slave, +Options) is nondet.
  399%
  400%   True when Slave is a slave server  in the sentinel cluster. Slave is
  401%   a dict holding the keys and values as described by the Redis command
  402%
  403%       SENTINEL SLAVES mastername
  404
  405sentinel_slave(ServerId, Pool, Slave, Options) :-
  406    sentinel_connect(ServerId, Pool, Conn, Options),
  407    redis(Conn, sentinel(slaves, Pool), Slaves),
  408    member(Pairs, Slaves),
  409    dict_create(Slave, redis, Pairs).
  410
  411%!  hello(+Connection, +Option)
  412%
  413%   Initialize the connection. This is  used   to  upgrade  to the RESP3
  414%   protocol and/or to authenticate.
  415
  416hello(Con, Options) :-
  417    option(version(V), Options),
  418    V >= 3,
  419    !,
  420    (   option(user(User), Options),
  421        option(password(Password), Options)
  422    ->  redis(Con, hello(3, auth, User, Password))
  423    ;   redis(Con, hello(3))
  424    ).
  425hello(Con, Options) :-
  426    option(password(Password), Options),
  427    !,
  428    redis(Con, auth(Password)).
  429hello(_, _).
  430
  431%!  redis_stream(+Spec, --Stream, +DoConnect) is det.
  432%
  433%   Get the stream to a Redis server from  Spec. Spec is either the name
  434%   of       a       registered       server       or       a       term
  435%   redis_connection(Id,Stream,Failures,Options).  If  the    stream  is
  436%   disconnected it will be reconnected.
  437
  438redis_stream(Var, S, _) :-
  439    (   var(Var)
  440    ->  !, instantiation_error(Var)
  441    ;   nonvar(S)
  442    ->  !, uninstantiation_error(S)
  443    ).
  444redis_stream(ServerName, S, Connect) :-
  445    atom(ServerName),
  446    !,
  447    (   connection(ServerName, S0)
  448    ->  S = S0
  449    ;   Connect == true,
  450        server(ServerName, Address, Options)
  451    ->  redis_connect(Address, Connection, Options),
  452        redis_stream(Connection, S, false),
  453        asserta(connection(ServerName, S))
  454    ;   existence_error(redis_server, ServerName)
  455    ).
  456redis_stream(redis_connection(_,S0,_,_), S, _) :-
  457    S0 \== (-),
  458    !,
  459    S = S0.
  460redis_stream(Redis, S, _) :-
  461    Redis = redis_connection(Id,-,_,Options),
  462    option(address(Address), Options),
  463    do_connect(Id,Address,Redis2,Options),
  464    arg(2, Redis2, S0),
  465    nb_setarg(2, Redis, S0),
  466    S = S0.
  467
  468has_redis_stream(Var, _) :-
  469    var(Var),
  470    !,
  471    instantiation_error(Var).
  472has_redis_stream(Alias, S) :-
  473    atom(Alias),
  474    !,
  475    connection(Alias, S).
  476has_redis_stream(redis_connection(_,S,_,_), S) :-
  477    S \== (-).
  478
  479
  480%!  redis_disconnect(+Connection) is det.
  481%!  redis_disconnect(+Connection, +Options) is det.
  482%
  483%   Disconnect from a redis server. The   second  form takes one option,
  484%   similar to close/2:
  485%
  486%     - force(Force)
  487%       When `true` (default `false`), do not raise any errors if
  488%       Connection does not exist or closing the connection raises
  489%       a network or I/O related exception.  This version is used
  490%       internally if a connection is in a broken state, either due
  491%       to a protocol error or a network issue.
  492
  493redis_disconnect(Redis) :-
  494    redis_disconnect(Redis, []).
  495
  496redis_disconnect(Redis, Options) :-
  497    option(force(true), Options),
  498    !,
  499    (   Redis = redis_connection(_Id, S, _, _Opts)
  500    ->  (   S == (-)
  501        ->  true
  502        ;   close(S, [force(true)]),
  503            nb_setarg(2, Redis, -)
  504        )
  505    ;   has_redis_stream(Redis, S)
  506    ->  close(S, [force(true)]),
  507        retractall(connection(_,S))
  508    ;   true
  509    ).
  510redis_disconnect(Redis, _Options) :-
  511    redis_stream(Redis, S, false),
  512    close(S),
  513    retractall(connection(_,S)).
  514
  515%!  redis(+Connection, +Request) is semidet.
  516%
  517%   This predicate is overloaded to handle two types of requests. First,
  518%   it is a shorthand for `redis(Connection, Command, _)` and second, it
  519%   can be used to exploit  Redis   _pipelines_  and _transactions_. The
  520%   second form is acticated if Request is  a _list_. In that case, each
  521%   element of the list is either a term  `Command -> Reply` or a simple
  522%   `Command`. Semantically this represents a   sequence  of redis/3 and
  523%   redis/2 calls.  It differs in the following aspects:
  524%
  525%     - All commands are sent in one batch, after which all replies are
  526%       read.  This reduces the number of _round trips_ and typically
  527%       greatly improves performance.
  528%     - If the first command is `multi` and the last `exec`, the
  529%       commands are executed as a Redis _transaction_, i.e., they
  530%       are executed _atomically_.
  531%     - If one of the commands returns an error, the subsequent commands
  532%       __are still executed__.
  533%     - You can not use variables from commands earlier in the list for
  534%       commands later in the list as a result of the above execution
  535%       order.
  536%
  537%   Procedurally, the process takes the following steps:
  538%
  539%     1. Send all commands
  540%     2. Read all replies and push messages
  541%     3. Handle all callbacks from push messages
  542%     4. Check whether one of the replies is an error.  If so,
  543%        raise this error (subsequent errors are lost)
  544%     5. Bind all replies for the `Command -> Reply` terms.
  545%
  546%   Examples
  547%
  548%   ```
  549%   ?- redis(default,
  550%            [ lpush(li,1),
  551%              lpush(li,2),
  552%              lrange(li,0,-1) -> List
  553%            ]).
  554%   List = ["2", "1"].
  555%   ```
  556
  557redis(Redis, PipeLine) :-
  558    is_list(PipeLine),
  559    !,
  560    redis_pipeline(Redis, PipeLine).
  561redis(Redis, Req) :-
  562    redis(Redis, Req, _).
  563
  564%!  redis(+Connection, +Command, -Reply) is semidet.
  565%
  566%   Execute a redis Command on  Connnection.   Next,  bind  Reply to the
  567%   returned result. Command is a  callable   term  whose functor is the
  568%   name of the Redis command  and   whose  arguments  are translated to
  569%   Redis arguments according to the rules below.  Note that all text is
  570%   always represented using UTF-8 encoding.
  571%
  572%     - Atomic values are emitted verbatim
  573%     - A term A:B:... where all arguments are either atoms,
  574%       strings or integers (__no floats__) is translated into
  575%       a string `"A:B:..."`.  This is a common shorthand for
  576%       representing Redis keys.
  577%     - A term Term as prolog is emitted as "\u0000T\u0000" followed
  578%       by Term in canonical form.
  579%     - Any other term is emitted as write/1.
  580%
  581%   Reply is either a plain term (often a  variable) or a term `Value as
  582%   Type`. In the latter form,  `Type`   dictates  how  the Redis _bulk_
  583%   reply is translated to Prolog. The default equals to `auto`, i.e.,
  584%   as a number of the content satisfies the Prolog number syntax and
  585%   as an atom otherwise.
  586%
  587%     - status(Atom)
  588%       Returned if the server replies with ``+ Status``.  Atom
  589%       is the textual value of `Status` converted to lower case,
  590%       e.g., status(ok) or status(pong).
  591%     - `nil`
  592%       This atom is returned for a NIL/NULL value.  Note that if
  593%       the reply is only `nil`, redis/3 _fails_.  The `nil` value
  594%       may be embedded inside lists or maps.
  595%     - A number
  596%       Returned if the server replies an integer (":Int"), double
  597%       (",Num") or big integer ("(Num")
  598%     - A string
  599%       Returned on a _bulk_ reply.  Bulk replies are supposed to be
  600%       in UTF-8 encoding.  The the bulk reply starts with
  601%       "\u0000T\u0000" it is supposed to be a Prolog term.
  602%       Note that this intepretation means it is __not__ possible
  603%       to read arbitrary binary blobs.
  604%     - A list of replies.  A list may also contain `nil`.  If Reply
  605%       as a whole would be `nil` the call fails.
  606%     - A list of _pairs_.  This is returned for the redis version 3
  607%       protocol "%Map".  Both the key and value respect the same
  608%       rules as above.
  609%
  610%   Redis _bulk_ replies are translated depending  on the `as` `Type` as
  611%   explained above.
  612%
  613%     - string
  614%     - string(Encoding)
  615%       Create a SWI-Prolog string object interpreting the blob as
  616%       following Encoding. Encoding is a restricted set of SWI-Prolog's
  617%       encodings: `bytes` (`iso_latin_1`), `utf8` and `text` (the
  618%       current locale translation).
  619%     - atom
  620%     - atom(Encoding)
  621%       As above, producing an atom.
  622%     - codes
  623%     - codes(Encoding)
  624%       As above, producing a list of integers (Unicode code points)
  625%     - chars
  626%     - chars(Encoding)
  627%       As above, producing a list of one-character atoms.
  628%     - integer
  629%     - float
  630%     - rational
  631%     - number
  632%       Interpret the bytes as a string representing a number.  If
  633%       the string does not represent a number of the requested type
  634%       a type_error(Type, String) is raised.
  635%     - tagged_integer
  636%       Same as integer, but demands the value to be between the Prolog
  637%       flags `min_tagged_integer` and `max_tagged_integer`, allowing
  638%       the value to be used as a dict key.
  639%     - auto
  640%       Same as auto(atom, number)
  641%     - auto(AsText,AsNumber)
  642%       If the bulk string confirms the syntax of AsNumber, convert
  643%       the value to the requested numberical type.  Else convert
  644%       the value to text according to AsText.  This is similar to
  645%       the Prolog predicate name/2.
  646%     - dict_key
  647%       Alias for auto(atom,tagged_integer).  This allows the value
  648%       to be used as a key for a SWI-Prolog dict.
  649%     - pairs(AsKey, AsValue)
  650%       Convert a map or array of even length into pairs for which the
  651%       key satisfies AsKey and the value AsValue.  The `pairs` type
  652%       can also be applied to a Redis array.  In this case the array
  653%       length must be even.  This notably allows fetching a Redis
  654%       _hash_ as pairs using ``HGETALL`` using version 2 of the
  655%       Redis protocol.
  656%     - dict(AsKey, AsValue)
  657%       Similar to pairs(AsKey, AsValue), but convert the resulting
  658%       pair list into a SWI-Prolog dict.  AsKey must convert to a
  659%       valid dict key, i.e., an atom or tagged integer. See `dict_key`.
  660%     - dict(AsValue)
  661%       Shorthand for dict(dict_key, AsValue).
  662%
  663%   Here are some simple examples
  664%
  665%   ```
  666%   ?- redis(default, set(a, 42), X).
  667%   X = status("OK").
  668%   ?- redis(default, get(a), X).
  669%   X = "42".
  670%   ?- redis(default, get(a), X as integer).
  671%   X = 42.
  672%   ?- redis(default, get(a), X as float).
  673%   X = 42.0.
  674%   ?- redis(default, set(swipl:version, 8)).
  675%   true.
  676%   ?- redis(default, incr(swipl:version), X).
  677%   X = 9.
  678%   ```
  679%
  680%   @error redis_error(Code, String)
  681
  682redis(Redis, Req, Out) :-
  683    out_val(Out, Val),
  684    redis1(Redis, Req, Out),
  685    Val \== nil.
  686
  687out_val(Out, Val) :-
  688    (   nonvar(Out),
  689        Out = (Val as _)
  690    ->  true
  691    ;   Val = Out
  692    ).
  693
  694redis1(Redis, Req, Out) :-
  695    Error = error(Formal, _),
  696    catch(redis2(Redis, Req, Out), Error, true),
  697    (   var(Formal)
  698    ->  true
  699    ;   recover(Error, Redis, redis1(Redis, Req, Out))
  700    ).
  701
  702redis2(Redis, Req, Out) :-
  703    atom(Redis),
  704    !,
  705    redis_stream(Redis, S, true),
  706    with_mutex(Redis,
  707               ( redis_write_msg(S, Req),
  708                 redis_read_stream(Redis, S, Out)
  709               )).
  710redis2(Redis, Req, Out) :-
  711    redis_stream(Redis, S, true),
  712    redis_write_msg(S, Req),
  713    redis_read_stream(Redis, S, Out).
  714
  715%!  redis_pipeline(+Redis, +PipeLine)
  716
  717redis_pipeline(Redis, PipeLine) :-
  718    Error = error(Formal, _),
  719    catch(redis_pipeline2(Redis, PipeLine), Error, true),
  720    (   var(Formal)
  721    ->  true
  722    ;   recover(Error, Redis, redis_pipeline(Redis, PipeLine))
  723    ).
  724
  725redis_pipeline2(Redis, PipeLine) :-
  726    atom(Redis),
  727    !,
  728    redis_stream(Redis, S, true),
  729    with_mutex(Redis,
  730               redis_pipeline3(Redis, S, PipeLine)).
  731redis_pipeline2(Redis, PipeLine) :-
  732    redis_stream(Redis, S, true),
  733    redis_pipeline3(Redis, S, PipeLine).
  734
  735redis_pipeline3(Redis, S, PipeLine) :-
  736    maplist(write_pipeline(S), PipeLine),
  737    flush_output(S),
  738    read_pipeline(Redis, S, PipeLine).
  739
  740write_pipeline(S, Command -> _Reply) :-
  741    !,
  742    redis_write_msg_no_flush(S, Command).
  743write_pipeline(S, Command) :-
  744    redis_write_msg_no_flush(S, Command).
  745
  746read_pipeline(Redis, S, PipeLine) :-
  747    E = error(Formal,_),
  748    catch(read_pipeline2(Redis, S, PipeLine), E, true),
  749    (   var(Formal)
  750    ->  true
  751    ;   reconnect_error(E)
  752    ->  redis_disconnect(Redis, [force(true)]),
  753        throw(E)
  754    ;   resync(Redis),
  755        throw(E)
  756    ).
  757
  758read_pipeline2(Redis, S, PipeLine) :-
  759    maplist(redis_read_msg3(S), PipeLine, Replies, Errors, Pushed),
  760    maplist(handle_push(Redis), Pushed),
  761    maplist(handle_error, Errors),
  762    maplist(bind_reply, PipeLine, Replies).
  763
  764redis_read_msg3(S, _Command -> ReplyIn, Reply, Error, Push) :-
  765    !,
  766    redis_read_msg(S, ReplyIn, Reply, Error, Push).
  767redis_read_msg3(S, Var, Reply, Error, Push) :-
  768    redis_read_msg(S, Var, Reply, Error, Push).
  769
  770handle_push(Redis, Pushed) :-
  771    handle_push_messages(Pushed, Redis).
  772handle_error(Error) :-
  773    (   var(Error)
  774    ->  true
  775    ;   throw(Error)
  776    ).
  777bind_reply(_Command -> Reply0, Reply) :-
  778    !,
  779    Reply0 = Reply.
  780bind_reply(_Command, _).
  781
  782
  783%!  recover(+Error, +Redis, :Goal)
  784%
  785%   Error happened while running Goal on Redis. If this is a recoverable
  786%   error (i.e., a network or disconnected peer),  wait a little and try
  787%   running Goal again.
  788
  789:- meta_predicate recover(+, +, 0).  790
  791recover(Error, Redis, Goal) :-
  792    Error = error(Formal, _),
  793    reconnect_error(Formal),
  794    auto_reconnect(Redis),
  795    !,
  796    debug(redis(recover), '~p: got error ~p; trying to reconnect',
  797          [Redis, Error]),
  798    redis_disconnect(Redis, [force(true)]),
  799    (   wait_to_retry(Redis, Error)
  800    ->  call(Goal),
  801        retractall(failure(Redis, _))
  802    ;   throw(Error)
  803    ).
  804recover(Error, _, _) :-
  805    throw(Error).
  806
  807auto_reconnect(redis_connection(_,_,_,Options)) :-
  808    !,
  809    option(reconnect(true), Options).
  810auto_reconnect(Server) :-
  811    ground(Server),
  812    server(Server, _, Options),
  813    option(reconnect(true), Options, true).
  814
  815reconnect_error(io_error(_Action, _On)).
  816reconnect_error(socket_error(_Code, _)).
  817reconnect_error(syntax_error(unexpected_eof)).
  818reconnect_error(existence_error(stream, _)).
  819
  820%!  wait(+Redis, +Error)
  821%
  822%   Wait for some time after a failure. First  we wait for 10ms. This is
  823%   doubled on each failure upto the   setting  `max_retry_wait`. If the
  824%   setting `max_retry_count` is exceeded we fail and the called signals
  825%   an exception.
  826
  827:- dynamic failure/2 as volatile.  828
  829wait_to_retry(Redis, Error) :-
  830    redis_failures(Redis, Failures),
  831    setting(max_retry_count, Count),
  832    Failures < Count,
  833    Failures2 is Failures+1,
  834    redis_set_failures(Redis, Failures2),
  835    setting(max_retry_wait, MaxWait),
  836    Wait is min(MaxWait*100, 1<<Failures)/100.0,
  837    debug(redis(recover), '  Sleeping ~p seconds', [Wait]),
  838    retry_message_level(Failures, Level),
  839    print_message(Level, redis(retry(Redis, Failures, Wait, Error))),
  840    sleep(Wait).
  841
  842redis_failures(redis_connection(_,_,Failures0,_), Failures) :-
  843    !,
  844    Failures = Failures0.
  845redis_failures(Server, Failures) :-
  846    atom(Server),
  847    (   failure(Server, Failures)
  848    ->  true
  849    ;   Failures = 0
  850    ).
  851
  852redis_set_failures(Connection, Count) :-
  853    compound(Connection),
  854    !,
  855    nb_setarg(3, Connection, Count).
  856redis_set_failures(Server, Count) :-
  857    atom(Server),
  858    retractall(failure(Server, _)),
  859    asserta(failure(Server, Count)).
  860
  861retry_message_level(0, warning) :- !.
  862retry_message_level(_, silent).
  863
  864
  865%!  redis(+Request)
  866%
  867%   Connect to the default redis server,   call  redist/3 using Request,
  868%   disconnect and print the result.  This   predicate  is  intended for
  869%   interactive usage.
  870
  871redis(Req) :-
  872    setup_call_cleanup(
  873        redis_connect(default, C, []),
  874        redis1(C, Req, Out),
  875        redis_disconnect(C)),
  876    print(Out).
  877
  878%!  redis_write(+Redis, +Command) is det.
  879%!  redis_read(+Redis, -Reply) is det.
  880%
  881%   Write command and read replies from a Redis server. These are
  882%   building blocks for subscribing to event streams.
  883
  884redis_write(Redis, Command) :-
  885    redis_stream(Redis, S, true),
  886    redis_write_msg(S, Command).
  887
  888redis_read(Redis, Reply) :-
  889    redis_stream(Redis, S, true),
  890    redis_read_stream(Redis, S, Reply).
  891
  892
  893		 /*******************************
  894		 *      HIGH LEVEL ACCESS	*
  895		 *******************************/
  896
  897%!  redis_get_list(+Redis, +Key, -List) is det.
  898%!  redis_get_list(+Redis, +Key, +ChunkSize, -List) is det.
  899%
  900%   Get the content of a Redis list in   List. If ChunkSize is given and
  901%   smaller than the list length, List is returned as a _lazy list_. The
  902%   actual values are requested using   redis  ``LRANGE`` requests. Note
  903%   that this results in O(N^2) complexity. Using   a  lazy list is most
  904%   useful for relatively short lists holding possibly large items.
  905%
  906%   Note that values retrieved are _strings_, unless the value was added
  907%   using `Term as prolog`.
  908%
  909%   It seems possible for ``LLEN`` to return   ``OK``. I don't know why.
  910%   As a work-around we return the empty list rather than an error.
  911%
  912%   @see lazy_list/2 for a discussion  on   the  difference between lazy
  913%   lists and normal lists.
  914
  915redis_get_list(Redis, Key, List) :-
  916    redis_get_list(Redis, Key, -1, List).
  917
  918redis_get_list(Redis, Key, Chunk, List) :-
  919    redis(Redis, llen(Key), Len),
  920    (   Len == status(ok)
  921    ->  List = []
  922    ;   (   Chunk >= Len
  923        ;   Chunk == -1
  924        )
  925    ->  (   Len == 0
  926        ->  List = []
  927        ;   End is Len-1,
  928            list_range(Redis, Key, 0, End, List)
  929        )
  930    ;   lazy_list(rlist_next(s(Redis,Key,0,Chunk,Len)), List)
  931    ).
  932
  933rlist_next(State, List, Tail) :-
  934    State = s(Redis,Key,Offset,Slice,Len),
  935    End is min(Len-1, Offset+Slice-1),
  936    list_range(Redis, Key, Offset, End, Elems),
  937    (   End =:= Len-1
  938    ->  List = Elems,
  939        Tail = []
  940    ;   Offset2 is Offset+Slice,
  941        nb_setarg(3, State, Offset2),
  942        append(Elems, Tail, List)
  943    ).
  944
  945% Redis LRANGE demands End > Start and returns inclusive.
  946
  947list_range(DB, Key, Start, Start, [Elem]) :-
  948    !,
  949    redis(DB, lindex(Key, Start), Elem).
  950list_range(DB, Key, Start, End, List) :-
  951    !,
  952    redis(DB, lrange(Key, Start, End), List).
  953
  954
  955
  956%!  redis_set_list(+Redis, +Key, +List) is det.
  957%
  958%   Associate a Redis key with a list.  As   Redis  has no concept of an
  959%   empty list, if List is `[]`, Key  is _deleted_. Note that key values
  960%   are always strings in  Redis.  The   same  conversion  rules  as for
  961%   redis/1-3 apply.
  962
  963redis_set_list(Redis, Key, List) :-
  964    redis(Redis, del(Key), _),
  965    (   List == []
  966    ->  true
  967    ;   Term =.. [rpush,Key|List],
  968        redis(Redis, Term, _Count)
  969    ).
  970
  971
  972%!  redis_get_hash(+Redis, +Key, -Data:dict) is det.
  973%!  redis_set_hash(+Redis, +Key, +Data:dict) is det.
  974%
  975%   Put/get a Redis hash as a Prolog  dict. Putting a dict first deletes
  976%   Key. Note that in many cases   applications will manage Redis hashes
  977%   by key. redis_get_hash/3 is notably a   user friendly alternative to
  978%   the Redis ``HGETALL`` command. If the  Redis   hash  is  not used by
  979%   other (non-Prolog) applications one  may   also  consider  using the
  980%   `Term as prolog` syntax to store the Prolog dict as-is.
  981
  982redis_get_hash(Redis, Key, Dict) :-
  983    redis(Redis, hgetall(Key), Dict as dict(auto)).
  984
  985redis_set_hash(Redis, Key, Dict) :-
  986    redis_array_dict(Array, _, Dict),
  987    Term =.. [hset,Key|Array],
  988    redis(Redis, del(Key), _),
  989    redis(Redis, Term, _Count).
  990
  991%!  redis_array_dict(?Array, ?Tag, ?Dict) is det.
  992%
  993%   Translate a Redis reply representing  hash   data  into a SWI-Prolog
  994%   dict. Array is either a list  of   alternating  keys and values or a
  995%   list of _pairs_. When translating to an array, this is always a list
  996%   of alternating keys and values.
  997%
  998%   @arg Tag is the SWI-Prolog dict tag.
  999
 1000redis_array_dict(Array, Tag, Dict) :-
 1001    nonvar(Array),
 1002    !,
 1003    array_to_pairs(Array, Pairs),
 1004    dict_pairs(Dict, Tag, Pairs).
 1005redis_array_dict(TwoList, Tag, Dict) :-
 1006    dict_pairs(Dict, Tag, Pairs),
 1007    pairs_to_array(Pairs, TwoList).
 1008
 1009array_to_pairs([], []) :-
 1010    !.
 1011array_to_pairs([NameS-Value|T0], [Name-Value|T]) :-
 1012    !,                                  % RESP3 returns a map as pairs.
 1013    atom_string(Name, NameS),
 1014    array_to_pairs(T0, T).
 1015array_to_pairs([NameS,Value|T0], [Name-Value|T]) :-
 1016    atom_string(Name, NameS),
 1017    array_to_pairs(T0, T).
 1018
 1019pairs_to_array([], []) :-
 1020    !.
 1021pairs_to_array([Name-Value|T0], [NameS,Value|T]) :-
 1022    atom_string(Name, NameS),
 1023    pairs_to_array(T0, T).
 1024
 1025%!  redis_scan(+Redis, -LazyList, +Options) is det.
 1026%!  redis_sscan(+Redis, +Set, -LazyList, +Options) is det.
 1027%!  redis_hscan(+Redis, +Hash, -LazyList, +Options) is det.
 1028%!  redis_zscan(+Redis, +Set, -LazyList, +Options) is det.
 1029%
 1030%   Map the Redis ``SCAN``, ``SSCAN``,   ``HSCAN`` and `ZSCAN`` commands
 1031%   into a _lazy list_. For redis_scan/3 and redis_sscan/4 the result is
 1032%   a list of strings. For redis_hscan/4   and redis_zscan/4, the result
 1033%   is a list of _pairs_.   Options processed:
 1034%
 1035%     - match(Pattern)
 1036%       Adds the ``MATCH`` subcommand, only returning matches for
 1037%       Pattern.
 1038%     - count(Count)
 1039%       Adds the ``COUNT`` subcommand, giving a hint to the size of the
 1040%       chunks fetched.
 1041%     - type(Type)
 1042%       Adds the ``TYPE`` subcommand, only returning answers of the
 1043%       indicated type.
 1044%
 1045%   @see lazy_list/2.
 1046
 1047redis_scan(Redis, LazyList, Options) :-
 1048    scan_options([match,count,type], Options, Parms),
 1049    lazy_list(scan_next(s(scan,Redis,0,Parms)), LazyList).
 1050
 1051redis_sscan(Redis, Set, LazyList, Options) :-
 1052    scan_options([match,count,type], Options, Parms),
 1053    lazy_list(scan_next(s(sscan(Set),Redis,0,Parms)), LazyList).
 1054
 1055redis_hscan(Redis, Hash, LazyList, Options) :-
 1056    scan_options([match,count,type], Options, Parms),
 1057    lazy_list(scan_next(s(hscan(Hash),Redis,0,Parms)), LazyList).
 1058
 1059redis_zscan(Redis, Set, LazyList, Options) :-
 1060    scan_options([match,count,type], Options, Parms),
 1061    lazy_list(scan_next(s(zscan(Set),Redis,0,Parms)), LazyList).
 1062
 1063scan_options([], _, []).
 1064scan_options([H|T0], Options, [H,V|T]) :-
 1065    Term =.. [H,V],
 1066    option(Term, Options),
 1067    !,
 1068    scan_options(T0, Options, T).
 1069scan_options([_|T0], Options, T) :-
 1070    scan_options(T0, Options, T).
 1071
 1072
 1073scan_next(State, List, Tail) :-
 1074    State = s(Command,Redis,Cursor,Params),
 1075    Command =.. CList,
 1076    append(CList, [Cursor|Params], CList2),
 1077    Term =.. CList2,
 1078    redis(Redis, Term, [NewCursor,Elems0]),
 1079    scan_pairs(Command, Elems0, Elems),
 1080    (   NewCursor == 0
 1081    ->  List = Elems,
 1082        Tail = []
 1083    ;   nb_setarg(3, State, NewCursor),
 1084        append(Elems, Tail, List)
 1085    ).
 1086
 1087scan_pairs(hscan(_), List, Pairs) :-
 1088    !,
 1089    scan_pairs(List, Pairs).
 1090scan_pairs(zscan(_), List, Pairs) :-
 1091    !,
 1092    scan_pairs(List, Pairs).
 1093scan_pairs(_, List, List).
 1094
 1095scan_pairs([], []).
 1096scan_pairs([Key,Value|T0], [Key-Value|T]) :-
 1097    !,
 1098    scan_pairs(T0, T).
 1099scan_pairs([Key-Value|T0], [Key-Value|T]) :-
 1100    scan_pairs(T0, T).
 1101
 1102
 1103		 /*******************************
 1104		 *              ABOUT		*
 1105		 *******************************/
 1106
 1107%!  redis_current_command(+Redis, ?Command) is nondet.
 1108%!  redis_current_command(+Redis, ?Command, -Properties) is nondet.
 1109%
 1110%   True when Command has Properties. Fails   if Command is not defined.
 1111%   The redis_current_command/3 version  returns   the  command argument
 1112%   specification. See Redis documentation for an explanation.
 1113
 1114redis_current_command(Redis, Command) :-
 1115    redis_current_command(Redis, Command, _).
 1116
 1117redis_current_command(Redis, Command, Properties) :-
 1118    nonvar(Command),
 1119    !,
 1120    redis(Redis, command(info, Command), [[_|Properties]]).
 1121redis_current_command(Redis, Command, Properties) :-
 1122    redis(Redis, command, Commands),
 1123    member([Name|Properties], Commands),
 1124    atom_string(Command, Name).
 1125
 1126%!  redis_property(+Redis, ?Property) is nondet.
 1127%
 1128%   True if Property is a property of   the Redis server. Currently uses
 1129%   redis(info, String) and parses the result.   As  this is for machine
 1130%   usage, properties names *_human are skipped.
 1131
 1132redis_property(Redis, Property) :-
 1133    redis(Redis, info, String),
 1134    info_terms(String, Terms),
 1135    member(Property, Terms).
 1136
 1137info_terms(Info, Pairs) :-
 1138    split_string(Info, "\n", "\r\n ", Lines),
 1139    convlist(info_line_term, Lines, Pairs).
 1140
 1141info_line_term(Line, Term) :-
 1142    sub_string(Line, B, _, A, :),
 1143    !,
 1144    sub_atom(Line, 0, B, _, Name),
 1145    \+ sub_atom(Name, _, _, 0, '_human'),
 1146    sub_string(Line, _, A, 0, ValueS),
 1147    (   number_string(Value, ValueS)
 1148    ->  true
 1149    ;   Value = ValueS
 1150    ),
 1151    Term =.. [Name,Value].
 1152
 1153
 1154		 /*******************************
 1155		 *            SUBSCRIBE		*
 1156		 *******************************/
 1157
 1158%!  redis_subscribe(+Redis, +Channels, -Id, +Options) is det.
 1159%
 1160%   Subscribe to one or more  Redis   PUB/SUB  channels.  This predicate
 1161%   creates a thread using thread_create/3 with  the given Options. Once
 1162%   running, the thread listens for messages.   The message content is a
 1163%   string or Prolog term  as  described   in  redis/3.  On  receiving a
 1164%   message, the following message is broadcasted:
 1165%
 1166%       redis(Id, Channel, Data)
 1167%
 1168%   If redis_unsubscribe/2 removes the  last   subscription,  the thread
 1169%   terminates.
 1170%
 1171%   To simply print the incomming messages use e.g.
 1172%
 1173%       ?- listen(redis(_, Channel, Data),
 1174%                 format('Channel ~p got ~p~n', [Channel,Data])).
 1175%       true.
 1176%       ?- redis_subscribe(default, test, Id, []).
 1177%       Id = redis_pubsub_3,
 1178%       ?- redis(publish(test, "Hello world")).
 1179%       Channel test got "Hello world"
 1180%       1
 1181%       true.
 1182%
 1183%   @arg Id is the thread identifier of  the listening thread. Note that
 1184%   the Options alias(Name) can be used to get a system wide name.
 1185
 1186:- dynamic ( subscription/2,            % Id, Channel
 1187             listening/3                % Id, Connection, Thread
 1188           ) as volatile. 1189
 1190redis_subscribe(Redis, Spec, Id, Options) :-
 1191    atom(Redis),
 1192    !,
 1193    channels(Spec, Channels),
 1194    pubsub_thread_options(ThreadOptions, Options),
 1195    thread_create(setup_call_cleanup(
 1196                      redis_connect(Redis, Conn, [reconnect(true)]),
 1197                      redis_subscribe1(Redis, Conn, Channels),
 1198                      redis_disconnect(Conn)),
 1199                  Thread,
 1200                  ThreadOptions),
 1201    pubsub_id(Thread, Id).
 1202redis_subscribe(Redis, Spec, Id, Options) :-
 1203    channels(Spec, Channels),
 1204    pubsub_thread_options(ThreadOptions, Options),
 1205    thread_create(redis_subscribe1(Redis, Redis, Channels),
 1206                  Thread,
 1207                  ThreadOptions),
 1208    pubsub_id(Thread, Id).
 1209
 1210pubsub_thread_options(ThreadOptions, Options) :-
 1211    merge_options(Options, [detached(true)], ThreadOptions).
 1212
 1213pubsub_id(Thread, Thread).
 1214%pubsub_id(Thread, Id) :-
 1215%    thread_property(Thread, id(TID)),
 1216%    atom_concat('redis_pubsub_', TID, Id).
 1217
 1218redis_subscribe1(Redis, Conn, Channels) :-
 1219    Error = error(Formal, _),
 1220    catch(redis_subscribe2(Redis, Conn, Channels), Error, true),
 1221    (   var(Formal)
 1222    ->  true
 1223    ;   recover(Error, Conn, redis1(Conn, echo("reconnect"), _)),
 1224        thread_self(Me),
 1225        pubsub_id(Me, Id),
 1226        findall(Channel, subscription(Id, Channel), CurrentChannels),
 1227        redis_subscribe1(Redis, Conn, CurrentChannels)
 1228    ).
 1229
 1230redis_subscribe2(Redis, Conn, Channels) :-
 1231    redis_subscribe3(Conn, Channels),
 1232    redis_listen(Redis, Conn).
 1233
 1234redis_subscribe3(Conn, Channels) :-
 1235    thread_self(Me),
 1236    pubsub_id(Me, Id),
 1237    prolog_listen(this_thread_exit, pubsub_clean(Id)),
 1238    maplist(register_subscription(Id), Channels),
 1239    redis_stream(Conn, S, true),
 1240    Req =.. [subscribe|Channels],
 1241    redis_write_msg(S, Req).
 1242
 1243pubsub_clean(Id) :-
 1244    retractall(listening(Id, _Connection, _Thread)),
 1245    retractall(subscription(Id, _Channel)).
 1246
 1247%!  redis_subscribe(+Id, +Channels) is det.
 1248%!  redis_unsubscribe(+Id, +Channels) is det.
 1249%
 1250%   Add/remove channels from for the   subscription. If no subscriptions
 1251%   remain, the listening thread terminates.
 1252%
 1253%   @arg Channels is either a single  channel   or  a list thereof. Each
 1254%   channel specification is either an atom   or a term `A:B:...`, where
 1255%   all parts are atoms.
 1256
 1257redis_subscribe(Id, Spec) :-
 1258    channels(Spec, Channels),
 1259    (   listening(Id, Connection, _Thread)
 1260    ->  true
 1261    ;   existence_error(redis_pubsub, Id)
 1262    ),
 1263    maplist(register_subscription(Id), Channels),
 1264    redis_stream(Connection, S, true),
 1265    Req =.. [subscribe|Channels],
 1266    redis_write_msg(S, Req).
 1267
 1268redis_unsubscribe(Id, Spec) :-
 1269    channels(Spec, Channels),
 1270    (   listening(Id, Connection, _Thread)
 1271    ->  true
 1272    ;   existence_error(redis_pubsub, Id)
 1273    ),
 1274    maplist(unregister_subscription(Id), Channels),
 1275    redis_stream(Connection, S, true),
 1276    Req =.. [unsubscribe|Channels],
 1277    redis_write_msg(S, Req).
 1278
 1279%!  redis_current_subscription(?Id, ?Channels)
 1280%
 1281%   True when a PUB/SUB subscription with Id is listening on Channels.
 1282
 1283redis_current_subscription(Id, Channels) :-
 1284    findall(Id-Channel, subscription(Id, Channel), Pairs),
 1285    keysort(Pairs, Sorted),
 1286    group_pairs_by_key(Sorted, Grouped),
 1287    member(Id-Channels, Grouped).
 1288
 1289channels(Spec, List) :-
 1290    is_list(Spec),
 1291    !,
 1292    maplist(channel_name, Spec, List).
 1293channels(Ch, [Key]) :-
 1294    channel_name(Ch, Key).
 1295
 1296channel_name(Atom, Atom) :-
 1297    atom(Atom),
 1298    !.
 1299channel_name(Key, Atom) :-
 1300    phrase(key_parts(Key), Parts),
 1301    !,
 1302    atomic_list_concat(Parts, :, Atom).
 1303channel_name(Key, _) :-
 1304    type_error(redis_key, Key).
 1305
 1306key_parts(Var) -->
 1307    { var(Var), !, fail }.
 1308key_parts(Atom) -->
 1309    { atom(Atom) },
 1310    !,
 1311    [Atom].
 1312key_parts(A:B) -->
 1313    key_parts(A),
 1314    key_parts(B).
 1315
 1316
 1317
 1318
 1319register_subscription(Id, Channel) :-
 1320    (   subscription(Id, Channel)
 1321    ->  true
 1322    ;   assertz(subscription(Id, Channel))
 1323    ).
 1324
 1325unregister_subscription(Id, Channel) :-
 1326    retractall(subscription(Id, Channel)).
 1327
 1328redis_listen(Redis, Conn) :-
 1329    thread_self(Me),
 1330    pubsub_id(Me, Id),
 1331    setup_call_cleanup(
 1332        assertz(listening(Id, Conn, Me), Ref),
 1333        redis_listen_loop(Redis, Id, Conn),
 1334        erase(Ref)).
 1335
 1336redis_listen_loop(Redis, Id, Conn) :-
 1337    redis_stream(Conn, S, true),
 1338    (   subscription(Id, _)
 1339    ->  redis_read_stream(Redis, S, Reply),
 1340        redis_broadcast(Redis, Reply),
 1341        redis_listen_loop(Redis, Id, Conn)
 1342    ;   true
 1343    ).
 1344
 1345redis_broadcast(_, [subscribe, _Channel, _N]) :-
 1346    !.
 1347redis_broadcast(Redis, [message, Channel, Data]) :-
 1348    !,
 1349    catch(broadcast(redis(Redis, Channel, Data)),
 1350          Error,
 1351          print_message(error, Error)).
 1352redis_broadcast(Redis, Message) :-
 1353    assertion((Message = [Type, Channel, _Data],
 1354               atom(Type),
 1355               atom(Channel))),
 1356    debug(redis(warning), '~p: Unknown message while listening: ~p',
 1357          [Redis,Message]).
 1358
 1359
 1360		 /*******************************
 1361		 *          READ/WRITE		*
 1362		 *******************************/
 1363
 1364%!  redis_read_stream(+Redis, +Stream, -Term) is det.
 1365%
 1366%   Read a message from a Redis stream.  Term is one of
 1367%
 1368%     - A list of terms (array)
 1369%     - A list of pairs (map, RESP3 only)
 1370%     - The atom `nil`
 1371%     - A number
 1372%     - A term status(String)
 1373%     - A string
 1374%     - A boolean (`true` or `false`).  RESP3 only.
 1375%
 1376%   If something goes wrong, the connection   is closed and an exception
 1377%   is raised.
 1378
 1379redis_read_stream(Redis, SI, Out) :-
 1380    E = error(Formal,_),
 1381    catch(redis_read_msg(SI, Out, Out0, Error, Push), E, true),
 1382    (   var(Formal)
 1383    ->  handle_push_messages(Push, Redis),
 1384        (   var(Error)
 1385        ->  Out = Out0
 1386        ;   resync(Redis),
 1387            throw(Error)
 1388        )
 1389    ;   redis_disconnect(Redis, [force(true)]),
 1390        throw(E)
 1391    ).
 1392
 1393handle_push_messages([], _).
 1394handle_push_messages([H|T], Redis) :-
 1395    (   catch(handle_push_message(H, Redis), E,
 1396              print_message(warning, E))
 1397    ->  true
 1398    ;   true
 1399    ),
 1400    handle_push_messages(T, Redis).
 1401
 1402handle_push_message(["pubsub"|List], Redis) :-
 1403    redis_broadcast(Redis, List).
 1404% some protocol version 3 push messages (such as
 1405% __keyspace@* events) seem to come directly
 1406% without a pubsub header
 1407handle_push_message([message|List], Redis) :-
 1408    redis_broadcast(Redis, [message|List]).
 1409
 1410
 1411%!  resync(+Redis) is det.
 1412%
 1413%   Re-synchronize  after  an  error.  This  may  happen  if  some  type
 1414%   conversion fails and we have read  a   partial  reply. It is hard to
 1415%   figure out what to read from where we are, so we echo a random magic
 1416%   sequence and read until we find the reply.
 1417
 1418resync(Redis) :-
 1419    E = error(Formal,_),
 1420    catch(do_resync(Redis), E, true),
 1421    (   var(Formal)
 1422    ->  true
 1423    ;   redis_disconnect(Redis, [force(true)])
 1424    ).
 1425
 1426do_resync(Redis) :-
 1427    A is random(1_000_000_000),
 1428    redis_stream(Redis, S, true),
 1429    redis_write_msg(S, echo(A)),
 1430    catch(call_with_time_limit(0.2, '$redis_resync'(S, A)),
 1431          time_limit_exceeded,
 1432          throw(error(time_limit_exceeded,_))).
 1433
 1434
 1435%!  redis_read_msg(+Stream, -Message, -Error, -PushMessages) is det.
 1436%!  redis_write_msg(+Stream, +Message) is det.
 1437%
 1438%   Read/write a Redis message. Both these predicates are in the foreign
 1439%   module `redis4pl`.
 1440%
 1441%   @arg PushMessages is a list of push   messages that may be non-[] if
 1442%   protocol version 3 (see redis_connect/3) is selected. Using protocol
 1443%   version 2 this list is always empty.
 1444
 1445
 1446
 1447		 /*******************************
 1448		 *            MESSAGES		*
 1449		 *******************************/
 1450
 1451:- multifile
 1452    prolog:error_message//1,
 1453    prolog:message//1. 1454
 1455prolog:error_message(redis_error(Code, String)) -->
 1456    [ 'REDIS: ~w: ~s'-[Code, String] ].
 1457
 1458prolog:message(redis(retry(_Redis, _Failures, Wait, Error))) -->
 1459    [ 'REDIS: connection error.  Retrying in ~2f seconds'-[Wait], nl ],
 1460    [ '    '-[] ], '$messages':translate_message(Error)