kronos-ruby 0.1.0.alpha.2

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: bb53d58571c884a14d1d1089f4b8ac3fd6512133
4
+ data.tar.gz: dcec1ad5fc215fab5ac52eb05dfcf226b7dcb393
5
+ SHA512:
6
+ metadata.gz: bbff4ed34107685fcc68e14d02c4a8e7307700923bb0ca4900e89334e29a29cf974f7187568db3e5a4cc9b57f2782cb04ee886a97ea0a2b2c855a36e3c3b7f19
7
+ data.tar.gz: e7bb79b5218489cbd2bf6a05c1cb78822faaf167575d3b6d5275c93fb65d09cefde77c4a6c2daf9b7c554faf3ec36f10add28c9aafe26b34aa7b2c6386899949
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.reek ADDED
@@ -0,0 +1,5 @@
1
+ IrresponsibleModule:
2
+ enabled: false
3
+
4
+ exclude_paths:
5
+ - vendor/bundle
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,26 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.4
3
+
4
+ Style/Documentation:
5
+ Enabled: false
6
+
7
+ Metrics/LineLength:
8
+ Max: 120
9
+
10
+ Metrics/ClassLength:
11
+ Max: 150
12
+
13
+ Metrics/BlockLength:
14
+ Enabled: false
15
+
16
+ Metrics/MethodLength:
17
+ Max: 15
18
+
19
+ Style/RegexpLiteral:
20
+ Enabled: false
21
+
22
+ Layout/IndentArray:
23
+ Enabled: false
24
+
25
+ Layout/IndentHash:
26
+ Enabled: false
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.1
5
+ before_install: gem install bundler -v 1.15.3
data/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Kronos
2
+
3
+ ## CHANGELOG
4
+
5
+ ### Unreleased
6
+ - [Added] Logger structure (Stdout and Slack)
7
+ - [Added] Storage structure (InMemory)
8
+ - [Added] Runner structure (Synchronous/Asynchronous)
9
+ - [Added] Config structure
10
+ - [Added] Docs
11
+ - [Added] Continuous Integration
12
+ - [Added] Project basis
13
+
14
+ ## Additional Information
15
+ - All notable changes to this project will be documented in this file.
16
+ - This project uses [Semantic Versioning](http://semver.org/) and to the [Keep-a-Changelog](https://github.com/olivierlacan/keep-a-changelog) guidelines.
17
+ - [Added] To new features
18
+ - [Changed] To changes in existing features
19
+ - [Deprecated] To features that will be removed in the future
20
+ - [Removed] To removed features
21
+ - [Fixed] To any bugfix
22
+ - [Security] To security fixes or improvements
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ # Specify your gem's dependencies in kronos.gemspec
8
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Gabriel Teles
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,60 @@
1
+ # Kronos
2
+ [![Build Status](https://semaphoreci.com/api/v1/pdvend/kronos/branches/master/badge.svg)](https://semaphoreci.com/pdvend/kronos)
3
+ [![Coverage Status](https://coveralls.io/repos/github/pdvend/kronos/badge.svg?branch=master)](https://coveralls.io/github/pdvend/kronos?branch=master)
4
+
5
+ This project allows you to use a scheduler with well defined concepts of runners, storage and tasks. It can work in various storage engines, like memory, redis, disk, database, etc. Also, it supports running in synchronous or asynchronous flows.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'kronos'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ `$ bundle`
18
+
19
+ Or install it yourself as:
20
+
21
+ `$ gem install kronos`
22
+
23
+
24
+ ## Usage
25
+
26
+ ```ruby
27
+ # Define your environment preferences (runner and storage) and register your tasks
28
+ Kronos
29
+ .config
30
+ .runner(Kronos::Runner::Synchronous) # or .runner(Kronos::Runner::Asynchronous)
31
+ .storage(Kronos::Storage::InMemory)
32
+ .logger(Kronos::Logger::Stdout) # or .logger(Kronos::Logger::Slack, "Your Slack Webhook URL here")
33
+ .register(:say_good_morning, '8am') { puts 'Good Morning, Team!' }
34
+ .register(:wish_happy_weekend, 'friday, 6pm') { puts 'Happy Weekend, Team!' }
35
+ # ...
36
+
37
+ # Then start Kronos (This method can be sync or async, acording to the runner you selected)
38
+ Kronos.start
39
+ ```
40
+
41
+ ### Web dashboard
42
+ To view Krono's web dashboard, simply mount it into your Rack stack:
43
+ ```ruby
44
+ mount Kronos::Web::App, at: '/kronos-dashboard'
45
+ ```
46
+
47
+ ## Developing
48
+ - Clone this repository
49
+ - Run `bin/setup` to install dependencies
50
+ - You can also run `bin/console` to start an iteractive console to test Kronos
51
+ - To install this gem onto your local machine, run `bundle exec rake install`.
52
+ - To release a new version, update `lib/version.rb` and [CHANGELOG.md](/CHANGELOG.md)
53
+
54
+ ## Contributing
55
+
56
+ Bug reports and pull requests are welcome on GitHub at https://github.com/pdvend/kronos.
57
+
58
+ ## License
59
+
60
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task(default: [:spec])
data/bin/console ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'kronos'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ require 'pry'
11
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('../lib', __FILE__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+
6
+ require 'kronos/version'
7
+
8
+ Gem::Specification.new do |spec|
9
+ spec.name = 'kronos-ruby'
10
+ pre_release = ENV['SEMAPHORE'] && ENV['PRE_RELEASE']
11
+ spec.version = Kronos::VERSION + (pre_release ? ".alpha.#{ENV['SEMAPHORE_DEPLOY_NUMBER']}" : '')
12
+ spec.authors = ['Gabriel Teles']
13
+ spec.email = ['gabriel@pdvend.com.br']
14
+
15
+ spec.summary = 'Persistent cron jobs manager'
16
+ spec.homepage = 'https://github.com/pdvend/kronos'
17
+ spec.license = 'MIT'
18
+
19
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
20
+ f.match(%r{^(test|spec|features)/})
21
+ end
22
+ spec.bindir = 'exe'
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ['lib']
25
+
26
+ spec.add_dependency 'concurrent-ruby'
27
+ spec.add_dependency 'chronic'
28
+ spec.add_development_dependency 'bundler'
29
+ spec.add_development_dependency 'coveralls'
30
+ spec.add_development_dependency 'fasterer'
31
+ spec.add_development_dependency 'pry'
32
+ spec.add_development_dependency 'rake'
33
+ spec.add_development_dependency 'rack'
34
+ spec.add_development_dependency 'reek'
35
+ spec.add_development_dependency 'rspec'
36
+ spec.add_development_dependency 'rubocop'
37
+ spec.add_development_dependency 'simplecov'
38
+ spec.add_development_dependency 'timecop'
39
+ spec.add_development_dependency 'webmock'
40
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class ConfigAgent
5
+ attr_reader :tasks
6
+
7
+ def initialize
8
+ @tasks = []
9
+ @instance = {}
10
+ end
11
+
12
+ def register(id, timestamp, &block)
13
+ raise(Kronos::Exception::AlreadyRegisteredId) if @tasks.lazy.map(&:id).include?(id)
14
+
15
+ task = Kronos::Task.new(id, timestamp, block)
16
+ tasks.push(task)
17
+
18
+ self
19
+ end
20
+
21
+ def storage(storage, *config)
22
+ @instance[:storage] = storage.new(*config)
23
+ self
24
+ end
25
+
26
+ def logger(logger, *config)
27
+ @instance[:logger] = logger.new(*config)
28
+ self
29
+ end
30
+
31
+ def runner(runner)
32
+ @_runner = runner
33
+ @instance[:runner] = nil
34
+ self
35
+ end
36
+
37
+ def runner_instance
38
+ @instance[:runner] ||= begin
39
+ raise(Kronos::Exception::NoRunnerRegistered) unless _runner
40
+
41
+ dependencies = Kronos::Dependencies.new(
42
+ storage: storage_instance,
43
+ logger: logger_instance
44
+ )
45
+
46
+ _runner.new(tasks, dependencies)
47
+ end
48
+ end
49
+
50
+ def storage_instance
51
+ @instance[:storage] || raise(Kronos::Exception::NoStorageRegistered)
52
+ end
53
+
54
+ def logger_instance
55
+ @instance[:logger] || raise(Kronos::Exception::NoLoggerRegistered)
56
+ end
57
+
58
+ private
59
+
60
+ attr_accessor :_runner, :_storage
61
+ end
62
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class Dependencies
5
+ attr_reader :storage, :logger
6
+
7
+ def initialize(storage: nil, logger: nil)
8
+ @storage = storage
9
+ @logger = logger
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class Exception
5
+ class AlreadyRegisteredId < Kronos::Exception
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class Exception
5
+ class NoLoggerRegistered < Kronos::Exception
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class Exception
5
+ class NoRunnerRegistered < Kronos::Exception
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class Exception
5
+ class NoStorageRegistered < Kronos::Exception
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class Exception
5
+ class UnrecognizedTimeFormat < Kronos::Exception
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class Exception < StandardError
5
+ end
6
+ end
7
+
8
+ require 'kronos/exception/already_registered_id'
9
+ require 'kronos/exception/no_logger_registered'
10
+ require 'kronos/exception/no_runner_registered'
11
+ require 'kronos/exception/no_storage_registered'
12
+ require 'kronos/exception/unrecognized_time_format'
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require 'json'
5
+
6
+ module Kronos
7
+ module Logger
8
+ class Slack
9
+ def initialize(slack_webhook_url)
10
+ @slack_uri = URI.parse(slack_webhook_url)
11
+ @use_ssl = @slack_uri.scheme == 'https'
12
+ end
13
+
14
+ def info(msg)
15
+ send_to_slack("[`Kronos`][`INFO`][`#{Time.now.iso8601}`] #{msg}", ':information_source:')
16
+ end
17
+
18
+ def error(msg)
19
+ send_to_slack("[`Kronos`][`ERROR`][`#{Time.now.iso8601}`] #{msg}", ':red_circle:')
20
+ end
21
+
22
+ def success(msg)
23
+ send_to_slack("[`Kronos`][`SUCCESS`][`#{Time.now.iso8601}`] #{msg}", ':white_check_mark:')
24
+ end
25
+
26
+ private
27
+
28
+ def send_to_slack(message, emoji)
29
+ request = Net::HTTP::Post.new(@slack_uri)
30
+ request.body = { text: message, icon_emoji: emoji }.to_json
31
+ Net::HTTP.start(@slack_uri.host, @slack_uri.port, use_ssl: @use_ssl) { |http| http.request(request) }
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ module Logger
5
+ class Stdout
6
+ def info(msg)
7
+ puts "[Kronos][INFO][#{Time.now.iso8601}] #{msg}"
8
+ end
9
+
10
+ def error(msg)
11
+ puts "[Kronos][ERROR][#{Time.now.iso8601}] #{msg}"
12
+ end
13
+
14
+ def success(msg)
15
+ puts "[Kronos][SUCCESS][#{Time.now.iso8601}] #{msg}"
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ module Logger
5
+ end
6
+ end
7
+
8
+ require 'kronos/logger/stdout'
9
+ require 'kronos/logger/slack'
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ class Report < ::OpenStruct
5
+ STATUSES = { success: 0, failure: 1 }.freeze
6
+
7
+ class << self
8
+ def success_from(task_id, metadata, timestamp = Time.now)
9
+ new(
10
+ task_id: check_task_id(task_id),
11
+ status: Kronos::Report::STATUSES[:success],
12
+ timestamp: check_timestamp(timestamp),
13
+ metadata: check_metadata(metadata)
14
+ )
15
+ end
16
+
17
+ def failure_from(task_id, exception, timestamp = Time.now)
18
+ new(
19
+ task_id: check_task_id(task_id),
20
+ status: Kronos::Report::STATUSES[:failure],
21
+ timestamp: check_timestamp(timestamp),
22
+ exception: check_exception(exception)
23
+ )
24
+ end
25
+
26
+ private :new
27
+
28
+ private
29
+
30
+ def check_timestamp(timestamp)
31
+ timestamp.is_a?(Time) ? timestamp : raise_invalid_argument('timestamp', timestamp, Time)
32
+ end
33
+
34
+ def check_task_id(task)
35
+ task.is_a?(Symbol) ? task : raise_invalid_argument('Task ID', task, Symbol)
36
+ end
37
+
38
+ def check_metadata(metadata)
39
+ raise_invalid_argument('metadata', metadata, Hash) unless metadata.is_a?(Hash)
40
+ return metadata if metadata.values.all? { |value| value.is_a?(String) }
41
+ raise(ArgumentError, 'Expected all values in metadata to be strings')
42
+ end
43
+
44
+ def check_exception(exception)
45
+ if exception.is_a?(Hash)
46
+ return exception if valid_exception_format(exception)
47
+ raise(ArgumentError, 'Invalid exception format')
48
+ elsif exception.is_a?(::Exception)
49
+ exception_hash_from(exception)
50
+ else
51
+ raise_invalid_argument('exception', exception, Hash)
52
+ end
53
+ end
54
+
55
+ def exception_hash_from(exception)
56
+ {
57
+ type: exception.class.name,
58
+ message: exception.message,
59
+ stacktrace: exception.backtrace
60
+ }
61
+ end
62
+
63
+ def valid_exception_format(exception)
64
+ type = exception[:type]
65
+ message = exception[:message]
66
+ stacktrace = exception[:stacktrace]
67
+
68
+ type.is_a?(String) &&
69
+ !type.empty? &&
70
+ message.is_a?(String) &&
71
+ !message.empty? &&
72
+ stacktrace.is_a?(Array) &&
73
+ stacktrace.all? { |line| line.is_a?(String) }
74
+ end
75
+
76
+ def raise_invalid_argument(name, received, expectation)
77
+ raise(ArgumentError, "Invalid #{name} given (#{received.class}). #{expectation} expected.")
78
+ end
79
+ end
80
+
81
+ def success?
82
+ status == Kronos::Report::STATUSES[:success]
83
+ end
84
+
85
+ def failure?
86
+ status == Kronos::Report::STATUSES[:failure]
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ module Runner
5
+ class Asynchronous < Synchronous
6
+ include Concurrent::Async
7
+ alias original_start start
8
+
9
+ def start
10
+ async.original_start
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kronos
4
+ module Runner
5
+ class Synchronous
6
+ # TODO: Let consumer configure it
7
+ METADATA_COLLECTORS = [
8
+ lambda do |block|
9
+ start = Time.now
10
+ result = block.call
11
+ finish = Time.now
12
+
13
+ { **result, start: start.to_s, finish: finish.to_s, duration: (finish - start).to_s }
14
+ end
15
+ ].freeze
16
+
17
+ ID_FUNC = lambda do |block|
18
+ lambda do
19
+ block.call
20
+ {}
21
+ end
22
+ end
23
+
24
+ def initialize(tasks, dependencies)
25
+ @tasks = tasks
26
+ @dependencies = dependencies
27
+ end
28
+
29
+ def start
30
+ loop do
31
+ run_resolved_tasks
32
+ schedule_current_tasks
33
+
34
+ # TODO: Configurable sleep between runs
35
+ sleep(1)
36
+ end
37
+ end
38
+
39
+ private
40
+
41
+ def schedule_current_tasks
42
+ @tasks.each(&method(:schedule_task))
43
+ end
44
+
45
+ def schedule_task(task)
46
+ schedule_next_run(task) unless @dependencies.storage.pending?(task)
47
+ end
48
+
49
+ def run_resolved_tasks
50
+ @dependencies.storage.resolved_tasks.each(&method(:process_task))
51
+ end
52
+
53
+ def process_task(task_id)
54
+ task = find_task(task_id)
55
+ return remove_task_from_schedule(task_id) unless task
56
+ run_task(task)
57
+ schedule_next_run(task)
58
+ end
59
+
60
+ def remove_task_from_schedule(task_id)
61
+ @dependencies.logger.info("Task `#{task_id}` was removed from definitions. Removing from schedule too.")
62
+ storage = @dependencies.storage
63
+ storage.remove(task_id)
64
+ storage.remove_reports_for(task_id)
65
+ end
66
+
67
+ # rubocop:disable RescueException
68
+ def run_task(task)
69
+ raw_execute_task(task)
70
+ rescue ::Exception => error
71
+ register_task_failure(task.id, error)
72
+ end
73
+ # rubocop:enable
74
+
75
+ def raw_execute_task(task)
76
+ metadata = collect_metadata { task.block.call }
77
+ task_id = task.id
78
+ @dependencies.logger.success("Task `#{task_id}` ran successfully.")
79
+ @dependencies.storage.register_report(Kronos::Report.success_from(task_id, metadata))
80
+ end
81
+
82
+ def register_task_failure(task_id, error)
83
+ @dependencies.logger.error("Task `#{task_id}` failed.")
84
+ @dependencies.storage.register_report(Kronos::Report.failure_from(task_id, error))
85
+ end
86
+
87
+ def collect_metadata(&block)
88
+ METADATA_COLLECTORS
89
+ .reverse
90
+ .reduce(ID_FUNC[block]) { |chain, collector| -> () { collector[chain] } }
91
+ .call
92
+ end
93
+
94
+ def schedule_next_run(task)
95
+ next_run = task.time
96
+ return @dependencies.storage.remove(task.id) if next_run < Time.now
97
+ schedule(task, next_run)
98
+ end
99
+
100
+ def schedule(task, next_run)
101
+ task_id = task.id
102
+ @dependencies.logger.info("Scheduling `#{task_id}` to run `#{next_run.iso8601}`")
103
+ @dependencies.storage.schedule(Kronos::ScheduledTask.new(task_id, next_run))
104
+ end
105
+
106
+ def find_task(task_id)
107
+ @tasks.find { |task| task.id == task_id }
108
+ end
109
+ end
110
+ end
111
+ end