delivery_boy 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: b0764539427dbbb53a7fefaa79c63177c899e18e
4
+ data.tar.gz: 6483a025b200c5e846d13ddb772bccaa656c945d
5
+ SHA512:
6
+ metadata.gz: 389af5e34963f8a97134939efa34b7b6519e20cc2f850b977c478982a60335635fdbf71974482bd2035218cf0369ea52fe3648fd088daf5d660e791d1ea9e267
7
+ data.tar.gz: dca33d4f8545897c0b372c49cc1e66b0561e598973ec6e58c848795f1c6e5e45dc3bdc50a47f4fad4170ce820b691f927d06b130348a6ed312c5780d86f540e9
@@ -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/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2.3
5
+ before_install: gem install bundler -v 1.15.3
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 delivery_boy.gemspec
6
+ gemspec
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,184 @@
1
+ # DeliveryBoy
2
+
3
+ This library provides a dead easy way to start publishing messages to a Kafka cluster from your Ruby or Rails application!
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'delivery_boy'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install delivery_boy
20
+
21
+ ## Usage
22
+
23
+ Once you've [installed the gem](#installation), and assuming your Kafka broker is running on localhost, you can simply start publishing messages to Kafka:
24
+
25
+ ```ruby
26
+ # app/controllers/comments_controller.rb
27
+ class CommentsController < ApplicationController
28
+ def create
29
+ @comment = Comment.create!(params)
30
+
31
+ # This will publish a JSON representation of the comment to the `comments` topic
32
+ # in Kafka. Make sure to create the topic first, or this may fail.
33
+ DeliveryBoy.deliver(comment.to_json, topic: "comments")
34
+ end
35
+ end
36
+ ```
37
+
38
+ The above example will block the server process until the message has been delivered. If you want deliveries to happen in the background in order to free up your server processes more quickly, call `#deliver_async` instead:
39
+
40
+ ```ruby
41
+ # app/controllers/comments_controller.rb
42
+ class CommentsController < ApplicationController
43
+ def show
44
+ @comment = Comment.find(params[:id])
45
+
46
+ event = {
47
+ name: "comment_viewed",
48
+ data: {
49
+ comment_id: @comment.id,
50
+ user_id: current_user.id
51
+ }
52
+ }
53
+
54
+ # By delivering messages asynchronously you free up your server processes faster.
55
+ DeliveryBoy.deliver_async(event.to_json, topic: "activity")
56
+ end
57
+ end
58
+ ```
59
+
60
+ In addition to improving response time, delivering messages asynchronously also protects your application against Kafka availability issues -- if messages cannot be delivered, they'll be buffered for later and retried automatically.
61
+
62
+ ### Configuration
63
+
64
+ You configure DeliveryBoy either through a config file or by setting environment variables.
65
+
66
+ If you're using Rails, the fastest way to get started is to execute the following in your terminal:
67
+
68
+ ```
69
+ $ bundle exec rails generate delivery_boy:install
70
+ ```
71
+
72
+ This will create a config file at `config/delivery_boy.yml` with configurations for each of your Rails environments. Open that file in order to make changes.
73
+
74
+ The following configuration variables can be set:
75
+
76
+ #### Basic
77
+
78
+ ##### `brokers`
79
+
80
+ A list of Kafka brokers that should be used to initialize the client. Defaults to just `localhost:9092` in development and test, but in production you need to pass a list of `hostname:port` strings.
81
+
82
+ ##### `client_id`
83
+
84
+ This is how the client will identify itself to the Kafka brokers. Default is `delivery_boy`.
85
+
86
+ #### Message delivery
87
+
88
+ ##### `delivery_interval`
89
+
90
+ The number of seconds between background message deliveries. Default is 10 seconds. Disable timer-based background deliveries by setting this to 0.
91
+
92
+ ##### `delivery_threshold`
93
+
94
+ The number of buffered messages that will trigger a background message delivery. Default is 100 messages. Disable buffer size based background deliveries by setting this to 0.
95
+
96
+ ##### `required_acks`
97
+
98
+ The number of Kafka replicas that must acknowledge messages before they're considered as successfully written. Default is _all_ replicas.
99
+
100
+ See [ruby-kafka](https://github.com/zendesk/ruby-kafka#message-durability) for more information.
101
+
102
+ ##### `ack_timeout`
103
+
104
+ A timeout executed by a broker when the client is sending messages to it. It defines the number of seconds the broker should wait for replicas to acknowledge the write before responding to the client with an error. As such, it relates to the `required_acks` setting. It should be set lower than `socket_timeout`.
105
+
106
+ ##### `max_retries`
107
+
108
+ The number of retries when attempting to deliver messages. The default is 2, so 3 attempts in total, but you can configure a higher or lower number.
109
+
110
+ ##### `retry_backoff`
111
+
112
+ The number of seconds to wait after a failed attempt to send messages to a Kafka broker before retrying. The `max_retries` setting defines the maximum number of retries to attempt, and so the total duration could be up to `max_retries * retry_backoff` seconds. The timeout can be arbitrarily long, and shouldn't be too short: if a broker goes down its partitions will be handed off to another broker, and that can take tens of seconds.
113
+
114
+ #### Compression
115
+
116
+ See [ruby-kafka](https://github.com/zendesk/ruby-kafka#compression) for more information.
117
+
118
+ ##### `compression_codec`
119
+
120
+ The codec used to compress messages. Must be either `snappy` or `gzip`.
121
+
122
+ ##### `compression_threshold`
123
+
124
+ The minimum number of messages that must be buffered before compression is attempted. By default only one message is required. Only relevant if `compression_codec` is set.
125
+
126
+ #### Network
127
+
128
+ ##### `connect_timeout`
129
+
130
+ The number of seconds to wait while connecting to a broker for the first time. When the Kafka library is initialized, it needs to connect to at least one host in `brokers` in order to discover the Kafka cluster. Each host is tried until there's one that works. Usually that means the first one, but if your entire cluster is down, or there's a network partition, you could wait up to `n * connect_timeout` seconds, where `n` is the number of hostnames in `brokers`.
131
+
132
+ ##### `socket_timeout`
133
+
134
+ Timeout when reading data from a socket connection to a Kafka broker. Must be larger than `ack_timeout` or you risk killing the socket before the broker has time to acknowledge your messages.
135
+
136
+ #### Buffering
137
+
138
+ When using the asynhronous API, messages are buffered in a background thread and delivered to Kafka based on the configured delivery policy. Because of this, problems that hinder the delivery of messages can cause the buffer to grow. In order to avoid unlimited buffer growth that would risk affecting the host application, some limits are put in place. After the buffer reaches the maximum size allowed, calling `DeliveryBoy.deliver_async` will raise `Kafka::BufferOverflow`.
139
+
140
+ ##### `max_buffer_bytesize`
141
+
142
+ The maximum number of bytes allowed in the buffer before new messages are rejected.
143
+
144
+ ##### `max_buffer_size`
145
+
146
+ The maximum number of messages allowed in the buffer before new messages are rejected.
147
+
148
+ ##### `max_queue_size`
149
+
150
+ The maximum number of messages allowed in the queue before new messages are rejected. The queue is used to ferry messages from the foreground threads of your application to the background thread that buffers and delivers messages. You typically only want to increase this number if you have a very high throughput of messages and the background thread can't keep up with spikes in throughput.
151
+
152
+ #### Authentication and authorization
153
+
154
+ See [ruby-kafka](https://github.com/zendesk/ruby-kafka#security) for more information.
155
+
156
+ ##### `ssl_ca_cert`
157
+
158
+ A PEM encoded CA cert, or an Array of PEM encoded CA certs, to use with an SSL connection.
159
+
160
+ ##### `ssl_client_cert`
161
+
162
+ A PEM encoded client cert to use with an SSL connection. Must be used in combination with `ssl_client_cert_key`.
163
+
164
+ ##### `ssl_client_cert_key`
165
+
166
+ A PEM encoded client cert key to use with an SSL connection. Must be used in combination with `ssl_client_cert`.
167
+
168
+ ### Instrumentation & monitoring
169
+
170
+ Since DeliveryBoy is just an opinionated API on top of ruby-kafka, you can use all the [instrumentation made available by that library](https://github.com/zendesk/ruby-kafka#instrumentation). You can also use the [existing monitoring solutions](https://github.com/zendesk/ruby-kafka#monitoring) that integrate with various monitoring services.
171
+
172
+ ## Contributing
173
+
174
+ Bug reports and pull requests are welcome on [GitHub](https://github.com/dasch/delivery_boy).
175
+
176
+ ## Copyright and license
177
+
178
+ Copyright 2017 Zendesk, Inc.
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
181
+
182
+ You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
183
+
184
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "delivery_boy"
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(__FILE__)
@@ -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,28 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "delivery_boy/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "delivery_boy"
8
+ spec.version = DeliveryBoy::VERSION
9
+ spec.authors = ["Daniel Schierbeck"]
10
+ spec.email = ["daniel.schierbeck@gmail.com"]
11
+
12
+ spec.summary = "A simple way to produce messages to Kafka from Ruby applications"
13
+ spec.description = "A simple way to produce messages to Kafka from Ruby applications"
14
+ spec.homepage = "https://github.com/zendesk/delivery_boy"
15
+ spec.license = "Apache License Version 2.0"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_runtime_dependency "ruby-kafka", "~> 0.4"
24
+
25
+ spec.add_development_dependency "bundler", "~> 1.15"
26
+ spec.add_development_dependency "rake", "~> 10.0"
27
+ spec.add_development_dependency "rspec", "~> 3.0"
28
+ end
@@ -0,0 +1,4 @@
1
+ require "delivery_boy"
2
+
3
+ DeliveryBoy.deliver_async "howdy", topic: "greetings"
4
+ DeliveryBoy.shutdown
@@ -0,0 +1,4 @@
1
+ require "delivery_boy"
2
+
3
+ DeliveryBoy.deliver "hello", topic: "greetings"
4
+ DeliveryBoy.shutdown
@@ -0,0 +1,92 @@
1
+ require "logger"
2
+ require "kafka"
3
+ require "delivery_boy/version"
4
+ require "delivery_boy/config"
5
+ require "delivery_boy/railtie" if defined?(Rails)
6
+
7
+ module DeliveryBoy
8
+ class << self
9
+ def deliver(value, topic:, **options)
10
+ sync_producer.produce(value, topic: topic, **options)
11
+ sync_producer.deliver_messages
12
+ rescue
13
+ # Make sure to clear any buffered messages if there's an error.
14
+ sync_producer.clear_buffer
15
+
16
+ raise
17
+ end
18
+
19
+ def deliver_async(value, topic:, **options)
20
+ async_producer.produce(value, topic: topic, **options)
21
+ end
22
+
23
+ def shutdown
24
+ sync_producer.shutdown if sync_producer?
25
+ async_producer.shutdown if async_producer?
26
+ end
27
+
28
+ def logger
29
+ @logger ||= Logger.new($stdout)
30
+ end
31
+
32
+ attr_writer :logger
33
+
34
+ def config
35
+ @config ||= DeliveryBoy::Config.new(env: ENV)
36
+ end
37
+
38
+ private
39
+
40
+ def sync_producer
41
+ # We want synchronous producers to be per-thread in order to avoid problems with
42
+ # concurrent deliveries.
43
+ Thread.current[:delivery_boy_sync_producer] ||= kafka.producer(**producer_options)
44
+ end
45
+
46
+ def sync_producer?
47
+ Thread.current.key?(:delivery_boy_sync_producer)
48
+ end
49
+
50
+ def async_producer
51
+ # The async producer doesn't have to be per-thread, since all deliveries are
52
+ # performed by a single background thread.
53
+ @async_producer ||= kafka.async_producer(
54
+ max_queue_size: config.max_queue_size,
55
+ delivery_threshold: config.delivery_threshold,
56
+ delivery_interval: config.delivery_interval,
57
+ **producer_options,
58
+ )
59
+ end
60
+
61
+ def async_producer?
62
+ !@async_producer.nil?
63
+ end
64
+
65
+ def kafka
66
+ @kafka ||= Kafka.new(
67
+ seed_brokers: config.brokers,
68
+ client_id: config.client_id,
69
+ logger: logger,
70
+ connect_timeout: config.connect_timeout,
71
+ socket_timeout: config.socket_timeout,
72
+ ssl_ca_cert: config.ssl_ca_cert,
73
+ ssl_client_cert: config.ssl_client_cert,
74
+ ssl_client_cert_key: config.ssl_client_cert_key,
75
+ )
76
+ end
77
+
78
+ # Options for both the sync and async producers.
79
+ def producer_options
80
+ {
81
+ required_acks: config.required_acks,
82
+ ack_timeout: config.ack_timeout,
83
+ max_retries: config.max_retries,
84
+ retry_backoff: config.retry_backoff,
85
+ max_buffer_size: config.max_buffer_size,
86
+ max_buffer_bytesize: config.max_buffer_bytesize,
87
+ compression_codec: config.compression_codec,
88
+ compression_threshold: config.compression_threshold,
89
+ }
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,98 @@
1
+ require "erb"
2
+ require "yaml"
3
+ require "delivery_boy/env_config_loader"
4
+ require "delivery_boy/config_file_loader"
5
+ require "delivery_boy/config_error"
6
+
7
+ module DeliveryBoy
8
+ class Config
9
+ VARIABLES = %w[
10
+ ack_timeout
11
+ brokers
12
+ client_id
13
+ compression_codec
14
+ compression_threshold
15
+ connect_timeout
16
+ delivery_interval
17
+ delivery_threshold
18
+ max_buffer_bytesize
19
+ max_buffer_size
20
+ max_queue_size
21
+ max_retries
22
+ required_acks
23
+ retry_backoff
24
+ socket_timeout
25
+ ssl_ca_cert
26
+ ssl_client_cert
27
+ ssl_client_cert_key
28
+ ]
29
+
30
+ DEFAULTS = {
31
+ ack_timeout: 5,
32
+ brokers: ["localhost:9092"],
33
+ client_id: "delivery_boy",
34
+ compression_threshold: 1,
35
+ connect_timeout: 10,
36
+ max_buffer_bytesize: 10_000_000,
37
+ max_buffer_size: 1000,
38
+ max_retries: 2,
39
+ required_acks: :all,
40
+ retry_backoff: 1,
41
+ socket_timeout: 30,
42
+ delivery_interval: 10,
43
+ delivery_threshold: 100,
44
+ max_queue_size: 1000,
45
+ }
46
+
47
+ attr_accessor(*VARIABLES)
48
+
49
+ def initialize(env:)
50
+ load_config(DEFAULTS)
51
+ load_env(env)
52
+ end
53
+
54
+ def load_file(path, environment)
55
+ loader = ConfigFileLoader.new(self)
56
+ loader.load_file(path, environment)
57
+ end
58
+
59
+ private
60
+
61
+ def load_config(config)
62
+ config.each do |variable, value|
63
+ set(variable, value)
64
+ end
65
+ end
66
+
67
+ def load_env(env)
68
+ loader = EnvConfigLoader.new(env, self)
69
+
70
+ loader.integer :ack_timeout
71
+ loader.symbol :compression_codec
72
+ loader.integer :compression_threshold
73
+ loader.integer :connect_timeout
74
+ loader.integer :delivery_interval
75
+ loader.integer :delivery_threshold
76
+ loader.integer :max_buffer_bytesize
77
+ loader.integer :max_buffer_size
78
+ loader.integer :max_queue_size
79
+ loader.integer :max_retries
80
+ loader.integer :required_acks
81
+ loader.integer :retry_backoff
82
+ loader.integer :socket_timeout
83
+ loader.string :ssl_ca_cert
84
+ loader.string :ssl_client_cert
85
+ loader.string :ssl_client_cert_key
86
+
87
+ loader.validate!
88
+ end
89
+
90
+ def set(variable, value)
91
+ unless VARIABLES.include?(variable.to_s)
92
+ raise ConfigError, "unknown configuration variable #{variable}"
93
+ end
94
+
95
+ instance_variable_set("@#{variable}", value)
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,4 @@
1
+ module DeliveryBoy
2
+ ConfigError = Class.new(StandardError)
3
+ end
4
+
@@ -0,0 +1,20 @@
1
+ module DeliveryBoy
2
+ class ConfigFileLoader
3
+ def initialize(config)
4
+ @config = config
5
+ end
6
+
7
+ def load_file(path, environment)
8
+ # First, load the ERB template from disk.
9
+ template = ERB.new(File.new(path).read)
10
+
11
+ # The last argument to `safe_load` allows us to use aliasing to share
12
+ # configuration between environments.
13
+ processed = YAML.safe_load(template.result(binding), [], [], true)
14
+
15
+ processed.fetch(environment).each do |variable, value|
16
+ @config.set(variable, value)
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,57 @@
1
+ require "delivery_boy/config_error"
2
+
3
+ module DeliveryBoy
4
+ class EnvConfigLoader
5
+ KEY_PREFIX = "DELIVERY_BOY"
6
+
7
+ def initialize(env, config)
8
+ @env = env
9
+ @config = config
10
+ @loaded_keys = []
11
+ end
12
+
13
+ def string(name)
14
+ set(name) {|value| value }
15
+ end
16
+
17
+ def symbol(name)
18
+ set(name) {|value| value.to_sym }
19
+ end
20
+
21
+ def integer(name)
22
+ set(name) do |value|
23
+ begin
24
+ Integer(value)
25
+ rescue ArgumentError
26
+ raise ConfigError, "#{value.inspect} is not an integer"
27
+ end
28
+ end
29
+ end
30
+
31
+ def string_list(name)
32
+ set(name) {|value| value.split(",") }
33
+ end
34
+
35
+ def validate!
36
+ # Make sure the user hasn't made a typo and added a key we don't know
37
+ # about.
38
+ @env.keys.grep(/^#{KEY_PREFIX}_/).each do |key|
39
+ unless @loaded_keys.include?(key)
40
+ raise ConfigError, "unknown config variable #{key}"
41
+ end
42
+ end
43
+ end
44
+
45
+ private
46
+
47
+ def set(name)
48
+ key = "#{KEY_PREFIX}_#{name.upcase}"
49
+
50
+ if @env.key?(key)
51
+ value = yield @env.fetch(key)
52
+ @config.set(name, value)
53
+ @loaded_keys << key
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,11 @@
1
+ module DeliveryBoy
2
+ class Railtie < Rails::Railtie
3
+ initializer "delivery_boy.load_config" do
4
+ config_file = "config/delivery_boy.yml"
5
+
6
+ if File.exist?(config_file)
7
+ DeliveryBoy.config.load_file(config_file, Rails.env)
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,3 @@
1
+ module DeliveryBoy
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,20 @@
1
+ # These config values will be shared by all environments but can be overridden.
2
+ common: &common
3
+ client_id: "<%= Rails.application.class.name.split("::").first.underscore %>"
4
+
5
+ development:
6
+ <<: *common
7
+ brokers:
8
+ - localhost:9092
9
+
10
+ test:
11
+ <<: *common
12
+ brokers:
13
+ - localhost:9092
14
+
15
+ production:
16
+ <<: *common
17
+ brokers:
18
+ - kafka1.myapp.com:9092
19
+ - kafka2.myapp.com:9092
20
+ - kafka3.myapp.com:9092
@@ -0,0 +1,11 @@
1
+ module DeliveryBoy
2
+ module Generators
3
+ class InstallGenerator < Rails::Generators::Base
4
+ source_root File.expand_path("../", __FILE__)
5
+
6
+ def create_config_file
7
+ template "config_file.yml.erb", "config/delivery_boy.yml"
8
+ end
9
+ end
10
+ end
11
+ end
metadata ADDED
@@ -0,0 +1,121 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: delivery_boy
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Daniel Schierbeck
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2017-09-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ruby-kafka
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.4'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.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: '1.15'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.15'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
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.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ description: A simple way to produce messages to Kafka from Ruby applications
70
+ email:
71
+ - daniel.schierbeck@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - ".travis.yml"
79
+ - Gemfile
80
+ - LICENSE.txt
81
+ - README.md
82
+ - Rakefile
83
+ - bin/console
84
+ - bin/setup
85
+ - delivery_boy.gemspec
86
+ - examples/async.rb
87
+ - examples/sync.rb
88
+ - lib/delivery_boy.rb
89
+ - lib/delivery_boy/config.rb
90
+ - lib/delivery_boy/config_error.rb
91
+ - lib/delivery_boy/config_file_loader.rb
92
+ - lib/delivery_boy/env_config_loader.rb
93
+ - lib/delivery_boy/railtie.rb
94
+ - lib/delivery_boy/version.rb
95
+ - lib/generators/delivery_boy/config_file.yml.erb
96
+ - lib/generators/delivery_boy/install_generator.rb
97
+ homepage: https://github.com/zendesk/delivery_boy
98
+ licenses:
99
+ - Apache License Version 2.0
100
+ metadata: {}
101
+ post_install_message:
102
+ rdoc_options: []
103
+ require_paths:
104
+ - lib
105
+ required_ruby_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - ">="
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ required_rubygems_version: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - ">="
113
+ - !ruby/object:Gem::Version
114
+ version: '0'
115
+ requirements: []
116
+ rubyforge_project:
117
+ rubygems_version: 2.4.5.1
118
+ signing_key:
119
+ specification_version: 4
120
+ summary: A simple way to produce messages to Kafka from Ruby applications
121
+ test_files: []