actn-jobs 0.0.1

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: c7ba55d931371dfd374240867d31863e02eed69b
4
+ data.tar.gz: f097835f57ea3c94583d06b365fa3aff6458f6c4
5
+ SHA512:
6
+ metadata.gz: 195441affe500cd214406941ae557fc3fe50c0a9d7ad24bb82cc66847c6aa70d4c15bfd1440190892aa92073ee7a72d461e6b248000f9a1164549b37f2ac42a1
7
+ data.tar.gz: 432f6f36416b2a969bbf2d4d33076a0d7ee057ee0fe1071d83b0c578fd1ab9e93afc0f33d64642cf8ecb2fa1b859ea862f3c4e5f681a2636b59b480a1b35a55a
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/.travis.yml ADDED
@@ -0,0 +1,3 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0.0
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in actn-jobs.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Onur Uyar
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # Actn::Jobs
2
+
3
+ Postgres Notify/Listen based Jobs
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'actn-jobs'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install actn-jobs
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Contributing
24
+
25
+ 1. Fork it ( http://github.com/<my-github-username>/actn-jobs/fork )
26
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
27
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
28
+ 4. Push to the branch (`git push origin my-new-feature`)
29
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.test_files = FileList['test/**/test*.rb']
7
+ end
8
+
9
+ task :default => :test
10
+
11
+ ENV['DATABASE_URL'] ||= "postgres://localhost:5432/actn_#{ENV['RACK_ENV'] ||= "development"}"
12
+
13
+ require 'actn/jobs'
14
+
15
+ load "actn/db/tasks/db.rake"
16
+ load "actn/jobs/tasks/jobs.rake"
data/actn-jobs.gemspec ADDED
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'actn/jobs/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "actn-jobs"
8
+ spec.version = Actn::Jobs::VERSION
9
+ spec.authors = ["Onur Uyar"]
10
+ spec.email = ["me@onuruyar.com"]
11
+ spec.summary = %q{Actn.io Jobs}
12
+ spec.homepage = "https://github.com/hackberry-gh/actn-jobs"
13
+ spec.license = "MIT"
14
+
15
+ spec.files = `git ls-files`.split($/)
16
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
17
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_development_dependency "bundler", "~> 1.5"
21
+ spec.add_development_dependency "rake"
22
+ spec.add_development_dependency "minitest"
23
+
24
+ spec.add_dependency 'actn-db'
25
+ end
data/db/1_jobs.sql ADDED
@@ -0,0 +1,67 @@
1
+ SET search_path TO public;
2
+
3
+ SELECT plv8_startup();
4
+
5
+ SELECT __create_table('core','jobs');
6
+
7
+ CREATE or REPLACE FUNCTION hook_trigger() RETURNS trigger AS
8
+ $$
9
+ upsert_func = plv8.find_function("__upsert")
10
+ model = JSON.parse(plv8.find_function("__find_model")(TG_TABLE_NAME.classify()))
11
+
12
+ callback = {
13
+ INSERT: "after_create"
14
+ UPDATE: "after_update"
15
+ DELETE: "after_destroy"
16
+ }[TG_OP]
17
+
18
+ # plv8.elog(NOTICE,"HOOK TRIGGER",JSON.stringify(model))
19
+
20
+ for hook in model?.hooks?[callback] or []
21
+ hook.run_at ?= new Date()
22
+ hook.callback = callback
23
+
24
+ job =
25
+ hook: hook
26
+ table_name: TG_TABLE_NAME
27
+ record_uuid: NEW?.data?.uuid or OLD?.data?.uuid
28
+ record: OLD.data if TG_OP is "DELETE"
29
+
30
+ res = upsert_func "core", "jobs", JSON.stringify(job)
31
+ plv8.execute "SELECT pg_notify('jobs', $1);", [res]
32
+
33
+
34
+ $$ LANGUAGE plcoffee STABLE STRICT;
35
+
36
+
37
+
38
+
39
+
40
+
41
+ CREATE or REPLACE FUNCTION jobs_model_callbacks() RETURNS trigger AS
42
+ $$
43
+ table_name = (NEW?.data?.name or OLD?.data?.name).tableize()
44
+
45
+ table_schema = (NEW?.data?.table_schema or OLD?.data?.table_schema) or "public"
46
+
47
+ return if table_schema is "core"
48
+
49
+ if TG_OP is "DELETE"
50
+ plv8.execute "DELETE FROM core.jobs WHERE __string(data, 'table_name'::text) = $1;", [table_name]
51
+
52
+ # if TG_OP is "DELETE" and OLD.data.hooks? or TG_OP is "UPDATE" and NEW.data.hooks?
53
+ # plv8.execute "DROP TRIGGER IF EXISTS #{table_schema}_#{table_name}_hook_trigger ON #{table_schema}.#{table_name}"
54
+
55
+
56
+ if TG_OP is "INSERT" or TG_OP is "UPDATE" and NEW.data.hooks? and not OLD.data.hooks?
57
+ plv8.execute """CREATE TRIGGER #{table_schema}_#{table_name}_hook_trigger
58
+ AFTER INSERT OR UPDATE OR DELETE ON #{table_schema}.#{table_name}
59
+ FOR EACH ROW EXECUTE PROCEDURE hook_trigger();"""
60
+
61
+
62
+
63
+ $$ LANGUAGE plcoffee STABLE STRICT;
64
+
65
+ CREATE TRIGGER jobs_core_models_callback_trigger
66
+ AFTER INSERT OR UPDATE OR DELETE ON core.models
67
+ FOR EACH ROW EXECUTE PROCEDURE jobs_model_callbacks();
@@ -0,0 +1,40 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-04/schema#",
3
+ "type": "object",
4
+ "properties": {
5
+ "hook": {
6
+ "$ref": "#/definitions/hook"
7
+ },
8
+ "table_name": { "type": "string" },
9
+ "record": { "type": "object" },
10
+ "record_uuid": { "type": "string" },
11
+ "result": {}
12
+ },
13
+ "required": ["hook", "table_name", "record_uuid"],
14
+ "definitions": {
15
+ "hook":{
16
+ "id": "#hook",
17
+ "description": "Async jobs for after callbacks",
18
+ "type": "object",
19
+ "patternProperties": {
20
+ "after_[create|update|destroy]" : {
21
+ "type": "array",
22
+ "items": {
23
+ "type" : "object",
24
+ "properties": {
25
+ "name": { "type": "string" },
26
+ "run_at": { "type": "date" },
27
+ "conditions": {
28
+ "type": "array",
29
+ "items": { "type": "string" }
30
+ }
31
+ },
32
+ "required": ["name"]
33
+ },
34
+ "minItems": 1,
35
+ "maxItems": 20
36
+ }
37
+ }
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,8 @@
1
+ require 'actn/jobs/base'
2
+
3
+ class Trace < Actn::Jobs::Base
4
+ def perform
5
+ puts "[Trace#perform, #{Time.now}]: #{job.inspect} #{record.inspect}"
6
+ end
7
+ end
8
+
data/lib/actn/hooks.rb ADDED
@@ -0,0 +1 @@
1
+ require "actn/hooks/trace"
@@ -0,0 +1,54 @@
1
+ require 'oj'
2
+ require 'time'
3
+ require 'actn/db/set'
4
+
5
+ module Actn
6
+ module Jobs
7
+
8
+ class Base
9
+ attr_accessor :job, :record
10
+
11
+ def initialize job
12
+ @job = job
13
+ @record = job.record || Oj.load(DB::Set[job.table_name].find_by({uuid: job.record_uuid}))
14
+ end
15
+
16
+ def perform
17
+ end
18
+
19
+ def test_and_perform
20
+
21
+ unless self.record
22
+ $stderr.puts "[#{self.class.name}#test_and_perform, #{Time.now}]: Record not found"
23
+ return
24
+ end
25
+
26
+ if job.hook['conditions'].nil? || ( !job.hook['conditions'].map{|c| eval(c,binding) ? true : false }.include?(false) )
27
+
28
+ run
29
+
30
+ else
31
+
32
+ Jobs.logger.warn "Conditions failed, CONDITIONS: #{job.hook['conditions']} RECORD: #{self.record}"
33
+ job.update(result: {error: "Conditions failed"})
34
+
35
+ end
36
+
37
+ end
38
+
39
+ private
40
+
41
+ def run
42
+ begin
43
+ result = perform
44
+ rescue Exception => e
45
+ job.update(result: {error: {message: e.message, stack: e.respond_to?(:backtrace) ? e.backtrace : e.inspect}})
46
+ Jobs.logger.error e
47
+ end
48
+ job.update(result: result)
49
+ end
50
+
51
+ end
52
+
53
+ end
54
+ end
@@ -0,0 +1,16 @@
1
+ require 'actn/db/mod'
2
+
3
+ module Actn
4
+ module Jobs
5
+ class Job < DB::Mod
6
+
7
+ self.table = "jobs"
8
+ self.schema = "core"
9
+
10
+ data_attr_accessor :hook, :table_name, :record, :record_uuid, :result
11
+
12
+ validates_presence_of :hook, :table_name
13
+
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,6 @@
1
+ module Actn
2
+ module Jobs
3
+ class JobError < StandardError
4
+ end
5
+ end
6
+ end
@@ -0,0 +1,8 @@
1
+ require "actn/jobs"
2
+
3
+ namespace :jobs do
4
+ desc "runs job worker"
5
+ task :work do
6
+ Actn::Jobs::Worker.start
7
+ end
8
+ end
@@ -0,0 +1,5 @@
1
+ module Actn
2
+ module Jobs
3
+ VERSION = "0.0.1"
4
+ end
5
+ end
@@ -0,0 +1,73 @@
1
+ $stdout.sync = true
2
+ $stderr.sync = true
3
+
4
+ require 'actn/db'
5
+ require 'actn/jobs/job'
6
+ require 'i18n'
7
+
8
+ module Actn
9
+ module Jobs
10
+
11
+ class Worker
12
+
13
+ CHANNEL = "jobs".freeze
14
+
15
+ I18n.enforce_available_locales = false
16
+
17
+ def self.start
18
+
19
+ # pg = Actn::DB.pg
20
+ pg = PG::EM::Client.new(Actn::DB.db_config.dup.tap{|s| s.delete(:size) })
21
+
22
+ EM.run do
23
+
24
+ notify_proc = Proc.new { |notify|
25
+
26
+ raise JobError.new("Payload Missing") unless payload = (Oj.load(notify[:extra]) rescue nil)
27
+
28
+ raise JobError.new("Job not found") unless job = Job.find(payload['uuid'])
29
+
30
+ hook = job.hook
31
+
32
+ raise JobError.new("Hook name missing") unless hook['name']
33
+
34
+ raise JobError.new("Hook class missing") unless hook_class = (Object.const_get(hook['name']) rescue nil)
35
+
36
+ if (run_at = ((Time.parse(hook['run_at']) rescue nil) || eval(hook['run_at'])) ) > Time.now
37
+
38
+ EM.add_timer(run_at - Time.now, proc{ notify_proc.call(notify) })
39
+
40
+ else
41
+
42
+ hook_class.new(job).test_and_perform
43
+
44
+ end
45
+
46
+
47
+ }
48
+
49
+ error_proc = Proc.new { |ex|
50
+ Jobs.logger.error ex
51
+ }
52
+
53
+ wait_proc = Proc.new { |notify|
54
+
55
+ notify_proc.call(notify) if notify
56
+
57
+ pg.wait_for_notify_defer.callback(&wait_proc).errback(&error_proc)
58
+
59
+ }
60
+
61
+ pg.wait_for_notify_defer.callback(&wait_proc).errback(&error_proc)
62
+
63
+ pg.query_defer("LISTEN #{CHANNEL}")
64
+
65
+ end
66
+
67
+
68
+ end
69
+
70
+ end
71
+ end
72
+
73
+ end
data/lib/actn/jobs.rb ADDED
@@ -0,0 +1,31 @@
1
+ require "actn/paths"
2
+ require "actn/db"
3
+ require "actn/jobs/version"
4
+ require "actn/jobs/job_error"
5
+ require "actn/jobs/job"
6
+ require "actn/jobs/worker"
7
+ require "actn/jobs/base"
8
+ require 'actn/hooks'
9
+ require 'logger'
10
+
11
+ module Actn
12
+ module Jobs
13
+
14
+ include Paths
15
+
16
+ def self.logger
17
+ @@logger ||= begin
18
+ logger = Logger.new(STDOUT)
19
+ logger.level = Logger::INFO
20
+ logger
21
+ end
22
+ end
23
+
24
+ def self.gem_root
25
+ @@gem_root ||= File.expand_path('../../../', __FILE__)
26
+ end
27
+
28
+ end
29
+ end
30
+
31
+ Actn::DB.paths << Actn::Jobs.gem_root
@@ -0,0 +1,74 @@
1
+ require 'minitest_helper'
2
+ require 'actn/db'
3
+
4
+ module Actn
5
+ module Jobs
6
+
7
+ class TestJobs < MiniTest::Test
8
+
9
+ def setup
10
+
11
+
12
+ @model = DB::Model.create(
13
+ {
14
+ name: "Car",
15
+ hooks: {
16
+ after_create: [
17
+ {
18
+ name: "Trace",
19
+ run_at: Time.now + 2 # 2 seconds later
20
+ },
21
+ {
22
+ name: "Trace"
23
+ }
24
+ ],
25
+ after_update: [
26
+ {
27
+ name: "Trace",
28
+ conditions: [
29
+ "record['first_name'] == 'Bonzo'"
30
+ ]
31
+ }
32
+ ],
33
+ after_destroy: [
34
+ {
35
+ name: "Trace"
36
+ }
37
+ ]
38
+ }
39
+ }
40
+ )
41
+ puts @model.inspect
42
+
43
+ @wrk_pid = fork do
44
+ Worker.start
45
+ end
46
+ Process.detach @wrk_pid
47
+ end
48
+
49
+ def teardown
50
+ Process.kill 'TERM', @wrk_pid
51
+ @model.destroy
52
+ end
53
+
54
+ def test_jobs
55
+ json = DB::Set['cars'].upsert(brand: "Ford")
56
+ uuid = Oj.load(json)['uuid']
57
+
58
+ puts Job.all.inspect
59
+
60
+ assert_equal 2, Job.count({where: {'hook.callback' => "after_create"}})
61
+
62
+ DB::Set['cars'].upsert(uuid: uuid, brand: "Ford", year: 1989)
63
+ assert_equal 1, Job.count({where: {'hook.callback' => "after_update"}})
64
+
65
+ sleep 3
66
+
67
+ DB::Set['cars'].delete(uuid: uuid)
68
+ assert_equal 1, Job.count({where: {'hook.callback' => "after_destroy"}})
69
+ end
70
+
71
+ end
72
+
73
+ end
74
+ end
@@ -0,0 +1,20 @@
1
+ $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
2
+ $stdout.sync = true
3
+ $stderr.sync = true
4
+
5
+ require 'actn/jobs'
6
+
7
+ require 'minitest/autorun'
8
+ require 'minitest/pride'
9
+
10
+ ENV['RACK_ENV'] = "test"
11
+ ENV['DATABASE_URL'] = "postgres://localhost:5432/actn_test"
12
+ I18n.enforce_available_locales = false
13
+
14
+ class MiniTest::Test
15
+ private
16
+
17
+ def random_str
18
+ (0...8).map { (65 + rand(26)).chr }.join
19
+ end
20
+ end
metadata ADDED
@@ -0,0 +1,122 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: actn-jobs
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Onur Uyar
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-10-03 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.5'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '1.5'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '>='
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '>='
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '>='
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: actn-db
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - '>='
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description:
70
+ email:
71
+ - me@onuruyar.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - .gitignore
77
+ - .travis.yml
78
+ - Gemfile
79
+ - LICENSE.txt
80
+ - README.md
81
+ - Rakefile
82
+ - actn-jobs.gemspec
83
+ - db/1_jobs.sql
84
+ - db/schemas/job.json
85
+ - lib/actn/hooks.rb
86
+ - lib/actn/hooks/trace.rb
87
+ - lib/actn/jobs.rb
88
+ - lib/actn/jobs/base.rb
89
+ - lib/actn/jobs/job.rb
90
+ - lib/actn/jobs/job_error.rb
91
+ - lib/actn/jobs/tasks/jobs.rake
92
+ - lib/actn/jobs/version.rb
93
+ - lib/actn/jobs/worker.rb
94
+ - test/actn/test_jobs.rb
95
+ - test/minitest_helper.rb
96
+ homepage: https://github.com/hackberry-gh/actn-jobs
97
+ licenses:
98
+ - MIT
99
+ metadata: {}
100
+ post_install_message:
101
+ rdoc_options: []
102
+ require_paths:
103
+ - lib
104
+ required_ruby_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - '>='
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ required_rubygems_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - '>='
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ requirements: []
115
+ rubyforge_project:
116
+ rubygems_version: 2.2.2
117
+ signing_key:
118
+ specification_version: 4
119
+ summary: Actn.io Jobs
120
+ test_files:
121
+ - test/actn/test_jobs.rb
122
+ - test/minitest_helper.rb