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)]).
151:- dynamic server/3. 152 153:- dynamic ( connection/2, % ServerName, Stream 154 sentinel/2 % Pool, Address 155 ) as volatile.
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(+Address,
-Connection, +Options). redis_connect/1 is equivalent to
redis_connect(localhost:6379, Connection, []). Options:
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.version(3) and password(Password) are specified, these
are used to authenticate using the HELLO command.3, the HELLO command is used to upgrade the protocol.cacert, key and cert
options.sentinel(MasterName)
to enable contacting a network of Redis servers guarded by a
sentinel network.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.
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]).
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).
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(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)).
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.
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 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).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_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 \== (-).
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, 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:
multi and the last exec, the
commands are executed as a Redis transaction, i.e., they
are executed atomically.Procedurally, the process takes the following steps:
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, _).
"A:B:...". This is a common shorthand for
representing Redis keys.
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.
status(Atom)
Returned if the server replies with + Status. Atom
is the textual value of Status converted to lower case,
e.g., status(ok) or status(pong).nil
This atom is returned for a NIL/NULL value. Note that if
the reply is only nil, redis/3 fails. The nil value
may be embedded inside lists or maps.nil. If Reply
as a whole would be nil the call fails.
Redis bulk replies are translated depending on the as Type as
explained above.
bytes (iso_latin_1), utf8 and text (the
current locale translation).type_error(Type, String) is raised.min_tagged_integer and max_tagged_integer, allowing
the value to be used as a dict key.auto(atom, number)auto(atom,tagged_integer). This allows the value
to be used as a key for a SWI-Prolog dict.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.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(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.
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).
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, _).
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, _)).
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).
871redis(Req) :-
872 setup_call_cleanup(
873 redis_connect(default, C, []),
874 redis1(C, Req, Out),
875 redis_disconnect(C)),
876 print(Out).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 *******************************/
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.
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).
[], 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 ).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).
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).
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 subcommand, only returning matches for
Pattern.COUNT subcommand, giving a hint to the size of the
chunks fetched.TYPE subcommand, only returning answers of the
indicated type.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 *******************************/
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(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(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.
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)).
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).
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 *******************************/
nilstatus(String)true or false). RESP3 only.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]).
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,_))).
redis4pl.
1447 /******************************* 1448 * MESSAGES * 1449 *******************************/ 1450 1451:- multifile 1452 prolog:error_message//1, 1453 prolog:message//1. 1454 1455prologerror_message(redis_error(Code, String)) --> 1456 [ 'REDIS: ~w: ~s'-[Code, String] ]. 1457 1458prologmessage(redis(retry(_Redis, _Failures, Wait, Error))) --> 1459 [ 'REDIS: connection error. Retrying in ~2f seconds'-[Wait], nl ], 1460 [ ' '-[] ], '$messages':translate_message(Error)
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"