View source with raw 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)]).

Redis client

This library is a client to Redis, a popular key value store to deal with caching and communication between micro services.

In the typical use case we register the details of one or more Redis servers using redis_server/3. Subsequenly, redis/2-3 is used to issue commands on the server. For example:

?- redis_server(default, redis:6379, [password("secret")]).
?- redis(default, set(user, "Bob")).
?- redis(default, get(user), User).
User = "Bob"
  151:- dynamic server/3.  152
  153:- dynamic ( connection/2,              % ServerName, Stream
  154	     sentinel/2			% Pool, Address
  155           ) as volatile.
 redis_server(+ServerName, +Address, +Options) is det
Register a redis server without connecting to it. The ServerName acts as a lazy connection alias. Initially the ServerName default points at localhost:6379 with no connect options. The default server is used for redis/1 and redis/2 and may be changed using this predicate. Options are described with redis_connect/3.

Connections established this way are by default automatically reconnected if the connection is lost for some reason unless a reconnect(false) option is specified.

  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, []).
 redis_connect(-Connection) is det
 redis_connect(+Address, -Connection, +Options) is det
redis_connect(-Connection, +Host, +Port) is det
Connect to a redis server. The main mode is redis_connect(+Address, -Connection, +Options). redis_connect/1 is equivalent to redis_connect(localhost:6379, Connection, []). Options:
reconnect(+Boolean)
If true, try to reconnect to the service when the connection seems lost. Default is true for connections specified using redis_server/3 and false for explictly opened connections.
user(+User)
If version(3) and password(Password) are specified, these are used to authenticate using the HELLO command.
password(+Password)
Authenticate using Password
version(+Version)
Specify the connection protocol version. Initially this is version 2. Redis 6 also supports version 3. When specified as 3, the HELLO command is used to upgrade the protocol.
tls(true)
When specified, initiate a TLS connection. If this option is specified we must also specify the cacert, key and cert options.
cacert(+File)
CA Certificate file to verify with.
cert(+File)
Client certificate to authenticate with.
key(+File)
Private key file to authenticate with.
sentinels(+ListOfAddresses)
Used together with an Address of the form sentinel(MasterName) to enable contacting a network of Redis servers guarded by a sentinel network.
sentinel_user(+User)
sentinel_password(+Password)
Authentication information for the senitels. When omitted we try to connect withour authentication.

Instead of using these predicates, redis/2 and redis/3 are normally used with a server name argument registered using redis_server/3. These predicates are meant for creating a temporary paralel connection or using a connection with a blocking call.

Arguments:
Address- is a term Host:Port, unix(File) or the name of a server registered using redis_server/3. The latter realises a new connection that is typically used for blocking redis commands such as listening for published messages, waiting on a list or stream.
Compatibility
- redis_connect(-Connection, +Host, +Port) provides compatibility to the original GNU-Prolog interface and is equivalent to redis_connect(Host:Port, Connection, []).
  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]).
 do_connect(+Id, +Address, -Conn, +Options)
Open the connection. A connection is a compound term of the shape
redis_connection(Id, Stream, Failures, Options)
  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).
 check_tls(+Address, +Options) is det
Raise an error if tls(true) is specified but cannot be honoured, rather than silently using a plain connection.
  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(_, _).
 tls_upgrade(+Address, +Raw, -Stream, +Options) is det
Upgrade to a TLS connection when tls(true) is specified.
  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)).
 tls_verify(+SSL, +ProblemCert, +AllCerts, +FirstCert, +Status) is semidet
Accept or reject the certificate verification. Similar to the Redis command line client (redis-cli), we accept the certificate as long as it is signed, not verifying the hostname.
  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.
 sentinel_master(+ServerId, +SentinelPool, -Connection, +Options) is det
Discover the master and connect to it.
  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).
 sentinel_slave(+ServerId, +Pool, -Slave, +Options) is nondet
True when Slave is a slave server in the sentinel cluster. Slave is a dict holding the keys and values as described by the Redis command
SENTINEL SLAVES mastername
  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).
 hello(+Connection, +Option)
Initialize the connection. This is used to upgrade to the RESP3 protocol and/or to authenticate.
  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(_, _).
 redis_stream(+Spec, --Stream, +DoConnect) is det
Get the stream to a Redis server from Spec. Spec is either the name of a registered server or a term redis_connection(Id,Stream,Failures,Options). If the stream is disconnected it will be reconnected.
  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 \== (-).
 redis_disconnect(+Connection) is det
 redis_disconnect(+Connection, +Options) is det
Disconnect from a redis server. The second form takes one option, similar to close/2:
force(Force)
When true (default false), do not raise any errors if Connection does not exist or closing the connection raises a network or I/O related exception. This version is used internally if a connection is in a broken state, either due to a protocol error or a network issue.
  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)).
 redis(+Connection, +Request) is semidet
This predicate is overloaded to handle two types of requests. First, it is a shorthand for redis(Connection, Command, _) and second, it can be used to exploit Redis pipelines and transactions. The second form is acticated if Request is a list. In that case, each element of the list is either a term Command -> Reply or a simple Command. Semantically this represents a sequence of redis/3 and redis/2 calls. It differs in the following aspects:

Procedurally, the process takes the following steps:

  1. Send all commands
  2. Read all replies and push messages
  3. Handle all callbacks from push messages
  4. Check whether one of the replies is an error. If so, raise this error (subsequent errors are lost)
  5. Bind all replies for the Command -> Reply terms.

Examples

?- redis(default,
         [ lpush(li,1),
           lpush(li,2),
           lrange(li,0,-1) -> List
         ]).
List = ["2", "1"].
  557redis(Redis, PipeLine) :-
  558    is_list(PipeLine),
  559    !,
  560    redis_pipeline(Redis, PipeLine).
  561redis(Redis, Req) :-
  562    redis(Redis, Req, _).
 redis(+Connection, +Command, -Reply) is semidet
Execute a redis Command on Connnection. Next, bind Reply to the returned result. Command is a callable term whose functor is the name of the Redis command and whose arguments are translated to Redis arguments according to the rules below. Note that all text is always represented using UTF-8 encoding.

Reply is either a plain term (often a variable) or a term Value as Type. In the latter form, Type dictates how the Redis bulk reply is translated to Prolog. The default equals to auto, i.e., as a number of the content satisfies the Prolog number syntax and as an atom otherwise.

Redis bulk replies are translated depending on the as Type as explained above.

string
string(Encoding)
Create a SWI-Prolog string object interpreting the blob as following Encoding. Encoding is a restricted set of SWI-Prolog's encodings: bytes (iso_latin_1), utf8 and text (the current locale translation).
atom
atom(Encoding)
As above, producing an atom.
codes
codes(Encoding)
As above, producing a list of integers (Unicode code points)
chars
chars(Encoding)
As above, producing a list of one-character atoms.
integer
float
rational
number
Interpret the bytes as a string representing a number. If the string does not represent a number of the requested type a type_error(Type, String) is raised.
tagged_integer
Same as integer, but demands the value to be between the Prolog flags min_tagged_integer and max_tagged_integer, allowing the value to be used as a dict key.
auto
Same as auto(atom, number)
auto(AsText, AsNumber)
If the bulk string confirms the syntax of AsNumber, convert the value to the requested numberical type. Else convert the value to text according to AsText. This is similar to the Prolog predicate name/2.
dict_key
Alias for auto(atom,tagged_integer). This allows the value to be used as a key for a SWI-Prolog dict.
pairs(AsKey, AsValue)
Convert a map or array of even length into pairs for which the key satisfies AsKey and the value AsValue. The pairs type can also be applied to a Redis array. In this case the array length must be even. This notably allows fetching a Redis hash as pairs using HGETALL using version 2 of the Redis protocol.
dict(AsKey, AsValue)
Similar to pairs(AsKey, AsValue), but convert the resulting pair list into a SWI-Prolog dict. AsKey must convert to a valid dict key, i.e., an atom or tagged integer. See dict_key.
dict(AsValue)
Shorthand for dict(dict_key, AsValue).

Here are some simple examples

?- redis(default, set(a, 42), X).
X = status("OK").
?- redis(default, get(a), X).
X = "42".
?- redis(default, get(a), X as integer).
X = 42.
?- redis(default, get(a), X as float).
X = 42.0.
?- redis(default, set(swipl:version, 8)).
true.
?- redis(default, incr(swipl:version), X).
X = 9.
Errors
- redis_error(Code, String)
  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).
 redis_pipeline(+Redis, +PipeLine)
  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, _).
 recover(+Error, +Redis, :Goal)
Error happened while running Goal on Redis. If this is a recoverable error (i.e., a network or disconnected peer), wait a little and try running Goal again.
  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, _)).
 wait(+Redis, +Error)
Wait for some time after a failure. First we wait for 10ms. This is doubled on each failure upto the setting max_retry_wait. If the setting max_retry_count is exceeded we fail and the called signals an exception.
  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).
 redis(+Request)
Connect to the default redis server, call redist/3 using Request, disconnect and print the result. This predicate is intended for interactive usage.
  871redis(Req) :-
  872    setup_call_cleanup(
  873        redis_connect(default, C, []),
  874        redis1(C, Req, Out),
  875        redis_disconnect(C)),
  876    print(Out).
 redis_write(+Redis, +Command) is det
 redis_read(+Redis, -Reply) is det
Write command and read replies from a Redis server. These are building blocks for subscribing to event streams.
  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		 *******************************/
 redis_get_list(+Redis, +Key, -List) is det
 redis_get_list(+Redis, +Key, +ChunkSize, -List) is det
Get the content of a Redis list in List. If ChunkSize is given and smaller than the list length, List is returned as a lazy list. The actual values are requested using redis LRANGE requests. Note that this results in O(N^2) complexity. Using a lazy list is most useful for relatively short lists holding possibly large items.

Note that values retrieved are strings, unless the value was added using Term as prolog.

It seems possible for LLEN to return OK. I don't know why. As a work-around we return the empty list rather than an error.

See also
- lazy_list/2 for a discussion on the difference between lazy lists and normal lists.
  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).
 redis_set_list(+Redis, +Key, +List) is det
Associate a Redis key with a list. As Redis has no concept of an empty list, if List is [], Key is deleted. Note that key values are always strings in Redis. The same conversion rules as for redis/1-3 apply.
  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    ).
 redis_get_hash(+Redis, +Key, -Data:dict) is det
 redis_set_hash(+Redis, +Key, +Data:dict) is det
Put/get a Redis hash as a Prolog dict. Putting a dict first deletes Key. Note that in many cases applications will manage Redis hashes by key. redis_get_hash/3 is notably a user friendly alternative to the Redis HGETALL command. If the Redis hash is not used by other (non-Prolog) applications one may also consider using the Term as prolog syntax to store the Prolog dict as-is.
  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).
 redis_array_dict(?Array, ?Tag, ?Dict) is det
Translate a Redis reply representing hash data into a SWI-Prolog dict. Array is either a list of alternating keys and values or a list of pairs. When translating to an array, this is always a list of alternating keys and values.
Arguments:
Tag- is the SWI-Prolog dict tag.
 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).
 redis_scan(+Redis, -LazyList, +Options) is det
 redis_sscan(+Redis, +Set, -LazyList, +Options) is det
 redis_hscan(+Redis, +Hash, -LazyList, +Options) is det
 redis_zscan(+Redis, +Set, -LazyList, +Options) is det
Map the Redis SCAN, SSCAN, HSCAN and ZSCAN` commands into a lazy list. For redis_scan/3 and redis_sscan/4 the result is a list of strings. For redis_hscan/4 and redis_zscan/4, the result is a list of pairs. Options processed:
match(Pattern)
Adds the MATCH subcommand, only returning matches for Pattern.
count(Count)
Adds the COUNT subcommand, giving a hint to the size of the chunks fetched.
type(Type)
Adds the TYPE subcommand, only returning answers of the indicated type.
See also
- lazy_list/2.
 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		 *******************************/
 redis_current_command(+Redis, ?Command) is nondet
 redis_current_command(+Redis, ?Command, -Properties) is nondet
True when Command has Properties. Fails if Command is not defined. The redis_current_command/3 version returns the command argument specification. See Redis documentation for an explanation.
 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).
 redis_property(+Redis, ?Property) is nondet
True if Property is a property of the Redis server. Currently uses redis(info, String) and parses the result. As this is for machine usage, properties names *_human are skipped.
 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		 *******************************/
 redis_subscribe(+Redis, +Channels, -Id, +Options) is det
Subscribe to one or more Redis PUB/SUB channels. This predicate creates a thread using thread_create/3 with the given Options. Once running, the thread listens for messages. The message content is a string or Prolog term as described in redis/3. On receiving a message, the following message is broadcasted:
redis(Id, Channel, Data)

If redis_unsubscribe/2 removes the last subscription, the thread terminates.

To simply print the incomming messages use e.g.

?- listen(redis(_, Channel, Data),
          format('Channel ~p got ~p~n', [Channel,Data])).
true.
?- redis_subscribe(default, test, Id, []).
Id = redis_pubsub_3,
?- redis(publish(test, "Hello world")).
Channel test got "Hello world"
1
true.
Arguments:
Id- is the thread identifier of the listening thread. Note that the Options alias(Name) can be used to get a system wide name.
 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)).
 redis_subscribe(+Id, +Channels) is det
 redis_unsubscribe(+Id, +Channels) is det
Add/remove channels from for the subscription. If no subscriptions remain, the listening thread terminates.
Arguments:
Channels- is either a single channel or a list thereof. Each channel specification is either an atom or a term `A:B:...`, where all parts are atoms.
 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).
 redis_current_subscription(?Id, ?Channels)
True when a PUB/SUB subscription with Id is listening on Channels.
 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		 *******************************/
 redis_read_stream(+Redis, +Stream, -Term) is det
Read a message from a Redis stream. Term is one of

If something goes wrong, the connection is closed and an exception is raised.

 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]).
 resync(+Redis) is det
Re-synchronize after an error. This may happen if some type conversion fails and we have read a partial reply. It is hard to figure out what to read from where we are, so we echo a random magic sequence and read until we find the reply.
 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,_))).
 redis_read_msg(+Stream, -Message, -Error, -PushMessages) is det
 redis_write_msg(+Stream, +Message) is det
Read/write a Redis message. Both these predicates are in the foreign module redis4pl.
Arguments:
PushMessages- is a list of push messages that may be non-[] if protocol version 3 (see redis_connect/3) is selected. Using protocol version 2 this list is always empty.
 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)