bulk-processor 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: 81b6cbba22963959c1e355f71f78790cbc0b6592
4
+ data.tar.gz: 8859344abc19572527f69ba9259c5b1289bde273
5
+ SHA512:
6
+ metadata.gz: 584baf85c25c5a741eb8392ab068a3e1798a71398dd3f53e0da6e24aca144648fb77c8442865a4f5c134193fbf255f4b5cf55f630bc1915241e1f2d229189ce7
7
+ data.tar.gz: 7a5cc788e2b8bc7caf6d4960aa28fd2233661b3e8f5d1b2d90ed4a474ba8885c35ee63fcf077b0b25a1a0c2cb9408ca1c22846105592a7de9a87b9330e04c93f
data/.gitignore ADDED
@@ -0,0 +1,2 @@
1
+ /Gemfile.lock
2
+ bulk-processor-*.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require 'spec_helper'
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1.5
4
+ - 2.2.3
5
+ branches:
6
+ only: master
@@ -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, 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 bulk-processor.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Apartment List Inc
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,138 @@
1
+ ![Travis status for apartmentlist/bulk-processor](https://travis-ci.org/apartmentlist/bulk-processor.svg?branch=master)
2
+
3
+
4
+ # BulkProcessor
5
+
6
+ Bulk upload data in a file (e.g. CSV), process in the background, then send a
7
+ success or failure report
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'bulk-processor'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install bulk-processor
24
+
25
+ ## Usage
26
+
27
+ Bulk processor requires the following configuration
28
+
29
+ ```ruby
30
+ BulkProcessor.queue_adapter = <adapter>
31
+ ```
32
+
33
+ The default is `:inline`, which skips queueing and processes synchronously. Since
34
+ this is backed by ActiveJob, all of the adapters in [ActiveJob::QueueAdapters]( http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html ),
35
+ including `:resque`.
36
+
37
+ You will also need to supply a class for item processing and a class/module for completion handling.
38
+ The item processor instance must respond to the following messages:
39
+
40
+ ```
41
+ class PetItemProcessor
42
+ # @return [Array<String>] column headers that must be present
43
+ def self.required_columns
44
+ ['species', 'name', 'age']
45
+ end
46
+
47
+ # @return [Array<String>] column headers that may be present. If a column
48
+ # header is present that is not in 'required_columns' or 'optional_columns',
49
+ # the file will be considered invalid and no rows will be processed.
50
+ def self.optional_columns
51
+ ['favorite_toy', 'talents']
52
+ end
53
+
54
+ # Instantiate the processor with a single row from the CSV represented by
55
+ # a Hash<String, String>
56
+ def initialize(record_hash, payload)
57
+ @record_hash = record_hash
58
+ @payload = payload
59
+ @messages = []
60
+ @success = false
61
+ end
62
+
63
+ # Process the row, e.g. create a new record in the DB, send an email, etc
64
+ def process!
65
+ pet = Pet.new(record_hash)
66
+ if pet.save
67
+ @success = true
68
+ else
69
+ @messages = pet.errors.full_messages
70
+ end
71
+ end
72
+
73
+ # @return [true|false] true iff the item was processed completely
74
+ def success?
75
+ @success
76
+ end
77
+
78
+ # @return [Array<String>] list of messages for this item to pass back to the
79
+ # completion handler.
80
+ def messages
81
+ @messages
82
+ end
83
+ end
84
+ ```
85
+
86
+ A completion handler must respond to the following messages
87
+
88
+ ```ruby
89
+ module NotificationHandler
90
+ # Handle full or partial processing of records. Unless there was a fatal
91
+ # error, all row indexes will be present either successes or errors, but not
92
+ # both.
93
+ #
94
+ # @param payload [Hash] the payload passed into 'BulkProcessor.process', can
95
+ # be used to pass metadata around, e.g. the email address to send a
96
+ # completion report to
97
+ # @param successes [Hash<Fixnum, Array<String>>] keys are all successfully
98
+ # processed rows, indexed from 0 (row 1 in the CSV is index 0 in this hash)
99
+ # The values are arrays of messages the item processor generated for the row
100
+ # (may be empty), e.g. { 0 => [], 1 => ['pet ID = 22 created'] }
101
+ # @param errors [Hash<Fixnum, Array<String>>] similar structure to successes,
102
+ # but rows that were not completed successfully.
103
+ # @param fatal_error [StandardError] if nil, then all rows were processed,
104
+ # else the error that was raise is passed in here
105
+ def self.complete(payload, successes, errors, fatal_error = nil)
106
+ if fatal_error
107
+ PetProcessorMailer.fail(payload['recipient'], successes, errors, fatal_error)
108
+ else
109
+ PetProcessorMailer.complete(payload['recipient'], successes, errors)
110
+ end
111
+ end
112
+ end
113
+ ```
114
+
115
+ Requesting file processing
116
+
117
+ ```ruby
118
+ processor = BulkProcessor.new(file_stream, PetItemProcessor, NotificationHandler, {recipient: current_user.email})
119
+ if processor.process
120
+ # The job has been enqueued, go get a coffee and wait
121
+ else
122
+ handle_invalid_file(processor.errors)
123
+ end
124
+ ```
125
+
126
+ ## Development
127
+
128
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.
129
+
130
+ 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` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
131
+
132
+ ## Contributing
133
+
134
+ 1. Fork it ( https://github.com/apartmentlist/bulk-processor/fork )
135
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
136
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
137
+ 4. Push to the branch (`git push origin my-new-feature`)
138
+ 5. Create a new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ require 'bundler/gem_tasks'
2
+
3
+ begin
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
9
+ rescue LoadError
10
+ # no rspec available
11
+ end
12
+
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'bulk_processor'
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
@@ -0,0 +1,30 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'bulk_processor/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'bulk-processor'
8
+ spec.version = BulkProcessor::VERSION
9
+ spec.authors = ['Tom Collier, Justin Richard']
10
+ spec.email = ['collier@apartmentlist.com, justin@apartmentlist.com']
11
+
12
+ spec.summary = 'Background process CSV data'
13
+ spec.description = <<-DESC
14
+ Bulk upload data in a file (e.g. CSV), process in the background, then send a
15
+ success or failure report
16
+ DESC
17
+ spec.license = 'MIT'
18
+
19
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ['lib']
22
+ spec.required_ruby_version = '>= 2.1'
23
+
24
+ spec.add_runtime_dependency 'activejob', '~> 4'
25
+
26
+ spec.add_development_dependency 'bundler'
27
+ spec.add_development_dependency 'pry-byebug', '~> 3'
28
+ spec.add_development_dependency 'rake', '~> 10.4'
29
+ spec.add_development_dependency 'rspec', '~> 3.3'
30
+ end
@@ -0,0 +1,9 @@
1
+ class BulkProcessor
2
+ class Config
3
+ attr_reader :queue_adapter
4
+
5
+ def queue_adapter=(adapter)
6
+ ActiveJob::Base.queue_adapter = @queue_adapter = adapter
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,26 @@
1
+ class BulkProcessor
2
+ class Job < ActiveJob::Base
3
+ queue_as 'bulk_processor'
4
+
5
+ def perform(records, item_proccessor, handler, payload)
6
+ item_proccessor_class = item_proccessor.constantize
7
+ handler_class = handler.constantize
8
+
9
+ successes = {}
10
+ failures = {}
11
+ records.each_with_index do |record, index|
12
+ processor = item_proccessor_class.new(record, payload)
13
+ processor.process!
14
+ if processor.success?
15
+ successes[index] = processor.messages
16
+ else
17
+ failures[index] = processor.messages
18
+ end
19
+ end
20
+ handler_class.complete(payload, successes, failures, nil)
21
+ rescue Exception => exception
22
+ handler_class.complete(payload, successes, failures, exception)
23
+ raise unless exception.is_a?(StandardError)
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,26 @@
1
+ class BulkProcessor
2
+ # Force encode a stream into UTF-8 by removing invalid and undefined
3
+ # characters.
4
+ class StreamEncoder
5
+ ENCODING_OPTIONS = { undef: :replace, invalid: :replace, replace: '' }
6
+ private_constant :ENCODING_OPTIONS
7
+
8
+ def initialize(stream)
9
+ @stream = stream
10
+ end
11
+
12
+ # Return the UTF-8 encoded string.
13
+ #
14
+ # Note: this method reads the stream, so it will need to be rewound before
15
+ # attempting to read again.
16
+ #
17
+ # @return [String] a UTF-8 encoded string
18
+ def encoded
19
+ stream.read.encode(Encoding::UTF_8, ENCODING_OPTIONS)
20
+ end
21
+
22
+ private
23
+
24
+ attr_reader :stream
25
+ end
26
+ end
@@ -0,0 +1,62 @@
1
+ class BulkProcessor
2
+ class ValidatedCSV
3
+ PARSING_OPTIONS = { headers: true, header_converters: :downcase }
4
+ private_constant :PARSING_OPTIONS
5
+
6
+ BAD_HEADERS_ERROR_MSG = "undefined method `encode' for nil:NilClass"
7
+ private_constant :BAD_HEADERS_ERROR_MSG
8
+
9
+ attr_reader :errors, :records
10
+
11
+ def initialize(stream, required_headers, optional_headers)
12
+ @stream = stream
13
+ @required_headers = required_headers
14
+ @optional_headers = optional_headers
15
+ @errors = []
16
+ end
17
+
18
+ def valid?
19
+ @errors = []
20
+
21
+ if missing_headers.any?
22
+ errors << "Missing required column(s): #{missing_headers.join(', ')}"
23
+ end
24
+
25
+ if extra_headers.any?
26
+ errors << "Unrecognized column(s) found: #{extra_headers.join(', ')}"
27
+ end
28
+
29
+ unless csv.headers.all?
30
+ errors << 'Missing or malformed column header, is one of them blank?'
31
+ end
32
+ rescue NoMethodError => error
33
+ if error.message == BAD_HEADERS_ERROR_MSG
34
+ errors << 'Missing or malformed column header, is one of them blank?'
35
+ else
36
+ raise error
37
+ end
38
+ ensure
39
+ return errors.empty?
40
+ end
41
+
42
+ def row_hashes
43
+ csv.map(&:to_hash)
44
+ end
45
+
46
+ private
47
+
48
+ attr_reader :stream, :required_headers, :optional_headers
49
+
50
+ def csv
51
+ @csv ||= CSV.parse(stream, PARSING_OPTIONS)
52
+ end
53
+
54
+ def missing_headers
55
+ required_headers - csv.headers
56
+ end
57
+
58
+ def extra_headers
59
+ csv.headers - [*required_headers, *optional_headers]
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,3 @@
1
+ class BulkProcessor
2
+ VERSION = '0.1.0'
3
+ end
@@ -0,0 +1,46 @@
1
+ require 'active_job'
2
+ require 'csv'
3
+
4
+ require 'bulk_processor/config'
5
+ require 'bulk_processor/job'
6
+ require 'bulk_processor/stream_encoder'
7
+ require 'bulk_processor/validated_csv'
8
+ require 'bulk_processor/version'
9
+
10
+ class BulkProcessor
11
+ class << self
12
+ def config
13
+ @config ||= Config.new
14
+ end
15
+
16
+ def configure
17
+ yield config
18
+ end
19
+
20
+ end
21
+
22
+ attr_reader :stream, :item_processor, :handler, :payload, :errors
23
+
24
+ def initialize(stream, item_processor, handler, payload = {})
25
+ @stream = stream
26
+ @item_processor = item_processor
27
+ @handler = handler
28
+ @payload = payload
29
+ @errors = []
30
+ end
31
+
32
+ def process
33
+ csv = ValidatedCSV.new(
34
+ StreamEncoder.new(stream).encoded,
35
+ item_processor.required_columns,
36
+ item_processor.optional_columns
37
+ )
38
+
39
+ if csv.valid?
40
+ Job.perform_later(csv.row_hashes, item_processor.to_s, handler.to_s, payload)
41
+ else
42
+ @errors = csv.errors
43
+ end
44
+ @errors.empty?
45
+ end
46
+ end
metadata ADDED
@@ -0,0 +1,133 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bulk-processor
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Tom Collier, Justin Richard
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2016-01-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activejob
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '4'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
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: pry-byebug
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.4'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.4'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.3'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.3'
83
+ description: |
84
+ Bulk upload data in a file (e.g. CSV), process in the background, then send a
85
+ success or failure report
86
+ email:
87
+ - collier@apartmentlist.com, justin@apartmentlist.com
88
+ executables: []
89
+ extensions: []
90
+ extra_rdoc_files: []
91
+ files:
92
+ - ".gitignore"
93
+ - ".rspec"
94
+ - ".travis.yml"
95
+ - CODE_OF_CONDUCT.md
96
+ - Gemfile
97
+ - LICENSE.txt
98
+ - README.md
99
+ - Rakefile
100
+ - bin/console
101
+ - bin/setup
102
+ - bulk-processor.gemspec
103
+ - lib/bulk_processor.rb
104
+ - lib/bulk_processor/config.rb
105
+ - lib/bulk_processor/job.rb
106
+ - lib/bulk_processor/stream_encoder.rb
107
+ - lib/bulk_processor/validated_csv.rb
108
+ - lib/bulk_processor/version.rb
109
+ homepage:
110
+ licenses:
111
+ - MIT
112
+ metadata: {}
113
+ post_install_message:
114
+ rdoc_options: []
115
+ require_paths:
116
+ - lib
117
+ required_ruby_version: !ruby/object:Gem::Requirement
118
+ requirements:
119
+ - - ">="
120
+ - !ruby/object:Gem::Version
121
+ version: '2.1'
122
+ required_rubygems_version: !ruby/object:Gem::Requirement
123
+ requirements:
124
+ - - ">="
125
+ - !ruby/object:Gem::Version
126
+ version: '0'
127
+ requirements: []
128
+ rubyforge_project:
129
+ rubygems_version: 2.4.3
130
+ signing_key:
131
+ specification_version: 4
132
+ summary: Background process CSV data
133
+ test_files: []