communicator 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.
- data/.document +5 -0
- data/.gitignore +24 -0
- data/.rvmrc +1 -0
- data/Gemfile +3 -0
- data/Gemfile.lock +44 -0
- data/LICENSE +20 -0
- data/README.rdoc +83 -0
- data/Rakefile +100 -0
- data/VERSION +1 -0
- data/communicator.gemspec +106 -0
- data/db/migrate/20101101075419_create_inbound_messages.rb +13 -0
- data/db/migrate/20101101075719_create_outbound_messages.rb +13 -0
- data/lib/communicator/active_record_integration.rb +42 -0
- data/lib/communicator/client.rb +63 -0
- data/lib/communicator/inbound_message.rb +50 -0
- data/lib/communicator/outbound_message.rb +30 -0
- data/lib/communicator/server.rb +62 -0
- data/lib/communicator/tasks.rb +16 -0
- data/lib/communicator.rb +41 -0
- data/test/config.ru +16 -0
- data/test/factories.rb +11 -0
- data/test/helper.rb +47 -0
- data/test/lib/post.rb +7 -0
- data/test/lib/test_server_database/inbound_message.rb +4 -0
- data/test/lib/test_server_database/outbound_message.rb +4 -0
- data/test/lib/test_server_database/post.rb +4 -0
- data/test/migrate/20101101093519_create_posts.rb +13 -0
- data/test/test_client.rb +146 -0
- data/test/test_message_models.rb +68 -0
- data/test/test_server.rb +133 -0
- metadata +249 -0
data/.document
ADDED
data/.gitignore
ADDED
data/.rvmrc
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
rvm use 1.8.7
|
data/Gemfile
ADDED
data/Gemfile.lock
ADDED
@@ -0,0 +1,44 @@
|
|
1
|
+
PATH
|
2
|
+
remote: .
|
3
|
+
specs:
|
4
|
+
communicator (0.1.0)
|
5
|
+
activerecord (< 3.0.0)
|
6
|
+
httparty (>= 0.6.1)
|
7
|
+
json (>= 1.4.0)
|
8
|
+
sinatra (~> 1.1.0)
|
9
|
+
|
10
|
+
GEM
|
11
|
+
remote: http://rubygems.org/
|
12
|
+
specs:
|
13
|
+
activerecord (2.3.10)
|
14
|
+
activesupport (= 2.3.10)
|
15
|
+
activesupport (2.3.10)
|
16
|
+
crack (0.1.8)
|
17
|
+
factory_girl (1.3.2)
|
18
|
+
httparty (0.6.1)
|
19
|
+
crack (= 0.1.8)
|
20
|
+
json (1.4.6)
|
21
|
+
rack (1.2.1)
|
22
|
+
rack-test (0.5.6)
|
23
|
+
rack (>= 1.0)
|
24
|
+
shoulda (2.10.3)
|
25
|
+
sinatra (1.1.0)
|
26
|
+
rack (~> 1.1)
|
27
|
+
tilt (~> 1.1)
|
28
|
+
sqlite3-ruby (1.3.2)
|
29
|
+
tilt (1.1)
|
30
|
+
|
31
|
+
PLATFORMS
|
32
|
+
ruby
|
33
|
+
|
34
|
+
DEPENDENCIES
|
35
|
+
activerecord (< 3.0.0)
|
36
|
+
bundler (>= 1.0.0)
|
37
|
+
communicator!
|
38
|
+
factory_girl (>= 1.2.3)
|
39
|
+
httparty (>= 0.6.1)
|
40
|
+
json (>= 1.4.0)
|
41
|
+
rack-test (>= 0.5.6)
|
42
|
+
shoulda (= 2.10.3)
|
43
|
+
sinatra (~> 1.1.0)
|
44
|
+
sqlite3-ruby (>= 1.3.0)
|
data/LICENSE
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
Copyright (c) 2010 Capita Unternehmensberatung GmbH
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
4
|
+
a copy of this software and associated documentation files (the
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
9
|
+
the following conditions:
|
10
|
+
|
11
|
+
The above copyright notice and this permission notice shall be
|
12
|
+
included in all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.rdoc
ADDED
@@ -0,0 +1,83 @@
|
|
1
|
+
= communicator
|
2
|
+
|
3
|
+
A simple communication layer to keep database records in sync between two
|
4
|
+
Rails apps.
|
5
|
+
|
6
|
+
== Setup
|
7
|
+
|
8
|
+
Install in Rails apps with:
|
9
|
+
|
10
|
+
gem 'communicator'
|
11
|
+
$ bundle install
|
12
|
+
|
13
|
+
Import rake tasks in your Rails.root/Rakefile:
|
14
|
+
|
15
|
+
require 'communicator/tasks'
|
16
|
+
|
17
|
+
Set up the database tables for the messages by importing the corresponding
|
18
|
+
migrations from the gem:
|
19
|
+
|
20
|
+
$ rake communicator:update_migrations
|
21
|
+
$ rake db:migrate
|
22
|
+
|
23
|
+
After doing these steps, you can proceed to configure either the server or client
|
24
|
+
side as specified in the following subsections.
|
25
|
+
|
26
|
+
== Server side
|
27
|
+
|
28
|
+
On the server side, you can mount the server component in a Rails 2.3 app
|
29
|
+
as a rack middleware inside environment.rb:
|
30
|
+
|
31
|
+
require 'communicator'
|
32
|
+
Communicator::Server.username = 'foo'
|
33
|
+
Communicator::Server.password = 'bar'
|
34
|
+
config.middleware.use 'Communicator::Server'
|
35
|
+
|
36
|
+
It will then be mounted at /messages.json for GET and POST requests, requesting
|
37
|
+
HTTP Basic Auth with the configured credentials.
|
38
|
+
|
39
|
+
== Client side
|
40
|
+
|
41
|
+
Tell the client the server url and port as well as the auth credentials inside
|
42
|
+
your environment.rb:
|
43
|
+
|
44
|
+
require 'communicator'
|
45
|
+
Communicator::Client.username = 'test'
|
46
|
+
Communicator::Client.password = 'test'
|
47
|
+
Communicator::Client.base_uri 'localhost:3001'
|
48
|
+
|
49
|
+
When everything's fine, you should be able to push and pull using the client:
|
50
|
+
|
51
|
+
Communicator::Client.push
|
52
|
+
Communicator::Client.pull
|
53
|
+
|
54
|
+
== Active Record integration
|
55
|
+
|
56
|
+
To keep models in sync, specify the model class (in underscored type) the local
|
57
|
+
class receives updates from like this:
|
58
|
+
|
59
|
+
class Post < ActiveRecord::Base
|
60
|
+
receives_from :post
|
61
|
+
end
|
62
|
+
|
63
|
+
Use the automatically added `publish` instance method on your models to push changes
|
64
|
+
to the other side. They will be enqueued in the local `outbound_messages` table and
|
65
|
+
will arrive at the other side when a client pulls or pushes.
|
66
|
+
|
67
|
+
When an update is received from a remote side, the message will be stored in
|
68
|
+
`inbound_messages` and the received changes will be applied to the local record,
|
69
|
+
either updating existing or creating new records.
|
70
|
+
|
71
|
+
== Note on Patches/Pull Requests
|
72
|
+
|
73
|
+
* Fork the project.
|
74
|
+
* Make your feature addition or bug fix.
|
75
|
+
* Add tests for it. This is important so I don't break it in a
|
76
|
+
future version unintentionally.
|
77
|
+
* Commit, do not mess with rakefile, version, or history.
|
78
|
+
(if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
|
79
|
+
* Send me a pull request. Bonus points for topic branches.
|
80
|
+
|
81
|
+
== Copyright
|
82
|
+
|
83
|
+
Copyright (c) 2010 Capita Unternehmensberatung GmbH. See LICENSE for details.
|
data/Rakefile
ADDED
@@ -0,0 +1,100 @@
|
|
1
|
+
require 'rubygems'
|
2
|
+
require 'rake'
|
3
|
+
|
4
|
+
begin
|
5
|
+
require 'jeweler'
|
6
|
+
Jeweler::Tasks.new do |gem|
|
7
|
+
gem.name = "communicator"
|
8
|
+
gem.summary = %Q{Data push/pull between apps with local inbound/outbound queue and easy publish/process interface}
|
9
|
+
gem.description = %Q{Data push/pull between apps with local inbound/outbound queue and easy publish/process interface}
|
10
|
+
gem.email = "christoph at olszowka de"
|
11
|
+
gem.homepage = "http://github.com/colszowka/communicator"
|
12
|
+
gem.authors = ["Christoph Olszowka"]
|
13
|
+
gem.add_dependency 'sinatra', "~> 1.1.0"
|
14
|
+
gem.add_dependency 'activerecord', "< 3.0.0"
|
15
|
+
gem.add_dependency 'httparty', '>= 0.6.1'
|
16
|
+
gem.add_dependency 'json', '>= 1.4.0'
|
17
|
+
|
18
|
+
gem.add_development_dependency "shoulda", "2.10.3"
|
19
|
+
gem.add_development_dependency 'factory_girl', ">= 1.2.3"
|
20
|
+
gem.add_development_dependency 'rack-test', ">= 0.5.6"
|
21
|
+
gem.add_development_dependency 'bundler', ">= 1.0.0"
|
22
|
+
gem.add_development_dependency 'sqlite3-ruby', ">= 1.3.0"
|
23
|
+
# gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
|
24
|
+
end
|
25
|
+
Jeweler::GemcutterTasks.new
|
26
|
+
rescue LoadError
|
27
|
+
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
|
28
|
+
end
|
29
|
+
|
30
|
+
|
31
|
+
|
32
|
+
namespace :db do
|
33
|
+
desc "Drop, create and migrate the test databases"
|
34
|
+
task :migrate do
|
35
|
+
require 'active_record'
|
36
|
+
# Drop existing db
|
37
|
+
system "rm db/*.sqlite3"
|
38
|
+
dev_null = File.new('/dev/null', 'w')
|
39
|
+
ActiveRecord::Base.logger = Logger.new(dev_null)
|
40
|
+
ActiveRecord::Migration.verbose = false
|
41
|
+
|
42
|
+
# Create and migrate test databases for server and client
|
43
|
+
%w(test_client test_server).each do |db_name|
|
44
|
+
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => "db/#{db_name}.sqlite3")
|
45
|
+
ActiveRecord::Migrator.migrate('db/migrate')
|
46
|
+
ActiveRecord::Migrator.migrate('test/migrate')
|
47
|
+
end
|
48
|
+
end
|
49
|
+
end
|
50
|
+
|
51
|
+
namespace :test_server do
|
52
|
+
desc "Starts the test server"
|
53
|
+
task :start do
|
54
|
+
Thread.new do
|
55
|
+
# Capture sinatra output (to hide it away...)
|
56
|
+
require "open3"
|
57
|
+
Open3.popen3("bundle exec rackup test/config.ru -p 20359 --pid=#{File.join(File.dirname(__FILE__), 'test', 'rack.pid')}")
|
58
|
+
end
|
59
|
+
sleep 2.0
|
60
|
+
|
61
|
+
Kernel.at_exit do
|
62
|
+
Rake::Task["test_server:stop"].invoke
|
63
|
+
end
|
64
|
+
end
|
65
|
+
|
66
|
+
desc "Stops the test server"
|
67
|
+
task :stop do
|
68
|
+
begin
|
69
|
+
pid = File.read(File.join(File.dirname(__FILE__), 'test', 'rack.pid')).strip.chomp
|
70
|
+
`kill -s KILL #{pid}`
|
71
|
+
puts "Killed test server with PID #{pid}"
|
72
|
+
rescue => err
|
73
|
+
puts "Nothing to stop..."
|
74
|
+
end
|
75
|
+
end
|
76
|
+
end
|
77
|
+
|
78
|
+
require 'rake/testtask'
|
79
|
+
Rake::TestTask.new(:test) do |test|
|
80
|
+
test.libs << 'lib' << 'test'
|
81
|
+
test.pattern = 'test/**/test_*.rb'
|
82
|
+
test.verbose = true
|
83
|
+
end
|
84
|
+
|
85
|
+
task :test => :check_dependencies
|
86
|
+
# Make sure database and test server are in place when tests start
|
87
|
+
task :test => :"db:migrate"
|
88
|
+
task :test => :"test_server:start"
|
89
|
+
|
90
|
+
task :default => :test
|
91
|
+
|
92
|
+
require 'rake/rdoctask'
|
93
|
+
Rake::RDocTask.new do |rdoc|
|
94
|
+
version = File.exist?('VERSION') ? File.read('VERSION') : ""
|
95
|
+
|
96
|
+
rdoc.rdoc_dir = 'rdoc'
|
97
|
+
rdoc.title = "communicator #{version}"
|
98
|
+
rdoc.rdoc_files.include('README*')
|
99
|
+
rdoc.rdoc_files.include('lib/**/*.rb')
|
100
|
+
end
|
data/VERSION
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
0.1.0
|
@@ -0,0 +1,106 @@
|
|
1
|
+
# Generated by jeweler
|
2
|
+
# DO NOT EDIT THIS FILE DIRECTLY
|
3
|
+
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
|
4
|
+
# -*- encoding: utf-8 -*-
|
5
|
+
|
6
|
+
Gem::Specification.new do |s|
|
7
|
+
s.name = %q{communicator}
|
8
|
+
s.version = "0.1.0"
|
9
|
+
|
10
|
+
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
|
11
|
+
s.authors = ["Christoph Olszowka"]
|
12
|
+
s.date = %q{2010-11-03}
|
13
|
+
s.description = %q{Data push/pull between apps with local inbound/outbound queue and easy publish/process interface}
|
14
|
+
s.email = %q{christoph at olszowka de}
|
15
|
+
s.extra_rdoc_files = [
|
16
|
+
"LICENSE",
|
17
|
+
"README.rdoc"
|
18
|
+
]
|
19
|
+
s.files = [
|
20
|
+
".document",
|
21
|
+
".gitignore",
|
22
|
+
".rvmrc",
|
23
|
+
"Gemfile",
|
24
|
+
"Gemfile.lock",
|
25
|
+
"LICENSE",
|
26
|
+
"README.rdoc",
|
27
|
+
"Rakefile",
|
28
|
+
"VERSION",
|
29
|
+
"communicator.gemspec",
|
30
|
+
"db/migrate/20101101075419_create_inbound_messages.rb",
|
31
|
+
"db/migrate/20101101075719_create_outbound_messages.rb",
|
32
|
+
"lib/communicator.rb",
|
33
|
+
"lib/communicator/active_record_integration.rb",
|
34
|
+
"lib/communicator/client.rb",
|
35
|
+
"lib/communicator/inbound_message.rb",
|
36
|
+
"lib/communicator/outbound_message.rb",
|
37
|
+
"lib/communicator/server.rb",
|
38
|
+
"lib/communicator/tasks.rb",
|
39
|
+
"test/config.ru",
|
40
|
+
"test/factories.rb",
|
41
|
+
"test/helper.rb",
|
42
|
+
"test/lib/post.rb",
|
43
|
+
"test/lib/test_server_database/inbound_message.rb",
|
44
|
+
"test/lib/test_server_database/outbound_message.rb",
|
45
|
+
"test/lib/test_server_database/post.rb",
|
46
|
+
"test/migrate/20101101093519_create_posts.rb",
|
47
|
+
"test/test_client.rb",
|
48
|
+
"test/test_message_models.rb",
|
49
|
+
"test/test_server.rb"
|
50
|
+
]
|
51
|
+
s.homepage = %q{http://github.com/colszowka/communicator}
|
52
|
+
s.rdoc_options = ["--charset=UTF-8"]
|
53
|
+
s.require_paths = ["lib"]
|
54
|
+
s.rubygems_version = %q{1.3.7}
|
55
|
+
s.summary = %q{Data push/pull between apps with local inbound/outbound queue and easy publish/process interface}
|
56
|
+
s.test_files = [
|
57
|
+
"test/factories.rb",
|
58
|
+
"test/helper.rb",
|
59
|
+
"test/lib/post.rb",
|
60
|
+
"test/lib/test_server_database/inbound_message.rb",
|
61
|
+
"test/lib/test_server_database/outbound_message.rb",
|
62
|
+
"test/lib/test_server_database/post.rb",
|
63
|
+
"test/migrate/20101101093519_create_posts.rb",
|
64
|
+
"test/test_client.rb",
|
65
|
+
"test/test_message_models.rb",
|
66
|
+
"test/test_server.rb"
|
67
|
+
]
|
68
|
+
|
69
|
+
if s.respond_to? :specification_version then
|
70
|
+
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
|
71
|
+
s.specification_version = 3
|
72
|
+
|
73
|
+
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
|
74
|
+
s.add_runtime_dependency(%q<sinatra>, ["~> 1.1.0"])
|
75
|
+
s.add_runtime_dependency(%q<activerecord>, ["< 3.0.0"])
|
76
|
+
s.add_runtime_dependency(%q<httparty>, [">= 0.6.1"])
|
77
|
+
s.add_runtime_dependency(%q<json>, [">= 1.4.0"])
|
78
|
+
s.add_development_dependency(%q<shoulda>, ["= 2.10.3"])
|
79
|
+
s.add_development_dependency(%q<factory_girl>, [">= 1.2.3"])
|
80
|
+
s.add_development_dependency(%q<rack-test>, [">= 0.5.6"])
|
81
|
+
s.add_development_dependency(%q<bundler>, [">= 1.0.0"])
|
82
|
+
s.add_development_dependency(%q<sqlite3-ruby>, [">= 1.3.0"])
|
83
|
+
else
|
84
|
+
s.add_dependency(%q<sinatra>, ["~> 1.1.0"])
|
85
|
+
s.add_dependency(%q<activerecord>, ["< 3.0.0"])
|
86
|
+
s.add_dependency(%q<httparty>, [">= 0.6.1"])
|
87
|
+
s.add_dependency(%q<json>, [">= 1.4.0"])
|
88
|
+
s.add_dependency(%q<shoulda>, ["= 2.10.3"])
|
89
|
+
s.add_dependency(%q<factory_girl>, [">= 1.2.3"])
|
90
|
+
s.add_dependency(%q<rack-test>, [">= 0.5.6"])
|
91
|
+
s.add_dependency(%q<bundler>, [">= 1.0.0"])
|
92
|
+
s.add_dependency(%q<sqlite3-ruby>, [">= 1.3.0"])
|
93
|
+
end
|
94
|
+
else
|
95
|
+
s.add_dependency(%q<sinatra>, ["~> 1.1.0"])
|
96
|
+
s.add_dependency(%q<activerecord>, ["< 3.0.0"])
|
97
|
+
s.add_dependency(%q<httparty>, [">= 0.6.1"])
|
98
|
+
s.add_dependency(%q<json>, [">= 1.4.0"])
|
99
|
+
s.add_dependency(%q<shoulda>, ["= 2.10.3"])
|
100
|
+
s.add_dependency(%q<factory_girl>, [">= 1.2.3"])
|
101
|
+
s.add_dependency(%q<rack-test>, [">= 0.5.6"])
|
102
|
+
s.add_dependency(%q<bundler>, [">= 1.0.0"])
|
103
|
+
s.add_dependency(%q<sqlite3-ruby>, [">= 1.3.0"])
|
104
|
+
end
|
105
|
+
end
|
106
|
+
|
@@ -0,0 +1,13 @@
|
|
1
|
+
class CreateInboundMessages < ActiveRecord::Migration
|
2
|
+
def self.up
|
3
|
+
create_table :inbound_messages do |t|
|
4
|
+
t.text :body, :null => false
|
5
|
+
t.datetime :processed_at, :default => nil
|
6
|
+
t.timestamps
|
7
|
+
end
|
8
|
+
end
|
9
|
+
|
10
|
+
def self.down
|
11
|
+
drop_table :inbound_messages
|
12
|
+
end
|
13
|
+
end
|
@@ -0,0 +1,13 @@
|
|
1
|
+
class CreateOutboundMessages < ActiveRecord::Migration
|
2
|
+
def self.up
|
3
|
+
create_table :outbound_messages do |t|
|
4
|
+
t.text :body, :null => false
|
5
|
+
t.datetime :delivered_at, :default => nil
|
6
|
+
t.timestamps
|
7
|
+
end
|
8
|
+
end
|
9
|
+
|
10
|
+
def self.down
|
11
|
+
drop_table :outbound_messages
|
12
|
+
end
|
13
|
+
end
|
@@ -0,0 +1,42 @@
|
|
1
|
+
# ActiveRecord hooks for Communicator
|
2
|
+
module Communicator::ActiveRecordIntegration
|
3
|
+
module ClassMethods
|
4
|
+
# Class method to register as a communicator receiver
|
5
|
+
#
|
6
|
+
# Usage (assuming you expect messages from "post"):
|
7
|
+
# class Post < ActiveRecord::Base
|
8
|
+
# receives_from :post
|
9
|
+
# end
|
10
|
+
#
|
11
|
+
def receives_from(source)
|
12
|
+
Communicator.register_receiver(self, source)
|
13
|
+
end
|
14
|
+
end
|
15
|
+
|
16
|
+
# Instance methods that are to be mixed in to receiver classes
|
17
|
+
module InstanceMethods
|
18
|
+
# Instance variable to store whether this instance has been updated from remote message
|
19
|
+
attr_accessor :updated_from_message
|
20
|
+
|
21
|
+
# Publishes this instance as an OutboundMessage with json representation as body
|
22
|
+
def publish
|
23
|
+
Communicator::OutboundMessage.create!(:body => {self.class.to_s.underscore => attributes}.to_json)
|
24
|
+
end
|
25
|
+
|
26
|
+
# Processes the given message body by applying all contained attributes and their values
|
27
|
+
# and saving
|
28
|
+
def process_message(input)
|
29
|
+
# When the input is still json, parse it. Otherwise we're assuming it's already a demarshalled hash
|
30
|
+
input = JSON.parse(input) if input.kind_of?(String)
|
31
|
+
input.each do |attr_name, value|
|
32
|
+
self.send("#{attr_name}=", value)
|
33
|
+
end
|
34
|
+
self.updated_from_message = true
|
35
|
+
save!
|
36
|
+
end
|
37
|
+
end
|
38
|
+
end
|
39
|
+
|
40
|
+
# Include class methods into active record base
|
41
|
+
ActiveRecord::Base.send :extend, Communicator::ActiveRecordIntegration::ClassMethods
|
42
|
+
|
@@ -0,0 +1,63 @@
|
|
1
|
+
require 'httparty'
|
2
|
+
class Communicator::Client
|
3
|
+
class ServerError < StandardError; end;
|
4
|
+
class AuthError < StandardError; end;
|
5
|
+
class InvalidStartingId < StandardError; end;
|
6
|
+
|
7
|
+
include HTTParty
|
8
|
+
|
9
|
+
class << self
|
10
|
+
attr_writer :username, :password
|
11
|
+
# Return configured username for http auth basic or raise an error message if not configured
|
12
|
+
def username
|
13
|
+
@username || raise(Communicator::MissingCredentials.new("No Username specified for HTTP AUTH. Please configure using Communicator::Client.username='xyz'"))
|
14
|
+
end
|
15
|
+
|
16
|
+
# Return configured password for http auth basic or raise an error message if not configured
|
17
|
+
def password
|
18
|
+
@password || raise(Communicator::MissingCredentials.new("No Password specified for HTTP AUTH. Please configure using Communicator::Client.password='xyz'"))
|
19
|
+
end
|
20
|
+
|
21
|
+
# Helper for basic auth in httparty-expected format for request options
|
22
|
+
def credentials
|
23
|
+
{:username => username, :password => password}
|
24
|
+
end
|
25
|
+
|
26
|
+
def pull
|
27
|
+
request = get('/messages.json', :query => {:from_id => Communicator::InboundMessage.last_id+1}, :basic_auth => credentials)
|
28
|
+
verify_response request.response
|
29
|
+
Communicator::InboundMessage.create_from_json_collection!(JSON.parse(request.parsed_response))
|
30
|
+
request
|
31
|
+
end
|
32
|
+
|
33
|
+
def push(from_id=nil)
|
34
|
+
messages = Communicator::OutboundMessage.delivery_collection(from_id)
|
35
|
+
request = post("/messages.json", :body => messages.map(&:payload).to_json, :basic_auth => credentials)
|
36
|
+
verify_response request.response
|
37
|
+
# Everything went fine? Mark the messages as delivered
|
38
|
+
messages.each {|m| m.delivered! }
|
39
|
+
request
|
40
|
+
|
41
|
+
# Retry when server sent a from_id expectation
|
42
|
+
rescue Communicator::Client::InvalidStartingId => err
|
43
|
+
unless from_id
|
44
|
+
push(request.response.body)
|
45
|
+
else
|
46
|
+
raise "Could not agree upon from_id with server!"
|
47
|
+
end
|
48
|
+
end
|
49
|
+
|
50
|
+
def verify_response(response)
|
51
|
+
if response.kind_of?(Net::HTTPSuccess)
|
52
|
+
return true
|
53
|
+
elsif response.kind_of?(Net::HTTPUnauthorized) or response.kind_of?(Net::HTTPForbidden)
|
54
|
+
raise Communicator::Client::AuthError.new("Failed to authenticate!")
|
55
|
+
elsif response.kind_of?(Net::HTTPConflict)
|
56
|
+
raise Communicator::Client::InvalidStartingId.new("Expected from_id to begin with #{response.body.strip.chomp}")
|
57
|
+
elsif response.kind_of?(Net::HTTPServerError)
|
58
|
+
raise Communicator::Client::ServerError.new("Request failed with #{response.class}")
|
59
|
+
end
|
60
|
+
end
|
61
|
+
end
|
62
|
+
|
63
|
+
end
|
@@ -0,0 +1,50 @@
|
|
1
|
+
class Communicator::InboundMessage < ActiveRecord::Base
|
2
|
+
set_table_name 'inbound_messages'
|
3
|
+
|
4
|
+
validates_presence_of :body
|
5
|
+
|
6
|
+
named_scope :unpublished, :conditions => {:processed_at => nil}
|
7
|
+
default_scope :order => "id ASC"
|
8
|
+
|
9
|
+
# Process messages that have been stored locally successfully
|
10
|
+
after_create do |r|
|
11
|
+
r.process!
|
12
|
+
end
|
13
|
+
|
14
|
+
# Creates an inbound message from a remote json hash
|
15
|
+
def self.create_from_json!(json_message)
|
16
|
+
inbound_msg = Communicator::InboundMessage.new(:body => json_message["body"])
|
17
|
+
inbound_msg.id = json_message["id"]
|
18
|
+
inbound_msg.save!
|
19
|
+
inbound_msg
|
20
|
+
end
|
21
|
+
|
22
|
+
# Expects an already demarshalled collection array containing remote message data, which
|
23
|
+
# will then all be processed indivdually using create_from_json!
|
24
|
+
def self.create_from_json_collection!(json_messages)
|
25
|
+
json_messages.map {|json_message| create_from_json!(json_message) }
|
26
|
+
end
|
27
|
+
|
28
|
+
# Find the last ID present locally
|
29
|
+
def self.last_id
|
30
|
+
count > 0 ? find(:first, :order => 'id DESC').id : 0
|
31
|
+
end
|
32
|
+
|
33
|
+
# Checks whether the given id is properly in line with the local last id
|
34
|
+
# The check will only be actually performed when there are any locally stored inbound messages
|
35
|
+
def self.valid_next_id?(from_id)
|
36
|
+
Communicator::InboundMessage.count == 0 or from_id.to_i == Communicator::InboundMessage.last_id + 1
|
37
|
+
end
|
38
|
+
|
39
|
+
def message_content
|
40
|
+
JSON.parse(body).with_indifferent_access
|
41
|
+
end
|
42
|
+
|
43
|
+
# Figure out who is the receiver of this message and process the message
|
44
|
+
def process!
|
45
|
+
source, message = JSON.parse(body).first
|
46
|
+
Communicator.receiver_for(source).find_or_initialize_by_id(message["id"]).process_message(message)
|
47
|
+
self.processed_at = Time.now
|
48
|
+
self.save!
|
49
|
+
end
|
50
|
+
end
|
@@ -0,0 +1,30 @@
|
|
1
|
+
class Communicator::OutboundMessage < ActiveRecord::Base
|
2
|
+
set_table_name "outbound_messages"
|
3
|
+
validates_presence_of :body
|
4
|
+
|
5
|
+
named_scope :undelivered, :conditions => {:delivered_at => nil}
|
6
|
+
default_scope :order => "id ASC"
|
7
|
+
|
8
|
+
# Returns an array of all undelivered messages. If the optional id is given
|
9
|
+
# will instead start from that id, not taking care whether the messages have
|
10
|
+
# already been marked as delivered.
|
11
|
+
def self.delivery_collection(from_id=nil)
|
12
|
+
(from_id ? all(:conditions => ["id >= ?", from_id]) : undelivered)
|
13
|
+
end
|
14
|
+
|
15
|
+
# Stripped down content hash for json delivery
|
16
|
+
def payload
|
17
|
+
{:id => id, :body => body}
|
18
|
+
end
|
19
|
+
|
20
|
+
# Will return the JSON-parsed content of this message's body
|
21
|
+
def message_content
|
22
|
+
JSON.parse(body).with_indifferent_access
|
23
|
+
end
|
24
|
+
|
25
|
+
# Set the delivered_at flag to NOW and save!
|
26
|
+
def delivered!
|
27
|
+
self.delivered_at = Time.now
|
28
|
+
self.save!
|
29
|
+
end
|
30
|
+
end
|
@@ -0,0 +1,62 @@
|
|
1
|
+
require 'sinatra'
|
2
|
+
|
3
|
+
class Communicator::Server < Sinatra::Base
|
4
|
+
# Configuration parameters
|
5
|
+
class << self
|
6
|
+
attr_writer :username, :password
|
7
|
+
|
8
|
+
# Return configured username for http auth basic or raise an error message if not configured
|
9
|
+
def username
|
10
|
+
@username || raise("No Username specified for HTTP AUTH. Please configure using Communicator::Server.username='xyz'")
|
11
|
+
end
|
12
|
+
|
13
|
+
# Return configured password for http auth basic or raise an error message if not configured
|
14
|
+
def password
|
15
|
+
@password || raise("No Password specified for HTTP AUTH. Please configure using Communicator::Server.password='xyz'")
|
16
|
+
end
|
17
|
+
end
|
18
|
+
|
19
|
+
use Rack::Auth::Basic do |username, password|
|
20
|
+
[username, password] == [Communicator::Server.username, Communicator::Server.password]
|
21
|
+
end
|
22
|
+
|
23
|
+
# PULL
|
24
|
+
get '/messages.json' do
|
25
|
+
# Require from_id attribute
|
26
|
+
return [409, "Specify from_id!"] unless params[:from_id]
|
27
|
+
|
28
|
+
# from_id is irrelevant when no messages are present
|
29
|
+
params[:from_id] = nil if Communicator::OutboundMessage.count == 0
|
30
|
+
|
31
|
+
# Fetch the messages and build the json
|
32
|
+
messages = Communicator::OutboundMessage.delivery_collection(params[:from_id])
|
33
|
+
json = messages.map(&:payload).to_json
|
34
|
+
# Flag the messages as delivered
|
35
|
+
messages.each {|m| m.delivered! }
|
36
|
+
# Collect the message payloads and render them as json
|
37
|
+
[200, json]
|
38
|
+
end
|
39
|
+
|
40
|
+
# PUSH
|
41
|
+
post '/messages.json' do
|
42
|
+
body = request.body.read.strip
|
43
|
+
# Make sure a message body is given!
|
44
|
+
return [409, "No data given"] if body.length < 2
|
45
|
+
# Parse json
|
46
|
+
json_messages = JSON.parse(body)
|
47
|
+
|
48
|
+
# If no messages present, just return
|
49
|
+
return [202, "No data given"] unless json_messages.length > 0
|
50
|
+
|
51
|
+
# Make sure the first id does directly follow the last one present locally - but only if we already have ANY messages
|
52
|
+
# On failure, render HTTPConflicht and expected from_id
|
53
|
+
return [409, (Communicator::InboundMessage.last_id + 1).to_s] unless Communicator::InboundMessage.valid_next_id?(json_messages.first["id"])
|
54
|
+
|
55
|
+
# Everything's fine? Let's store messages!
|
56
|
+
Communicator::InboundMessage.create_from_json_collection!(json_messages)
|
57
|
+
|
58
|
+
202 # ACCEPTED
|
59
|
+
end
|
60
|
+
end
|
61
|
+
|
62
|
+
require 'pp'
|