hanami-events-cloud_pubsub 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b74e245658e07e3de644521a132de72abda946f063da3d4753baaafd90d3c4a5
4
+ data.tar.gz: 828da43db5d56a53f88111da0f10295d15f8f2c5acba0c0bf7b2b110e732b75e
5
+ SHA512:
6
+ metadata.gz: 1278b410daba4892e127631c86058cb00397b5903547a9e03b96df7908382a10c8166ebf624edaa2990ff53c2a727996ea9df1347ca901f69eccf0d0aef0573c
7
+ data.tar.gz: 4bf717414948e69b9f48eac0b9c9e60d2fab73c0ad90d1cf6fd9bbf74a1cdf5881cc72f16d722d032b040c9c8a50697cd81dce67408959c6b5b49a7171eec413
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /log/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,31 @@
1
+ ---
2
+ inherit_from: .rubocop_todo.yml
3
+
4
+ AllCops:
5
+ TargetRubyVersion: 2.3
6
+
7
+ Metrics/BlockLength:
8
+ Exclude:
9
+ - spec/**/*.rb
10
+ - ./*.gemspec
11
+
12
+ Metrics/ModuleLength:
13
+ Exclude:
14
+ - spec/**/*.rb
15
+
16
+ Style/LambdaCall:
17
+ Enabled: false
18
+
19
+ Style/Lambda:
20
+ Enabled: false
21
+
22
+ Style/ClassAndModuleChildren:
23
+ Enabled: false
24
+
25
+ Style/Documentation:
26
+ Exclude:
27
+ - apps/**/*.rb
28
+ - spec/**/*.rb
29
+
30
+ Style/BlockDelimiters:
31
+ Enabled: false
data/.rubocop_todo.yml ADDED
@@ -0,0 +1,20 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config`
3
+ # on 2018-06-05 14:43:37 -0400 using RuboCop version 0.56.0.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
8
+
9
+ # Offense count: 4
10
+ # Configuration parameters: AllowedVariables.
11
+ Style/GlobalVars:
12
+ Exclude:
13
+ - 'examples/server.rb'
14
+ - 'lib/hanami/events/cloud_pubsub/cli.rb'
15
+
16
+ # Offense count: 14
17
+ # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
18
+ # URISchemes: http, https
19
+ Metrics/LineLength:
20
+ Max: 96
data/.travis.yml ADDED
@@ -0,0 +1,28 @@
1
+ ---
2
+ sudo: required
3
+ cache: bundler
4
+ services:
5
+ - docker
6
+ language: ruby
7
+ env:
8
+ - DOCKER_COMPOSE_VERSION=1.21.2
9
+ rvm:
10
+ - 2.4
11
+ before_install:
12
+ - gem install bundler -v 1.16.1
13
+ - sudo rm /usr/local/bin/docker-compose
14
+ - curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname
15
+ -s`-`uname -m` > docker-compose
16
+ - chmod +x docker-compose
17
+ - sudo mv docker-compose /usr/local/bin
18
+ - docker-compose up -d
19
+ after_failure:
20
+ - cat log/test.log
21
+ deploy:
22
+ provider: rubygems
23
+ api_key:
24
+ secure: q/B3zDEld8yzf1plU1vlnUIhqk7hhdrqdF8uRnSvikweM9MSeGk1x6lcZ4mxnwCVPuQEP49iI4sNtFHiJnP/Dv6f48A6ltpVlyST1vghhXlaIi9+r9pCJqB+vAOii7poq9lWyKWj15MMB5xE52Alz7WzUccOL55gmJ4q+Lia6+z04m+VdOuEY1Lyn38O9jtZJBBfnbjar+qKoHXCNSKuJfXrFBi+2LKvaxJFWS8NBvhnDILNkcooh01rp6/dtNuUMFTLd1i+zMMBYc1PyGP0+fNZE9MXUViy3soDfgXlPDyiwtTzASLCu6HXQg8g9SwBxMnkRQRxAKYzoAPoECcr9NxMR1riH6xaA2wkwW/rKcBP5JPfbRymRgSui4uhYSq7WJR5KNxpH2JYK+rW/EL9SB+7BT67g3ZNL6YGpL3R7/S5RLdHk+lJIY8uFRtzhYgchSa0tkBAm/qbll5d4B9wq7O1/McNwUQJKFs7CsVXL/arZUFgQVGdkQDOIeCITzeFy4iP3JASewOk+yCUyCbBCya2AicU7BOjYpghD0QNmyaunTPhCySdBe4mS3QkAspHGg10H5dggNS0IqHYmUTlmHiYg9Pf9TF85krQih/s3hr/+i13u+y8iBwA7n/mXTt5IQ+NQgXNSC0uJvSjHU2Rzr9yKZ1lLEXMB0y+S9OVeZA=
25
+ gem: hanami-events-cloud_pubsub
26
+ on:
27
+ tags: true
28
+ repo: adHawk/hanami-events-cloud_pubsub
@@ -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 i.kerseymer@gmail.com. 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,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ # Specify your gem's dependencies in hanami-events-cloud_pubsub.gemspec
8
+ gemspec
9
+
10
+ group :test do
11
+ gem 'hanami-events', github: 'ianks/events', branch: 'args-to-subscribe'
12
+ gem 'pry'
13
+ gem 'rubocop'
14
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,139 @@
1
+ GIT
2
+ remote: https://github.com/ianks/events
3
+ revision: 29539d68cae73faa638b5b4691fd87ec2b34a447
4
+ branch: args-to-subscribe
5
+ specs:
6
+ hanami-events (0.1.0)
7
+ dry-container (~> 0.6)
8
+
9
+ PATH
10
+ remote: .
11
+ specs:
12
+ hanami-events-cloud_pubsub (0.1.0)
13
+ google-cloud-pubsub (~> 0.30.2)
14
+ hanami-cli
15
+ hanami-events
16
+
17
+ GEM
18
+ remote: https://rubygems.org/
19
+ specs:
20
+ addressable (2.5.2)
21
+ public_suffix (>= 2.0.2, < 4.0)
22
+ ast (2.4.0)
23
+ coderay (1.1.2)
24
+ concurrent-ruby (1.0.5)
25
+ diff-lcs (1.3)
26
+ dry-configurable (0.7.0)
27
+ concurrent-ruby (~> 1.0)
28
+ dry-container (0.6.0)
29
+ concurrent-ruby (~> 1.0)
30
+ dry-configurable (~> 0.1, >= 0.1.3)
31
+ faraday (0.15.2)
32
+ multipart-post (>= 1.2, < 3)
33
+ google-cloud-core (1.2.0)
34
+ google-cloud-env (~> 1.0)
35
+ google-cloud-env (1.0.1)
36
+ faraday (~> 0.11)
37
+ google-cloud-pubsub (0.30.2)
38
+ concurrent-ruby (~> 1.0)
39
+ google-cloud-core (~> 1.2)
40
+ google-gax (~> 1.0)
41
+ grpc-google-iam-v1 (~> 0.6.9)
42
+ google-gax (1.2.0)
43
+ google-protobuf (~> 3.2)
44
+ googleapis-common-protos (>= 1.3.5, < 2.0)
45
+ googleauth (~> 0.6.2)
46
+ grpc (>= 1.7.2, < 2.0)
47
+ rly (~> 0.2.3)
48
+ google-protobuf (3.5.1.2)
49
+ googleapis-common-protos (1.3.7)
50
+ google-protobuf (~> 3.0)
51
+ googleapis-common-protos-types (~> 1.0)
52
+ grpc (~> 1.0)
53
+ googleapis-common-protos-types (1.0.1)
54
+ google-protobuf (~> 3.0)
55
+ googleauth (0.6.2)
56
+ faraday (~> 0.12)
57
+ jwt (>= 1.4, < 3.0)
58
+ logging (~> 2.0)
59
+ memoist (~> 0.12)
60
+ multi_json (~> 1.11)
61
+ os (~> 0.9)
62
+ signet (~> 0.7)
63
+ grpc (1.12.0)
64
+ google-protobuf (~> 3.1)
65
+ googleapis-common-protos-types (~> 1.0.0)
66
+ googleauth (>= 0.5.1, < 0.7)
67
+ grpc-google-iam-v1 (0.6.9)
68
+ googleapis-common-protos (>= 1.3.1, < 2.0)
69
+ grpc (~> 1.0)
70
+ hanami-cli (0.2.0)
71
+ concurrent-ruby (~> 1.0)
72
+ hanami-utils (~> 1.2)
73
+ hanami-utils (1.2.0)
74
+ concurrent-ruby (~> 1.0)
75
+ transproc (~> 1.0)
76
+ jwt (2.1.0)
77
+ little-plugger (1.1.4)
78
+ logging (2.2.2)
79
+ little-plugger (~> 1.1)
80
+ multi_json (~> 1.10)
81
+ memoist (0.16.0)
82
+ method_source (0.9.0)
83
+ multi_json (1.13.1)
84
+ multipart-post (2.0.0)
85
+ os (0.9.6)
86
+ parallel (1.12.1)
87
+ parser (2.5.1.0)
88
+ ast (~> 2.4.0)
89
+ powerpack (0.1.1)
90
+ pry (0.11.3)
91
+ coderay (~> 1.1.0)
92
+ method_source (~> 0.9.0)
93
+ public_suffix (3.0.2)
94
+ rainbow (3.0.0)
95
+ rake (12.3.1)
96
+ rly (0.2.3)
97
+ rspec (3.7.0)
98
+ rspec-core (~> 3.7.0)
99
+ rspec-expectations (~> 3.7.0)
100
+ rspec-mocks (~> 3.7.0)
101
+ rspec-core (3.7.1)
102
+ rspec-support (~> 3.7.0)
103
+ rspec-expectations (3.7.0)
104
+ diff-lcs (>= 1.2.0, < 2.0)
105
+ rspec-support (~> 3.7.0)
106
+ rspec-mocks (3.7.0)
107
+ diff-lcs (>= 1.2.0, < 2.0)
108
+ rspec-support (~> 3.7.0)
109
+ rspec-support (3.7.1)
110
+ rubocop (0.56.0)
111
+ parallel (~> 1.10)
112
+ parser (>= 2.5)
113
+ powerpack (~> 0.1)
114
+ rainbow (>= 2.2.2, < 4.0)
115
+ ruby-progressbar (~> 1.7)
116
+ unicode-display_width (~> 1.0, >= 1.0.1)
117
+ ruby-progressbar (1.9.0)
118
+ signet (0.8.1)
119
+ addressable (~> 2.3)
120
+ faraday (~> 0.9)
121
+ jwt (>= 1.5, < 3.0)
122
+ multi_json (~> 1.10)
123
+ transproc (1.0.2)
124
+ unicode-display_width (1.4.0)
125
+
126
+ PLATFORMS
127
+ ruby
128
+
129
+ DEPENDENCIES
130
+ bundler (~> 1.16)
131
+ hanami-events!
132
+ hanami-events-cloud_pubsub!
133
+ pry
134
+ rake (~> 12.3)
135
+ rspec (~> 3.0)
136
+ rubocop
137
+
138
+ BUNDLED WITH
139
+ 1.16.1
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Ian Ker-Seymer
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,99 @@
1
+ # Hanami::Events::CloudPubsub
2
+ [![Build Status](https://travis-ci.org/adHawk/hanami-events-cloud_pubsub.svg?branch=master)](https://travis-ci.org/adHawk/hanami-events-cloud_pubsub) [![Maintainability](https://api.codeclimate.com/v1/badges/7341f70d4ed1d0bd7a5d/maintainability)](https://codeclimate.com/github/adHawk/hanami-events-cloud_pubsub/maintainability)
3
+
4
+ ## Installation
5
+
6
+ Add this line to your application's Gemfile:
7
+
8
+ ```ruby
9
+ gem 'hanami-events-cloud_pubsub'
10
+ ```
11
+
12
+ And then execute:
13
+
14
+ $ bundle
15
+
16
+ ## Usage
17
+
18
+ This gem is compatible with the
19
+ [hanami-events](https://github.com/hanami/events) gem, with a couple caveats:
20
+
21
+ 1. All subscribers must specify an `id:` attribute. When you subscribe, you
22
+ should pass this:
23
+
24
+ ```ruby
25
+ $events.subscribe('user.deleted', id: 'my-subscriber-id') do |payload|
26
+ puts "Deleted user: #{payload}"
27
+ end
28
+ ```
29
+
30
+ 2. If you want mixin behavior, follow this example until [this patch is
31
+ merged](https://github.com/hanami/events/pull/76)
32
+
33
+ ```ruby
34
+ class WelcomeMailer
35
+ include Hanami::Events::CloudPubsub::Mixin
36
+
37
+ subscribe_to $events, 'user.created', id: 'welcome-mailer'
38
+
39
+ def call(payload)
40
+ payload
41
+ end
42
+ end
43
+ ```
44
+
45
+ 3. Responding to events is done in a different process via the CLI.
46
+
47
+ First, create a config file:
48
+
49
+ ```ruby
50
+ # config/cloudpubsub.rb
51
+
52
+ require 'config/environment'
53
+
54
+ Hanami.boot
55
+ ```
56
+
57
+ Then, run the worker process:
58
+
59
+ ```sh
60
+ bundle exec exe/cloudpubsub run --config config/cloudpubsub.rb
61
+ ```
62
+
63
+ If you would like to use an emulator process for testing:
64
+
65
+ ```sh
66
+ docker run -p 8085:8085 adhawk/google-pubsub-emulator # start the emulator
67
+ bundle exec exe/cloudpubsub run --emulator --config config/cloudpubsub.rb # use emulator for the worker
68
+ ```
69
+
70
+ ## Development
71
+
72
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
73
+ `rake spec` to run the tests. You can also run `bin/console` for an interactive
74
+ prompt that will allow you to experiment.
75
+
76
+ To install this gem onto your local machine, run `bundle exec rake install`. To
77
+ release a new version, update the version number in `version.rb`, and then run
78
+ `bundle exec rake release`, which will create a git tag for the version, push
79
+ git commits and tags, and push the `.gem` file to
80
+ [rubygems.org](https://rubygems.org).
81
+
82
+ ## Contributing
83
+
84
+ Bug reports and pull requests are welcome on GitHub at
85
+ https://github.com/ianks/hanami-events-cloud_pubsub. This project is intended
86
+ to be a safe, welcoming space for collaboration, and contributors are expected
87
+ to adhere to the [Contributor Covenant](http://contributor-covenant.org) code
88
+ of conduct.
89
+
90
+ ## License
91
+
92
+ The gem is available as open source under the terms of the [MIT
93
+ License](https://opensource.org/licenses/MIT).
94
+
95
+ ## Code of Conduct
96
+
97
+ Everyone interacting in the Hanami::Events::CloudPubsub project’s codebases,
98
+ issue trackers, chat rooms and mailing lists is expected to follow the [code of
99
+ conduct](https://github.com/ianks/hanami-events-cloud_pubsub/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'hanami/events/cloud_pubsub'
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 'irb'
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ echo "Please make sure docker and docker-compose are installed"
9
+
10
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,8 @@
1
+ ---
2
+ version: '3.6'
3
+
4
+ services:
5
+ pubsub:
6
+ image: adhawk/google-pubsub-emulator
7
+ ports:
8
+ - 8085:8085
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ ENV['PUBSUB_EMULATOR_HOST'] ||= 'localhost:8085'
4
+
5
+ require 'bundler/setup'
6
+
7
+ require 'google/cloud/pubsub'
8
+ require 'hanami/events'
9
+ require 'hanami/events/cloud_pubsub'
10
+
11
+ Hanami::Events::CloudPubsub.setup
12
+
13
+ pubsub = Google::Cloud::Pubsub.new project_id: 'emulator'
14
+
15
+ events = Hanami::Events.initialize(:cloud_pubsub, pubsub: pubsub, logger: Logger.new(STDOUT))
16
+
17
+ 3.times do
18
+ events.broadcast('user.deleted', user_id: 1)
19
+ end
20
+
21
+ events.adapter.flush_messages
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ # To run this server:
4
+ # bundle exec exe/cloudpubsub run --emulator --config examples/server.rb
5
+
6
+ $events.subscribe('user.deleted', id: 'testing-1') do |payload|
7
+ puts "Deleted user: #{payload}"
8
+ end
9
+
10
+ $events.subscribe('user.deleted', id: 'testing-2') do |payload|
11
+ puts "Deleted2 user: #{payload}"
12
+ end
data/exe/cloudpubsub ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'hanami/cli'
6
+ require 'hanami/events/cloud_pubsub/cli'
7
+
8
+ Hanami::CLI.new(Hanami::Events::CloudPubsub::CLI::Commands).call
@@ -0,0 +1,34 @@
1
+
2
+ # frozen_string_literal: true
3
+
4
+ lib = File.expand_path('lib', __dir__)
5
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
6
+ require 'hanami/events/cloud_pubsub/version'
7
+
8
+ Gem::Specification.new do |spec|
9
+ spec.name = 'hanami-events-cloud_pubsub'
10
+ spec.version = Hanami::Events::CloudPubsub::VERSION
11
+ spec.authors = ['Ian Ker-Seymer']
12
+ spec.email = ['i.kerseymer@gmail.com']
13
+
14
+ spec.summary = 'Google Cloud Pub/Sub adapter for the hanami-events gem'
15
+ spec.description = 'Makes it easy to use Cloud Pub/Sub with Hanami'
16
+ spec.homepage = 'https://github.com/adHawk/hanami-events-cloud_pubsub'
17
+ spec.license = 'MIT'
18
+
19
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
20
+ f.match(%r{^(test|spec|features)/})
21
+ end
22
+ spec.bindir = 'exe'
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ['lib']
25
+
26
+ spec.add_dependency 'google-cloud-pubsub', '~> 0.30.2'
27
+
28
+ spec.add_runtime_dependency 'hanami-cli'
29
+ spec.add_runtime_dependency 'hanami-events'
30
+
31
+ spec.add_development_dependency 'bundler', '~> 1.16'
32
+ spec.add_development_dependency 'rake', '~> 12.3'
33
+ spec.add_development_dependency 'rspec', '~> 3.0'
34
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'hanami/events/cloud_pubsub/listener'
4
+
5
+ module Hanami
6
+ module Events
7
+ class Adapter
8
+ # Adapter for Google Cloud Pub/Sub
9
+ #
10
+ # @api private
11
+ class CloudPubsub
12
+ attr_reader :subscribers, :listeners, :topic_registry
13
+
14
+ def initialize(params)
15
+ @pubsub = params[:pubsub]
16
+ @logger = params[:logger] || Logger.new(STDOUT)
17
+ @listen = params[:listen] || false
18
+ @subscribers = Concurrent::Array.new
19
+ @listeners = Concurrent::Array.new
20
+ @serializer_type = params.fetch(:serializer, :json).to_sym
21
+ @topic_registry = {}
22
+ @mutex = Mutex.new
23
+ end
24
+
25
+ # Brodcasts event to all subscribes
26
+ #
27
+ # @param event [Symbol, String] the event name
28
+ # @param payload [Hash] the event data
29
+ def broadcast(event_name, payload)
30
+ topic = topic_for event_name
31
+ payload = serializer.serialize(payload)
32
+ attributes = { id: SecureRandom.uuid, event_name: event_name }
33
+
34
+ topic.publish_async(payload, attributes) do |result|
35
+ logger.info "Published event #{result.inspect}"
36
+ end
37
+ end
38
+
39
+ # Subscribes block for selected event
40
+ #
41
+ # @param event_name [Symbol, String] the event name
42
+ # @param block [Block] to execute when event is broadcasted
43
+ def subscribe(event_name, id:, &block)
44
+ return false unless listening?
45
+
46
+ logger.debug("Subscribed listener \"#{id}\" for event \"#{event_name}\"")
47
+
48
+ @subscribers << Subscriber.new(event_name, block, logger)
49
+ topic = topic_for event_name
50
+
51
+ register_listener(event_name, topic, id)
52
+ end
53
+
54
+ def flush_messages
55
+ pubs = topic_registry.values.map(&:async_publisher).compact
56
+ pubs.each(&:stop).map(&:wait!)
57
+ end
58
+
59
+ def listen(should_listen = true)
60
+ @listen = should_listen
61
+ self
62
+ end
63
+
64
+ def listening?
65
+ !!@listen # rubocop:disable Style/DoubleNegation
66
+ end
67
+
68
+ private
69
+
70
+ attr_reader :logger
71
+
72
+ def register_listener(event_name, topic, subscriber_id)
73
+ listener = ::Hanami::Events::CloudPubsub::Listener.new(
74
+ subscriber_id: subscriber_id,
75
+ event_name: event_name,
76
+ handler: method(:call_subscribers),
77
+ logger: logger,
78
+ topic: topic
79
+ )
80
+
81
+ @listeners << listener
82
+ listener.register
83
+ end
84
+
85
+ def call_subscribers(message)
86
+ data = message.data
87
+ payload = serializer.deserialize(data)
88
+ event_name = message.attributes['event_name']
89
+ payload['id'] = message.attributes['id']
90
+
91
+ @subscribers.each do |subscriber|
92
+ subscriber.call(event_name, payload)
93
+ end
94
+ end
95
+
96
+ def serializer
97
+ @serializer ||= Hanami::Events::Serializer[@serializer_type].new
98
+ end
99
+
100
+ def topic_for(event_name)
101
+ @topic_registry[event_name.to_s] ||=
102
+ begin
103
+ @pubsub.find_topic(event_name) || @pubsub.create_topic(event_name)
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'hanami/events'
4
+ require 'hanami/events/cloud_pubsub/version'
5
+ require 'hanami/events/cloud_pubsub/runner'
6
+ require 'hanami/events/cloud_pubsub/mixin'
7
+ require 'google/cloud/pubsub'
8
+
9
+ module Hanami
10
+ module Events
11
+ # CloudPubsub
12
+ module CloudPubsub
13
+ def self.setup
14
+ Hanami::Events::Adapter.register(:cloud_pubsub) do
15
+ require_relative 'adapter/cloud_pubsub'
16
+
17
+ ::Hanami::Events::Adapter::CloudPubsub
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'hanami/cli'
4
+ require 'hanami/events/cloud_pubsub'
5
+
6
+ module Hanami
7
+ module Events
8
+ module CloudPubsub
9
+ module CLI
10
+ # CLI Commands
11
+ module Commands
12
+ extend Hanami::CLI::Registry
13
+
14
+ # Command to run the worker
15
+ class Run < Hanami::CLI::Command
16
+ option :emulator,
17
+ type: :boolean,
18
+ default: false,
19
+ desc: 'Whether to use the Cloud Pub/Sub emulator'
20
+
21
+ option :config,
22
+ type: :string,
23
+ default: './config/cloudpubsub.rb',
24
+ desc: 'Config file which is loaded before starting the runner'
25
+
26
+ def call(opts)
27
+ CloudPubsub.setup
28
+ parse_opts(opts)
29
+ setup_signal_handlers
30
+ build_runner
31
+ load_config
32
+ start_runner
33
+ sleep_forever
34
+ rescue Interrupt
35
+ shutdown
36
+ end
37
+
38
+ private
39
+
40
+ def sleep_forever
41
+ sleep
42
+ end
43
+
44
+ def load_config
45
+ load @config
46
+ end
47
+
48
+ def start_runner
49
+ logger.info "Starting CloudPubsub runner (pid: #{Process.pid})"
50
+ @runner.start
51
+ end
52
+
53
+ def parse_opts(opts)
54
+ @emulator = opts[:emulator]
55
+ logger.info 'Running if emulator mode' if @emulator
56
+ @config = opts[:config]
57
+ logger.debug "Using config file: #{@config}"
58
+ end
59
+
60
+ def build_runner
61
+ pubsub_opts = {}
62
+
63
+ ENV['PUBSUB_EMULATOR_HOST'] ||= 'localhost:8085' if @emulator
64
+ pubsub_opts[:project_id] = 'emulator' if @emulator
65
+
66
+ pubsub = Google::Cloud::Pubsub.new pubsub_opts
67
+ $events = Hanami::Events.initialize(:cloud_pubsub,
68
+ pubsub: pubsub,
69
+ logger: logger,
70
+ listen: true)
71
+ @runner = Runner.new(logger: logger, adapter: $events.adapter)
72
+ end
73
+
74
+ def logger
75
+ if defined?(Hanami.logger)
76
+ Hanami.logger
77
+ else
78
+ Logger.new(STDOUT).tap { |logger| logger.level = Logger::INFO }
79
+ end
80
+ end
81
+
82
+ def setup_signal_handlers
83
+ Signal.trap('TSTP') do
84
+ Thread.new { @runner.pause }
85
+ end
86
+
87
+ Signal.trap('CONT') do
88
+ Thread.new { @runner.start }
89
+ end
90
+
91
+ Signal.trap('TTIN') do
92
+ Thread.new { @runner.print_debug_info }
93
+ end
94
+ end
95
+
96
+ def shutdown
97
+ STDOUT.flush
98
+ @runner.gracefully_shutdown
99
+ end
100
+ end
101
+
102
+ Commands.register 'run', Run
103
+ end
104
+ end
105
+ end
106
+ end
107
+ end
File without changes
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hanami
4
+ module Events
5
+ module CloudPubsub
6
+ # @api private
7
+ class Listener
8
+ class NoSubscriberError < StandardError; end
9
+
10
+ attr_reader :topic,
11
+ :subscriber,
12
+ :subscriber_id,
13
+ :logger,
14
+ :handler,
15
+ :event_name
16
+
17
+ def initialize(topic:, logger:, handler:, event_name:, subscriber_id:)
18
+ @topic = topic
19
+ @logger = logger
20
+ @handler = handler
21
+ @event_name = event_name
22
+ @subscriber_id = subscriber_id
23
+ end
24
+
25
+ def register
26
+ subscription = subscription_for(subscriber_id)
27
+
28
+ listener = subscription.listen do |message|
29
+ handle_message(message)
30
+ end
31
+
32
+ @subscriber = listener
33
+
34
+ self
35
+ end
36
+
37
+ def start
38
+ ensure_subscriber!
39
+ @subscriber.start
40
+ end
41
+
42
+ def shutdown
43
+ subscriber.stop.wait!
44
+ self
45
+ end
46
+
47
+ def stop
48
+ subscriber.stop
49
+ self
50
+ end
51
+
52
+ def wait
53
+ subscriber.wait!
54
+ self
55
+ end
56
+
57
+ def format
58
+ subscriber.to_s
59
+ end
60
+
61
+ private
62
+
63
+ def handle_message(msg)
64
+ run_handler(msg)
65
+ end
66
+
67
+ #:reek:TooManyStatements
68
+ #:reek:DuplicateMethodCall
69
+ # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
70
+ def run_handler(message)
71
+ id = message.message_id
72
+ succeeded = false
73
+ failed = false
74
+
75
+ handler.call(message)
76
+ succeeded = true
77
+ rescue Exception => err # rubocop:disable all
78
+ failed = true
79
+ logger.error "Message(#{id}) failed with exception #{err.inspect}"
80
+ raise err
81
+ ensure
82
+ id = message.message_id
83
+ if succeeded || failed
84
+ message.acknowledge!
85
+ logger.debug "Message(#{id}) was acknowledged"
86
+ else
87
+ message.reject!
88
+ logger.warn "Message(#{id}) was terminated from outside, rescheduling"
89
+ end
90
+ end
91
+ # rubocop:enable Metrics/MethodLength, Metrics/AbcSize
92
+
93
+ def subscription_for(name)
94
+ topic.find_subscription(name) || topic.create_subscription(name)
95
+ end
96
+
97
+ def ensure_subscriber!
98
+ raise NoSubscriberError, 'No subsriber has been registererd' unless @subscriber
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hanami
4
+ module Events
5
+ module CloudPubsub
6
+ # Mixin that extends class by `subscribe_to` method.
7
+ #
8
+ # @example
9
+ # $events = Hanami::Events.initialize(:memory)
10
+ #
11
+ # class WelcomeMailer
12
+ # include Hanami::Events::Mixin
13
+ #
14
+ # subscribe_to $events, 'user.created', id: 'welcome-mailer'
15
+ #
16
+ # def call(payload)
17
+ # # send email
18
+ # end
19
+ # end
20
+ #
21
+ # @since 0.1.0
22
+ #
23
+ # @api public
24
+ module Mixin
25
+ def self.included(klass)
26
+ klass.extend(ClassMethods)
27
+ end
28
+
29
+ # Class interfaces
30
+ module ClassMethods
31
+ def subscribe_to(event_bus, event_name, id:)
32
+ klass = self
33
+ event_bus.subscribe(event_name, id: id) { |payload| klass.new.call(payload) }
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hanami
4
+ module Events
5
+ module CloudPubsub
6
+ # Responsible for starting and managing the work processes
7
+ class Runner
8
+ attr_reader :events, :logger, :adapter
9
+
10
+ def initialize(adapter:, logger:, sleep_time: 2)
11
+ @logger = logger
12
+ @adapter = adapter
13
+ @sleep_time = sleep_time
14
+ end
15
+
16
+ # Called to start the runner (subscribes to topics/etc)
17
+ def start(_options = {})
18
+ logger.info 'Starting CloudPubsub listeners'
19
+ adapter.listeners.map(&:start)
20
+ end
21
+
22
+ # Will be called on TSTP
23
+ #
24
+ # Stop processing new events (unsubscribe from topics, etc)
25
+ #
26
+ # For example, if you needed to restart a Redis server you could first
27
+ # call pause to allow for a safe restart of the runner.
28
+ def pause
29
+ logger.info 'Pausing CloudPubsub runner'
30
+ adapter.listeners.each(&:stop)
31
+ end
32
+
33
+ # Will be called on SIGINT, TERM
34
+ #
35
+ # Responsible for gracefully shutting down the runner. This may involve
36
+ # waiting for messages to finish processing, etc. If this method succesfully
37
+ # runs, there should be no potential for undefined behavior.
38
+ def gracefully_shutdown
39
+ pause
40
+ logger.info "Gracefully shutting down CloudPubsub runner: #{self}"
41
+ sleep_for_a_bit
42
+ adapter.flush_messages
43
+ adapter.listeners.each(&:wait)
44
+ end
45
+
46
+ # (optional) Kill all subscribers
47
+ #
48
+ # If a gracefully_shutdown times out or fails, this method will be called.
49
+ # It is a last ditch effort to salvage resources and is used as a "damage
50
+ # control" mechanism.
51
+ #
52
+ # Should we provide a mechanism to report what caused a forced shutdown?
53
+ def force_shutdown!; end
54
+
55
+ # Is the runner ready to start processing events?
56
+ #
57
+ # Starting the runner may be asyncronous (spawning threads, etc)
58
+ # Instead of making `start` blocking, expose a way to probe for readiness
59
+ # After this check occurs, `healthy?` will be honored.
60
+ #
61
+ # This pattern is similar to Kubernete's healthiness and readniess probes
62
+ # and is much more useful than only having a `healthy?` check
63
+ #
64
+ # See: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/
65
+ def ready?
66
+ adapter.listeners.all?(&:started?)
67
+ end
68
+
69
+ # Is the runner healthy enough to keep going?
70
+ #
71
+ # Indicated whether or not the runner is healthy, useful for determing
72
+ # whether or not the process should be restarted
73
+ def healthy?
74
+ ready?
75
+ end
76
+
77
+ # Print out some useful debugging information
78
+ #
79
+ # Called on TTIN to inspect the state of the runner in a terminal friendly
80
+ # output. This provides a simple debugging if the runner gets stuck for
81
+ # some reason.
82
+ #
83
+ # See: https://github.com/mperham/sidekiq/blob/e447dae961ebc894f12848d9f33446a07ffc67dc/bin/sidekiqload#L74
84
+ def print_debug_info(stream = STDOUT)
85
+ stream.puts '=== Subscribers ==='
86
+ adapter.listeners.each do |listener|
87
+ stream.puts listener.format
88
+ end
89
+ end
90
+
91
+ def sleep_for_a_bit
92
+ sleep @sleep_time
93
+ end
94
+ end
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hanami
4
+ module Events
5
+ module CloudPubsub
6
+ VERSION = '0.1.0'
7
+ end
8
+ end
9
+ end
metadata ADDED
@@ -0,0 +1,156 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hanami-events-cloud_pubsub
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ian Ker-Seymer
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-06-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: google-cloud-pubsub
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.30.2
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.30.2
27
+ - !ruby/object:Gem::Dependency
28
+ name: hanami-cli
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
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: hanami-events
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.16'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.16'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '12.3'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '12.3'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.0'
97
+ description: Makes it easy to use Cloud Pub/Sub with Hanami
98
+ email:
99
+ - i.kerseymer@gmail.com
100
+ executables:
101
+ - cloudpubsub
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".gitignore"
106
+ - ".rspec"
107
+ - ".rubocop.yml"
108
+ - ".rubocop_todo.yml"
109
+ - ".travis.yml"
110
+ - CODE_OF_CONDUCT.md
111
+ - Gemfile
112
+ - Gemfile.lock
113
+ - LICENSE.txt
114
+ - README.md
115
+ - Rakefile
116
+ - bin/console
117
+ - bin/setup
118
+ - docker-compose.yml
119
+ - examples/client.rb
120
+ - examples/server.rb
121
+ - exe/cloudpubsub
122
+ - hanami-events-cloud_pubsub.gemspec
123
+ - lib/hanami/events/adapter/cloud_pubsub.rb
124
+ - lib/hanami/events/cloud_pubsub.rb
125
+ - lib/hanami/events/cloud_pubsub/cli.rb
126
+ - lib/hanami/events/cloud_pubsub/handler.rb
127
+ - lib/hanami/events/cloud_pubsub/listener.rb
128
+ - lib/hanami/events/cloud_pubsub/mixin.rb
129
+ - lib/hanami/events/cloud_pubsub/runner.rb
130
+ - lib/hanami/events/cloud_pubsub/version.rb
131
+ - log/.keep
132
+ homepage: https://github.com/adHawk/hanami-events-cloud_pubsub
133
+ licenses:
134
+ - MIT
135
+ metadata: {}
136
+ post_install_message:
137
+ rdoc_options: []
138
+ require_paths:
139
+ - lib
140
+ required_ruby_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ required_rubygems_version: !ruby/object:Gem::Requirement
146
+ requirements:
147
+ - - ">="
148
+ - !ruby/object:Gem::Version
149
+ version: '0'
150
+ requirements: []
151
+ rubyforge_project:
152
+ rubygems_version: 2.7.7
153
+ signing_key:
154
+ specification_version: 4
155
+ summary: Google Cloud Pub/Sub adapter for the hanami-events gem
156
+ test_files: []