pub_sub_model_sync 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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b0738657d975fdfaa12d2f28bfa942674faacd737e9be11435718204d3d90f3b
4
+ data.tar.gz: 234400d0857ad54f4498d531db75557e641b08dc3d237c37122cad07ecfa4d92
5
+ SHA512:
6
+ metadata.gz: 92a83128b548aa1b0b495ad0c67617d30c62b4566e154609009b089d136d439e40b8a0d0c7fe8b48a13aa940f232129eca5c3c20bec4f3d3288411a4757d6ca3
7
+ data.tar.gz: 319cc08d44633713db44eae121fda9187536f4b34abdfa8a030fa519f6e48b9aa2bf9c43542b02c133eb095e95a42b03e9d8fd5b62100ee063264fecbb13c5b8
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,24 @@
1
+ # This is the configuration used to check the rubocop source code.
2
+
3
+ AllCops:
4
+ Exclude:
5
+ - 'spec/spec_helper.rb'
6
+ - 'Gemfile'
7
+ - 'Rakefile'
8
+ - 'bin/*'
9
+ TargetRubyVersion: 2.3
10
+
11
+ Metrics/BlockLength:
12
+ Exclude:
13
+ - 'spec/**/*.rb'
14
+
15
+
16
+ Style/SymbolArray:
17
+ Exclude:
18
+ - 'Gemfile'
19
+
20
+ Style/Documentation:
21
+ Enabled: false
22
+
23
+ Style/RescueStandardError:
24
+ EnforcedStyle: implicit
@@ -0,0 +1,13 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.3.1
7
+ before_install: gem install bundler -v 2.0.2
8
+
9
+ script:
10
+ - bundle install
11
+ # disabled cause of: An error occurred while Style/PercentLiteralDelimiters cop
12
+ # - bundle exec rubocop
13
+ - bundle exec rspec
@@ -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 owenperedo@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,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ gem 'rubocop', '~> 0.80.1', require: false
4
+
5
+ # Specify your gem's dependencies in pub_sub_model_sync.gemspec
6
+ gemspec
@@ -0,0 +1,216 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ pub_sub_model_sync (0.1.0)
5
+ activesupport
6
+ google-cloud-pubsub
7
+ rails
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ actioncable (5.2.4.1)
13
+ actionpack (= 5.2.4.1)
14
+ nio4r (~> 2.0)
15
+ websocket-driver (>= 0.6.1)
16
+ actionmailer (5.2.4.1)
17
+ actionpack (= 5.2.4.1)
18
+ actionview (= 5.2.4.1)
19
+ activejob (= 5.2.4.1)
20
+ mail (~> 2.5, >= 2.5.4)
21
+ rails-dom-testing (~> 2.0)
22
+ actionpack (5.2.4.1)
23
+ actionview (= 5.2.4.1)
24
+ activesupport (= 5.2.4.1)
25
+ rack (~> 2.0, >= 2.0.8)
26
+ rack-test (>= 0.6.3)
27
+ rails-dom-testing (~> 2.0)
28
+ rails-html-sanitizer (~> 1.0, >= 1.0.2)
29
+ actionview (5.2.4.1)
30
+ activesupport (= 5.2.4.1)
31
+ builder (~> 3.1)
32
+ erubi (~> 1.4)
33
+ rails-dom-testing (~> 2.0)
34
+ rails-html-sanitizer (~> 1.0, >= 1.0.3)
35
+ activejob (5.2.4.1)
36
+ activesupport (= 5.2.4.1)
37
+ globalid (>= 0.3.6)
38
+ activemodel (5.2.4.1)
39
+ activesupport (= 5.2.4.1)
40
+ activerecord (5.2.4.1)
41
+ activemodel (= 5.2.4.1)
42
+ activesupport (= 5.2.4.1)
43
+ arel (>= 9.0)
44
+ activestorage (5.2.4.1)
45
+ actionpack (= 5.2.4.1)
46
+ activerecord (= 5.2.4.1)
47
+ marcel (~> 0.3.1)
48
+ activesupport (5.2.4.1)
49
+ concurrent-ruby (~> 1.0, >= 1.0.2)
50
+ i18n (>= 0.7, < 2)
51
+ minitest (~> 5.1)
52
+ tzinfo (~> 1.1)
53
+ addressable (2.7.0)
54
+ public_suffix (>= 2.0.2, < 5.0)
55
+ arel (9.0.0)
56
+ ast (2.4.0)
57
+ builder (3.2.4)
58
+ concurrent-ruby (1.1.6)
59
+ crass (1.0.6)
60
+ diff-lcs (1.3)
61
+ erubi (1.9.0)
62
+ faraday (0.17.3)
63
+ multipart-post (>= 1.2, < 3)
64
+ globalid (0.4.2)
65
+ activesupport (>= 4.2.0)
66
+ google-cloud-core (1.3.2)
67
+ google-cloud-env (~> 1.0)
68
+ google-cloud-env (1.2.1)
69
+ faraday (~> 0.11)
70
+ google-cloud-pubsub (1.0.2)
71
+ concurrent-ruby (~> 1.1)
72
+ google-cloud-core (~> 1.2)
73
+ google-gax (~> 1.7)
74
+ googleapis-common-protos (>= 1.3.9, < 2.0)
75
+ grpc-google-iam-v1 (~> 0.6.9)
76
+ google-gax (1.7.1)
77
+ google-protobuf (~> 3.2)
78
+ googleapis-common-protos (>= 1.3.5, < 2.0)
79
+ googleauth (>= 0.6.2, < 0.10.0)
80
+ grpc (>= 1.7.2, < 2.0)
81
+ rly (~> 0.2.3)
82
+ google-protobuf (3.11.4)
83
+ googleapis-common-protos (1.3.9)
84
+ google-protobuf (~> 3.0)
85
+ googleapis-common-protos-types (~> 1.0)
86
+ grpc (~> 1.0)
87
+ googleapis-common-protos-types (1.0.4)
88
+ google-protobuf (~> 3.0)
89
+ googleauth (0.9.0)
90
+ faraday (~> 0.12)
91
+ jwt (>= 1.4, < 3.0)
92
+ memoist (~> 0.16)
93
+ multi_json (~> 1.11)
94
+ os (>= 0.9, < 2.0)
95
+ signet (~> 0.7)
96
+ grpc (1.27.0)
97
+ google-protobuf (~> 3.11)
98
+ googleapis-common-protos-types (~> 1.0)
99
+ grpc-google-iam-v1 (0.6.9)
100
+ googleapis-common-protos (>= 1.3.1, < 2.0)
101
+ grpc (~> 1.0)
102
+ i18n (1.8.2)
103
+ concurrent-ruby (~> 1.0)
104
+ jaro_winkler (1.5.4)
105
+ jwt (2.2.1)
106
+ loofah (2.4.0)
107
+ crass (~> 1.0.2)
108
+ nokogiri (>= 1.5.9)
109
+ mail (2.7.1)
110
+ mini_mime (>= 0.1.1)
111
+ marcel (0.3.3)
112
+ mimemagic (~> 0.3.2)
113
+ memoist (0.16.2)
114
+ method_source (0.9.2)
115
+ mimemagic (0.3.4)
116
+ mini_mime (1.0.2)
117
+ mini_portile2 (2.4.0)
118
+ minitest (5.14.0)
119
+ multi_json (1.14.1)
120
+ multipart-post (2.1.1)
121
+ nio4r (2.5.2)
122
+ nokogiri (1.10.9)
123
+ mini_portile2 (~> 2.4.0)
124
+ os (1.0.1)
125
+ parallel (1.19.1)
126
+ parser (2.7.0.4)
127
+ ast (~> 2.4.0)
128
+ public_suffix (4.0.3)
129
+ rack (2.2.2)
130
+ rack-test (1.1.0)
131
+ rack (>= 1.0, < 3)
132
+ rails (5.2.4.1)
133
+ actioncable (= 5.2.4.1)
134
+ actionmailer (= 5.2.4.1)
135
+ actionpack (= 5.2.4.1)
136
+ actionview (= 5.2.4.1)
137
+ activejob (= 5.2.4.1)
138
+ activemodel (= 5.2.4.1)
139
+ activerecord (= 5.2.4.1)
140
+ activestorage (= 5.2.4.1)
141
+ activesupport (= 5.2.4.1)
142
+ bundler (>= 1.3.0)
143
+ railties (= 5.2.4.1)
144
+ sprockets-rails (>= 2.0.0)
145
+ rails-dom-testing (2.0.3)
146
+ activesupport (>= 4.2.0)
147
+ nokogiri (>= 1.6)
148
+ rails-html-sanitizer (1.3.0)
149
+ loofah (~> 2.3)
150
+ railties (5.2.4.1)
151
+ actionpack (= 5.2.4.1)
152
+ activesupport (= 5.2.4.1)
153
+ method_source
154
+ rake (>= 0.8.7)
155
+ thor (>= 0.19.0, < 2.0)
156
+ rainbow (3.0.0)
157
+ rake (13.0.1)
158
+ rexml (3.2.4)
159
+ rly (0.2.3)
160
+ rspec (3.9.0)
161
+ rspec-core (~> 3.9.0)
162
+ rspec-expectations (~> 3.9.0)
163
+ rspec-mocks (~> 3.9.0)
164
+ rspec-core (3.9.1)
165
+ rspec-support (~> 3.9.1)
166
+ rspec-expectations (3.9.0)
167
+ diff-lcs (>= 1.2.0, < 2.0)
168
+ rspec-support (~> 3.9.0)
169
+ rspec-mocks (3.9.1)
170
+ diff-lcs (>= 1.2.0, < 2.0)
171
+ rspec-support (~> 3.9.0)
172
+ rspec-support (3.9.2)
173
+ rubocop (0.80.1)
174
+ jaro_winkler (~> 1.5.1)
175
+ parallel (~> 1.10)
176
+ parser (>= 2.7.0.1)
177
+ rainbow (>= 2.2.2, < 4.0)
178
+ rexml
179
+ ruby-progressbar (~> 1.7)
180
+ unicode-display_width (>= 1.4.0, < 1.7)
181
+ ruby-progressbar (1.10.1)
182
+ signet (0.11.0)
183
+ addressable (~> 2.3)
184
+ faraday (~> 0.9)
185
+ jwt (>= 1.5, < 3.0)
186
+ multi_json (~> 1.10)
187
+ sprockets (3.7.2)
188
+ concurrent-ruby (~> 1.0)
189
+ rack (> 1, < 3)
190
+ sprockets-rails (3.2.1)
191
+ actionpack (>= 4.0)
192
+ activesupport (>= 4.0)
193
+ sprockets (>= 3.0.0)
194
+ sqlite3 (1.4.2)
195
+ thor (1.0.1)
196
+ thread_safe (0.3.6)
197
+ tzinfo (1.2.6)
198
+ thread_safe (~> 0.1)
199
+ unicode-display_width (1.6.1)
200
+ websocket-driver (0.7.1)
201
+ websocket-extensions (>= 0.1.0)
202
+ websocket-extensions (0.1.4)
203
+
204
+ PLATFORMS
205
+ ruby
206
+
207
+ DEPENDENCIES
208
+ bundler
209
+ pub_sub_model_sync!
210
+ rake
211
+ rspec
212
+ rubocop (~> 0.80.1)
213
+ sqlite3
214
+
215
+ BUNDLED WITH
216
+ 2.0.2
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Owen
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.
@@ -0,0 +1,160 @@
1
+ # PubSubModelSync
2
+ Permit to sync models between rails apps through google (Proximately RabbitMQ) pub/sub service.
3
+ Note: This gem is based on [MultipleMan](https://github.com/influitive/multiple_man) which for now looks unmaintained.
4
+
5
+ # Features
6
+ - Sync CRUD operation between Rails apps. So, all changes made on App1, will be reflected on App2.
7
+ Example: If User is created on App1, this user will be created on App2 too with the accepted attributes.
8
+ - Ability to make class level communication
9
+ Example: If User from App1 wants to generate_email, this can be listened on App2 to make corresponding actions
10
+
11
+ ## Installation
12
+ Add this line to your application's Gemfile:
13
+ ```ruby
14
+ gem 'pub_sub_model_sync'
15
+ ```
16
+ And then execute: $ bundle install
17
+
18
+
19
+ ## Usage
20
+
21
+ - Configure pub/sub service (Google pub/sub)
22
+ ```ruby
23
+ # initializers/pub_sub_config.rb
24
+ PubSubModelSync::Config.project = ''
25
+ PubSubModelSync::Config.credentials = ''
26
+ PubSubModelSync::Config.topic_name = ''
27
+ PubSubModelSync::Config.subscription_name = ''
28
+ ```
29
+ See details here:
30
+ https://github.com/googleapis/google-cloud-ruby/tree/master/google-cloud-pubsub
31
+
32
+ - Add publishers/subscribers to your models (See examples below)
33
+
34
+ - Start listening for publishers (Only if the app has subscribers)
35
+ ```ruby
36
+ rake pub_sub_model_sync:start
37
+ ```
38
+
39
+ ## Examples
40
+ ```ruby
41
+ # App 1
42
+ # attributes: name email age
43
+ class User < ActiveRecord::Base
44
+ include PubSubModelSync::PublisherConcern
45
+ ps_msync_publish(%i[name email])
46
+ end
47
+
48
+ # App 2
49
+ class User < ActiveRecord::Base
50
+ include PubSubModelSync::SubscriberConcern
51
+ ps_msync_subscribe(%i[name])
52
+ ps_msync_class_subscribe(:greeting)
53
+
54
+ def self.greeting(data)
55
+ puts 'Class message called'
56
+ end
57
+ end
58
+
59
+ # Samples
60
+ User.create(name: 'test user') # Review your App 2 to see the created user (only name will be saved)
61
+ User.ps_msync_class_publish({ msg: 'Hello' }, action: :greeting) # User.greeting method (Class method) will be called in App2
62
+ ```
63
+
64
+ ## Advanced Example
65
+ ```ruby
66
+ # App 1
67
+ class User < ActiveRecord::Base
68
+ self.table_name = 'publisher_users'
69
+ include PubSubModelSync::PublisherConcern
70
+ ps_msync_publish(%i[name], actions: %i[update], as_klass: 'Client', id: :client_id)
71
+
72
+ def ps_msync_skip_for?(_action)
73
+ false # here logic with action to skip push message
74
+ end
75
+ end
76
+
77
+ # App 2
78
+ class User < ActiveRecord::Base
79
+ self.table_name = 'subscriber_users'
80
+ include PubSubModelSync::SubscriberConcern
81
+ ps_msync_subscribe(%i[name], actions: %i[update], as_klass: 'Client', id: :custom_id)
82
+ ps_msync_class_subscribe(:greeting, as_action: :custom_greeting, as_klass: 'CustomUser')
83
+
84
+ def self.greeting(data)
85
+ puts 'Class message called through custom_greeting'
86
+ end
87
+ end
88
+ ```
89
+
90
+ ## Testing
91
+ - Rspec:
92
+ ```ruby
93
+ # mock google service
94
+ # rails_helper.rb
95
+ require 'pub_sub_model_sync/mock_google_service'
96
+ config.before(:each) do
97
+ pub_sub_mock = PubSubModelSync::MockGoogleService.new
98
+ allow(Google::Cloud::Pubsub).to receive(:new).and_return(pub_sub_mock)
99
+ end
100
+ ```
101
+ - Examples:
102
+ ```ruby
103
+ # Subscriber
104
+ it 'receive model message' do
105
+ action = :create
106
+ data = { name: 'name' }
107
+ user_id = 999
108
+ attrs = PubSubModelSync::Publisher.build_attrs('User', action, user_id)
109
+ publisher = PubSubModelSync::MessageProcessor.new(data, 'User', action, id: user_id)
110
+ publisher.process
111
+ expect(User.where(id: user_id).any?).to be_truth
112
+ end
113
+
114
+ it 'receive class message' do
115
+ action = :greeting
116
+ data = { msg: 'hello' }
117
+ publisher = PubSubModelSync::MessageProcessor.new(data, 'User', action)
118
+ publisher.process
119
+ expect(User).to receive(action)
120
+ end
121
+
122
+ # Publisher
123
+ it 'publish model action' do
124
+ publisher = PubSubModelSync::Publisher
125
+ data = { name: 'hello'}
126
+ action = :create
127
+ User.ps_msync_class_publish(data, action: action)
128
+ user = User.create(name: 'name', email: 'email')
129
+ expect_any_instance_of(publisher).to receive(:publish_model).with(user, :create, anything)
130
+ end
131
+
132
+ it 'publish class message' do
133
+ publisher = PubSubModelSync::Publisher
134
+ data = {msg: 'hello'}
135
+ action = :greeting
136
+ User.ps_msync_class_publish(data, action: action)
137
+ expect_any_instance_of(publisher).to receive(:publish_data).with('User', data, action)
138
+ end
139
+ ```
140
+
141
+ There are two special methods to extract configured crud settings (attrs, id, ...):
142
+
143
+ Subscribers: ```User.ps_msync_subscriber_settings```
144
+
145
+ Publishers: ```User.ps_msync_publisher_settings```
146
+
147
+ Note: Inspect all configured listeners with:
148
+ ``` PubSubModelSync::Config.listeners ```
149
+
150
+ ## Contributing
151
+
152
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/pub_sub_model_sync. 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.
153
+
154
+ ## License
155
+
156
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
157
+
158
+ ## Code of Conduct
159
+
160
+ Everyone interacting in the PubSubModelSync project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/pub_sub_model_sync/blob/master/CODE_OF_CONDUCT.md).
@@ -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 'pub_sub_model_sync'
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,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pub_sub_model_sync/version'
4
+ require 'active_support'
5
+
6
+ require 'pub_sub_model_sync/railtie'
7
+ require 'pub_sub_model_sync/config'
8
+ require 'pub_sub_model_sync/subscriber_concern'
9
+ require 'pub_sub_model_sync/publisher'
10
+ require 'pub_sub_model_sync/publisher_concern'
11
+ require 'pub_sub_model_sync/runner'
12
+ require 'pub_sub_model_sync/connector'
13
+ require 'pub_sub_model_sync/message_processor'
14
+
15
+ module PubSubModelSync
16
+ class Error < StandardError; end
17
+ # Your code goes here...
18
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PubSubModelSync
4
+ class Config
5
+ cattr_accessor :listeners, default: []
6
+ cattr_accessor :project, :credentials, :topic_name, :subscription_name
7
+ cattr_accessor :logger
8
+ def self.log(msg, kind = :info)
9
+ msg = "PS_MSYNC ==> #{msg}"
10
+ logger ? logger.send(kind, msg) : puts(msg)
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'google/cloud/pubsub'
4
+ module PubSubModelSync
5
+ class Connector
6
+ attr_accessor :service, :topic, :subscription, :config, :subscriber
7
+
8
+ def initialize
9
+ @config = PubSubModelSync::Config
10
+ @service = Google::Cloud::Pubsub.new(project: config.project,
11
+ credentials: config.credentials)
12
+ @topic = service.topic(config.topic_name) ||
13
+ service.create_topic(config.topic_name)
14
+ end
15
+
16
+ def listen_messages
17
+ @subscription = subscribe_to_topic
18
+ @subscriber = subscription.listen(&method(:process_message))
19
+ log('Listener starting...')
20
+ subscriber.start
21
+ log('Listener started')
22
+ sleep
23
+ subscriber.stop.wait!
24
+ log('Listener stopped')
25
+ end
26
+
27
+ def stop
28
+ log('Listener stopping...')
29
+ subscriber.stop!
30
+ end
31
+
32
+ private
33
+
34
+ def subscribe_to_topic
35
+ topic.subscription(config.subscription_name) ||
36
+ topic.subscribe(config.subscription_name)
37
+ end
38
+
39
+ def process_message(received_message)
40
+ message = received_message.message
41
+ attrs = message.attributes.symbolize_keys
42
+ return unless attrs[:service_model_sync]
43
+
44
+ data = JSON.parse(message.data).symbolize_keys
45
+ args = [data, attrs[:klass], attrs[:action], attrs]
46
+ PubSubModelSync::MessageProcessor.new(*args).process
47
+ rescue => e
48
+ log("Error processing message: #{[received_message, e.message]}")
49
+ ensure
50
+ received_message.acknowledge!
51
+ end
52
+
53
+ def log(msg)
54
+ config.log(msg)
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PubSubModelSync
4
+ class MessageProcessor
5
+ attr_accessor :data, :attrs, :settings
6
+
7
+ # @param data (Hash): any hash value to deliver
8
+ # @param settings (optional): { id: id_val }
9
+ def initialize(data, klass, action, settings = {})
10
+ @data = data
11
+ @settings = settings
12
+ @attrs = settings.merge(klass: klass, action: action)
13
+ end
14
+
15
+ def process
16
+ log 'processing message'
17
+ listeners = filter_listeners
18
+ eval_message(listeners) if listeners.any?
19
+ log 'processed message'
20
+ end
21
+
22
+ private
23
+
24
+ def eval_message(listeners)
25
+ listeners.each do |listener|
26
+ if listener[:direct_mode]
27
+ call_class_listener(listener)
28
+ else
29
+ call_listener(listener)
30
+ end
31
+ end
32
+ end
33
+
34
+ def call_class_listener(listener)
35
+ model_class = listener[:klass].constantize
36
+ model_class.send(listener[:action], data)
37
+ rescue => e
38
+ log("Error listener (#{listener}): #{e.message}", :error)
39
+ end
40
+
41
+ # support for: create, update, destroy
42
+ def call_listener(listener)
43
+ listener_add_crud_settings(listener)
44
+ model = find_model(listener)
45
+ if attrs[:action].to_sym == :destroy
46
+ model.destroy!
47
+ else
48
+ populate_model(model, listener)
49
+ model.save!
50
+ end
51
+ rescue => e
52
+ log("Error listener (#{listener}): #{e.message}", :error)
53
+ end
54
+
55
+ def find_model(listener)
56
+ model_class = listener[:klass].constantize
57
+ identifier = listener[:settings][:id] || :id
58
+ model_class.where(identifier => attrs[:id]).first ||
59
+ model_class.new(identifier => attrs[:id])
60
+ end
61
+
62
+ def populate_model(model, listener)
63
+ values = data.slice(*listener[:settings][:attrs])
64
+ values.each do |attr, value|
65
+ model.send("#{attr}=", value)
66
+ end
67
+ end
68
+
69
+ def filter_listeners
70
+ listeners = PubSubModelSync::Config.listeners
71
+ listeners.select do |listener|
72
+ listener[:as_klass].to_s == attrs[:klass].to_s &&
73
+ listener[:as_action].to_s == attrs[:action].to_s
74
+ end
75
+ end
76
+
77
+ def listener_add_crud_settings(listener)
78
+ model_class = listener[:klass].constantize
79
+ listener[:settings] = model_class.ps_msync_subscriber_settings
80
+ end
81
+
82
+ def log(message, kind = :info)
83
+ PubSubModelSync::Config.log "#{message} ==> #{[data, attrs]}", kind
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PubSubModelSync
4
+ class MockGoogleService
5
+ class MockStop
6
+ def wait!
7
+ true
8
+ end
9
+ end
10
+ class MockSubscriber
11
+ def start
12
+ true
13
+ end
14
+
15
+ def stop
16
+ @stop ||= MockStop.new
17
+ end
18
+ end
19
+ class MockSubscription
20
+ def listen(*_args)
21
+ @listen ||= MockSubscriber.new
22
+ end
23
+ end
24
+ class MockTopic
25
+ def subscription(*_args)
26
+ @subscription ||= MockSubscription.new
27
+ end
28
+ alias subscribe subscription
29
+
30
+ def publish(*_args)
31
+ true
32
+ end
33
+ end
34
+ def topic(*_args)
35
+ @topic ||= MockTopic.new
36
+ end
37
+ alias create_topic topic
38
+ end
39
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PubSubModelSync
4
+ class Publisher
5
+ attr_accessor :connector
6
+ def initialize
7
+ @connector = PubSubModelSync::Connector.new
8
+ end
9
+
10
+ def publish_data(klass, data, action)
11
+ attributes = self.class.build_attrs(klass, action)
12
+ publish(data, attributes)
13
+ end
14
+
15
+ # @param settings (Hash): { attrs: [], as_klass: nil, id: nil }
16
+ def publish_model(model, action, settings = nil)
17
+ settings ||= model.class.ps_msync_publisher_settings
18
+ attributes = build_model_attrs(model, action, settings)
19
+ data = {}
20
+ if action != 'destroy'
21
+ data = model.as_json(only: settings[:attrs], methods: settings[:attrs])
22
+ end
23
+ publish(data.symbolize_keys, attributes)
24
+ end
25
+
26
+ def self.build_attrs(klass, action, id = nil)
27
+ {
28
+ klass: klass.to_s,
29
+ action: action.to_sym,
30
+ id: id,
31
+ service_model_sync: true
32
+ }
33
+ end
34
+
35
+ private
36
+
37
+ def publish(data, attributes)
38
+ log("Publishing: #{[data, attributes]}")
39
+ connector.topic.publish(data.to_json, attributes)
40
+ end
41
+
42
+ def build_model_attrs(model, action, settings)
43
+ as_klass = (settings[:as_klass] || model.class.name).to_s
44
+ id_val = model.send(settings[:id] || :id)
45
+ self.class.build_attrs(as_klass, action, id_val)
46
+ end
47
+
48
+ def log(msg)
49
+ PubSubModelSync::Config.log(msg)
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PubSubModelSync
4
+ module PublisherConcern
5
+ def self.included(base)
6
+ base.extend(ClassMethods)
7
+ end
8
+
9
+ # Permit to skip a publish callback
10
+ def ps_msync_skip_for?(_action)
11
+ false
12
+ end
13
+
14
+ module ClassMethods
15
+ # Permit to publish crud actions (:create, :update, :destroy)
16
+ # @param settings (Hash): { actions: nil, as_klass: nil, id: nil }
17
+ def ps_msync_publish(attrs, settings = {})
18
+ actions = settings.delete(:actions) || %i[create update destroy]
19
+ @ps_msync_publisher_settings = settings.merge(attrs: attrs)
20
+ ps_msync_register_callbacks(actions)
21
+ end
22
+
23
+ def ps_msync_publisher_settings
24
+ @ps_msync_publisher_settings
25
+ end
26
+
27
+ def ps_msync_class_publish(data, action:, as_klass: nil)
28
+ as_klass = (as_klass || name).to_s
29
+ ps_msync_publisher.publish_data(as_klass, data, action.to_sym)
30
+ end
31
+
32
+ def ps_msync_publisher
33
+ PubSubModelSync::Publisher.new
34
+ end
35
+
36
+ private
37
+
38
+ def ps_msync_register_callbacks(actions)
39
+ actions.each do |action|
40
+ after_commit(on: action) do |model|
41
+ unless model.ps_msync_skip_for?(action)
42
+ publisher = model.class.ps_msync_publisher
43
+ publisher.publish_model(model, action.to_sym)
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pub_sub_model_sync'
4
+ require 'rails'
5
+ module PubSubModelSync
6
+ class Railtie < ::Rails::Railtie
7
+ railtie_name :pub_sub_model_sync
8
+
9
+ rake_tasks do
10
+ load 'pub_sub_model_sync/tasks/worker.rake'
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/core_ext/module'
4
+ module PubSubModelSync
5
+ class Runner
6
+ class ShutDown < StandardError; end
7
+ attr_accessor :connector
8
+
9
+ def run
10
+ trap_signals!
11
+ preload_framework!
12
+ start_listeners
13
+ rescue ShutDown
14
+ connector.stop
15
+ end
16
+
17
+ private
18
+
19
+ def start_listeners
20
+ @connector = PubSubModelSync::Connector.new
21
+ connector.listen_messages
22
+ end
23
+
24
+ def trap_signals!
25
+ handler = proc do |signal|
26
+ puts "received #{Signal.signame(signal)}"
27
+ raise ShutDown
28
+ end
29
+ %w[INT QUIT TERM].each { |signal| Signal.trap(signal, handler) }
30
+ end
31
+
32
+ def preload_framework!
33
+ Rails.application.try(:eager_load!) if defined?(Rails)
34
+ Zeitwerk::Loader.eager_load_all if defined?(Zeitwerk::Loader)
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PubSubModelSync
4
+ module SubscriberConcern
5
+ def self.included(base)
6
+ base.extend(ClassMethods)
7
+ end
8
+
9
+ module ClassMethods
10
+ # @param settings (Hash): { as_klass: nil, actions: nil, id: nil }
11
+ def ps_msync_subscribe(attrs, settings = {})
12
+ settings[:as_klass] = (settings[:as_klass] || name).to_s
13
+ actions = settings.delete(:actions) || %i[create update destroy]
14
+ @ps_msync_subscriber_settings = { attrs: attrs }.merge(settings)
15
+ actions.each do |action|
16
+ add_ps_msync_subscriber(settings[:as_klass], action, action, false)
17
+ end
18
+ end
19
+
20
+ def ps_msync_class_subscribe(action, as_action: nil, as_klass: nil)
21
+ add_ps_msync_subscriber(as_klass, action, as_action, true)
22
+ end
23
+
24
+ def ps_msync_subscriber_settings
25
+ @ps_msync_subscriber_settings || {}
26
+ end
27
+
28
+ private
29
+
30
+ def add_ps_msync_subscriber(as_klass, action, as_action, direct_mode)
31
+ listener = {
32
+ klass: name,
33
+ as_klass: (as_klass || name).to_s,
34
+ action: action.to_sym,
35
+ as_action: (as_action || action).to_sym,
36
+ direct_mode: direct_mode
37
+ }
38
+ PubSubModelSync::Config.listeners << listener
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ namespace :pub_sub_model_sync do
4
+ desc 'Start listening syncs'
5
+ task start: :environment do
6
+ PubSubModelSync::Runner.new.run
7
+ end
8
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PubSubModelSync
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'pub_sub_model_sync/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'pub_sub_model_sync'
9
+ spec.version = PubSubModelSync::VERSION
10
+ spec.authors = ['Owen']
11
+ spec.email = ['owenperedo@gmail.com']
12
+
13
+ spec.summary = 'Permit to sync models between apps through pub/sub'
14
+ spec.description = 'Permit to sync models between apps through pub/sub'
15
+ spec.homepage = 'https://github.com/owen2345/pub_sub_model_sync'
16
+ spec.license = 'MIT'
17
+
18
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
19
+
20
+ spec.metadata['homepage_uri'] = spec.homepage
21
+ spec.metadata['source_code_uri'] = spec.homepage
22
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md"
23
+
24
+ # Specify which files should be added to the gem when it is released.
25
+ # The `git ls-files -z` loads the files in the RubyGem that have been added
26
+ # into git.
27
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
28
+ `git ls-files -z`.split("\x0")
29
+ .reject { |f| f.match(%r{^(test|spec|features)/}) }
30
+ end
31
+ spec.bindir = 'exe'
32
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ['lib']
34
+
35
+ spec.add_dependency 'activesupport'
36
+ spec.add_dependency 'google-cloud-pubsub'
37
+ spec.add_dependency 'rails'
38
+
39
+ spec.add_development_dependency 'bundler'
40
+ spec.add_development_dependency 'rake'
41
+ spec.add_development_dependency 'rspec'
42
+ spec.add_development_dependency 'sqlite3'
43
+ end
metadata ADDED
@@ -0,0 +1,170 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pub_sub_model_sync
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Owen
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-03-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: google-cloud-pubsub
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: rails
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: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: sqlite3
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ description: Permit to sync models between apps through pub/sub
112
+ email:
113
+ - owenperedo@gmail.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - ".rspec"
120
+ - ".rubocop.yml"
121
+ - ".travis.yml"
122
+ - CODE_OF_CONDUCT.md
123
+ - Gemfile
124
+ - Gemfile.lock
125
+ - LICENSE.txt
126
+ - README.md
127
+ - Rakefile
128
+ - bin/console
129
+ - bin/setup
130
+ - lib/pub_sub_model_sync.rb
131
+ - lib/pub_sub_model_sync/config.rb
132
+ - lib/pub_sub_model_sync/connector.rb
133
+ - lib/pub_sub_model_sync/message_processor.rb
134
+ - lib/pub_sub_model_sync/mock_google_service.rb
135
+ - lib/pub_sub_model_sync/publisher.rb
136
+ - lib/pub_sub_model_sync/publisher_concern.rb
137
+ - lib/pub_sub_model_sync/railtie.rb
138
+ - lib/pub_sub_model_sync/runner.rb
139
+ - lib/pub_sub_model_sync/subscriber_concern.rb
140
+ - lib/pub_sub_model_sync/tasks/worker.rake
141
+ - lib/pub_sub_model_sync/version.rb
142
+ - pub_sub_model_sync.gemspec
143
+ homepage: https://github.com/owen2345/pub_sub_model_sync
144
+ licenses:
145
+ - MIT
146
+ metadata:
147
+ homepage_uri: https://github.com/owen2345/pub_sub_model_sync
148
+ source_code_uri: https://github.com/owen2345/pub_sub_model_sync
149
+ changelog_uri: https://github.com/owen2345/pub_sub_model_sync/blob/master/CHANGELOG.md
150
+ post_install_message:
151
+ rdoc_options: []
152
+ require_paths:
153
+ - lib
154
+ required_ruby_version: !ruby/object:Gem::Requirement
155
+ requirements:
156
+ - - ">="
157
+ - !ruby/object:Gem::Version
158
+ version: '0'
159
+ required_rubygems_version: !ruby/object:Gem::Requirement
160
+ requirements:
161
+ - - ">="
162
+ - !ruby/object:Gem::Version
163
+ version: '0'
164
+ requirements: []
165
+ rubyforge_project:
166
+ rubygems_version: 2.7.7
167
+ signing_key:
168
+ specification_version: 4
169
+ summary: Permit to sync models between apps through pub/sub
170
+ test_files: []