Skip to content

Commit

Permalink
feat: rewrite w/@lassjs, added Cluster/Sentinel/ioredis support
Browse files Browse the repository at this point in the history
  • Loading branch information
niftylettuce committed Apr 26, 2019
1 parent f3ab737 commit f936b7b
Show file tree
Hide file tree
Showing 17 changed files with 9,159 additions and 273 deletions.
10 changes: 10 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"presets": [
["@babel/env", {
"targets": {
"node": "4"
}
}]
],
"plugins": [ "@babel/transform-runtime" ]
}
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
7 changes: 7 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": ["eslint:recommended", "plugin:node/recommended"],
"rules": {
"no-constant-condition": "off",
"no-fallthrough": "off"
}
}
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ pids
logs
results
coverage

npm-debug.log
node_modules
.DS_Store
.idea
lib
2 changes: 2 additions & 0 deletions .remarkignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
HISTORY.md
benchmark/*.md
File renamed without changes.
263 changes: 192 additions & 71 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,52 +1,64 @@
koa-redis
=========
# koa-redis

[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Coveralls][coveralls-image]][coveralls-url]
[![David deps][david-image]][david-url]
[![David devDeps][david-dev-image]][david-dev-url]
[![node version][node-image]][node-url]
[![npm download][download-image]][download-url]
[![license][license-image]][license-url]
[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org)

[npm-image]: https://img.shields.io/npm/v/koa-redis.svg?style=flat-square
[npm-url]: https://npmjs.org/package/koa-redis
[travis-image]: https://img.shields.io/travis/koajs/koa-redis.svg?style=flat-square
[travis-url]: https://travis-ci.org/koajs/koa-redis
[coveralls-image]: https://img.shields.io/coveralls/koajs/koa-redis.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/koajs/koa-redis?branch=master
[david-image]: https://img.shields.io/david/koajs/koa-redis.svg?style=flat-square&label=deps
[david-url]: https://david-dm.org/koajs/koa-redis
[david-dev-image]: https://img.shields.io/david/dev/koajs/koa-redis.svg?style=flat-square&label=devDeps
[david-dev-url]: https://david-dm.org/koajs/koa-redis#info=devDependencies
[david-opt-image]: https://img.shields.io/david/optional/koajs/koa-redis.svg?style=flat-square&label=optDeps
[david-opt-url]: https://david-dm.org/koajs/koa-redis#info=devDependencies
[node-image]: https://img.shields.io/node/v/koa-redis.svg?style=flat-square
[node-url]: http://nodejs.org/download/
[download-image]: https://img.shields.io/npm/dm/koa-redis.svg?style=flat-square
[download-url]: https://npmjs.org/package/koa-redis
[gittip-image]: https://img.shields.io/gittip/dead-horse.svg?style=flat-square
[gittip-url]: https://www.gittip.com/dead-horse/
[license-image]: https://img.shields.io/npm/l/koa-redis.svg?style=flat-square
[license-url]: https://github.com/koajs/koa-redis/blob/master/LICENSE

Redis storage for koa session middleware/cache.
> Redis storage for Koa session middleware/cache with Sentinel and Cluster support
[![NPM](https://nodei.co/npm/koa-redis.svg?downloads=true)](https://nodei.co/npm/koa-redis/)


## Table of Contents

* [Install](#install)
* [Usage](#usage)
* [Example](#example)
* [Options](#options)
* [Events](#events)
* [API](#api)
* [Benchmark](#benchmark)
* [Testing](#testing)
* [License](#license)
* [Contributors](#contributors)


## Install

[npm][]:

```sh
npm install koa-redis
```

[yarn][]:

```sh
yarn add koa-redis
```


## Usage

`koa-redis` works with [koa-generic-session](https://github.com/koajs/generic-session) (a generic session middleware for koa).

### Example

For more examples, please see the [examples folder of `koa-generic-session`](https://github.com/koajs/generic-session/tree/master/example).

#### Basic

```js
var session = require('koa-generic-session');
var redisStore = require('koa-redis');
var koa = require('koa');
const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const koa = require('koa');

var app = koa();
const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(session({
store: redisStore({
Expand All @@ -69,7 +81,7 @@ app.use(function *() {
});

function get() {
var session = this.session;
const session = this.session;
session.count = session.count || 0;
session.count++;
this.body = session.count;
Expand All @@ -88,96 +100,205 @@ function *regenerate() {

app.listen(8080);
```
For more examples, please see the [examples folder of `koa-generic-session`](https://github.com/koajs/generic-session/tree/master/example).

#### Sentinel

```js
const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const koa = require('koa');

const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(session({
store: redisStore({
// Options specified here
// <https://github.com/luin/ioredis#sentinel>
sentinels: [
{ host: 'localhost', port: 26379 },
{ host: 'localhost', port: 26380 }
// ...
],
name: 'mymaster'
})
}));

// ...
```

#### Cluster

```js
const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const koa = require('koa');

const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(session({
store: redisStore({
// Options specified here
// <https://github.com/luin/ioredis#cluster>
isRedisCluster: true,
nodes: [
{
port: 6380,
host: '127.0.0.1'
},
{
port: 6381,
host: '127.0.0.1'
}
// ...
],
// <https://github.com/luin/ioredis/blob/master/API.md#new-clusterstartupnodes-options>
clusterOptions: {
// ...
redisOptions: {
// ...
}
}
})
}));

// ...
```

### Options

- *all [`node_redis`](https://www.npmjs.com/package/redis#options-is-an-object-with-the-following-possible-properties) options* - Useful things include `url`, `host`, `port`, and `path` to the server. Defaults to `127.0.0.1:6379`
- `db` (number) - will run `client.select(db)` after connection
- `client` (object) - supply your own client, all other options are ignored unless `duplicate` is also supplied
- `duplicate` (boolean) - When true, it will run `client.duplicate(options)` on the supplied `client` and use all other options supplied. This is useful if you want to select a different DB for sessions but also want to base from the same client object.
- `serialize` - Used to serialize the data that is saved into the store.
- `unserialize` - Used to unserialize the data that is fetched from the store.
- **DEPRECATED:** old options - `pass` and `socket` have been replaced by `auth_pass` and `path`, but they should be backward compatible (still work).
* _all [`ioredis`](https://github.com/luin/ioredis/blob/master/API.md#new-redisport-host-options) options_ - Useful things include `url`, `host`, `port`, and `path` to the server. Defaults to `127.0.0.1:6379`
* `db` (number) - will run `client.select(db)` after connection
* `client` (object) - supply your own client, all other options are ignored unless `duplicate` is also supplied
* `duplicate` (boolean) - When true, it will run `client.duplicate(options)` on the supplied `client` and use all other options supplied. This is useful if you want to select a different DB for sessions but also want to base from the same client object.
* `serialize` - Used to serialize the data that is saved into the store.
* `unserialize` - Used to unserialize the data that is fetched from the store.
* `isRedisCluster` (boolean) - Used for creating a Redis cluster instance per [`ioredis`][cluster] Cluster options, if set to `true`, then a new Redis cluster will be instantiated with `new Redis.Cluster(options.nodes, options.clusterOptions)` (see [Cluster docs][cluster] for more info).
* `nodes` (array) - Conditionally used for creating a Redis cluster instance when `isRedisCluster` option is `true`, this is the first argument passed to `new Redis.Cluster` and contains a list of all the nodes of the cluster ou want to connect to (see [Cluster docs][cluster] for more info).
* `clusterOptions` (object) - Conditionally used for created a Redi cluster instance when `isRedisCluster` option is `true`, this is the second argument passed to `new Redis.Cluster` and contains options, such as `redisOptions` (see [Cluster docs][cluster] for more info).
* **DEPRECATED:** old options - `auth_pass` and `pass` have been replaced with `password`, and `socket` has been replaced with `path`, however all of these options are backwards compatible.

### Events
See the [`node_redis` docs](https://www.npmjs.com/package/redis#connection-events) for more info.
- `ready`
- `connect`
- `reconnecting`
- `error`
- `end`
- `warning`

See the [`ioredis` docs](https://github.com/luin/ioredis#connection-events) for more info.

* `ready`
* `connect`
* `reconnecting`
* `error`
* `end`
* `warning`

### API

These are some the functions that `koa-generic-session` uses that you can use manually. You will need to initialize differently than the example above:

```js
var session = require('koa-generic-session');
var redisStore = require('koa-redis')({
const session = require('koa-generic-session');
const redisStore = require('koa-redis')({
// Options specified here
});
var app = require('koa')();
const app = require('koa')();

app.keys = ['keys', 'keykeys'];
app.use(session({
store: redisStore
}));
```

#### module([options])
Initialize the Redis connection with the optionally provided options (see above). *The variable `session` below references this*.
#### module([options](#options))

Initialize the Redis connection with the optionally provided options (see above). _The variable `session` below references this_.

#### session.get(sid)

Generator that gets a session by ID. Returns parsed JSON is exists, `null` if it does not exist, and nothing upon error.

#### session.set(sid, sess, ttl)
Generator that sets a JSON session by ID with an optional time-to-live (ttl) in milliseconds. Yields `node_redis`'s `client.set()` or `client.setex()`.

Generator that sets a JSON session by ID with an optional time-to-live (ttl) in milliseconds. Yields `ioredis`'s `client.set()` or `client.setex()`.

#### session.destroy(sid)
Generator that destroys a session (removes it from Redis) by ID. Tields `node_redis`'s `client.del()`.

Generator that destroys a session (removes it from Redis) by ID. Tields `ioredis`'s `client.del()`.

#### session.quit()
Generator that stops a Redis session after everything in the queue has completed. Yields `node_redis`'s `client.quit()`.

Generator that stops a Redis session after everything in the queue has completed. Yields `ioredis`'s `client.quit()`.

#### session.end()

Alias to `session.quit()`. It is not safe to use the real end function, as it cuts off the queue.

#### session.connected

Boolean giving the connection status updated using `client.connected` after any of the events above is fired.

#### session.\_redisClient
Direct access to the `node_redis` client object.

Direct access to the `ioredis` client object.

#### session.client
Direct access to the `co-redis` wrapper around the `node_redis` client.

Direct access to the `co-redis` wrapper around the `ioredis` client.


## Benchmark

|Server|Transaction rate|Response time|
|------|----------------|-------------|
|connect without session|**6763.56 trans/sec**|**0.01 secs**|
|koa without session|**5684.75 trans/sec**|**0.01 secs**|
|connect with session|**2759.70 trans/sec**|**0.02 secs**|
|koa with session|**2355.38 trans/sec**|**0.02 secs**|
| Server | Transaction rate | Response time |
| ----------------------- | --------------------- | ------------- |
| connect without session | **6763.56 trans/sec** | **0.01 secs** |
| koa without session | **5684.75 trans/sec** | **0.01 secs** |
| connect with session | **2759.70 trans/sec** | **0.02 secs** |
| koa with session | **2355.38 trans/sec** | **0.02 secs** |

Detailed benchmark report [here](https://github.com/koajs/koa-redis/tree/master/benchmark)


## Testing

1. Start a Redis server on `localhost:6379`. You can use [`redis-windows`](https://github.com/ServiceStack/redis-windows) if you are on Windows or just want a quick VM-based server.
2. Clone the repository and run `npm i` in it (Windows should work fine).
3. If you want to see debug output, turn on the prompt's `DEBUG` flag.
4. Run `npm test` to run the tests and generate coverage. To run the tests without generating coverage, run `npm run-script test-only`.

## Authors
See the [contributing tab](https://github.com/koajs/koa-redis/graphs/contributors)

## Licences
(The MIT License)
## License

[MIT](LICENSE) © dead_horse


Copyright (c) 2015 dead-horse and other contributors
## Contributors

| Name | Website |
| -------------- | -------------------------- |
| **dead_horse** | |
| **Nick Baugh** | <http://niftylettuce.com/> |


##

[travis-image]: https://img.shields.io/travis/koajs/koa-redis.svg?style=flat-square

[travis-url]: https://travis-ci.org/koajs/koa-redis

[coveralls-image]: https://img.shields.io/coveralls/koajs/koa-redis.svg?style=flat-square

[coveralls-url]: https://coveralls.io/r/koajs/koa-redis?branch=master

[david-image]: https://img.shields.io/david/koajs/koa-redis.svg?style=flat-square&label=deps

[david-url]: https://david-dm.org/koajs/koa-redis

[david-dev-image]: https://img.shields.io/david/dev/koajs/koa-redis.svg?style=flat-square&label=devDeps

[david-dev-url]: https://david-dm.org/koajs/koa-redis#info=devDependencies

[license-image]: https://img.shields.io/npm/l/koa-redis.svg?style=flat-square

[license-url]: https://github.com/koajs/koa-redis/blob/master/LICENSE

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
[cluster]: https://github.com/luin/ioredis/blob/master/API.md#new-clusterstartupnodes-options

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
[npm]: https://www.npmjs.com/

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[yarn]: https://yarnpkg.com/
Loading

0 comments on commit f936b7b

Please sign in to comment.