qyu-store-activerecord 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2eeebb8ce15f18feb6e0fbd463c383083072d04b95fb2cba3a1072773419cdea
4
+ data.tar.gz: 575311876e87c6c3fc2eaba1723bafabb3d367820fdf292eb282c2d0f1cfd929
5
+ SHA512:
6
+ metadata.gz: 3fadf2f0e68d70883569551cd101442ce9cf53c5c33abfd42ceeba0a2e956bdbef8164179fc5977f17948aa20a214df638a1361eaeb763e4dc66d8191f7f276e
7
+ data.tar.gz: e1ab06aee149b17edff19da1bb53e8bb118ce2114d1bef6e3d5f5c3f37ff33797583e99880f1b33ce814729bcbe9536df36e7c558825af3a40c0572f2464d72f
@@ -0,0 +1,59 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /spec/examples.txt
9
+ /test/tmp/
10
+ /test/version_tmp/
11
+ /tmp/
12
+
13
+ # Used by dotenv library to load environment variables.
14
+ # .env
15
+
16
+ ## Specific to RubyMotion:
17
+ .dat*
18
+ .repl_history
19
+ build/
20
+ *.bridgesupport
21
+ build-iPhoneOS/
22
+ build-iPhoneSimulator/
23
+
24
+ ## Specific to RubyMotion (use of CocoaPods):
25
+ #
26
+ # We recommend against adding the Pods directory to your .gitignore. However
27
+ # you should judge for yourself, the pros and cons are mentioned at:
28
+ # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
29
+ #
30
+ # vendor/Pods/
31
+
32
+ ## Documentation cache and generated files:
33
+ /.yardoc/
34
+ /_yardoc/
35
+ /doc/
36
+ /rdoc/
37
+
38
+ ## Environment normalization:
39
+ /.bundle/
40
+ /vendor/bundle
41
+ /lib/bundler/man/
42
+
43
+ # for a library or gem, you might want to ignore these files since the code is
44
+ # intended to run in multiple environments; otherwise, check them in:
45
+ # Gemfile.lock
46
+ # .ruby-version
47
+ # .ruby-gemset
48
+
49
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
50
+ .rvmrc
51
+
52
+ # rspec failure tracking
53
+ .rspec_status
54
+
55
+ Dockerfile
56
+ docker-compose.yml
57
+ .env
58
+
59
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,15 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.2
5
+ addons:
6
+ apt:
7
+ sources:
8
+ - precise-pgdg-9.5
9
+ packages:
10
+ - postgresql-9.5
11
+ - postgresql-contrib-9.5
12
+ postgresql: 9.5
13
+ before_script:
14
+ - sudo cp /etc/postgresql/9.4/main/pg_hba.conf /etc/postgresql/9.5/main/pg_hba.conf
15
+ before_install: gem install bundler -v 1.16.0
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at me@zzet.org. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in qyu-store-activerecord.gemspec
6
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 FindHotel
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,74 @@
1
+ # Qyu::Store::ActiveRecord
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/qyu-store-activerecord.svg)](https://rubygems.org/gems/qyu-store-activerecord)
4
+ [![Build Status](https://travis-ci.org/FindHotel/qyu-store-activerecord.svg)](https://travis-ci.org/FindHotel/qyu-store-activerecord)
5
+
6
+ ## Requirements:
7
+
8
+ * Ruby 2.4.0 or newer
9
+
10
+ ## Installation
11
+
12
+ Add this line to your application's Gemfile:
13
+
14
+ ```ruby
15
+ gem 'qyu-store-activerecord'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself as:
23
+
24
+ $ gem install qyu-store-activerecord
25
+
26
+ ## Configuration
27
+
28
+ To start using Qyu; you need a queue configuration and a state store configuration. Here's an example:
29
+ ```ruby
30
+ require 'qyu'
31
+ require 'qyu/store/activerecord'
32
+
33
+ Qyu.configure(
34
+ queue: {
35
+ type: :memory
36
+ # Or one of the other production-ready queues available
37
+ # Check https://github.com/FindHotel/qyu/wiki/Message-Queues
38
+ },
39
+ store: {
40
+ type: :active_record,
41
+ db_type: database_adapter,
42
+ db_host: database_host,
43
+ db_port: database_port,
44
+ db_name: database_name,
45
+ db_user: database_user,
46
+ db_password: database_password,
47
+ lease_period: 60
48
+ },
49
+ # optional Defaults to STDOUT
50
+ logger: Logger.new(STDOUT)
51
+ )
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ TODO: Write usage instructions here
57
+
58
+ ## Development
59
+
60
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
61
+
62
+ 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).
63
+
64
+ ## Contributing
65
+
66
+ Bug reports and pull requests are welcome on GitHub at https://github.com/FindHotel/qyu-store-activerecord. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
67
+
68
+ ## License
69
+
70
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
71
+
72
+ ## Code of Conduct
73
+
74
+ Everyone interacting in the Qyu::Store::ActiveRecord project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/FindHotel/qyu-store-activerecord/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,8 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ load 'lib/qyu/store/activerecord/tasks/db.rake'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task :default => :spec
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "qyu"
5
+ require "qyu/store/activerecord"
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
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "pry"
15
+ Pry.start
@@ -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,37 @@
1
+ require_relative "./activerecord/version"
2
+ require 'active_record'
3
+
4
+ module Qyu
5
+ module Store
6
+ module ActiveRecord
7
+ autoload :Adapter, 'qyu/store/activerecord/adapter'
8
+ autoload :ConfigurationValidator, 'qyu/store/activerecord/configuration_validator'
9
+ autoload :Logger, 'qyu/store/activerecord/logger'
10
+ autoload :Utils, 'qyu/store/activerecord/utils'
11
+ autoload :Job, 'qyu/store/activerecord/models/job'
12
+ autoload :Task, 'qyu/store/activerecord/models/task'
13
+ autoload :Workflow, 'qyu/store/activerecord/models/workflow'
14
+
15
+ class << self
16
+ def interface
17
+ defined?(Qyu::Store::Base) ? Qyu::Store::Base : Object
18
+ end
19
+ end
20
+ end
21
+ end
22
+
23
+ class << self
24
+ unless defined?(logger)
25
+ def logger=(logger)
26
+ @@__logger = logger
27
+ end
28
+
29
+ def logger
30
+ @@__logger ||= Qyu::Store::ActiveRecord::Logger.new(STDOUT)
31
+ end
32
+ end
33
+ end
34
+ end
35
+
36
+ Qyu::Config::StoreConfig.register(Qyu::Store::ActiveRecord::Adapter) if defined?(Qyu::Config::StoreConfig)
37
+ Qyu::Factory::StoreFactory.register(Qyu::Store::ActiveRecord::Adapter) if defined?(Qyu::Factory::StoreFactory)
@@ -0,0 +1,242 @@
1
+ require 'securerandom'
2
+
3
+ module Qyu
4
+ module Store
5
+ module ActiveRecord
6
+ class Adapter < Qyu::Store::ActiveRecord.interface
7
+ TYPE = :active_record
8
+
9
+ class << self
10
+ def valid_config?(config)
11
+ ConfigurationValidator.new(config).valid?
12
+ end
13
+ end
14
+
15
+ cattr_reader :db_configuration
16
+
17
+ def initialize(config)
18
+ init_client(config)
19
+ end
20
+
21
+ ## Workflow
22
+ def persist_workflow(name, descriptor)
23
+ with_connection do
24
+ Workflow.create!(name: name, descriptor: descriptor).id
25
+ end
26
+ end
27
+
28
+ def find_workflow(id)
29
+ wflow = Workflow.find_by(id: id)
30
+ deserialize_workflow(wflow)
31
+ end
32
+
33
+ def find_workflow_by_name(name)
34
+ wflow = Workflow.find_by(name: name)
35
+ deserialize_workflow(wflow)
36
+ end
37
+
38
+ def delete_workflow(id)
39
+ Workflow.destroy(id)
40
+ end
41
+
42
+ def delete_workflow_by_name(name)
43
+ Workflow.where(name: name).destroy_all
44
+ end
45
+
46
+ ## Job
47
+ def persist_job(workflow, payload)
48
+ with_connection do
49
+ Job.create!(payload: payload, workflow_id: workflow.id).id
50
+ end
51
+ end
52
+
53
+ def find_job(id)
54
+ j = Job.find_by(id: id)
55
+ return if j.nil?
56
+
57
+ wflow = Workflow.find_by(id: j.workflow_id)
58
+ return if wflow.nil?
59
+
60
+ deserialize_job(j, wflow)
61
+ end
62
+
63
+ def select_jobs(limit, offset, order = :asc)
64
+ Job.includes(:workflow).order(id: order).limit(limit).offset(offset).as_json(include: :workflow)
65
+ end
66
+
67
+ def count_jobs
68
+ Job.count
69
+ end
70
+
71
+ def delete_job(id)
72
+ Job.destroy(id)
73
+ end
74
+
75
+ def clear_completed_jobs
76
+ Job.joins(:tasks).where(tasks: { status: 'completed' }).destroy_all
77
+ end
78
+
79
+ ## Task
80
+ def find_or_persist_task(name, queue_name, payload, job_id, parent_task_id)
81
+ id = nil
82
+ transaction do
83
+ id_payload_combos = Task.where(
84
+ name: name,
85
+ queue_name: queue_name,
86
+ job_id: job_id,
87
+ parent_task_id: parent_task_id
88
+ ).pluck(:id, :payload)
89
+
90
+ id_payload_combos.each do |t_id, t_payload|
91
+ if compare_payloads(t_payload, payload)
92
+ id = t_id
93
+ break
94
+ end
95
+ end
96
+
97
+ if id.nil?
98
+ id = Task.create!(name: name, queue_name: queue_name, payload: payload, job_id: job_id, parent_task_id: parent_task_id).id
99
+ end
100
+
101
+ yield(id)
102
+ end
103
+
104
+ id
105
+ end
106
+
107
+ def find_task(id)
108
+ task = Task.find_by(id: id)
109
+ deserialize_task(task)
110
+ end
111
+
112
+ def find_task_ids_by_job_id_and_name(job_id, name)
113
+ Task.where(job_id: job_id, name: name).pluck(:id)
114
+ end
115
+
116
+ def find_task_ids_by_job_id_name_and_parent_task_ids(job_id, name, parent_task_ids)
117
+ Task.where(job_id: job_id, name: name, parent_task_id: parent_task_ids).pluck(:id)
118
+ end
119
+
120
+ def task_status_counts(job_id)
121
+ counts = Task.where(job_id: job_id).group(:name, :status).count
122
+ counts.each_with_object({}) do |(k, v), obj|
123
+ obj[k[0]] ||= Hash.new(0)
124
+ obj[k[0]][k[1]] = v
125
+ end
126
+ end
127
+
128
+ def select_tasks_by_job_id(job_id)
129
+ Task.where(job_id: job_id).as_json
130
+ end
131
+
132
+ def lock_task!(id, lease_time)
133
+ Qyu.logger.debug '[LOCK] lock_task!'
134
+
135
+ uuid = SecureRandom.uuid
136
+ Qyu.logger.debug "[LOCK] uuid = #{uuid}"
137
+
138
+ locked_until = seconds_after_time(lease_time)
139
+ Qyu.logger.debug "[LOCK] locked_until = #{locked_until}"
140
+
141
+ results = Task.where('id = ? AND (locked_until < now() OR locked_until IS NULL)', id).update(locked_by: uuid, locked_until: locked_until)
142
+
143
+ return [nil, nil] if results.empty?
144
+
145
+ locked_until = results[0].locked_until
146
+ Qyu.logger.debug "[LOCK] locked_until from DB = #{locked_until}"
147
+
148
+ [uuid, locked_until]
149
+ end
150
+
151
+ def unlock_task!(id, lease_token)
152
+ results = Task.where(id: id, locked_by: lease_token).update(locked_by: nil, locked_until: nil)
153
+ !results.empty?
154
+ end
155
+
156
+ def renew_lock_lease(id, lease_time, lease_token)
157
+ Qyu.logger.debug "renew_lock_lease id = #{id}, lease_time = #{lease_time}, lease_token = #{lease_token}"
158
+
159
+ results = with_connection do
160
+ Task.where('id = ? AND locked_until > now() AND locked_by = ?', id, lease_token).update(locked_until: seconds_after_time(lease_time))
161
+ end
162
+
163
+ Qyu.logger.debug "renew_lock_lease results = #{results}"
164
+
165
+ return nil if results.empty?
166
+
167
+ results[0].locked_until
168
+ end
169
+
170
+ def update_status(id, status)
171
+ results = Task.where(id: id).update(status: status)
172
+
173
+ results.any? && results[0].status == status
174
+ end
175
+
176
+ def with_connection
177
+ ::ActiveRecord::Base.connection_pool.with_connection do
178
+ yield
179
+ end
180
+ end
181
+
182
+ def transaction
183
+ ::ActiveRecord::Base.transaction do
184
+ yield
185
+ end
186
+ end
187
+
188
+ private
189
+
190
+ def compare_payloads(payload1, payload2)
191
+ sort(payload1) == sort(payload2)
192
+ end
193
+
194
+ def sort(payload)
195
+ payload
196
+ end
197
+
198
+ # t['payload'] = JSON.parse(t['payload'])
199
+ def deserialize_task(task)
200
+ return if task.nil?
201
+
202
+ task.as_json
203
+ end
204
+
205
+ # j['payload'] = JSON.parse(j['payload'])
206
+ # j['descriptor'] = JSON.parse(j['descriptor'])
207
+ def deserialize_job(job, workflow)
208
+ j = job.as_json
209
+ j['workflow'] = deserialize_workflow(workflow)
210
+ j
211
+ end
212
+
213
+ def deserialize_workflow(workflow)
214
+ return if workflow.nil?
215
+
216
+ wflow = workflow.as_json
217
+ # wflow['descriptor'] = JSON.parse(wflow['descriptor'])
218
+ wflow
219
+ end
220
+
221
+ def init_client(config)
222
+ @@db_configuration = {
223
+ adapter: config[:db_type],
224
+ database: config[:db_name],
225
+ username: config[:db_user],
226
+ host: config[:db_host],
227
+ port: config[:db_port],
228
+ pool: config.fetch(:db_pool) { 5 }
229
+ }
230
+
231
+ @@db_configuration[:password] = config[:db_password] if config[:db_password]
232
+
233
+ Utils.ensure_db_ready(@@db_configuration)
234
+ end
235
+
236
+ def seconds_after_time(seconds, start_time = Time.now.utc)
237
+ start_time + seconds
238
+ end
239
+ end
240
+ end
241
+ end
242
+ end
@@ -0,0 +1,41 @@
1
+ module Qyu
2
+ module Store
3
+ module ActiveRecord
4
+ class ConfigurationValidator
5
+ REQUIRED_ATTRIBUTES = %i(db_type db_name db_host db_port).freeze
6
+
7
+ attr_reader :errors
8
+
9
+ def initialize(config)
10
+ @config = config
11
+ @errors = []
12
+ end
13
+
14
+ def valid?
15
+ validate
16
+ errors.empty?
17
+ end
18
+
19
+ def validate
20
+ REQUIRED_ATTRIBUTES.each do |attribute|
21
+ next if @config[attribute].present?
22
+
23
+ @errors << "#{attribute} must be present."
24
+ end
25
+
26
+ validate_database_adapter
27
+ end
28
+
29
+ private
30
+
31
+ def validate_database_adapter
32
+ sample_config = { 'test' => { adapter: @config[:db_type] } }
33
+
34
+ ::ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver.new(sample_config).spec(:test)
35
+ rescue LoadError => ex
36
+ @errors << ex.message
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ class CreateInitialModels < ActiveRecord::Migration[5.0]
4
+ def change
5
+ create_table :workflows do |t|
6
+ t.string :name, null: false, unique: true
7
+ t.jsonb :descriptor, null: false
8
+ end
9
+
10
+ add_index :workflows, :name, unique: true, name: 'workflows_name_unique_index'
11
+
12
+ create_table :jobs do |t|
13
+ t.jsonb :payload
14
+
15
+ t.references :workflow, foreign_key: true
16
+
17
+ t.timestamps
18
+ end
19
+
20
+ create_table :tasks do |t|
21
+ t.string :name
22
+ t.string :queue_name
23
+ t.string :status
24
+ t.column :locked_until, 'timestamp with time zone'
25
+ t.string :locked_by
26
+ t.jsonb :payload
27
+
28
+ t.references :job, foreign_key: true
29
+ t.references :parent_task, table_name: 'tasks', foreign_key: { to_table: 'tasks' }
30
+
31
+ t.timestamps
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,10 @@
1
+ require 'logger'
2
+
3
+ module Qyu
4
+ module Store
5
+ module ActiveRecord
6
+ class Logger < ::Logger
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,11 @@
1
+ module Qyu
2
+ module Store
3
+ module ActiveRecord
4
+ class Job < ::ActiveRecord::Base
5
+ belongs_to :workflow
6
+
7
+ has_many :tasks, dependent: :destroy
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,13 @@
1
+ module Qyu
2
+ module Store
3
+ module ActiveRecord
4
+ class Task < ::ActiveRecord::Base
5
+ belongs_to :job
6
+ belongs_to :parent_task, class_name: 'Task', foreign_key: :id
7
+ has_many :children_tasks, class_name: 'Task',
8
+ foreign_key: 'parent_task_id',
9
+ dependent: :destroy
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,9 @@
1
+ module Qyu
2
+ module Store
3
+ module ActiveRecord
4
+ class Workflow < ::ActiveRecord::Base
5
+ has_many :jobs, dependent: :destroy
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'qyu/store/activerecord'
4
+ require 'uri'
5
+ require 'cgi'
6
+
7
+ namespace :qyu do
8
+ namespace :db do
9
+ migrations_path = "#{__dir__}/../db/migrate/"
10
+
11
+ db_config = Qyu::Store::ActiveRecord::Adapter.db_configuration
12
+ db_config ||= begin
13
+ url = ENV['QYU_DB_URL']
14
+
15
+ if !url.nil?
16
+ db_url = URI(url)
17
+ db_params = CGI::parse(db_url.query.to_s)
18
+
19
+ db_type = db_url.scheme == 'postgres' ? 'postgresql' : db_url.scheme
20
+ db_host = db_url.host
21
+ db_port = db_url.port
22
+ db_name = db_url.path[1..-1]
23
+ db_user = db_url.user
24
+ db_password = db_url.password
25
+ db_pool = db_params['pool'].first
26
+ else
27
+ db_type = ENV['QYU_DB_ADAPTER']
28
+ db_host = ENV['QYU_DB_HOST']
29
+ db_port = ENV['QYU_DB_PORT']
30
+ db_name = ENV['QYU_DB_NAME']
31
+ db_user = ENV['QYU_DB_USERNAME']
32
+ db_password = ENV['QYU_DB_PASSWORD']
33
+ db_pool = ENV['QYU_DB_POOL']
34
+ end
35
+
36
+ db_config = {
37
+ adapter: db_type,
38
+ database: db_name,
39
+ username: db_user,
40
+ host: db_host,
41
+ port: db_port,
42
+ pool: db_pool
43
+ }
44
+
45
+ db_config[:password] = db_password if db_password
46
+ end
47
+
48
+ desc 'Create the database'
49
+ task :create do
50
+ ActiveRecord::Base.establish_connection(db_config.merge(database: 'postgres'))
51
+ ActiveRecord::Base.connection.create_database(db_config[:database])
52
+
53
+ puts 'Qyu Database created.'
54
+ end
55
+
56
+ desc 'Migrate the database'
57
+ task :migrate do
58
+ ActiveRecord::Base.establish_connection(db_config)
59
+ ActiveRecord::Migrator.migrate(migrations_path)
60
+
61
+ Rake::Task['qyu:db:structure'].invoke
62
+
63
+ puts 'Qyu database migrated.'
64
+ end
65
+
66
+ desc 'Setup the database'
67
+ task :setup do
68
+ Rake::Task['arc_yu:db:create'].invoke
69
+ Rake::Task['arc_yu:db:migrate'].invoke
70
+ puts 'Qyu database set up.'
71
+ end
72
+
73
+ desc 'Migrate the database w/o updating the schema'
74
+ task :migrate_without_schema_update do
75
+ ActiveRecord::Base.establish_connection(db_config)
76
+ ActiveRecord::Migrator.migrate(migrations_path)
77
+
78
+ puts 'Qyu database migrated.'
79
+ end
80
+
81
+ desc 'Rollback the database'
82
+ task :rollback do
83
+ ActiveRecord::Base.establish_connection(db_config)
84
+ ActiveRecord::Migrator.rollback(migrations_path)
85
+
86
+ Rake::Task['qyu:db:structure'].invoke
87
+
88
+ puts 'Qyu migration reverted.'
89
+ end
90
+
91
+ desc 'Drop the database'
92
+ task :drop do
93
+ ActiveRecord::Base.establish_connection(db_config.merge(database: 'postgres'))
94
+ ActiveRecord::Base.connection.drop_database(db_config[:database])
95
+
96
+ puts 'Qyu database deleted.'
97
+ end
98
+
99
+ desc 'Reset the database'
100
+ task reset: %i(drop create migrate)
101
+
102
+ desc 'Create a db/structure.sql, this file specific for PostgreSQL and contains all custom columns definitions'
103
+ task :structure do
104
+ ActiveRecord::Base.establish_connection(db_config)
105
+
106
+ file = "#{__dir__}/structure.sql"
107
+
108
+ db_config.stringify_keys!
109
+ ActiveRecord::Base.schema_format = :sql
110
+ ActiveRecord::Tasks::PostgreSQLDatabaseTasks.new(db_config).structure_dump(file, {})
111
+ end
112
+
113
+ namespace :g do
114
+ desc 'Generate migration'
115
+ task :migration do
116
+ name = ARGV[1] || fail('Specify name: rake g:migration your_migration')
117
+ timestamp = Time.now.strftime('%Y%m%d%H%M%S')
118
+ path = File.join([migrations_path, "{timestamp}_#{name}.rb"])
119
+ migration_class = name.split('_').map(&:capitalize).join
120
+
121
+ File.open(path, 'w') do |file|
122
+ file.write <<-EOF.gsub(' ' * 12, '')
123
+ class #{migration_class} < ActiveRecord::Migration[5.0]
124
+ def up
125
+ end
126
+
127
+ def down
128
+ end
129
+ end
130
+ EOF
131
+ end
132
+
133
+ puts "Qyu migration #{path} created"
134
+ abort # needed stop other tasks
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,29 @@
1
+ require 'rake'
2
+
3
+ load 'qyu/store/activerecord/tasks/db.rake'
4
+
5
+ module Qyu
6
+ module Store
7
+ module ActiveRecord
8
+ class Utils
9
+ def self.ensure_db_ready(db_config)
10
+ begin
11
+ ::ActiveRecord::Base.establish_connection(db_config).connection
12
+ rescue ::ActiveRecord::NoDatabaseError
13
+ # :nocov:
14
+ Rake::Task['qyu:db:create'].invoke
15
+ # :nocov:
16
+ end
17
+
18
+ begin
19
+ Rake::Task['qyu:db:migrate_without_schema_update'].invoke
20
+ # :nocov:
21
+ rescue ::ActiveRecord::ConcurrentMigrationError
22
+ ArcYu.logger.info 'Concurrent Qyu database migration running. Skipping...'
23
+ # :nocov:
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,7 @@
1
+ module Qyu
2
+ module Store
3
+ module ActiveRecord
4
+ VERSION = "1.0.0"
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,33 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "qyu/store/activerecord/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "qyu-store-activerecord"
8
+ spec.version = Qyu::Store::ActiveRecord::VERSION
9
+ spec.authors = ["Andrew Kumanyaev"]
10
+ spec.email = ["me@zzet.org"]
11
+
12
+ spec.summary = %q{ActiveRecord state store for Qyu https://rubygems.org/gems/qyu}
13
+ spec.description = %q{ActiveRecord state store for Qyu https://rubygems.org/gems/qyu}
14
+ spec.homepage = "https://github.com/FindHotel/qyu-store-activerecord"
15
+ spec.license = "MIT"
16
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
17
+ f.match(%r{^(test|spec|features)/})
18
+ end
19
+ spec.bindir = "exe"
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_development_dependency 'bundler', '~> 1.16'
24
+ spec.add_development_dependency 'rake', '~> 10.0'
25
+ spec.add_development_dependency 'pry', '~> 0.11'
26
+ spec.add_development_dependency 'rspec', '~> 3.5'
27
+ spec.add_development_dependency 'shoulda-matchers', '~> 3.1'
28
+ spec.add_development_dependency 'simplecov'
29
+ spec.add_development_dependency 'factory_bot'
30
+ spec.add_development_dependency 'pg', '~> 0.18'
31
+
32
+ spec.add_runtime_dependency 'activerecord', '~> 5.1'
33
+ end
metadata ADDED
@@ -0,0 +1,192 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: qyu-store-activerecord
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Andrew Kumanyaev
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-02-02 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.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
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: pry
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.11'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.11'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.5'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.5'
69
+ - !ruby/object:Gem::Dependency
70
+ name: shoulda-matchers
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.1'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.1'
83
+ - !ruby/object:Gem::Dependency
84
+ name: simplecov
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: factory_bot
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: pg
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '0.18'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '0.18'
125
+ - !ruby/object:Gem::Dependency
126
+ name: activerecord
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - "~>"
130
+ - !ruby/object:Gem::Version
131
+ version: '5.1'
132
+ type: :runtime
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - "~>"
137
+ - !ruby/object:Gem::Version
138
+ version: '5.1'
139
+ description: ActiveRecord state store for Qyu https://rubygems.org/gems/qyu
140
+ email:
141
+ - me@zzet.org
142
+ executables: []
143
+ extensions: []
144
+ extra_rdoc_files: []
145
+ files:
146
+ - ".gitignore"
147
+ - ".rspec"
148
+ - ".travis.yml"
149
+ - CODE_OF_CONDUCT.md
150
+ - Gemfile
151
+ - LICENSE
152
+ - README.md
153
+ - Rakefile
154
+ - bin/console
155
+ - bin/setup
156
+ - lib/qyu/store/activerecord.rb
157
+ - lib/qyu/store/activerecord/adapter.rb
158
+ - lib/qyu/store/activerecord/configuration_validator.rb
159
+ - lib/qyu/store/activerecord/db/migrate/20170529131352_create_initial_models.rb
160
+ - lib/qyu/store/activerecord/logger.rb
161
+ - lib/qyu/store/activerecord/models/job.rb
162
+ - lib/qyu/store/activerecord/models/task.rb
163
+ - lib/qyu/store/activerecord/models/workflow.rb
164
+ - lib/qyu/store/activerecord/tasks/db.rake
165
+ - lib/qyu/store/activerecord/utils.rb
166
+ - lib/qyu/store/activerecord/version.rb
167
+ - qyu-store-activerecord.gemspec
168
+ homepage: https://github.com/FindHotel/qyu-store-activerecord
169
+ licenses:
170
+ - MIT
171
+ metadata: {}
172
+ post_install_message:
173
+ rdoc_options: []
174
+ require_paths:
175
+ - lib
176
+ required_ruby_version: !ruby/object:Gem::Requirement
177
+ requirements:
178
+ - - ">="
179
+ - !ruby/object:Gem::Version
180
+ version: '0'
181
+ required_rubygems_version: !ruby/object:Gem::Requirement
182
+ requirements:
183
+ - - ">="
184
+ - !ruby/object:Gem::Version
185
+ version: '0'
186
+ requirements: []
187
+ rubyforge_project:
188
+ rubygems_version: 2.7.4
189
+ signing_key:
190
+ specification_version: 4
191
+ summary: ActiveRecord state store for Qyu https://rubygems.org/gems/qyu
192
+ test_files: []