Skip to content

Commit

Permalink
Initial gem structure
Browse files Browse the repository at this point in the history
  • Loading branch information
oss92 committed Nov 17, 2017
1 parent 5c87685 commit ef99fbf
Show file tree
Hide file tree
Showing 18 changed files with 634 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--format documentation
--color
--require spec_helper
5 changes: 5 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
sudo: false
language: ruby
rvm:
- 2.4.2
before_install: gem install bundler -v 1.16.0
74 changes: 74 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

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, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
6 changes: 6 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

# Specify your gem's dependencies in qyu-store-redis.gemspec
gemspec
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Qyu::Store::Redis

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/qyu/store/redis`. To experiment with that code, run `bin/console` for an interactive prompt.

TODO: Delete this and the text above, and describe your gem

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'qyu-store-redis'
```

And then execute:

$ bundle

Or install it yourself as:

$ gem install qyu-store-redis

## Usage

TODO: Write usage instructions here

## Development

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.

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).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/FindHotel/qyu-store-redis. 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.

## License

The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).

## Code of Conduct

Everyone interacting in the Qyu::Store::Redis project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/FindHotel/qyu-store-redis/blob/master/CODE_OF_CONDUCT.md).
6 changes: 6 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require 'bundler/gem_tasks'
require 'rspec/core/rake_task'

RSpec::Core::RakeTask.new(:spec)

task :default => :spec
15 changes: 15 additions & 0 deletions bin/console
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env ruby

require "bundler/setup"
require "qyu"
require "qyu/store/redis"

# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.

# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start

require "pry"
Pry.start
8 changes: 8 additions & 0 deletions bin/setup
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx

bundle install

# Do any other automated setup that you need to do here
13 changes: 13 additions & 0 deletions lib/qyu.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module Qyu
class << self
unless defined?(logger)
def logger=(logger)
@@__logger = logger
end

def logger
@@__logger ||= Qyu::Store::Redis::Logger.new(STDOUT)
end
end
end
end
18 changes: 18 additions & 0 deletions lib/qyu/store/redis.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
require_relative "./redis/version"
require 'json'
require 'redis'

module Qyu
module Store
module Redis
autoload :Adapter, 'qyu/store/redis/adapter'
autoload :Logger, 'qyu/store/redis/logger'

class << self
def interface
defined?(Qyu::Store::Base) ? Qyu::Store::Base : Object
end
end
end
end
end
188 changes: 188 additions & 0 deletions lib/qyu/store/redis/adapter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
require 'securerandom'

module Qyu
module Store
module Redis
class Adapter < Qyu::Store::Redis.interface
TYPE = :redis

class << self
def valid_config?(config)
true
end
end

def initialize(config)
init_client(config)
end

def find_or_persist_task(name, queue_name, payload, job_id, parent_task_id)
# TODO
end

def persist_workflow(name, descriptor)
key = "workflow:#{SecureRandom.uuid}"
@client.hmset(key, :name, name, :descriptor, serialize { descriptor })
{ name: name, descriptor: descriptor }
end

def persist_job(workflow, payload)
key = "job:#{SecureRandom.uuid}"
@client.hmset(key, :workflow, serialize { workflow }, :payload, serialize { payload })
end

def find_workflow(id)
workflow = @client.hgetall("workflow:#{id}")
return if workflow.eql?({})
workflow[:descriptor] = parse { workflow[:descriptor] }
workflow
end

def find_workflow_by_name(name)
# TODO should store workflow by name and scan by ID as name will be mostly used
end

def find_task(id)
task = @client.hgetall("task:#{id}")
return if task.eql?({})
task[:payload] = parse { task[:payload] }
task
end

def find_task_ids_by_job_id_and_name(job_id, name)
# TODO use sets
end

def find_task_ids_by_job_id_name_and_parent_task_ids(job_id, name, parent_task_ids)
# TODO use sets
end

def find_job(id)
job = @client.hgetall("job:#{id}")
return if job.eql?({})
job[:payload] = parse { job[:payload] }
job[:workflow] = parse { job[:workflow] }
job
end

def select_jobs(limit, offset, order = :asc)
# TODO jobs embedded in them their workflows
end

def select_tasks_by_job_id(job_id)
# TODO get tasks that belong to job
end

def count_jobs
@client.keys["job:*"].count
end

def lock_task!(id, lease_time)
Qyu.logger.debug '[LOCK] lock_task!'

uuid = SecureRandom.uuid
Qyu.logger.debug "[LOCK] uuid = #{uuid}"

locked_until = seconds_after_time(lease_time)
Qyu.logger.debug "[LOCK] locked_until = #{locked_until}"

key = "task:#{id}"
task = find_task(id)
# TODO raise task not found
response = nil
if task['locked_until'].eql?('') || DateTime.parse(task['locked_until']) < DateTime.now
response = redis.hmset(key, 'locked_by', uuid, 'locked_until', locked_until).eql?('OK')
end

response.eql?('OK') ? [uuid, locked_until] : [nil, nil]
end

def unlock_task!(id, lease_token)
key = "task:#{id}"
task = find_task(id)
# TODO raise task not found
if task['locked_by'].eql?(lease_token)
redis.hmset(key, 'locked_by', nil, 'locked_until', nil).eql?('OK')
else
false
end
end

def renew_lock_lease(id, lease_time, lease_token)
Qyu.logger.debug "renew_lock_lease id = #{id}, lease_time = #{lease_time}, lease_token = #{lease_token}"

key = "task:#{id}"
task = find_task(id)
# TODO raise task not found
return nil if task['locked_until'].eql?('')
if task['locked_by'].eql?(lease_token) && DateTime.parse(task['locked_until']) > DateTime.now
redis.hmset(key, 'locked_until', seconds_after_time(lease_time))
locked_until
else
return nil
end
end

def update_status(id, status)
key = "task:#{id}"
redis.hmset(key, 'status', status).eql?('OK')
end

def serialize
yield.to_json
end

def parse
JSON.parse(yield)
end

def transaction
# TODO
yield
end

private

def compare_payloads(payload1, payload2)
sort(payload1) == sort(payload2)
end

def sort(payload)
payload
end

def init_client(config)
load_config(config)
@client = ::Redis.new(@@redis_configuration)
end

def load_config(config)
if config[:url]
@@redis_configuration = { url: config[:url] }
else
@@redis_configuration = {
host: config[:host],
port: config[:port],
password: config[:password],
db: config[:db]
}.compact
end

@@redis_configuration[:ssl_params] = config[:ssl_params] if config[:ssl_params]
@@redis_configuration[:timeout] = config[:timeout] if config[:timeout]
@@redis_configuration[:connect_timeout] = config[:connect_timeout] if config[:connect_timeout]
@@redis_configuration[:read_timeout] = config[:read_timeout] if config[:read_timeout]
@@redis_configuration[:write_timeout] = config[:write_timeout] if config[:write_timeout]
true
end

def seconds_after_time(seconds, start_time = Time.now.utc)
start_time + seconds
end
end
end
end
end

Qyu::Config::StoreConfig.register(Qyu::Store::Redis::Adapter) if defined?(Qyu::Config::StoreConfig)
Qyu::Factory::StoreFactory.register(Qyu::Store::Redis::Adapter) if defined?(Qyu::Factory::StoreFactory)
Loading

0 comments on commit ef99fbf

Please sign in to comment.