Giter VIP home page Giter VIP logo

node-background-task's Introduction

kinvey logo

node-background-task

Distributed task execution framework for node, backed by redis. Build Status

var bgTask = require('background-task').connect({ taskKey: 'someKey' })
  , task;

task = {
  someKey      : 'someValue',
  someOtherKey : ['someValues', 'someMoreValues']
};

bgTask.addTask(task, function(resp){
    console.log(resp);
});

Migrating from v1 to v2

v2 of NBT has switched from using the node_redis module to using ioredis. The host, password, and port keys in the options object that is used when initializing a client/server are deprecated. Use redisOptions instead.

The shutdown method now contains an optional callback.

Installation

$ npm install background-task

Quick Start

Background tasks involve two concepts, creators and workers. Creators have tasks that they need executed, workers know how to execute tasks. Workers listen for events tagged with a specific task and execute them. Should no worker execute the task in a specific time (which can be customized) then a failure is reported back.

Additionally, the number of active tasks can be limited using a "task key" (which must be a property at the top level of you task object), where only N tasks can be pending on a certain key prior to failures.

Task Creators

  • connect(options) -- Creates a new instance of a BackgroundTask, allowing you to specify options.
  • addTask(task, callback[, progress]) -- Schedule a task for background execution, calling progress on task progress and `callback when complete.

Task Workers

Processing for a worker is kicked off by the TASK_AVAILABLE event, once you get this event you can either accept the task, or ignore the task. If multiple workers accept the task then the first to accept will handle the task.

  • connect(options) -- Create a new instance of a BackgroundTask, allowing you to specify options. You must specify isWorker: true to register as a background worker.
  • acceptTask(callback) -- Accepts a task from the queue to start processing, callback must accept two args, id and a paramater for the task.
  • completeTask(taskId, status, msg) -- Mark a task as complete.
  • progressTask(taskId, msg) -- Report task progress.
  • shutdown(callback -- Shuts down NBT

Options

The options hash for creators and workers allows you to set:

  • redisOptions -- The redis options object. Supports all options used by ioredis v2.4.2
  • maxTasksPerKey -- limit the amount of active tasks based on the "task key".
  • taskKey -- the task key.
  • task -- listen for specific tasks only.
  • timeout -- task timeout (in ms).

The following options are deprecated and will be removed in the next major release of this library. Use redisOptions instead.

  • DEPRECATED password -- redis password.
  • DEPRECATED host -- redis host.
  • DEPRECATED port -- redis port.

Events

node-background-task uses the following events:

  • TASK_AVAILABLE -- There is data available for a background worker.
  • TASK_DONE -- A task has finished and the response is ready, task may not be successful, just complete.
  • TASK_PROGRESS -- Progress is reported for a task.
  • TASK_ERROR -- Something went wrong.

Features

  • Lightweight
  • Backed by redis (Can be portable to other DBs)
  • Callback and Event based
  • Easy to build distributed architectures
  • Workers are event driven, not polling
  • Task limiting

Why?

We looked at the excellent coffee-resque project to fit an internal need, however we needed a non-polling based worker architecture. There are up and down-sides to this approach, but the balance was correct for the architecture that we're creating at Kinvey.

License

Copyright 2013 Kinvey, Inc

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

node-background-task's People

Contributors

mjsalinger avatar echoabstract avatar vseventer avatar sjl2024 avatar segdeha avatar aaylward avatar marcbachmann avatar m0rganic avatar

Stargazers

 avatar Rahaman Jamilur  avatar ozgur avatar Meena Brend avatar Kyozki avatar  avatar  avatar bxio avatar Josh avatar Dave Spector avatar Phellipe Andrade avatar Kostas Nasis avatar Chris Chang avatar Gabriel Ferreira avatar Patrick Faramaz avatar Dmitry Nikitin avatar Omri Bruchim avatar Alexander Petrovich avatar  avatar Peter Parada avatar Mozart Brum avatar Everton Ribeiro avatar Lucas Ricoy avatar Chun-wei Kuo avatar Rahil Wazir avatar Vahagn Mkrtchyan avatar Mauro avatar Berkus Decker avatar BenHen avatar James Dixon avatar Fernando Girotto avatar Peter P. Gengler avatar  avatar lyfeyaj avatar B.S. avatar Dai Hovey avatar Kostas Bariotis avatar Sharad K avatar Baskar Puvanathasan avatar Alessandro (Ale) Segala avatar Ilya Radchenko avatar Tamás András Horváth avatar Jonathan Warykowski avatar Vitaliy avatar Stephen Reid avatar Florian Ferbach avatar Konstantin Pavlov avatar Dick Hardt avatar Cameron Jackson avatar El Jesse || El jeffe avatar Rex Sheng avatar Daniel Lohse avatar Roman Pearah avatar G.Grandes avatar Vasanth Vaidyanathan avatar Matthias Gernand avatar ryan avatar Bryan MacFarlane avatar jeep avatar Tim Shnaider avatar John Oliva avatar Jon Morehouse avatar Laurian Gridinoc avatar  avatar David Willoughby avatar Dan Tamas avatar OKI Yukihiro avatar

Watchers

Nick Sakovich avatar Caroline avatar Lucas avatar James Cloos avatar Jeremy Clark avatar  avatar Ivan avatar Bogdan Naydenov avatar Ivan I. Ivanov avatar Tejas Ranade avatar Georgi Alexandrov avatar Sravish Sridhar avatar Edward Fleming avatar Tara Z. Manicsic avatar Lyubomir Dokov avatar  avatar  avatar Jikku Venkat avatar Andras avatar James Valente avatar  avatar Dimitar Kerezov avatar Justin Carrasco avatar  avatar Denny avatar Toma Nikolov avatar Rajiv avatar  avatar Tsvetan Milanov avatar  avatar  avatar Boris Karastanev avatar  avatar Vishwa Krishnamurthy avatar  avatar

node-background-task's Issues

common.wrapError being used incorrectly?

Looks like common.wrapError is being used incorrectly in notification_bus around line 170:

    this.dataClient.on('taskError', function (evt) {
      common.wrapError(evt);
    });
    this.pubClient.on('taskError', function (evt) {
      common.wrapError(evt);
    });
    this.subClient.on('taskError', function (evt) {
      common.wrapError(evt);
    });

common.wrapError returns a function, so these listeners won't do anything. It seems like wrapError is designed to "pipe" an error event from one emitter to another, and I don't know which emitter these listeners are attempting to pipe to.

Various queries

Great starter framework, thanks for open sourcing this.

  • How do you handle TaskClient instance dying for whatever reason leaving orphaned tasks in Redis e.g. watcher process, periodic task cleanup sweep?
  • How are you handling addTask with no available workers i.e. there is no queue system. It is easily possible that no workers in a pool are able to accept a task and therefore the pub broadcast is effectively lost as TaskClient is waiting on a guaranteed timeout.

I presume there is a more complicated dispatch/scheduler system @ Kinvey wrapped around this module.

Provide client instead of options?

I'm using ioredis in my application both for session storage, db caching, and background tasks. Can I share that client instance between all three?

Additional info in TASK_AVAILABLE for choosing to acceptTask

To acceptTask I want additional info in the sendNotification message beyond id and status as a filter.

The quickest fix would be to specify additional attributes that are added to the pubMessage in sendNotification, and to pass this to that.emit('TASK_AVAILABLE') in task_server.js, or just pass in the entire msg.

task_server.js

this.notificationBus.on('notification_received', function (id) {
      that.emit('TASK_AVAILABLE', id.id, id.target);
    });

notification_bus.js

pubMessage.target = message.taskDetails.target

I can now filter tasks in bgTask.on('TASK_AVAILABLE', function(...) {} );

Since there is no queue system I'm trying to achieve this since there may be no workers available and therefore timeout is guaranteed with current design:

Someone is posting a task with a 1sec timeout.
If no completion in timeout, repeat X times until Y reached, return back error

If completed, poster monitors TASK_AVAILABLE for 'target' of original message id and accepts/complete this. This task was generated by the worker and includes the result.
The worker ignores the completionCallback when posting it's return task.

A hack, but achieves a retry system until a worker is available or ultimate timeout is reached, without requiring a polling system by workers on a queue.

Task responses are orphaned when the client dies

When the client app dies suddenly, any tasks in flight will be orphaned. Proposed solution is that response hashes are generated with the client hostname as part of them, and cleaned up on client initialization.

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.