power_strip 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: cfbdf19d7bf07bffbe82762068326c83275bbbd2
4
+ data.tar.gz: 4822d861290a272543619889ed2cbfaa39537a95
5
+ SHA512:
6
+ metadata.gz: 593302575354edec1f8b8d10e63779df75b59d9757bf0d18fb23aec48786b10d2031a264ee339d9a8081ffd007cdf75212db926994c9d976f6af0df41f02ff0a
7
+ data.tar.gz: 5a418383fce11f99fc3113fd8620d7a2a7b385278abe67c9743f39f8994811d02854d79567bb1dd3ec3dad02ddfd0c011e52f6dd83514818a7edfe1feaef0931
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.1
5
+ before_install: gem install bundler -v 1.12.5
@@ -0,0 +1,49 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, and in the interest of
4
+ fostering an open and welcoming community, we pledge to respect all people who
5
+ contribute through reporting issues, posting feature requests, updating
6
+ documentation, submitting pull requests or patches, and other activities.
7
+
8
+ We are committed to making participation in this project a harassment-free
9
+ experience for everyone, regardless of level of experience, gender, gender
10
+ identity and expression, sexual orientation, disability, personal appearance,
11
+ body size, race, ethnicity, age, religion, or nationality.
12
+
13
+ Examples of unacceptable behavior by participants include:
14
+
15
+ * The use of sexualized language or imagery
16
+ * Personal attacks
17
+ * Trolling or insulting/derogatory comments
18
+ * Public or private harassment
19
+ * Publishing other's private information, such as physical or electronic
20
+ addresses, without explicit permission
21
+ * Other unethical or unprofessional conduct
22
+
23
+ Project maintainers have the right and responsibility to remove, edit, or
24
+ reject comments, commits, code, wiki edits, issues, and other contributions
25
+ that are not aligned to this Code of Conduct, or to ban temporarily or
26
+ permanently any contributor for other behaviors that they deem inappropriate,
27
+ threatening, offensive, or harmful.
28
+
29
+ By adopting this Code of Conduct, project maintainers commit themselves to
30
+ fairly and consistently applying these principles to every aspect of managing
31
+ this project. Project maintainers who do not follow or enforce the Code of
32
+ Conduct may be permanently removed from the project team.
33
+
34
+ This code of conduct applies both within project spaces and in public spaces
35
+ when an individual is representing the project or its community.
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
+ reported by contacting a project maintainer at jgaskins@gmail.com. All
39
+ complaints will be reviewed and investigated and will result in a response that
40
+ is deemed necessary and appropriate to the circumstances. Maintainers are
41
+ obligated to maintain confidentiality with regard to the reporter of an
42
+ incident.
43
+
44
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
+ version 1.3.0, available at
46
+ [http://contributor-covenant.org/version/1/3/0/][version]
47
+
48
+ [homepage]: http://contributor-covenant.org
49
+ [version]: http://contributor-covenant.org/version/1/3/0/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in power_strip.gemspec
4
+ gemspec
data/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # PowerStrip
2
+
3
+ PowerStrip is a Ruby library to manage WebSockets easily. It combines the following pieces:
4
+
5
+ - Rack app you can mount into your Ruby web app to handle incoming WebSocket connections
6
+ - Connection manager
7
+ - API for handling channels and events
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'power_strip'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle
20
+
21
+ ## Server-Side Usage
22
+
23
+ Call `PowerStrip.start` to turn on the PowerStrip and mount `PowerStrip` as an endpoint of your app. Here are a couple of examples to get you started with Rails and Roda:
24
+
25
+ ### Rails
26
+
27
+ ```ruby
28
+ # config/initializers/power_strip.rb
29
+ PowerStrip.start
30
+
31
+ # config/routes.rb
32
+ mount PowerStrip, at: '/chat' # Example for a chat app
33
+ ```
34
+
35
+ ### Roda
36
+
37
+ ```ruby
38
+ # config.ru
39
+ require 'power_strip'
40
+
41
+ PowerStrip.start
42
+
43
+ class MyApp < Roda
44
+ r.on('chat') { r.run PowerStrip }
45
+ end
46
+ ```
47
+
48
+ ### Sending updates to clients:
49
+
50
+ ```ruby
51
+ PowerStrip[channel_name].send(event_name, key: value)
52
+ ```
53
+
54
+ ## Client-Side Usage
55
+
56
+ If your front-end app is written in Ruby (via Opal), you can start with just a few lines of code:
57
+
58
+ ```ruby
59
+ require 'opal'
60
+ require 'power_strip'
61
+
62
+ # This URL should point to where you have PowerStrip mounted on the server
63
+ client = PowerStrip::Client.new('ws://localhost:9292/chat')
64
+
65
+ client.on(:connect) { store.dispatch Connected.new }
66
+ client.on(:disconnect) { store.dispatch Disconnected.new }
67
+
68
+ channel = client.subscribe(:chat)
69
+ channel.on :message do |message|
70
+ # Tell your app you've received this message. The payload is in message.data.
71
+ end
72
+ ```
73
+
74
+ ### JavaScript
75
+
76
+ ```javascript
77
+ // Note: this isn't implemented yet because I'm a Ruby developer
78
+ import { Client } from 'power_strip';
79
+
80
+ const client = new Client('ws://localhost:9292/chat');
81
+
82
+ client.on('connect', () => dispatch(connected()));
83
+ client.on('disconnect', () => dispatch(disconnected()));
84
+
85
+ const channel = client.subscribe('chat');
86
+ channel.on('message', message => {
87
+ dispatch(receivedMessage(message.data));
88
+ });
89
+ ```
90
+
91
+ ## Sending Messages Client->Server
92
+
93
+ Set up a message handler on the server:
94
+
95
+ ```ruby
96
+ require 'power_strip'
97
+
98
+ # Handle :message events in the "chat" channel.
99
+ # @param message [PowerStrip::Message] the message we received
100
+ # @param connection [Faye::WebSocket] the client connection this is from
101
+ PowerStrip.on :message, channel: 'chat' do |message, connection|
102
+ IncomingMessageWorker.perform_async message
103
+ end
104
+ ```
105
+
106
+ Notice we don't do work directly on the message. We instead pass it off to a background worker. This is so that we can handle as many incoming messages as possible. To be able to send messages back to that channel, we can simply use the Server->Client message command specified above. Note the `perform` method here:
107
+
108
+ ```ruby
109
+ require 'sidekiq'
110
+ require 'power_strip'
111
+
112
+ class IncomingMessageWorker
113
+ include Sidekiq::Worker
114
+
115
+ # @param message [PowerStrip::Message]
116
+ def perform(message)
117
+ # Simplest case, we send the message back out to everyone on the same channel
118
+ PowerStrip[message.channel].send :message, message.data
119
+ end
120
+ end
121
+ ```
122
+
123
+ ## Development
124
+
125
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
126
+
127
+ 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).
128
+
129
+ ## Contributing
130
+
131
+ Bug reports and pull requests are welcome on GitHub at https://github.com/clearwater-rb/power_strip. 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.
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 "power_strip"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,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,107 @@
1
+ require 'faye/websocket'
2
+ require 'redis'
3
+ require 'set'
4
+ require 'json'
5
+
6
+ require 'power_strip/channel_list'
7
+ require 'power_strip/message'
8
+
9
+ module PowerStrip
10
+ class App
11
+ attr_reader :redis, :sockets, :channels
12
+
13
+ def self.instance(**args)
14
+ @instance ||= new(**args)
15
+ end
16
+
17
+ def initialize(redis: Redis.new)
18
+ @redis = redis
19
+ @channels = ChannelList.new(redis: redis)
20
+ @handlers = Hash.new do |channels,channel|
21
+ channels[channel] = Hash.new do |handlers, event|
22
+ handlers[event] = []
23
+ end
24
+ end
25
+ end
26
+
27
+ def call env
28
+ if Faye::WebSocket.websocket? env
29
+ socket = Faye::WebSocket.new(env)
30
+
31
+ subscriptions = Set.new
32
+
33
+ socket.on :message do |event|
34
+ message = Message.new(JSON.parse(event.data))
35
+ channel_name = message.channel
36
+ channel = channels[channel_name]
37
+
38
+ case message.event
39
+ when '@subscribe'
40
+ channel << socket
41
+ subscriptions << channel_name
42
+
43
+ socket.send({
44
+ event: :subscribed,
45
+ channel: channel_name,
46
+ }.to_json)
47
+ when '@unsubscribe'
48
+ channels[channel_name].delete socket
49
+ if channels[channel_name].empty?
50
+ channels.delete channel_name
51
+ end
52
+
53
+ subscriptions.delete channel_name
54
+
55
+ socket.send({
56
+ event: :unsubscribed,
57
+ channel: channel_name,
58
+ }.to_json)
59
+ else
60
+ @handlers[channel_name][message.event].each do |callback|
61
+ begin
62
+ callback[message, socket]
63
+ rescue => e
64
+ warn "[PowerStrip] #{e.inspect}"
65
+ end
66
+ end
67
+ end
68
+ end
69
+
70
+ socket.on :close do
71
+ subscriptions.each do |channel_name|
72
+ channels[channel_name].delete socket
73
+ end
74
+ end
75
+
76
+ socket.rack_response
77
+ else
78
+ bad_request
79
+ end
80
+ end
81
+
82
+ def on event, channel:, &block
83
+ @handlers[channel.to_s][event.to_s] << block
84
+ end
85
+
86
+ def listen
87
+ redis.dup.subscribe(:power_strip) do |on|
88
+ on.message do |_, message|
89
+ channel = JSON.parse(message)['channel']
90
+ channels[channel].sockets.each do |socket|
91
+ socket.send message
92
+ end
93
+ end
94
+ end
95
+ end
96
+
97
+ private
98
+
99
+ def bad_request
100
+ [
101
+ 400,
102
+ { 'Content-Type' => 'text/plain' },
103
+ ['This endpoint only handles websockets'],
104
+ ]
105
+ end
106
+ end
107
+ end
@@ -0,0 +1,33 @@
1
+ require 'set'
2
+
3
+ require 'power_strip/message'
4
+
5
+ module PowerStrip
6
+ class Channel
7
+ attr_reader :name, :sockets
8
+
9
+ def initialize(name, redis:)
10
+ @name = name
11
+ @redis = redis
12
+ @sockets = Set.new
13
+ end
14
+
15
+ def << socket
16
+ @sockets << socket
17
+ end
18
+
19
+ def delete socket
20
+ @sockets.delete socket
21
+ end
22
+
23
+ def send event, message
24
+ message = Message.new(
25
+ channel: name,
26
+ event: event,
27
+ data: message
28
+ )
29
+ @redis.publish :power_strip, message.to_json
30
+ self
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,24 @@
1
+ require 'power_strip/channel'
2
+
3
+ module PowerStrip
4
+ class ChannelList
5
+ def initialize(redis:)
6
+ @redis = redis
7
+ @channels = Hash.new do |hash, channel|
8
+ hash[channel.to_s] = Channel.new(channel, redis: redis)
9
+ end
10
+ end
11
+
12
+ def [] name
13
+ @channels[name.to_s]
14
+ end
15
+
16
+ def to_a
17
+ @channels.values
18
+ end
19
+
20
+ def delete channel_name
21
+ @channels.delete channel_name.to_s
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,12 @@
1
+ require 'grand_central/model'
2
+ require 'json'
3
+
4
+ module PowerStrip
5
+ class Message < GrandCentral::Model
6
+ attributes(:channel, :event, :data)
7
+
8
+ def to_json(*args)
9
+ to_h.to_json
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,3 @@
1
+ module PowerStrip
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,41 @@
1
+ require 'faye/websocket'
2
+ require 'grand_central/model'
3
+ require 'redis'
4
+ require 'set'
5
+ require 'json'
6
+
7
+ require 'power_strip/version'
8
+ require 'power_strip/app'
9
+
10
+ module PowerStrip
11
+ module_function
12
+
13
+ def call env
14
+ app.call env
15
+ end
16
+
17
+ def app
18
+ @app ||= App.instance
19
+ end
20
+
21
+ def start(**args)
22
+ @app = App.instance(**args)
23
+ @thread = Thread.new { app.listen }
24
+ end
25
+
26
+ def [] channel
27
+ app.channels[channel]
28
+ end
29
+
30
+ def on event_name, channel:, &block
31
+ app.on event_name, channel: channel, &block
32
+ end
33
+ end
34
+
35
+ begin
36
+ require 'opal'
37
+ Opal.append_path File.expand_path('../opal', __FILE__)
38
+ rescue
39
+ require 'sprockets'
40
+ Sprockets.append_path File.expand_path('../js', __FILE__)
41
+ end
@@ -0,0 +1,26 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'power_strip/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "power_strip"
8
+ spec.version = PowerStrip::VERSION
9
+ spec.authors = ["Jamie Gaskins"]
10
+ spec.email = ["jgaskins@gmail.com"]
11
+
12
+ spec.summary = %q{Push data from server to client with Ruby}
13
+ spec.homepage = "https://github.com/clearwater-rb/power_strip"
14
+
15
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
16
+ spec.bindir = "exe"
17
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_runtime_dependency "faye-websocket", "~> 0.10.4"
21
+ spec.add_runtime_dependency "grand_central"
22
+
23
+ spec.add_development_dependency "bundler", "~> 1.12"
24
+ spec.add_development_dependency "rake", "~> 10.0"
25
+ spec.add_development_dependency "rspec", "~> 3.0"
26
+ end
metadata ADDED
@@ -0,0 +1,129 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: power_strip
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jamie Gaskins
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-11-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faye-websocket
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.10.4
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.10.4
27
+ - !ruby/object:Gem::Dependency
28
+ name: grand_central
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: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.12'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.12'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ description:
84
+ email:
85
+ - jgaskins@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - ".rspec"
92
+ - ".travis.yml"
93
+ - CODE_OF_CONDUCT.md
94
+ - Gemfile
95
+ - README.md
96
+ - Rakefile
97
+ - bin/console
98
+ - bin/setup
99
+ - lib/power_strip.rb
100
+ - lib/power_strip/app.rb
101
+ - lib/power_strip/channel.rb
102
+ - lib/power_strip/channel_list.rb
103
+ - lib/power_strip/message.rb
104
+ - lib/power_strip/version.rb
105
+ - power_strip.gemspec
106
+ homepage: https://github.com/clearwater-rb/power_strip
107
+ licenses: []
108
+ metadata: {}
109
+ post_install_message:
110
+ rdoc_options: []
111
+ require_paths:
112
+ - lib
113
+ required_ruby_version: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ required_rubygems_version: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - ">="
121
+ - !ruby/object:Gem::Version
122
+ version: '0'
123
+ requirements: []
124
+ rubyforge_project:
125
+ rubygems_version: 2.5.1
126
+ signing_key:
127
+ specification_version: 4
128
+ summary: Push data from server to client with Ruby
129
+ test_files: []