salesforce_streamer 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b38b1183300426662be05b97122259977fe6b492201845fe167dcc6d3c112aa2
4
+ data.tar.gz: 375d1d6c83fefdd0acd19df20c8fce763056b28894f73f175b9f3a164dbbbe61
5
+ SHA512:
6
+ metadata.gz: 23b0bb31b46d75b186907acaeba9931cb9bde5ccfd9e2ea7c92e30fa9b4a26fe238ace2eb1a841fbc0801cd376a37261e53c192e395fbb3ddd163739115e08c4
7
+ data.tar.gz: 992b2c38a77a92729d370a78c90c35d629f88341994be75b219c1aba65258502c8ef3c60aae573786946c5d270bbdcbdb1c7e405b8f36d18232ded3242403f54
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.byebug_history
3
+ /.yardoc
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,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,8 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6
7
+ - 2.5
8
+ before_install: gem install bundler -v 2.0.1
@@ -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 scott@renofi.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,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in salesforce_streamer.gemspec
4
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,92 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ salesforce_streamer (0.1.0)
5
+ faye (~> 0.8.9)
6
+ restforce (~> 3.1.0)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ addressable (2.6.0)
12
+ public_suffix (>= 2.0.2, < 4.0)
13
+ byebug (11.0.1)
14
+ codecov (0.1.14)
15
+ json
16
+ simplecov
17
+ url
18
+ cookiejar (0.3.3)
19
+ diff-lcs (1.3)
20
+ docile (1.3.2)
21
+ em-http-request (1.1.5)
22
+ addressable (>= 2.3.4)
23
+ cookiejar (!= 0.3.1)
24
+ em-socksify (>= 0.3)
25
+ eventmachine (>= 1.0.3)
26
+ http_parser.rb (>= 0.6.0)
27
+ em-socksify (0.3.2)
28
+ eventmachine (>= 1.0.0.beta.4)
29
+ eventmachine (1.2.7)
30
+ faraday (0.15.4)
31
+ multipart-post (>= 1.2, < 3)
32
+ faraday_middleware (0.13.1)
33
+ faraday (>= 0.7.4, < 1.0)
34
+ faye (0.8.11)
35
+ cookiejar (>= 0.3.0)
36
+ em-http-request (>= 0.3.0)
37
+ eventmachine (>= 0.12.0)
38
+ faye-websocket (>= 0.4.0)
39
+ rack (>= 1.0.0)
40
+ yajl-ruby (>= 1.0.0)
41
+ faye-websocket (0.10.9)
42
+ eventmachine (>= 0.12.0)
43
+ websocket-driver (>= 0.5.1)
44
+ hashie (3.6.0)
45
+ http_parser.rb (0.6.0)
46
+ json (2.2.0)
47
+ multipart-post (2.1.1)
48
+ public_suffix (3.1.1)
49
+ rack (2.0.7)
50
+ rake (10.5.0)
51
+ restforce (3.1.0)
52
+ faraday (>= 0.9.0, <= 1.0)
53
+ faraday_middleware (>= 0.8.8, <= 1.0)
54
+ hashie (>= 1.2.0, < 4.0)
55
+ json (>= 1.7.5)
56
+ rspec (3.8.0)
57
+ rspec-core (~> 3.8.0)
58
+ rspec-expectations (~> 3.8.0)
59
+ rspec-mocks (~> 3.8.0)
60
+ rspec-core (3.8.2)
61
+ rspec-support (~> 3.8.0)
62
+ rspec-expectations (3.8.4)
63
+ diff-lcs (>= 1.2.0, < 2.0)
64
+ rspec-support (~> 3.8.0)
65
+ rspec-mocks (3.8.1)
66
+ diff-lcs (>= 1.2.0, < 2.0)
67
+ rspec-support (~> 3.8.0)
68
+ rspec-support (3.8.2)
69
+ simplecov (0.17.0)
70
+ docile (~> 1.1)
71
+ json (>= 1.8, < 3)
72
+ simplecov-html (~> 0.10.0)
73
+ simplecov-html (0.10.2)
74
+ url (0.3.2)
75
+ websocket-driver (0.7.1)
76
+ websocket-extensions (>= 0.1.0)
77
+ websocket-extensions (0.1.4)
78
+ yajl-ruby (1.4.1)
79
+
80
+ PLATFORMS
81
+ ruby
82
+
83
+ DEPENDENCIES
84
+ bundler (~> 2.0)
85
+ byebug (~> 11.0.1)
86
+ codecov (~> 0.1.14)
87
+ rake (~> 10.0)
88
+ rspec (~> 3.0)
89
+ salesforce_streamer!
90
+
91
+ BUNDLED WITH
92
+ 2.0.1
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Scott Serok
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,133 @@
1
+ [![Build Status](https://travis-ci.org/RenoFi/salesforce_streamer.svg?branch=master)](https://travis-ci.org/RenoFi/salesforce_streamer)
2
+
3
+ [![codecov](https://codecov.io/gh/RenoFi/salesforce_streamer/branch/master/graph/badge.svg)](https://codecov.io/gh/RenoFi/salesforce_streamer)
4
+
5
+ # SalesforceStreamer
6
+
7
+ A wrapper around the Restforce Streaming API to receive real time updates from
8
+ your Salesforce instance with a built-in PushTopic manager.
9
+
10
+ ## Installation
11
+
12
+ Add this line to your application's Gemfile:
13
+
14
+ ```ruby
15
+ gem 'salesforce_streamer'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ ## Usage
23
+
24
+ ### Configure Push Topics
25
+
26
+ Create a YAML file to configure your server subscriptions. The configuration
27
+ for each subscription must have a nested `salesforce:` key. These settings will
28
+ be synced to your Salesforce instance when the `-x` flag is set on the command
29
+ line. For more information about the `replay:` and `notify_fields_for` options
30
+ please see the Salesforce Streaming API reference documentation.
31
+
32
+ ```yaml
33
+ # config/streamer.yml
34
+ ---
35
+ base: &DEFAULT
36
+ accounts:
37
+ handler: "AccountChangeHandler"
38
+ replay: -1
39
+ salesforce:
40
+ name: "AllAccounts"
41
+ api_version: "41.0"
42
+ description: "Sync Accounts"
43
+ notify_for_fields: "Referenced"
44
+ query: "Select Id, Name From Account"
45
+
46
+ development:
47
+ <<: *DEFAULT
48
+ ```
49
+
50
+ It's important to note that the way push topics are managed is by the Salesforce
51
+ name attribute. This should uniquely identify each push topic. It is not
52
+ recommended to change the name of your push topic definitions; otherwise, the
53
+ push topic manager will not find a push topic in Salesforce resulting in the
54
+ creation of a brand new push topic. If the push topic manager identifies a
55
+ difference in any of the other Salesforce attributes, then it will update the
56
+ push topic in Salesforce before starting the streaming server.
57
+
58
+ ### Define Message Handlers
59
+
60
+ Define your handlers somewhere in your project. They must respond to
61
+ `.call(str)`.
62
+
63
+ ```ruby
64
+ # lib/account_change_handler.rb
65
+ class AccountChangeHandler
66
+ def self.call(message)
67
+ puts message
68
+ end
69
+ end
70
+ ```
71
+
72
+ ### Prepare The Environment
73
+
74
+ Set your Restforce ENV variables in order to establish a connection. See the
75
+ Restforce API documentation for more details. Then start the server using the
76
+ command line interface.
77
+
78
+ ### Launch The Streamer
79
+
80
+ Launch the `streamer` service, pointing it to your push topic configuration YAML
81
+ file and the entry point to your application.
82
+
83
+ ```
84
+ $ bundle exec streamer -C config/streamer.yml -r ./lib/app -x -v INFO
85
+ I, [2019-07-09T15:19:55.862296 #78537] INFO -- : Launching Streamer Services
86
+ I, [2019-07-09T15:19:55.862351 #78537] INFO -- : Running Topic Manager
87
+ I, [2019-07-09T15:19:56.860998 #78537] INFO -- : New PushTopic AllAccounts
88
+ I, [2019-07-09T15:19:56.861079 #78537] INFO -- : Upsert PushTopic AllAccounts
89
+ I, [2019-07-09T15:19:57.591241 #78537] INFO -- : Starting Server
90
+ ```
91
+
92
+ For very verbose logs, also use the `--verbose-restforce` flag to activate the
93
+ Restforce client logger - not recommended for production.
94
+
95
+ You can start up the server without syncing the push topic configuration if you
96
+ know the topics are already configured appropriately. Remove the `-x` flag from
97
+ the CLI to skip the topic management component.
98
+
99
+ ```
100
+ $ bundle exec streamer -C config/streamer.yml -r ./lib/app -v INFO
101
+ I, [2019-07-08T22:16:34.104271 #26973] INFO -- : Launching Streamer Services
102
+ I, [2019-07-09T15:19:55.862351 #78537] INFO -- : Running Topic Manager
103
+ I, [2019-07-09T15:19:56.860998 #78537] INFO -- : New PushTopic AllAccounts
104
+ I, [2019-07-09T15:19:56.861079 #78537] INFO -- : Upsert PushTopic AllAccounts
105
+ I, [2019-07-09T15:19:56.861109 #78537] INFO -- : Skipping upsert because manage topics is off
106
+ I, [2019-07-08T22:16:34.794933 #26973] INFO -- : Starting Server
107
+ ```
108
+
109
+ By default, the CLI will load the YAML based on the `RACK_ENV` environment
110
+ variable, or default to `:development` if not set. You can override this in the
111
+ CLI with the `-e ENV` flag.
112
+
113
+ ```
114
+ $ bundle exec streamer -C config/streamer.yml -r ./lib/app -e production
115
+ ```
116
+
117
+ ## Development
118
+
119
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
120
+
121
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
122
+
123
+ ## Contributing
124
+
125
+ Bug reports and pull requests are welcome on GitHub at https://github.com/renofi/salesforce_streamer. 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.
126
+
127
+ ## License
128
+
129
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
130
+
131
+ ## Code of Conduct
132
+
133
+ Everyone interacting in the SalesforceStreamer project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/renofi/salesforce_streamer/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -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
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "salesforce_streamer"
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__)
data/bin/setup ADDED
@@ -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
data/exe/streamer ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'salesforce_streamer'
4
+ require 'salesforce_streamer/cli'
5
+
6
+ cli = SalesforceStreamer::CLI.new ARGV
7
+ cli.run
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Original source code at
4
+ # https://github.com/dwaite/cookiejar/blob/master/lib/cookiejar/cookie_validation.rb
5
+ # Re-opening the CookieValidation module to rewrite the domains_match method to
6
+ # skip the validation of domains. Open issue at
7
+ # https://github.com/restforce/restforce/issues/120
8
+ module CoreExtensions
9
+ module CookieJar
10
+ module CookieValidation
11
+ def self.extended(base)
12
+ base.class_eval do
13
+
14
+ def self.domains_match(tested_domain, base_domain)
15
+ return true if tested_domain[-15..-1].eql?('.salesforce.com')
16
+
17
+ # original implementation
18
+ base = effective_host base_domain
19
+ search_domains = compute_search_domains_for_host base
20
+ search_domains.find do |domain|
21
+ domain == tested_domain
22
+ end
23
+ end
24
+
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
30
+
31
+ CookieJar::CookieValidation.extend(CoreExtensions::CookieJar::CookieValidation)
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ class CLI
5
+ def initialize(argv)
6
+ @argv = argv
7
+ @config = Configuration.new
8
+ @push_topics_loaded = false
9
+ setup_options
10
+ @parser.parse! @argv
11
+ end
12
+
13
+ def run
14
+ validate!
15
+ Launcher.new(config: @config).run
16
+ end
17
+
18
+ private
19
+
20
+ def validate!
21
+ raise(MissingCLIFlagError, '--config PATH') unless @push_topics_loaded
22
+ raise(MissingCLIFlagError, '--require PATH') unless @config.require_path
23
+ rescue MissingCLIFlagError => e
24
+ puts e
25
+ puts @parser
26
+ exit 1
27
+ end
28
+
29
+ def setup_options
30
+ @parser = OptionParser.new do |o|
31
+ o.on "-C", "--config PATH", "Load PATH as a config file" do |arg|
32
+ @config.load_push_topic_data arg
33
+ @push_topics_loaded = true
34
+ end
35
+
36
+ o.on "-e", "--environment ENVIRONMENT",
37
+ "The environment to run the app on (default development)" do |arg|
38
+ @config.environment = arg
39
+ end
40
+
41
+ o.on "-r", "--require PATH", "Load PATH as the entry point to your application" do |arg|
42
+ @config.require_path = arg
43
+ end
44
+
45
+ o.on "--verbose-restforce", "Activate the Restforce logger" do
46
+ @config.restforce_logger!
47
+ end
48
+
49
+ o.on "-v", "--verbose LEVEL", "Set the log level (default no logging)" do |arg|
50
+ logger = Logger.new(STDOUT)
51
+ logger.level = arg
52
+ @config.logger = logger
53
+ end
54
+
55
+ o.on "-V", "--version", "Print the version information" do
56
+ puts "streamer version #{SalesforceStreamer::VERSION}"
57
+ exit 0
58
+ end
59
+
60
+ o.on "-x", "--topics", "Activate PushTopic Management (default off)" do
61
+ @config.manage_topics = true
62
+ end
63
+
64
+ o.banner = "streamer OPTIONS"
65
+
66
+ o.on_tail "-h", "--help", "Show help" do
67
+ puts o
68
+ exit 0
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ # Manages server configuration.
5
+ class Configuration
6
+ attr_accessor :environment, :logger, :require_path
7
+ attr_reader :push_topic_data
8
+ attr_writer :manage_topics
9
+
10
+ def initialize
11
+ @environment = ENV['RACK_ENV'] || :development
12
+ @logger = Logger.new(IO::NULL)
13
+ @manage_topics = false
14
+ end
15
+
16
+ def manage_topics?
17
+ @manage_topics
18
+ end
19
+
20
+ def load_push_topic_data(path)
21
+ data = YAML.safe_load(File.read(path), [], [], true)
22
+ @push_topic_data = data[environment.to_s]
23
+ end
24
+
25
+ def restforce_logger!
26
+ Restforce.log = true
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ class MissingCLIFlagError < StandardError
5
+ def initialize(flag)
6
+ super 'Missing required command line flag: ' + flag.to_s
7
+ end
8
+ end
9
+
10
+ class NilQueryError < StandardError
11
+ def initialize(name)
12
+ super 'Query not defined for ' + name.to_s
13
+ end
14
+ end
15
+
16
+ class PushTopicHandlerMissingError < StandardError
17
+ def initialize(message)
18
+ super "Unable to load constant #{message.to_s}."
19
+ end
20
+ end
21
+
22
+ class PushTopicNameTooLongError < StandardError
23
+ def initialize(name)
24
+ super 'PushTopic name: ' + name.to_s + ' (' + name.size.to_s + '/25)'
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ # SalesforceStreamer::Launcher is the entry point for starting the Restforce
5
+ # Streaming API server. It is responsible for upserting each PushTopic and
6
+ # starting the server.
7
+ class Launcher
8
+ def initialize(config:)
9
+ @config = config
10
+ @logger = config.logger
11
+ load_server_configuration
12
+ @manager = TopicManager.new push_topics: @push_topics, config: @config
13
+ @server = Server.new push_topics: @push_topics, config: @config
14
+ end
15
+
16
+ # Manages each PushTopic configured and starts the Streaming API listener.
17
+ def run
18
+ @logger.info 'Launching Streamer Services'
19
+ @manager.run
20
+ @server.push_topics = @manager.push_topics
21
+ @server.run
22
+ end
23
+
24
+ private
25
+
26
+ def load_server_configuration
27
+ require_application
28
+ initialize_push_topics
29
+ end
30
+
31
+ def require_application
32
+ if @config.require_path
33
+ @logger.debug 'Loading the require path'
34
+ require @config.require_path
35
+ end
36
+ end
37
+
38
+ def initialize_push_topics
39
+ @logger.debug 'Loading and validating PushTopics configuration'
40
+ @push_topics = []
41
+ @config.push_topic_data.values.each do |topic_data|
42
+ @logger.debug topic_data.to_s
43
+ @push_topics << PushTopic.new(data: topic_data)
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ # Models the PushTopic object for both Restforce and Streamer
5
+ class PushTopic
6
+ attr_accessor :id
7
+ attr_reader :name, :replay, :description, :notify_for_fields, :query,
8
+ :handler, :handler_constant, :api_version
9
+
10
+ def initialize(data:)
11
+ @handler = data['handler']
12
+ @replay = data.dig('replay')&.to_i || -1
13
+ @name = data.dig('salesforce', 'name')
14
+ @api_version = data.dig('salesforce', 'api_version') || '41.0'
15
+ @description = data.dig('salesforce', 'description') || @name
16
+ @notify_for_fields = data.dig('salesforce', 'notify_for_fields') || 'Referenced'
17
+ @query = strip_spaces(data.dig('salesforce', 'query'))
18
+ validate!
19
+ end
20
+
21
+ def to_s
22
+ "PushTopic id=#{id} name=#{name} handler=#{handler} " \
23
+ "replay=#{replay} notify_for_fields=#{notify_for_fields} " \
24
+ "description=#{description} api_version=#{api_version} query=#{query}"
25
+ end
26
+
27
+ private
28
+
29
+ def validate!
30
+ raise(PushTopicNameTooLongError, @name) if @name.size > 25
31
+ @handler_constant = Object.const_get(@handler)
32
+ true
33
+ rescue NameError, TypeError => e
34
+ message = 'handler=' + @handler.to_s + ' exception=' + e.to_s
35
+ raise(PushTopicHandlerMissingError, message)
36
+ end
37
+
38
+ def strip_spaces(str)
39
+ raise(NilQueryError, @name) unless str
40
+ str.gsub(/\s+/, ' ')
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ class SalesforceClient
5
+ def initialize(client: Restforce.new)
6
+ @client = client
7
+ end
8
+
9
+ def authenticate!
10
+ @client.authenticate!
11
+ end
12
+
13
+ def subscribe(*args)
14
+ @client.subscribe(args) do
15
+ yield
16
+ end
17
+ end
18
+
19
+ # Returns nil or an instance of Restforce::SObject
20
+ def find_push_topic_by_name(name)
21
+ query = QUERY.dup.gsub(/\s+/, ' ').gsub('{{NAME}}', name)
22
+ @client.query(query).first
23
+ end
24
+
25
+ # Returns true or raises an exception if the upsert fails
26
+ def upsert_push_topic(push_topic)
27
+ @client.upsert!('PushTopic', :Id,
28
+ 'Id' => push_topic.id,
29
+ 'Name' => push_topic.name,
30
+ 'ApiVersion' => push_topic.api_version,
31
+ 'Description' => push_topic.description,
32
+ 'NotifyForFields' => push_topic.notify_for_fields,
33
+ 'Query' => push_topic.query
34
+ )
35
+ end
36
+
37
+ private
38
+
39
+ QUERY = <<~SOQL.chomp.freeze
40
+ SELECT Id, Name, ApiVersion, Description, NotifyForFields, Query, isActive
41
+ FROM PushTopic
42
+ WHERE Name = '{{NAME}}'
43
+ SOQL
44
+ end
45
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ class Server
5
+ attr_writer :push_topics
6
+
7
+ def initialize(config:, push_topics: [])
8
+ @logger = config.logger
9
+ @push_topics = push_topics
10
+ @client = Restforce.new
11
+ end
12
+
13
+ def run
14
+ @client.authenticate!
15
+ @logger.info 'Starting Server'
16
+ catch_signals
17
+ start_em
18
+ end
19
+
20
+ private
21
+
22
+ def catch_signals
23
+ %w[INT USR1 USR2 TERM TTIN TSTP].each do |sig|
24
+ trap sig do
25
+ puts "Caught signal #{sig}. Shutting down..."
26
+ exit 0
27
+ end
28
+ end
29
+ end
30
+
31
+ def start_em
32
+ EM.run do
33
+ @push_topics.map do |topic|
34
+ @client.subscribe topic.name, replay: topic.replay.to_i do |msg|
35
+ @logger.debug(msg)
36
+ topic.handler_constant.call(msg)
37
+ @logger.info("Message processed: channel=#{topic.name} replayId=#{msg.dig('event', 'replayId')}")
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ class TopicManager
5
+ attr_reader :push_topics
6
+
7
+ def initialize(push_topics:, config:)
8
+ @push_topics = push_topics
9
+ @config = config
10
+ @logger = config.logger
11
+ @client = Restforce.new
12
+ end
13
+
14
+ def run
15
+ @logger.info 'Running Topic Manager'
16
+ @push_topics.each do |push_topic|
17
+ @logger.debug push_topic.to_s
18
+ if diff?(push_topic)
19
+ upsert(push_topic)
20
+ end
21
+ end
22
+ end
23
+
24
+ private
25
+
26
+ def diff?(push_topic)
27
+ hashie = @client.find_push_topic_by_name(push_topic.name)
28
+ unless hashie
29
+ @logger.info "New PushTopic #{push_topic.name}"
30
+ return true
31
+ end
32
+ @logger.debug "Remote PushTopic found with hash=#{hashie.to_h}"
33
+ push_topic.id = hashie.Id
34
+ return true unless push_topic.query.eql?(hashie.Query)
35
+ return true unless push_topic.notify_for_fields.eql?(hashie.NotifyForFields)
36
+ return true unless push_topic.api_version.to_s.eql?(hashie.ApiVersion.to_s)
37
+ @logger.debug 'No differences detected'
38
+ false
39
+ end
40
+
41
+ def upsert(push_topic)
42
+ @logger.info "Upsert PushTopic #{push_topic.name}"
43
+ if @config.manage_topics?
44
+ @client.upsert_push_topic(push_topic)
45
+ else
46
+ @logger.info 'Skipping upsert because manage topics is off'
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SalesforceStreamer
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faye'
4
+ require 'logger'
5
+ require 'optparse'
6
+ require 'restforce'
7
+ require 'yaml'
8
+
9
+ require 'salesforce_streamer/configuration'
10
+ require 'salesforce_streamer/errors'
11
+ require 'salesforce_streamer/push_topic'
12
+ require 'salesforce_streamer/topic_manager'
13
+ require 'salesforce_streamer/salesforce_client'
14
+ require 'salesforce_streamer/server'
15
+ require 'salesforce_streamer/version'
16
+ require 'salesforce_streamer/launcher'
17
+
18
+ require 'core_extensions/cookiejar/cookie_validation'
19
+
20
+ # SalesforceStreamer wraps the Restforce Streaming API implementation so that
21
+ # your PushTopics are managed in the same place as your server set up.
22
+ #
23
+ # Establishing a connection to your Salesforce instances is performed using the
24
+ # Restforce client and your ENV variables.
25
+ #
26
+ # export SALESFORCE_HOST="test.salesforce.com"
27
+ # export SALESFORCE_USERNAME="user@domain.tld"
28
+ # export SALESFORCE_PASSWORD="password"
29
+ # export SALESFORCE_SECURITY_TOKEN="security token"
30
+ # export SALESFORCE_CLIENT_ID="long client id"
31
+ # export SALESFORCE_CLIENT_SECRET="long client secret"
32
+ # export SALESFORCE_API_VERSION="41.0"
33
+ #
34
+ # Define each PushTopic and handler inside of a YAML config file and load it
35
+ # upon starting up the server.
36
+ #
37
+ # bundle exec streamer -C config/streamer.yml
38
+ #
39
+ # Starting up the server takes a few moments before accepting new events. First,
40
+ # the server launches the PushTopic manager to upsert each PushTopic defined in
41
+ # the configuration file provided. Once each PushTopic is up to date, then the
42
+ # server launches the event manager to listen for and handle messages.
43
+ #
44
+ # Turn on verbose logging for troubleshooting. The -r flag will activate the
45
+ # Restforce logger, so this is not recommended for production. The -v flag
46
+ # activates a Logger to STDOUT with DEBUG level by default. Set the log level
47
+ # with the -v flag.
48
+ #
49
+ # bundle exec streamer -C config/streamer.yml -r
50
+ # bundle exec streamer -C config/streamer.yml -v
51
+ # bundle exec streamer -C config/streamer.yml -v INFO
52
+ # bundle exec streamer -C config/streamer.yml -r -v
53
+ # bundle exec streamer -C config/streamer.yml -r -v INFO
54
+ #
55
+ module SalesforceStreamer
56
+ end
@@ -0,0 +1,44 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "salesforce_streamer/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "salesforce_streamer"
8
+ spec.version = SalesforceStreamer::VERSION
9
+ spec.authors = ["Scott Serok"]
10
+ spec.email = ["scott@renofi.com"]
11
+
12
+ spec.summary = 'A wrapper around the Restforce Streaming API.'
13
+ spec.description = 'A wrapper around the Restforce Streaming API.'
14
+ spec.homepage = 'https://github.com/renofi/salesforce_streamer'
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata["homepage_uri"] = spec.homepage
21
+ spec.metadata["source_code_uri"] = spec.homepage
22
+ spec.metadata["changelog_uri"] = spec.homepage
23
+ else
24
+ raise "RubyGems 2.0 or newer is required to protect against " \
25
+ "public gem pushes."
26
+ end
27
+
28
+ # Specify which files should be added to the gem when it is released.
29
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
30
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
31
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
32
+ end
33
+ spec.bindir = "exe"
34
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
35
+ spec.require_paths = ["lib"]
36
+
37
+ spec.add_development_dependency "bundler", "~> 2.0"
38
+ spec.add_development_dependency "rake", "~> 10.0"
39
+ spec.add_development_dependency "rspec", "~> 3.0"
40
+ spec.add_development_dependency "byebug", "~> 11.0.1"
41
+ spec.add_development_dependency "codecov", "~> 0.1.14"
42
+ spec.add_dependency "restforce", "~> 3.1.0"
43
+ spec.add_dependency "faye", "~> 0.8.9"
44
+ end
metadata ADDED
@@ -0,0 +1,169 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: salesforce_streamer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Scott Serok
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-07-11 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: byebug
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 11.0.1
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 11.0.1
69
+ - !ruby/object:Gem::Dependency
70
+ name: codecov
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: 0.1.14
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: 0.1.14
83
+ - !ruby/object:Gem::Dependency
84
+ name: restforce
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: 3.1.0
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: 3.1.0
97
+ - !ruby/object:Gem::Dependency
98
+ name: faye
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: 0.8.9
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: 0.8.9
111
+ description: A wrapper around the Restforce Streaming API.
112
+ email:
113
+ - scott@renofi.com
114
+ executables:
115
+ - streamer
116
+ extensions: []
117
+ extra_rdoc_files: []
118
+ files:
119
+ - ".gitignore"
120
+ - ".rspec"
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
+ - exe/streamer
131
+ - lib/core_extensions/cookiejar/cookie_validation.rb
132
+ - lib/salesforce_streamer.rb
133
+ - lib/salesforce_streamer/cli.rb
134
+ - lib/salesforce_streamer/configuration.rb
135
+ - lib/salesforce_streamer/errors.rb
136
+ - lib/salesforce_streamer/launcher.rb
137
+ - lib/salesforce_streamer/push_topic.rb
138
+ - lib/salesforce_streamer/salesforce_client.rb
139
+ - lib/salesforce_streamer/server.rb
140
+ - lib/salesforce_streamer/topic_manager.rb
141
+ - lib/salesforce_streamer/version.rb
142
+ - salesforce_streamer.gemspec
143
+ homepage: https://github.com/renofi/salesforce_streamer
144
+ licenses:
145
+ - MIT
146
+ metadata:
147
+ homepage_uri: https://github.com/renofi/salesforce_streamer
148
+ source_code_uri: https://github.com/renofi/salesforce_streamer
149
+ changelog_uri: https://github.com/renofi/salesforce_streamer
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
+ rubygems_version: 3.0.3
166
+ signing_key:
167
+ specification_version: 4
168
+ summary: A wrapper around the Restforce Streaming API.
169
+ test_files: []