Coder Social home page Coder Social logo

redis / node-redis Goto Github PK

View Code? Open in Web Editor NEW
16.7K 16.7K 1.8K 106.12 MB

Redis Node.js client

Home Page: https://redis.js.org/

License: MIT License

TypeScript 99.34% Dockerfile 0.01% Shell 0.01% JavaScript 0.65%
node-redis nodejs redis redis-client redis-cluster

node-redis's Introduction

This README is just a fast quick start document. You can find more detailed documentation at redis.io.

What is Redis?

Redis is often referred to as a data structures server. What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a server-client model with TCP sockets and a simple protocol. So different processes can query and modify the same data structures in a shared way.

Data structures implemented into Redis have a few special properties:

  • Redis cares to store them on disk, even if they are always served and modified into the server memory. This means that Redis is fast, but that it is also non-volatile.
  • The implementation of data structures emphasizes memory efficiency, so data structures inside Redis will likely use less memory compared to the same data structure modelled using a high-level programming language.
  • Redis offers a number of features that are natural to find in a database, like replication, tunable levels of durability, clustering, and high availability.

Another good example is to think of Redis as a more complex version of memcached, where the operations are not just SETs and GETs, but operations that work with complex data types like Lists, Sets, ordered data structures, and so forth.

If you want to know more, this is a list of selected starting points:

Building Redis

Redis can be compiled and used on Linux, OSX, OpenBSD, NetBSD, FreeBSD. We support big endian and little endian architectures, and both 32 bit and 64 bit systems.

It may compile on Solaris derived systems (for instance SmartOS) but our support for this platform is best effort and Redis is not guaranteed to work as well as in Linux, OSX, and *BSD.

It is as simple as:

% make

To build with TLS support, you'll need OpenSSL development libraries (e.g. libssl-dev on Debian/Ubuntu) and run:

% make BUILD_TLS=yes

To build with systemd support, you'll need systemd development libraries (such as libsystemd-dev on Debian/Ubuntu or systemd-devel on CentOS) and run:

% make USE_SYSTEMD=yes

To append a suffix to Redis program names, use:

% make PROG_SUFFIX="-alt"

You can build a 32 bit Redis binary using:

% make 32bit

After building Redis, it is a good idea to test it using:

% make test

If TLS is built, running the tests with TLS enabled (you will need tcl-tls installed):

% ./utils/gen-test-certs.sh
% ./runtest --tls

Fixing build problems with dependencies or cached build options

Redis has some dependencies which are included in the deps directory. make does not automatically rebuild dependencies even if something in the source code of dependencies changes.

When you update the source code with git pull or when code inside the dependencies tree is modified in any other way, make sure to use the following command in order to really clean everything and rebuild from scratch:

% make distclean

This will clean: jemalloc, lua, hiredis, linenoise and other dependencies.

Also if you force certain build options like 32bit target, no C compiler optimizations (for debugging purposes), and other similar build time options, those options are cached indefinitely until you issue a make distclean command.

Fixing problems building 32 bit binaries

If after building Redis with a 32 bit target you need to rebuild it with a 64 bit target, or the other way around, you need to perform a make distclean in the root directory of the Redis distribution.

In case of build errors when trying to build a 32 bit binary of Redis, try the following steps:

  • Install the package libc6-dev-i386 (also try g++-multilib).
  • Try using the following command line instead of make 32bit: make CFLAGS="-m32 -march=native" LDFLAGS="-m32"

Allocator

Selecting a non-default memory allocator when building Redis is done by setting the MALLOC environment variable. Redis is compiled and linked against libc malloc by default, with the exception of jemalloc being the default on Linux systems. This default was picked because jemalloc has proven to have fewer fragmentation problems than libc malloc.

To force compiling against libc malloc, use:

% make MALLOC=libc

To compile against jemalloc on Mac OS X systems, use:

% make MALLOC=jemalloc

Monotonic clock

By default, Redis will build using the POSIX clock_gettime function as the monotonic clock source. On most modern systems, the internal processor clock can be used to improve performance. Cautions can be found here: http://oliveryang.net/2015/09/pitfalls-of-TSC-usage/

To build with support for the processor's internal instruction clock, use:

% make CFLAGS="-DUSE_PROCESSOR_CLOCK"

Verbose build

Redis will build with a user-friendly colorized output by default. If you want to see a more verbose output, use the following:

% make V=1

Running Redis

To run Redis with the default configuration, just type:

% cd src
% ./redis-server

If you want to provide your redis.conf, you have to run it using an additional parameter (the path of the configuration file):

% cd src
% ./redis-server /path/to/redis.conf

It is possible to alter the Redis configuration by passing parameters directly as options using the command line. Examples:

% ./redis-server --port 9999 --replicaof 127.0.0.1 6379
% ./redis-server /etc/redis/6379.conf --loglevel debug

All the options in redis.conf are also supported as options using the command line, with exactly the same name.

Running Redis with TLS:

Please consult the TLS.md file for more information on how to use Redis with TLS.

Playing with Redis

You can use redis-cli to play with Redis. Start a redis-server instance, then in another terminal try the following:

% cd src
% ./redis-cli
redis> ping
PONG
redis> set foo bar
OK
redis> get foo
"bar"
redis> incr mycounter
(integer) 1
redis> incr mycounter
(integer) 2
redis>

You can find the list of all the available commands at https://redis.io/commands.

Installing Redis

In order to install Redis binaries into /usr/local/bin, just use:

% make install

You can use make PREFIX=/some/other/directory install if you wish to use a different destination.

make install will just install binaries in your system, but will not configure init scripts and configuration files in the appropriate place. This is not needed if you just want to play a bit with Redis, but if you are installing it the proper way for a production system, we have a script that does this for Ubuntu and Debian systems:

% cd utils
% ./install_server.sh

Note: install_server.sh will not work on Mac OSX; it is built for Linux only.

The script will ask you a few questions and will setup everything you need to run Redis properly as a background daemon that will start again on system reboots.

You'll be able to stop and start Redis using the script named /etc/init.d/redis_<portnumber>, for instance /etc/init.d/redis_6379.

Code contributions

By contributing code to the Redis project in any form, including sending a pull request via GitHub, a code fragment or patch via private email or public discussion groups, you agree to release your code under the terms of the Redis Software Grant and Contributor License Agreement. Redis software contains contributions to the original Redis core project, which are owned by their contributors and licensed under the 3BSD license. Any copy of that license in this repository applies only to those contributions. Redis releases all Redis project versions from 7.4.x and thereafter under the RSALv2/SSPL dual-license as described in the LICENSE.txt file included in the Redis source distribution.

Please see the CONTRIBUTING.md file in this source distribution for more information. For security bugs and vulnerabilities, please see SECURITY.md.

Redis Trademarks

The purpose of a trademark is to identify the goods and services of a person or company without causing confusion. As the registered owner of its name and logo, Redis accepts certain limited uses of its trademarks but it has requirements that must be followed as described in its Trademark Guidelines available at: https://redis.com/legal/trademark-guidelines/.

Redis internals

If you are reading this README you are likely in front of a Github page or you just untarred the Redis distribution tar ball. In both the cases you are basically one step away from the source code, so here we explain the Redis source code layout, what is in each file as a general idea, the most important functions and structures inside the Redis server and so forth. We keep all the discussion at a high level without digging into the details since this document would be huge otherwise and our code base changes continuously, but a general idea should be a good starting point to understand more. Moreover most of the code is heavily commented and easy to follow.

Source code layout

The Redis root directory just contains this README, the Makefile which calls the real Makefile inside the src directory and an example configuration for Redis and Sentinel. You can find a few shell scripts that are used in order to execute the Redis, Redis Cluster and Redis Sentinel unit tests, which are implemented inside the tests directory.

Inside the root are the following important directories:

  • src: contains the Redis implementation, written in C.
  • tests: contains the unit tests, implemented in Tcl.
  • deps: contains libraries Redis uses. Everything needed to compile Redis is inside this directory; your system just needs to provide libc, a POSIX compatible interface and a C compiler. Notably deps contains a copy of jemalloc, which is the default allocator of Redis under Linux. Note that under deps there are also things which started with the Redis project, but for which the main repository is not redis/redis.

There are a few more directories but they are not very important for our goals here. We'll focus mostly on src, where the Redis implementation is contained, exploring what there is inside each file. The order in which files are exposed is the logical one to follow in order to disclose different layers of complexity incrementally.

Note: lately Redis was refactored quite a bit. Function names and file names have been changed, so you may find that this documentation reflects the unstable branch more closely. For instance, in Redis 3.0 the server.c and server.h files were named redis.c and redis.h. However the overall structure is the same. Keep in mind that all the new developments and pull requests should be performed against the unstable branch.

server.h

The simplest way to understand how a program works is to understand the data structures it uses. So we'll start from the main header file of Redis, which is server.h.

All the server configuration and in general all the shared state is defined in a global structure called server, of type struct redisServer. A few important fields in this structure are:

  • server.db is an array of Redis databases, where data is stored.
  • server.commands is the command table.
  • server.clients is a linked list of clients connected to the server.
  • server.master is a special client, the master, if the instance is a replica.

There are tons of other fields. Most fields are commented directly inside the structure definition.

Another important Redis data structure is the one defining a client. In the past it was called redisClient, now just client. The structure has many fields, here we'll just show the main ones:

struct client {
    int fd;
    sds querybuf;
    int argc;
    robj **argv;
    redisDb *db;
    int flags;
    list *reply;
    // ... many other fields ...
    char buf[PROTO_REPLY_CHUNK_BYTES];
}

The client structure defines a connected client:

  • The fd field is the client socket file descriptor.
  • argc and argv are populated with the command the client is executing, so that functions implementing a given Redis command can read the arguments.
  • querybuf accumulates the requests from the client, which are parsed by the Redis server according to the Redis protocol and executed by calling the implementations of the commands the client is executing.
  • reply and buf are dynamic and static buffers that accumulate the replies the server sends to the client. These buffers are incrementally written to the socket as soon as the file descriptor is writable.

As you can see in the client structure above, arguments in a command are described as robj structures. The following is the full robj structure, which defines a Redis object:

struct redisObject {
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits access time). */
    int refcount;
    void *ptr;
};

Basically this structure can represent all the basic Redis data types like strings, lists, sets, sorted sets and so forth. The interesting thing is that it has a type field, so that it is possible to know what type a given object has, and a refcount, so that the same object can be referenced in multiple places without allocating it multiple times. Finally the ptr field points to the actual representation of the object, which might vary even for the same type, depending on the encoding used.

Redis objects are used extensively in the Redis internals, however in order to avoid the overhead of indirect accesses, recently in many places we just use plain dynamic strings not wrapped inside a Redis object.

server.c

This is the entry point of the Redis server, where the main() function is defined. The following are the most important steps in order to startup the Redis server.

  • initServerConfig() sets up the default values of the server structure.
  • initServer() allocates the data structures needed to operate, setup the listening socket, and so forth.
  • aeMain() starts the event loop which listens for new connections.

There are two special functions called periodically by the event loop:

  1. serverCron() is called periodically (according to server.hz frequency), and performs tasks that must be performed from time to time, like checking for timed out clients.
  2. beforeSleep() is called every time the event loop fired, Redis served a few requests, and is returning back into the event loop.

Inside server.c you can find code that handles other vital things of the Redis server:

  • call() is used in order to call a given command in the context of a given client.
  • activeExpireCycle() handles eviction of keys with a time to live set via the EXPIRE command.
  • performEvictions() is called when a new write command should be performed but Redis is out of memory according to the maxmemory directive.
  • The global variable redisCommandTable defines all the Redis commands, specifying the name of the command, the function implementing the command, the number of arguments required, and other properties of each command.

commands.c

This file is auto generated by utils/generate-command-code.py, the content is based on the JSON files in the src/commands folder. These are meant to be the single source of truth about the Redis commands, and all the metadata about them. These JSON files are not meant to be used by anyone directly, instead that metadata can be obtained via the COMMAND command.

networking.c

This file defines all the I/O functions with clients, masters and replicas (which in Redis are just special clients):

  • createClient() allocates and initializes a new client.
  • The addReply*() family of functions are used by command implementations in order to append data to the client structure, that will be transmitted to the client as a reply for a given command executed.
  • writeToClient() transmits the data pending in the output buffers to the client and is called by the writable event handler sendReplyToClient().
  • readQueryFromClient() is the readable event handler and accumulates data read from the client into the query buffer.
  • processInputBuffer() is the entry point in order to parse the client query buffer according to the Redis protocol. Once commands are ready to be processed, it calls processCommand() which is defined inside server.c in order to actually execute the command.
  • freeClient() deallocates, disconnects and removes a client.

aof.c and rdb.c

As you can guess from the names, these files implement the RDB and AOF persistence for Redis. Redis uses a persistence model based on the fork() system call in order to create a process with the same (shared) memory content of the main Redis process. This secondary process dumps the content of the memory on disk. This is used by rdb.c to create the snapshots on disk and by aof.c in order to perform the AOF rewrite when the append only file gets too big.

The implementation inside aof.c has additional functions in order to implement an API that allows commands to append new commands into the AOF file as clients execute them.

The call() function defined inside server.c is responsible for calling the functions that in turn will write the commands into the AOF.

db.c

Certain Redis commands operate on specific data types; others are general. Examples of generic commands are DEL and EXPIRE. They operate on keys and not on their values specifically. All those generic commands are defined inside db.c.

Moreover db.c implements an API in order to perform certain operations on the Redis dataset without directly accessing the internal data structures.

The most important functions inside db.c which are used in many command implementations are the following:

  • lookupKeyRead() and lookupKeyWrite() are used in order to get a pointer to the value associated to a given key, or NULL if the key does not exist.
  • dbAdd() and its higher level counterpart setKey() create a new key in a Redis database.
  • dbDelete() removes a key and its associated value.
  • emptyData() removes an entire single database or all the databases defined.

The rest of the file implements the generic commands exposed to the client.

object.c

The robj structure defining Redis objects was already described. Inside object.c there are all the functions that operate with Redis objects at a basic level, like functions to allocate new objects, handle the reference counting and so forth. Notable functions inside this file:

  • incrRefCount() and decrRefCount() are used in order to increment or decrement an object reference count. When it drops to 0 the object is finally freed.
  • createObject() allocates a new object. There are also specialized functions to allocate string objects having a specific content, like createStringObjectFromLongLong() and similar functions.

This file also implements the OBJECT command.

replication.c

This is one of the most complex files inside Redis, it is recommended to approach it only after getting a bit familiar with the rest of the code base. In this file there is the implementation of both the master and replica role of Redis.

One of the most important functions inside this file is replicationFeedSlaves() that writes commands to the clients representing replica instances connected to our master, so that the replicas can get the writes performed by the clients: this way their data set will remain synchronized with the one in the master.

This file also implements both the SYNC and PSYNC commands that are used in order to perform the first synchronization between masters and replicas, or to continue the replication after a disconnection.

Script

The script unit is composed of 3 units:

  • script.c - integration of scripts with Redis (commands execution, set replication/resp, ...)
  • script_lua.c - responsible to execute Lua code, uses script.c to interact with Redis from within the Lua code.
  • function_lua.c - contains the Lua engine implementation, uses script_lua.c to execute the Lua code.
  • functions.c - contains Redis Functions implementation (FUNCTION command), uses functions_lua.c if the function it wants to invoke needs the Lua engine.
  • eval.c - contains the eval implementation using script_lua.c to invoke the Lua code.

Other C files

  • t_hash.c, t_list.c, t_set.c, t_string.c, t_zset.c and t_stream.c contains the implementation of the Redis data types. They implement both an API to access a given data type, and the client command implementations for these data types.
  • ae.c implements the Redis event loop, it's a self contained library which is simple to read and understand.
  • sds.c is the Redis string library, check https://github.com/antirez/sds for more information.
  • anet.c is a library to use POSIX networking in a simpler way compared to the raw interface exposed by the kernel.
  • dict.c is an implementation of a non-blocking hash table which rehashes incrementally.
  • cluster.c implements the Redis Cluster. Probably a good read only after being very familiar with the rest of the Redis code base. If you want to read cluster.c make sure to read the Redis Cluster specification.

Anatomy of a Redis command

All the Redis commands are defined in the following way:

void foobarCommand(client *c) {
    printf("%s",c->argv[1]->ptr); /* Do something with the argument. */
    addReply(c,shared.ok); /* Reply something to the client. */
}

The command function is referenced by a JSON file, together with its metadata, see commands.c described above for details. The command flags are documented in the comment above the struct redisCommand in server.h. For other details, please refer to the COMMAND command. https://redis.io/commands/command/

After the command operates in some way, it returns a reply to the client, usually using addReply() or a similar function defined inside networking.c.

There are tons of command implementations inside the Redis source code that can serve as examples of actual commands implementations (e.g. pingCommand). Writing a few toy commands can be a good exercise to get familiar with the code base.

There are also many other files not described here, but it is useless to cover everything. We just want to help you with the first steps. Eventually you'll find your way inside the Redis code base :-)

Enjoy!

node-redis's People

Contributors

andy-ganchrow avatar avital-fine avatar avitalfineredis avatar bcoe avatar bobrik avatar bridgear avatar brycebaril avatar chayim avatar dependabot[bot] avatar dtrejo avatar dvv avatar erinishimoticha avatar gkorland avatar greenkeeperio-bot avatar jerrysievert avatar leibale avatar migounette avatar mranney avatar paddybyers avatar pietern avatar ralexstokes avatar raydog avatar roamm avatar salakar avatar shin- avatar stockholmux avatar thanpolas avatar tim-smart avatar tj avatar tomaszdurka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-redis's Issues

Broken pipe and Stream not writable errors

Hi,

I seem to be getting this unhandled exception. Not sure why or how it happens, but it keeps crashing my processes.

Any idea what I should do to avoid this?

node.js:50
  throw e;
  ^
Error: EPIPE, Broken pipe
  at Stream._writeImpl (net:316:14)
  at Stream._writeOut (net:748:25)
  at Stream.write (net:681:17)
  at RedisClient.send_command   (/usr/local/lib/node/.npm/redis/0.3.5/package/index.js:645:16)
  at RedisClient.<anonymous>   (/usr/local/lib/node/.npm/redis/0.3.5/package/index.js:718:27)
  at Object.log (/home/skejti/Plateboiler-js/lib/logging.js:8:11)
  at Object.info (/home/skejti/Plateboiler-js/lib/logging.js:13:45)
  at /home/skejti/Plateboiler-js/plateboiler.js:65:16
  at Object.onload (/home/skejti/Plateboiler-js/jsdom/lib/jsdom.js:59:32)
  at /home/skejti/Plateboiler-js/jsdom/lib/jsdom/browser/index.js:360:1

Can't auth

Hi,

I'm trying to connect to a redistogo instance but the auth example I found in the node_redis source code doesn't work.

This is what I'm doing:

var redis = require("redis"),
    client = redis.createClient(MYPORT, "catfish.redistogo.com");

client.on("error", redis.print);

// whenever the client connects, make sure to auth
client.on("connect", function () {
    client.auth("MYPASS", redis.print);
});

client.auth("MYPASS");

I just got a

Error: Ready check failed: Error: Error: ERR operation not permitted

Using the same credentials with redis-cli I can successfully connect with my istance.

Versions:
$ npm list installed redis
npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
[email protected] active installed Wrapper for reply processing code in hiredis
[email protected] active installed Redis client library

Cheers,
Giacomo

web_server.js: Cannot find module 'redis'

node v0.3
redis v2.2 antirez git

wfm most test.js

at resolveModuleFilename (node.js:265:13)
at loadModule (node.js:231:20)
at require (node.js:291:14)
at Object. (/Users/jaymini/node_redis/examples/web_server.js:4:20)
at Module._compile (node.js:348:23)
at Object..js (node.js:356:12)
at Module.load (node.js:279:25)
at Array. (node.js:370:24)
at EventEmitter._tickCallback (node.js:42:22)
at node.js:634:9

Error after connect when Redis is loading the dataset in memory

The connect event is emitted, but Redis is not necessarily ready if it is still loading keys from disk. All calls return an error "LOADING Redis is loading the dataset in memory". It would be preferable to either, delay the connect event until after Redis is ready, or to add a subsequent event (eg. 'ready') to indicate to clients that Redis is ready to handle commands.

This could also cause offline_queueed commands to also fail if they are executed inbetween connect and LOADING the dataset.

maybe a stupid question

hey, I'm new to redis (and node), so I apologize in advance if I'm simply doing something stupid.

I can save and get data in a node app just fine using your module. In particular I'm using hset and hget a lot. However, if I open a new terminal, type redis-cli and attempt to get any of the data that way, it's like the database is empty. I keep getting back "Invalid argument(s)". Any ideas why this would happen?

One time callback

Hi,

how can I assign a one time callback to an event? Node.js documentation says that eventEmitters have a .once function, but when I try to use it with a redis client I get this sort of error:

redis.once("idle", inner_recurse);
    ^
TypeError: Object #<a RedisClient> has no method 'once'
  at Timer.callback (/home/skejti/Plateboiler/rapid.queue/worker.js:23:9)
  at node.js:607:9

What I want to achieve is to only go into recursion when the command queue is empty. So I first check that the queue length is 0 and if it's not I assign a one time callback to the "idle" event. This is to prevent essentially race conditions with recursion being called every time the queue is emptied anywhere in the algorithm's flow.

Am I going about it the wrong way perhaps?

idiomatic HMSET

I was comparing redis-node and node-redi. As to the HMSET commnad, I think redis-node uses a more idiomatic and handy way showed as follows:

// The commands are also idiomatic
client.hmset("hash", { t: "rex", steg: "asaurus" }, function (err, status) {
if (err) throw err;
sys.log(status); // true
});

My question is, would you consider or have a plan to implement hmset like this ?

Disconnect/Reconnect does not reset pub/sub variable

Restarted redis. App got into the following loop trying to re-authenticate.

26 Sep 19:40:50 - redis client reconnecting
26 Sep 19:40:50 - Error: { message: 'Connection in pub/sub mode, only pub/sub commands may be used'
, stack: [Getter/Setter]
}

[ repeat ... ]

Unknown error occurs after extended run time

Hey there. Getting this error on my production app after an extended run. Was wondering if you had any idea what it was. I'm new to node and from this stack trace am not sure where I could put a catch to catch the error so I can cleanly exit and restart the app.

Exception in RedisReplyParser: Error: end cannot be longer than parent.length
at Buffer.toString (buffer:39:19)
at RedisReplyParser.execute (/disk1/home/logplex/vendor/node_redis/index.js:91:52)
at RedisClient.on_data (/disk1/home/logplex/vendor/node_redis/index.js:429:27)
at Stream.<anonymous> (/disk1/home/logplex/vendor/node_redis/index.js:351:14)
at Stream.emit (events:26:26)
at IOWatcher.callback (net:489:16)
at node.js:764:9

using node 0.3.0, tests fail right, left and center

The parsing of the response seems to have totally broken in node 0.3.0 -- I just get raw buffer objects back.
I'm using node 0.3.0, redis 2.0.4 and node_redis 0.3.8.
Btw: I tried this out, because redis-client also had the same problem, just shuffing buffers back.

Why keep Buffers?

Is there a good reason, why only single line requests are converted to strings and others kept as Buffers. I know that converting to strings would take a little more CPU, but to use the answers, we still need to to do that, so there is no almost no win. I think we should be consistent about the result and always convert to string (except those that always return integers). So.. is there something I'm missing or what's the reason?

Q: about client.end() placement

Given the following express app route flow:

app.get('/', getSesh, function(req, res){
multi = client.multi();
client.zrevrangebyscore('frontPage', epoch(), epoch()-450061, "limit", "0", "75", function(err, data){
    if(err){console.log(err)}
    for (d in data)
    {
        multi.hgetall(data[d]){
        })
    }
    multi.exec(function(err, reply){
        if(err){console.log(err)}
        articles = reply;
        res.render('index', {
            locals: {title: "MOSTMODERNIST", articles: articles, admin: req.isAdmin}
        });
        res.end();
    }); 
});
});

Where / when should I put client.end()? I've experimented and gotten gnarly results. Previously I wasn't quitting them, letting redis disconnect them.

many tia

Cannot read property 'length' of undefined

I'm not sure what's going on here, but I sometimes get this error:

Message: Redis connection to database:6379 failed - Cannot read property 'length' of undefined
Error: Redis connection to database:6379 failed - Cannot read property 'length' of undefined
at Stream.<anonymous> (/home/prod/.node_libraries/.npm/redis/0.5.0/package/index.js:140:28)
at Stream.emit (events:31:17)
at Array.<anonymous> (net:1004:27)
at EventEmitter._tickCallback (node.js:55:22)
at node.js:773:9

Is there something I can do to trace this deeper?

changes binary data into javascript strings?

It seems like when I have binary data in redis and try to move that same data from one key to another using node_redis, it gets altered in the process. I'm not sure exactly where this happens.

I'm here at redis-cli:
redis> get "z"
"\x92\x95\xd0\x94\x01\x00\xd0\xc0\x0e\xcd\x02\x17"

Now I fire up node_redis and copy key "z" into key "x":
c = redis.createClient(null, 'localhost')
c.get('z', function(e, r) {c.set('x', r)})

Now I'm back at redis-cli:
redis> get "x"
"\xef\xbf\xbd\xef\xbf\xbd\xd0\x94\x01\x00\xef\xbf\xbd\xef\xbf\xbd\x0e\xef\xbf\xbd\x02\x17"

It seems like if I simply move data from one key to another key, it shouldn't get transformed in the process right?

Unrelated footnote: this bug appeared when we transitioned from fictorial's redis library to this one.

Auto-closing of connections

Using fictorial's redis-client, I was able to set an auto-close mode for tests using code similar to:

client = redis.createClient();
client.addListener("drained", function() {
  this.close();
});

It automatically closed the connection to Redis whenever there were no items remaining in the queue to process (in or outbound). For tests, it allowed me to not worry about explicitly closing the connection (and cause running tests to fail) in order for the process to exit normally (otherwise it sits and hangs, as something is still open/running).

Is there a way to do something similar using this client?

Is there a different pattern I should be using for my tests? E.g., client per test with a close() call inside a finally block?

hmget fails when args.length > 1

var redis = require('redis')
  , client = redis.createClient();

client.hset('hash', 'key', 'val');

client.hmget('hash', ['key'], redis.print);
client.hmget('hash', 'key', 'key', redis.print);
client.hmget('hash', ['key', 'key'], redis.print);

client.quit();

/* output:
Reply: val
Reply: val,val
Reply: 
*/

Suggestion: use same function for both upper and lower case commands

In http://github.com/mranney/node_redis/blob/master/index.js#L696

This code:

exports.commands.forEach(function (command) {
    RedisClient.prototype[command] = function () {
        var args = to_array(arguments);
        args.unshift(command); // put command at the beginning
        this.send_command.apply(this, args);
    };
    // same as above, but command is lower case
    RedisClient.prototype[command.toLowerCase()] = function () {
        var args = to_array(arguments);
        args.unshift(command); // put command at the beginning
        this.send_command.apply(this, args);
    };
});

Could be reduced to the following code (with the added upside of using less memory, since the same function is shared for the two command names):

exports.commands.forEach(function (command) {
    RedisClient.prototype[command] = function () {
        var args = to_array(arguments);
        args.unshift(command); // put command at the beginning
        this.send_command.apply(this, args);
    };
    // same as above, but command is lower case
    RedisClient.prototype[command.toLowerCase()] = RedisClient.prototype[command];
});

Support for new bit commands

Current development version (2.2-RC2) of Redis supports four new commands related to bit manipulation. Please provide support for those commands. They are SETBIT, GETBIT, SETRANGE and GETRANGE.

Complains about HSET?

I tried to run the sample code you give, and I get:

sleet:persuasion davida$ node !$
node t.js
Reply: OK
Error: ERR unknown command 'HSET'
Error: ERR unknown command 'HSET'
Redis connection error to 127.0.0.1:6379 - TypeError: Cannot read property 'length' of undefined

(what's a bit weird is that I can do redis-cli hset ... w/ no problems).

Any ideas?

typo

"client.get() is the same as clieint.GET()"

pipelining in node_redis

Hi,
I wonder if that driver supports redis pipelining? I didn't find any samples. Maybe it pipelines by default?

depend on hiredis

For portability, a pure JavaScript reply parser is used by default.

Is portability a real, or theoretical issue? If it's real, wouldn't adding platform support to hiredis be the open-source thing to do?

Export the function that populates RedisClient.prototype

Please, export the function that populates RedisClient.prototype, so the user may add commands currently missing in node_redis at zero cost.

Also this would enable the user to "auto-update somehow" the interface in a sub-optimal fashion (e. g. downloading and parsing the commands.json) until there is a clear way to do it.

Thanks. :)

document reconnect scenarios

node_redis reconnects automatically when the connection fails, and often this does what you'd expect. There are some scenarios where unexpected things happen though, like if you have an outstanding blocking command like blpop, or if you are in subscribe mode. Further, sometimes on reconnect, you might notice that redis-server returns an error on all non-info commands, including subscribe.

outside of client's scope?

Hi there. I'm not sure if I have run up against a limitation of this module, or of my skill. I can't seem to do anything with the return of a query outside of the optional function. The only way I can do anything to the data, is to put everything inside that function, i.e. passing the data as locals (res.render). Can you please set me straight?

For instance, I unable to attach the reply to a variable.

var data = client.get("test", function(err, reply){})

Similarly, I am unable to do this:

var data;
client.get("test", function(err, reply){
data = reply.toString()
})  // data undefined 

Only this works, but it is not the ideal construction:

client.get("tester", function(err, data) {
res.render('index', {
    locals: {
      title: '',
      body: data
   }
     })
});

MGET and empty array

Hey,

I know that original Redis syntax requires at least one key for MGET command, but since node_redis allows arrays, maybe it could allow an empty array as well? It could simply return an empty array without even sending command to Redis. It might be useful when doing nested calls to Redis and the command above can return an empty array.

Everything is a buffer

Everything returned from keys, hkeys, etc is a Buffer.

For such simple types I have to wonder why...

Returning wrong value

I think I managed to create race conditions where redis returns the wrong result for a query. Just trying to confirm my suspicion.

Is it possible for node_redis to confuse which result goes to which callback if I do stuff like this:

 redis.set('key1', 'something');
 redis.expire('key1', 100);
 redis.set('key2', 'something else');
 redis.set('key3', 'foo');
 redis.get('key1', function (err, data) { ... });
 redis.get('key2', function (err, data) {
     // what seems to be happening here is that after running for a while, it seems the wrong data starts getting returned
 });

has no method 'split'

I just upgraded to Node.js v0.4.1 and saw this error "has no method 'split'" from index.js line 182 -
var lines = res.split("\r\n"), obj = {}, retry_time;

Quick monkeying seems to show that "res" is a Buffer not a String, and when I changed this line to

var lines = res.toString().split("\r\n"), obj = {}, retry_time;

everything seems to be fine. Is this a bug?

node_redis and Step

I'm playing with Step and node_redis. However it seems for some reason my code gets stuck when I use client.get("foo",this). It just doesn't seem to return this correctly so Step can proceed to next function. Any ideas why this is happening?

pass zunionstore array of keys

Is it possible to pass zunionstore an array for all of the keys that need to be unionized?

I have had no trouble with variables yet, and I can use an Array for multiple keys in mget(). I've been trying it here without success. eg:

var keys = ["mine", "yours"];
client.zunionstore("both", keys.length, keys, function(err, res){...})

Redis returns a syntax error apropos the keys.

Callback potentially called twice on multi.exec error

I haven't actually tried this but was reviewing the code to determine the callback sequence for multi execs. I think that you are missing a return on line 559 of index.js. The way it is coded, if send_command sends an err to this function, it will invoke the top-level callback once with the err and then again with (null, replies). You should change this line to:
return callback(new Error(err));

PSUBSCRIBE example

... if you want it. See this gist.

I thought you had a bug until I went and wrestled with the Redis docs for a while. But maybe that's not such a bad thing.

hmget returning array?

I don't get an object when I use hmget, to retrieve specified fields from a given hash:

hash =  {ingr1: eggs, ingr2: peppers, ingr3: potatoes}
hmget(hash, ingr1, ingr2)
// [eggs, peppers]

Curious if I am wrong to suggest this is wonky. hgetall() returns field:value.

re-auth on reconnect

After sending an auth command, it can be surprising when an auto-reconnect happens and you need to send auth again. We should remember the auth and re-send it on reconnect.

document pipelining

node_redis pipelines sort of automatically. This is quite a bit different than in other Redis client libraries, and it needs to be documented.

range passed as string should be passed as integer

For example this:
client.zrevrange('some-key', 0, -1)

produces this:

"zrevrange" "iMarionette:callQueue" "0" "-1"

but should produce this:

"zrevrange" "iMarionette:callQueue" 0 -1

and as a result I'm not able to get back any data using ranges.

No?

Error: Redis reply parser error: TypeError: undefined is not a function

I'm trying to do a simple wrapper around node_redis. I have simple function like
exports.set = function(key,value,my_callback) {
client.set(key,value,function(err,reply) {
my_callback(reply.toString())
})}

but it fails with error in the title. I tracked that it has got something to do with parsing but unfortunately I'm not skilled enough to fix it myself and push the fix :( I have hiredis installed from npm.

Error: Redis reply parser error: TypeError: undefined is not a function
at CALL_NON_FUNCTION (native)
at Object.my_callback (/tmp/lib.js:15:2)
at Object.callback (/tmp/db/redis_wrapper.js:60:27)
at RedisClient.return_reply (/usr/local/lib/node/.npm/redis/0.4.1/package/index.js:259:25)
at HiredisReplyParser.<anonymous> (/usr/local/lib/node/.npm/redis/0.4.1/package/index.js:94:18)
at HiredisReplyParser.emit (events.js:31:17)
at HiredisReplyParser.execute (/usr/local/lib/node/.npm/redis/0.4.1/package/lib/parser/hiredis.js:35:22)
at RedisClient.on_data (/usr/local/lib/node/.npm/redis/0.4.1/package/index.js:216:27)
at Stream.<anonymous> (/usr/local/lib/node/.npm/redis/0.4.1/package/index.js:120:14)
at Stream.emit (events.js:31:17)

multi + smembers

Not sure if you can reproduce this, but this query was hanging for me:

client.multi([
  ['smembers', ['some set'], fn],
  ['del', ['some set'], fn]
]);

socket error randomly occuring with multi.exec

Hi I've got a problem with a socket error 'sometimes' occuring in my test suite. It only seems to occur during a multi-exec command I use. There's nothing interesting happening on the redis-server logs (i.e. it hasn't temporarily died).

Here's a back trace:

.......Redis connection error to 127.0.0.1:6379 - Error: Redis connection to 127.0.0.1:6379 failed - EPIPE, Broken pipe

   uncaught: Error: Socket is not writable
    at Socket._writeOut (net.js:370:11)
    at Socket.write (net.js:356:17)
    at RedisClient.send_command (/usr/local/lib/node/.npm/redis/0.5.7/package/index.js:513:16)
    at Multi.exec (/usr/local/lib/node/.npm/redis/0.5.7/package/index.js:684:17)
    at Function.loadFromIds (/Users/weepy/src/mmodel/lib/stores/redis.js:147:8)
    at Object.callback (/Users/weepy/src/mmodel/lib/stores/redis.js:132:13)
    at RedisClient.return_reply (/usr/local/lib/node/.npm/redis/0.5.7/package/index.js:385:29)
    at RedisReplyParser. (/usr/local/lib/node/.npm/redis/0.5.7/package/index.js:86:14)
    at RedisReplyParser.emit (events.js:42:17)
    at RedisReplyParser.add_multi_bulk_reply (/usr/local/lib/node/.npm/redis/0.5.7/package/lib/parser/javascript.js:297:14)


   Failures: 1


hgetall returns {} when no results

Testing for if(results) ends up with a false positive.
This could be an easy fix by setting the result to be null if no properties/keys have been set, but I'm just putting this out just in case there is something against this by design?

Client sending wrong command to server - getting stuck in loop.

Getting a strange error. Happens pretty regularly. Node process breaks after about 30-60 mins of running. I get a message like this:

no callback to send error: 'ERR unknown command \'}\''
Exception in RedisReplyParser: Error: ERR unknown command '}'
at RedisClient.return_error (/disk1/home/logplex/vendor/node_redis/index.js:443:15)
at RedisReplyParser.<anonymous>      (/disk1/home/logplex/vendor/node_redis/index.js:324:18)
at RedisReplyParser.emit (events:26:26)
at RedisReplyParser.send_error (/disk1/home/logplex/vendor/node_redis/index.js:236:14)
at RedisReplyParser.execute (/disk1/home/logplex/vendor/node_redis/index.js:91:22)
at RedisClient.on_data (/disk1/home/logplex/vendor/node_redis/index.js:429:27)
at Stream.<anonymous> (/disk1/home/logplex/vendor/node_redis/index.js:351:14)
at Stream.emit (events:26:26)
at IOWatcher.callback (net:489:16)
at node.js:764:9

The ERR unknown command is coming from inside redis. It apparently was sent a '}' command. The client can't figure out what command send this and throws an
exception. A fraction of a second later the error will repeat but with more info following the ERR. It will spiral out of control eventually looking like t
his:

no callback to send error: 'ERR unknown command \'=>""}}}\':0+OK:0:501:0+OK:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:501:0:0:0:0+OK:0:0:0:0:501:0+OK:0:0:0:0:0:0:0:501:0:0:0:501:0:501:0:501:0:0:0:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:0:0:0+OK:0+OK:0:0:0:0:0:0:501:0:501:0+OK:0:0:0:0+OK:0:0:0:0:0:0:0+OK:0:501:0:0:0:501:0:0:0:0:0:0+OK:0:0:0:0:501:0+OK:0:0:0:0:0:0:0:0:0:0+OK:0:0:0:501:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:501:0:501:0+OK:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:501:0:501:0:501:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:501:0:0+OK:0:0:501:0:0:0:501:0:0:0+OK:0:0:0:0:0:0:0:501:0:0:0:501:0+OK:0:501:0:0:0:501:0:501:0:0:0:0:0+OK:0:0:0:0:0+OK:0:0:0:501' 
Exception in RedisReplyParser: Error: ERR unknown command '=>""}}}':0+OK:0:501:0+OK:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:501:0:0:0:0+OK:0:0:0:0:501:0+OK:0:0:0:0:0:0:0:501:0:0:0:501:0:501:0:501:0:0:0:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:0:0:0+OK:0+OK:0:0:0:0:0:0:501:0:501:0+OK:0:0:0:0+OK:0:0:0:0:0:0:0+OK:0:501:0:0:0:501:0:0:0:0:0:0+OK:0:0:0:0:501:0+OK:0:0:0:0:0:0:0:0:0:0+OK:0:0:0:501:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:501:0:501:0+OK:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:501:0:501:0:501:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:501:0:0+OK:0:0:501:0:0:0:501:0:0:0+OK:0:0:0:0:0:0:0:501:0:0:0:501:0+OK:0:501:0:0:0:501:0:501:0:0:0:0:0+OK:0:0:0:0:0+OK:0:0:0:501
at RedisClient.return_error (/disk1/home/logplex/vendor/node_redis/index.js:443:15)
at RedisReplyParser.<anonymous> (/disk1/home/logplex/vendor/node_redis/index.js:324:18)
at RedisReplyParser.emit (events:26:26)
at RedisReplyParser.send_error (/disk1/home/logplex/vendor/node_redis/index.js:236:14)
at RedisReplyParser.execute (/disk1/home/logplex/vendor/node_redis/index.js:91:22)
at RedisClient.on_data (/disk1/home/logplex/vendor/node_redis/index.js:429:27)
at Stream.<anonymous> (/disk1/home/logplex/vendor/node_redis/index.js:351:14)
at Stream.emit (events:26:26)
at IOWatcher.callback (net:489:16)
at node.js:764:9

I've not been able to debug it further.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.