Skip to content

Instantly share code, notes, and snippets.

@matthax
Created December 6, 2018 22:46
Show Gist options
  • Save matthax/d87c0b1bc0d381c7549f89cbc3bd1941 to your computer and use it in GitHub Desktop.
Save matthax/d87c0b1bc0d381c7549f89cbc3bd1941 to your computer and use it in GitHub Desktop.
IORedis Duplex Stream Example
/**
* MIT License
Copyright (c) 2018 Matthew D. Bark
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
*/
const { Duplex } = require('stream');
const Redis = require('ioredis');
/**
* @typedef {Object} RedisChunk
* @property {Object} id The id of the message
* @property {String} message The message contents
*/
/**
* @typedef {Object} ConsumerOptions
* @property {String} group The consumer group to use when reading, if any
* @property {String} start The position the client should begin reading from
* @property {String} name The name of the client to use
* @property {Number} block The timeout (in ms) to wait before the read times out
*/
const parsexread = response => (
response.reduce((data, [stream, messages]) => {
// if (typeof data[stream] === 'undefined') data[stream] = [];
data[stream] = []; // eslint-disable-line no-param-reassign
messages.forEach(([id, message]) => {
data[stream].push({ id, message });
});
return data;
}, {})
);
class RedisStream extends Duplex {
/**
* Creates a Duplex stream for reading and writing to a redis stream
* @param {Object|Redis} clientOptions Options passed to ioredis, or an IORedis.Redis instance
* @param {ConsumerOptions} consumerOptions Optional configuration passed to the consumer
* @property {String} clientOptions.host The redis host
*/
constructor(
clientOptions,
stream,
consumerOptions = {
group: null,
consumer: 'consumer',
block: 10000,
cursor: '0-0',
},
duplexOptions = {
readableObjectMode: true,
writableObjectMode: true,
writableHighWaterMark: 1,
readableHighWaterMark: 10,
},
) {
super(duplexOptions);
/**
* @type {Redis}
* @description The redis client
*/
this.redis = clientOptions instanceof Redis ? clientOptions : new Redis(clientOptions);
// this will actually kinda work, but definitely not expected
// or really well defined behavior so just throw the error
if (!stream) {
throw Error('Stream is a required argument');
}
this.stream = stream;
this.group = consumerOptions.group;
this.consumer = consumerOptions.consumer;
// groups can use > to get the latest unread events
// but this won't work for standard consumers
this.cursor = consumerOptions.cursor;
this.block = consumerOptions.block || 10000;
// this.blocked = false; // could be used as a fallback for node v8/v9
// https://github.com/nodejs/node/issues/3203#issuecomment-343152157 for more
this.redis.once('end', () => { this.emit('end'); });
}
_process(read, size) {
if (read) {
const parsed = parsexread(read);
const messages = parsed[this.stream];
this.cursor = messages[messages.length - 1].id;
messages.forEach(message => this.push(message));
} else {
// You can customize this to your liking but in my case
// if there are no messages available I just retry the read
this._read(size); // eslint-disable-line no-underscore-dangle
}
}
_read(size) {
// if (this.blocked) return null;
if (this.group) {
this.redis.xreadgroup('BLOCK', this.block, 'GROUP', this.group, this.consumer, 'COUNT', size, 'STREAMS', this.stream, '>').then((response) => {
this._process(response, size); // eslint-disable-line no-underscore-dangle
}).catch((error) => {
this.emit('error', error);
});
} else {
this.redis.xread('BLOCK', this.block, 'COUNT', size || 1, 'STREAMS', this.stream, this.cursor).then((response) => {
this._process(response, size); // eslint-disable-line no-underscore-dangle
}).catch((error) => {
this.emit('error', error);
});
}
}
/**
*
* @param {RedisChunk} chunk The data to write
* @param {String} encoding The encoding
* @param {Function} callback Called when the write is completed
*/
_write({ id, message }, encoding, callback) {
// I use a custom formatter but for the example I'll just provide an array
this.redis.xadd(this.stream, id, ...message).then((response) => {
this.emit('wrote', response);
if (callback) callback(null);
}).catch((error) => {
if (callback) callback(error);
});
}
}
module.exports = RedisStream;
/**
* MIT License
Copyright (c) 2018 Matthew D. Bark
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
*/
const RedisStream = require('./ioredis-duplex');
const group = 'test';
const streamName = 'slack:test';
const stream = new RedisStream('localhost', streamName);
const groupStream = new RedisStream('localhost', streamName, { group, cursor: '>' });
stream.on('error', console.error);
stream.on('wrote', (id) => { console.info('wrote', id); });
stream.on('timeout', (ts, cursor) => { console.debug('Timed out waiting for new messages', cursor); });
stream.on('data', ({ id, message }) => { console.log(`[${id}]`, message); });
stream.on('end', () => { console.info('The stream ended!'); });
groupStream.on('data', ({ id, message }) => { console.log(`[${group}.${id}]`, message); });
const write = () => {
const now = new Date();
const text = `Fired from interval ${now.toLocaleDateString()} - ${now.toLocaleTimeString()}`;
stream.write({
id: '*',
message: ['text', text],
}, (error) => {
if (error) console.error('Could not write', text, error);
});
};
write(); // just to force the stream creation
stream.redis.xgroup('CREATE', streamName, group, '0').then((result) => {
console.log(result);
return result;
}).catch((err) => {
console.error(err);
return err;
});
stream.read();
const interval = setInterval(write, 5000);
process.on('beforeExit', () => { clearInterval(interval); });
echo node v10.1 or later is required
echo see https://github.com/nodejs/node/issues/3203 and https://github.com/nodejs/node/pull/17979
node ioredis-index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment