taskflow-mongoid 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9f6207e24297a546ecaf6ac571ef038ff85df29d
4
+ data.tar.gz: 897ccc7e04641d6506b106ce269513b85498bb44
5
+ SHA512:
6
+ metadata.gz: 62153a6ef8a35f7840b01d3fdd4cb7466c5bce59a6a7bc53763b4dc0a0f15628d07f016f88964148ca844fb62b9f67c1b1a13fec644b9d32086ddd93eeeec6a6
7
+ data.tar.gz: 0910446837c77db561162c8ccbb20bc4e6c506d4ca466526caf0969163ec34a14eb65a8804619f280a8f85c05efa7933c8503021aa1b9c6b9bb11470e6ffa6f1
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.gem
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in taskflow.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 qujianping
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,158 @@
1
+ # Taskflow
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/taskflow`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'taskflow-mongoid',:require=>'taskflow'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install taskflow-mongoid
22
+
23
+ ## Usage
24
+
25
+ example:
26
+ ```ruby
27
+ class PlayFlow < Taskflow::Flow
28
+ NAME = "Play FLow"
29
+ def configure
30
+ t1 = run PendingTask, params: input, name: 'pending-task'
31
+ t2 = run OkTask,after: t1,name: 'ok-task'
32
+ t3 = run AlwaysFailTask,after: t1,name: 'always-fail-task'
33
+ t4 = run RetryPassTask,after: t1,name: 'retry-pass-task'
34
+ t5 = run OkTask,after: t4,name: 'just-play-task'
35
+ run SummaryTask,after: [t2,t3,t5],name: 'summary-task'
36
+ run OkTask,params: {love: 3},name: 'finished-task'
37
+ end
38
+ end
39
+ class PendingTask < Taskflow::Task
40
+ def go(logger)
41
+ logger.info "I got input paramter: #{input}"
42
+ logger.info 'first step,then suspend'
43
+ if data[:who]
44
+ logger.info "cool, #{data[:who]} wake me up!"
45
+ tflogger.info 'Pending task wake up'
46
+ set_output :reason=>'you are cool'
47
+ else
48
+ logger.info 'I would suspended now, wake for your wakeup.'
49
+ suspend
50
+ end
51
+ end
52
+ end
53
+ class OkTask < Taskflow::Task
54
+ def go(logger)
55
+ set_output "result"=>(rand 10)
56
+ logger.info "#{self.name} finished"
57
+ end
58
+ end
59
+ class AlwaysFailTask < Taskflow::Task
60
+ def go(logger)
61
+ logger.info 'I would always fail, pls skip me'
62
+ raise 'Ops, always fail!!!'
63
+ end
64
+ end
65
+ class SummaryTask < Taskflow::Task
66
+ def go(logger)
67
+ logger.info 'get upstream output'
68
+ upstream.each do |task|
69
+ logger.info "Upstream task[#{task.name}]: #{task.output}"
70
+ end
71
+ end
72
+ end
73
+
74
+ class RetryPassTask < Taskflow::Task
75
+ def go(logger)
76
+ if data.empty?
77
+ set_data :success_next_time=>true
78
+ raise 'fail, please retry'
79
+ else
80
+ logger.info 'second time ok'
81
+ end
82
+ logger.info 'retry succeed'
83
+ end
84
+ end
85
+ ```
86
+ Then schedule taskflow like below:
87
+
88
+ ```ruby
89
+ f=Taskflow::Flow.launch 'PlayFlow',:params=>{word: 'hello'},:launched_by=>'Jason',:workflow_description=>'desc'
90
+ # find PendingTask
91
+ t=f.tasks.where(state: 'paused',result: 'suspend').first
92
+ t.wakeup :who=>'Tom'
93
+ # find AlwaysFailTask
94
+ t=f.tasks.find_by name: 'always-fail-task'
95
+ puts t.error
96
+ # {"class"=>"RuntimeError", "message"=>"Ops, always fail!!!", "backtrace"=>["/U..."]}
97
+ t.skip
98
+ t=f.tasks.find_by name: 'retry-pass-task'
99
+ t.resume
100
+ # wait for while
101
+ puts f.state # => stopped
102
+ # and we can check the log of taskflow itself
103
+ puts f.logger.records
104
+
105
+ # all sidekiq log
106
+ Taskflow::Worker JID-905f46ac2a14b79329cc2526 INFO: start
107
+ Taskflow::Worker JID-905f46ac2a14b79329cc2526 INFO: I got input paramter: {"word"=>"hello"}
108
+ Taskflow::Worker JID-905f46ac2a14b79329cc2526 INFO: first step,then suspend
109
+ Taskflow::Worker JID-905f46ac2a14b79329cc2526 INFO: I would suspended now, wake for your wakeup.
110
+ Taskflow::Worker JID-905f46ac2a14b79329cc2526 INFO: done: 0.034 sec
111
+ Taskflow::Worker JID-cdcba34bc5f4746d0f0b68ad INFO: start
112
+ Taskflow::Worker JID-cdcba34bc5f4746d0f0b68ad INFO: I got input paramter: {"word"=>"hello"}
113
+ Taskflow::Worker JID-cdcba34bc5f4746d0f0b68ad INFO: first step,then suspend
114
+ Taskflow::Worker JID-cdcba34bc5f4746d0f0b68ad INFO: cool, Tom wake me up!
115
+ Taskflow::Worker JID-cdcba34bc5f4746d0f0b68ad INFO: done: 0.059 sec
116
+ Taskflow::Worker JID-2167fefe864f5de18ca7341e INFO: start
117
+ Taskflow::Worker JID-f1131d60a2d7530953f346ec INFO: start
118
+ Taskflow::Worker JID-259ef2694a65e235cf010b1e INFO: start
119
+ Taskflow::Worker JID-259ef2694a65e235cf010b1e INFO: I would always fail, pls skip me
120
+ Taskflow::Worker JID-2167fefe864f5de18ca7341e INFO: ok-task finished
121
+ Taskflow::Worker JID-259ef2694a65e235cf010b1e INFO: done: 0.077 sec
122
+ Taskflow::Worker JID-2167fefe864f5de18ca7341e INFO: done: 0.083 sec
123
+ Taskflow::Worker JID-f1131d60a2d7530953f346ec INFO: done: 0.084 sec
124
+ Taskflow::Worker JID-2d4f24491b84a68334cebaab INFO: start
125
+ Taskflow::Worker JID-2d4f24491b84a68334cebaab INFO: done: 0.022 sec
126
+ Taskflow::Worker JID-6312d5b0e1c66602bf04372e INFO: start
127
+ Taskflow::Worker JID-6312d5b0e1c66602bf04372e INFO: second time ok
128
+ Taskflow::Worker JID-6312d5b0e1c66602bf04372e INFO: retry succeed
129
+ Taskflow::Worker JID-6312d5b0e1c66602bf04372e INFO: done: 0.027 sec
130
+ Taskflow::Worker JID-dda69c567c7009219f6237b6 INFO: start
131
+ Taskflow::Worker JID-dda69c567c7009219f6237b6 INFO: just-play-task finished
132
+ Taskflow::Worker JID-dda69c567c7009219f6237b6 INFO: done: 0.032 sec
133
+ Taskflow::Worker JID-7163d1fa16a685d016642a6b INFO: start
134
+ Taskflow::Worker JID-7163d1fa16a685d016642a6b INFO: get upstream output
135
+ Taskflow::Worker JID-7163d1fa16a685d016642a6b INFO: Upstream task[ok-task]: {"result"=>4}
136
+ Taskflow::Worker JID-7163d1fa16a685d016642a6b INFO: Upstream task[always-fail-task]: {}
137
+ Taskflow::Worker JID-7163d1fa16a685d016642a6b INFO: Upstream task[just-play-task]: {"result"=>0}
138
+ Taskflow::Worker JID-7163d1fa16a685d016642a6b INFO: done: 0.03 sec
139
+ Taskflow::Worker JID-d7d0c92da5ab820bc1f66651 INFO: start
140
+ Taskflow::Worker JID-d7d0c92da5ab820bc1f66651 INFO: finished-task finished
141
+ Taskflow::Worker JID-d7d0c92da5ab820bc1f66651 INFO: done: 0.021 sec
142
+ ```
143
+
144
+ ## Development
145
+
146
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
147
+
148
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
149
+
150
+ ## Contributing
151
+
152
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/taskflow. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
153
+
154
+
155
+ ## License
156
+
157
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
158
+
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "taskflow"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
data/lib/taskflow.rb ADDED
@@ -0,0 +1,11 @@
1
+ require "taskflow/version"
2
+ require 'active_support/core_ext/hash/indifferent_access'
3
+ require 'taskflow/flow'
4
+ require 'taskflow/task'
5
+ require 'taskflow/worker'
6
+ require 'taskflow/logger'
7
+ require 'taskflow/record'
8
+
9
+ module Taskflow
10
+ # Your code goes here...
11
+ end
@@ -0,0 +1,117 @@
1
+ # coding: utf-8
2
+ class Taskflow::Flow
3
+ include ::Mongoid::Document
4
+
5
+ field :name, type: String
6
+ field :klass, type: String, default: -> { self.class.to_s }
7
+ field :state, type: String, default: 'pending'
8
+ field :category, type: String, default: 'simple'
9
+ field :result, type: String
10
+ field :launched_by, type: String
11
+ field :halt_by, type: String
12
+ field :input,type: Hash
13
+ field :progress,type: Float, default: 0
14
+ field :started_at, type: Time
15
+ field :ended_at, type: Time
16
+ field :next_config, type: Hash
17
+
18
+ after_create :configure_tasks
19
+
20
+ has_many :tasks, :class_name=>'Taskflow::Task',:inverse_of=>:flow,:dependent => :destroy
21
+ has_one :logger,:class_name=>'Taskflow::Logger',:inverse_of=>:flow, :dependent => :destroy
22
+
23
+ class << self
24
+
25
+ # opts support :params,
26
+ def can_launch?(klass,opts={})
27
+ opts = HashWithIndifferentAccess.new opts
28
+ !Taskflow::Flow.ne(state: 'stopped').where(klass: klass,input: opts[:params]).exists?
29
+ end
30
+
31
+ def launch(klass,opts={})
32
+ opts = HashWithIndifferentAccess.new opts
33
+ flow_klass = Kernel.const_get klass
34
+ name = flow_klass.const_get 'NAME'
35
+ opts[:launched_by] ||= 'task-flow-engine'
36
+ flow = flow_klass.create name: name,input: opts[:params],launched_by: opts[:launched_by]
37
+ if opts[:next_workflow_config]
38
+ flow.update next_config: opts[:next_workflow_config]
39
+ end
40
+ flow.create_logger name: name,description: opts[:workflow_description]
41
+ flow.schedule
42
+ end
43
+ end
44
+
45
+ def running_steps
46
+ self.tasks.in(state: ['running','paused'])
47
+ end
48
+
49
+ # opts support :name,:params
50
+ def run(klass,opts={})
51
+ obj = {
52
+ klass: klass.to_s,
53
+ name: opts[:name] || klass.to_s,
54
+ input: opts[:params],
55
+ index: self.tasks.size + 1
56
+ }
57
+ task = klass.create obj.select{|k,v| v }
58
+ if opts[:before]
59
+ task.downstream << opts[:before]
60
+ end
61
+ if opts[:after]
62
+ task.upstream << opts[:after]
63
+ end
64
+ if opts[:before].nil? && opts[:after].nil? && self.tasks.last
65
+ self.tasks.last.downstream << task
66
+ end
67
+ self.tasks << task
68
+ task
69
+ end
70
+
71
+ def stop!(user_id=nil)
72
+ percent = self.tasks.map(&:progress).sum / self.tasks.size
73
+ self.update_attributes! progress: percent,halt_by: user_id,ended_at: Time.now, state: 'stopped',result: 'warning'
74
+ end
75
+
76
+ def resume
77
+ self.tasks.where(state: 'paused',result: 'error').each do |task|
78
+ task.resume
79
+ end
80
+ end
81
+
82
+ def schedule
83
+ return if self.halt_by || self.state == 'stopped'
84
+ self.update_attributes! state: 'running',started_at: Time.now if self.state == 'pending'
85
+ task_list = []
86
+ self.reload.tasks.where(state: 'pending').each do |task|
87
+ # 上游全部完成
88
+ if task.upstream.empty? || task.upstream.all?{|t| %w(skipped stopped).include? t.state }
89
+ task_list << task.id.to_s
90
+ end
91
+ end
92
+ task_list.each{|tid| Taskflow::Worker.perform_async self.id.to_s,tid }
93
+ self
94
+ end
95
+
96
+ private
97
+ def configure_tasks
98
+ begin
99
+ configure
100
+ sort_index 1,[]
101
+ rescue=>exception
102
+ self.destroy
103
+ raise exception
104
+ end
105
+ reload
106
+ end
107
+
108
+ def sort_index(i,scanned)
109
+ queue = self.tasks.nin(id: scanned).select{|t| t.upstream.empty? || t.upstream.all?{|upt| scanned.include?(upt.id.to_s)}}
110
+ return if queue.empty?
111
+ queue.each do |task|
112
+ task.update_attributes index: i
113
+ scanned << task.id.to_s
114
+ end
115
+ sort_index i + 1,scanned
116
+ end
117
+ end
@@ -0,0 +1,51 @@
1
+ class Taskflow::Logger
2
+ include ::Mongoid::Document
3
+ belongs_to :flow, :class_name=>'Taskflow::Flow',:inverse_of=>:logger
4
+
5
+ field :name, type: String
6
+ field :description, type: String
7
+ field :created_at, type: Time, default: ->{ Time.now }
8
+
9
+ embeds_many :records,:class_name=>'Taskflow::Record',:inverse_of=>:logger
10
+
11
+ def log(content,options={})
12
+ raise 'Need step id to write a log' if options[:step_id].nil? && @step_id.nil?
13
+ options[:step_id] ||= @step_id
14
+ options[:writer] ||= @writer
15
+ @step_id ||= options[:step_id]
16
+ @writer ||= options[:writer]
17
+ options.merge! :content=>content
18
+ record = self.records.last
19
+ if record && options.all?{|k,v| record.send(k) == v }
20
+ record.update_attributes! written_at: Time.now
21
+ else
22
+ self.records.create options
23
+ end
24
+ end
25
+
26
+ def info(content,options={})
27
+ options.merge!(:level=>'INFO')
28
+ self.log content,options
29
+ end
30
+
31
+ def error(content,options={})
32
+ options.merge!(:level=>'ERROR')
33
+ self.log content,options
34
+ end
35
+
36
+ def fatal(content,options={})
37
+ options.merge!(:level=>'FATAL')
38
+ self.log content,options
39
+ end
40
+
41
+ def warning(content,options={})
42
+ options.merge!(:level=>'WARNING')
43
+ self.log content,options
44
+ end
45
+
46
+ def debug(content,options={})
47
+ options.merge!(:level=>'DEBUG')
48
+ self.log content,options
49
+ end
50
+
51
+ end
@@ -0,0 +1,11 @@
1
+ class Taskflow::Record
2
+ include ::Mongoid::Document
3
+ embedded_in :logger,:class_name=>'Taskflow::Logger',:inverse_of=>:records
4
+
5
+ field :step_id, type: Integer
6
+ field :writer, type: String
7
+ field :written_at, type: Time, default: ->{ Time.now }
8
+ field :level, type: String, default: 'INFO'
9
+ field :content, type: String
10
+ field :tags, type: Hash, default: {}
11
+ end
@@ -0,0 +1,98 @@
1
+ # coding: utf-8
2
+ class Taskflow::Task
3
+ include ::Mongoid::Document
4
+
5
+ field :index, type: Integer, default: 1
6
+ field :name, type: String
7
+ field :klass, type: String, default: -> { self.class.to_s }
8
+ # all aviable states: :pending, :running, :paused, :stopped, :skipped
9
+ field :state, type: String, default: 'pending'
10
+ field :result,type: String
11
+
12
+ field :started_at, type: Time
13
+ field :ended_at, type: Time
14
+
15
+ field :output,type: Hash, default: {}
16
+ # task flow params would be set here
17
+ field :input,type: Hash, default: {}
18
+ field :error, type: Hash
19
+
20
+ field :progress, type: Float, default: 0
21
+
22
+ # tmp data, would be wipe out after task finished
23
+ field :data, type: Hash, default: {}
24
+
25
+ # do not save myself in up or downstream
26
+ before_save :remove_self_in_stream
27
+
28
+ has_and_belongs_to_many :downstream, :class_name=>'Taskflow::Task',:inverse_of=>:upstream
29
+ has_and_belongs_to_many :upstream, :class_name=>'Taskflow::Task',:inverse_of=>:downstream
30
+
31
+ belongs_to :flow,:class_name=>'Taskflow::Flow',:inverse_of=>:tasks
32
+
33
+ def go(sidekiq_logger)
34
+ end
35
+
36
+ def resume
37
+ if self.state == 'paused' && self.result == 'error'
38
+ self.flow.update_attributes! state: 'running'
39
+ Taskflow::Worker.perform_async self.flow.id.to_s,self.id.to_s
40
+ end
41
+ end
42
+
43
+ def wakeup(arguments={})
44
+ self.reload
45
+ if self.state == 'paused' && self.result == 'suspend'
46
+ self.data = self.data.merge arguments
47
+ self.result = nil
48
+ self.save
49
+ Taskflow::Worker.perform_async self.flow.id.to_s,self.id.to_s
50
+ end
51
+ end
52
+
53
+ def skip
54
+ self.reload
55
+ if self.state == 'paused'
56
+ self.update_attributes! state: 'skipped'
57
+ Taskflow::Worker.perform_async self.flow.id.to_s,self.id.to_s
58
+ end
59
+ end
60
+
61
+ private
62
+
63
+ def remove_self_in_stream
64
+ downstream.delete self if downstream.include? self
65
+ upstream.delete self if upstream.include? self
66
+ end
67
+
68
+ def suspend
69
+ throw :control,:suspend
70
+ end
71
+
72
+ def tflogger
73
+ @tflogger ||= (
74
+ _logger = flow.logger
75
+ _logger.instance_variable_set '@step_id',self.index
76
+ _logger.instance_variable_set '@writer',self.name
77
+ _logger
78
+ )
79
+ end
80
+
81
+ def method_missing(name,*args)
82
+ if /^(set|append|clear)_(input|output|data)$/ =~ name.to_s
83
+ act,fd = name.to_s.split '_'
84
+ if act == 'set'
85
+ return false unless args.first
86
+ self.update_attributes! "#{fd}"=>args.first
87
+ elsif act == 'append'
88
+ return false unless args.first
89
+ self.update_attributes! "#{fd}"=>self.send("#{fd}").merge(args.first)
90
+ else
91
+ self.update_attributes! "#{fd}"=>{}
92
+ end
93
+ else
94
+ super
95
+ end
96
+ end
97
+
98
+ end
@@ -0,0 +1,3 @@
1
+ module Taskflow
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,90 @@
1
+ # coding: utf-8
2
+ class Taskflow::Worker
3
+ include ::Sidekiq::Worker
4
+ sidekiq_options :retry => false
5
+
6
+ def perform(task_flow_id,job_id,opts={})
7
+ flow = Taskflow::Flow.find task_flow_id
8
+ task = Taskflow::Task.find job_id
9
+ begin
10
+ reason = catch :control do
11
+ check_flow_state flow
12
+ check_task_state task
13
+ task.update_attributes! state: 'running',started_at: Time.now,ended_at: nil, progress: 0.5,output: {},error: nil,result: nil
14
+ task.go logger
15
+ end
16
+ case reason
17
+ when :flow_halt
18
+ flow.update_attributes! ended_at: Time.now unless flow.ended_at
19
+ when :suspend
20
+ task.update_attributes! result: 'suspend',state: 'paused'
21
+ when :skip
22
+ task.update_attributes! state: 'skipped',data: {}
23
+ when :already_running,:already_stopped
24
+ return
25
+ else
26
+ task.update_attributes! data: {},ended_at: Time.now,progress: 1,state: 'stopped',result: 'success'
27
+ end
28
+ rescue=>exception
29
+ task.error = {
30
+ class: exception.class.to_s,
31
+ message: exception.to_s,
32
+ backtrace: exception.backtrace
33
+ }
34
+ task.state = 'paused'
35
+ task.result = 'error'
36
+ task.ended_at = Time.now
37
+ task.save
38
+ end
39
+ update_flow flow.reload
40
+ flow.schedule
41
+ end
42
+
43
+ private
44
+ def check_flow_state(flow)
45
+ if flow.state == 'stopped' || flow.halt_by
46
+ throw :control, :flow_halt
47
+ end
48
+ end
49
+ def check_task_state(task)
50
+ case task.state
51
+ when 'pending'
52
+ task.update_attributes state: 'running'
53
+ when 'running'
54
+ throw :control, :already_running
55
+ when 'paused'
56
+ throw :control, :suspend if task.result == 'suspend'
57
+ when 'stopped'
58
+ throw :control, :already_stopped
59
+ when 'skipped'
60
+ throw :control,:skip
61
+ else
62
+ raise "Unkown task state #{task.state}"
63
+ end
64
+ end
65
+
66
+ def update_flow(flow)
67
+ return if flow.halt_by || flow.state == 'stopped'
68
+ flow.progress = flow.tasks.map(&:progress).sum / flow.tasks.size
69
+ if flow.halt_by
70
+ flow.state = 'stopped'
71
+ elsif flow.tasks.all?{|t| %w(stopped skipped).include? t.state }
72
+ flow.state = 'stopped'
73
+ elsif flow.tasks.any?{|t| t.state == 'paused' }
74
+ flow.state = 'paused'
75
+ flow.result = flow.tasks.find_by(state: 'paused').result
76
+ else
77
+ flow.state = 'running'
78
+ end
79
+ if flow.state == 'stopped'
80
+ flow.result = flow.tasks.all?{|t| t.result == 'success' } ? 'success' : 'warning'
81
+ flow.ended_at = Time.now
82
+ if flow.next_config
83
+ logger.info "Auto boot next flow, #{flow.next_config}"
84
+ Taskflow::Flow.launch flow.next_config[:name],flow.next_config[:config]
85
+ end
86
+ end
87
+ flow.save
88
+ end
89
+
90
+ end
data/taskflow.gemspec ADDED
@@ -0,0 +1,34 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'taskflow/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "taskflow-mongoid"
8
+ spec.version = Taskflow::VERSION
9
+ spec.authors = ["qujianping"]
10
+ spec.email = ["qjpcpu@gmail.com"]
11
+
12
+ spec.summary = %q{Easy task flow based on sidekiq.}
13
+ spec.description = %q{Easy task flow based on sidekiq.}
14
+ spec.homepage = "https://github.com/qjpcpu/taskflow-mongoid"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18
+ # delete this section to allow pushing this gem to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23
+ end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_development_dependency "bundler", "~> 1.10"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ spec.add_runtime_dependency "sidekiq","~> 3.3"
33
+ spec.add_runtime_dependency "mongoid","~> 4.0"
34
+ end
metadata ADDED
@@ -0,0 +1,117 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: taskflow-mongoid
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - qujianping
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2015-07-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: sidekiq
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.3'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.3'
55
+ - !ruby/object:Gem::Dependency
56
+ name: mongoid
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '4.0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '4.0'
69
+ description: Easy task flow based on sidekiq.
70
+ email:
71
+ - qjpcpu@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - CODE_OF_CONDUCT.md
78
+ - Gemfile
79
+ - LICENSE.txt
80
+ - README.md
81
+ - Rakefile
82
+ - bin/console
83
+ - bin/setup
84
+ - lib/taskflow.rb
85
+ - lib/taskflow/flow.rb
86
+ - lib/taskflow/logger.rb
87
+ - lib/taskflow/record.rb
88
+ - lib/taskflow/task.rb
89
+ - lib/taskflow/version.rb
90
+ - lib/taskflow/worker.rb
91
+ - taskflow.gemspec
92
+ homepage: https://github.com/qjpcpu/taskflow-mongoid
93
+ licenses:
94
+ - MIT
95
+ metadata:
96
+ allowed_push_host: https://rubygems.org
97
+ post_install_message:
98
+ rdoc_options: []
99
+ require_paths:
100
+ - lib
101
+ required_ruby_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ required_rubygems_version: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ requirements: []
112
+ rubyforge_project:
113
+ rubygems_version: 2.2.2
114
+ signing_key:
115
+ specification_version: 4
116
+ summary: Easy task flow based on sidekiq.
117
+ test_files: []