-
Notifications
You must be signed in to change notification settings - Fork 42
/
client_drivers.rb
271 lines (237 loc) · 9.98 KB
/
client_drivers.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#### this is going to need some refactoring so that HyperMesh can add its methods in here...
module Hyperstack
# Client side handling of synchronization messages
# When a synchronization message comes in, the client will sync_dispatch
# We use ERB to determine the configuration and implement the appropriate
# client interface to sync_change or sync_destroy
def self.anti_csrf_token
ClientDrivers.opts[:form_authenticity_token]
end
class Application
extend Component::IsomorphicHelpers::ClassMethods
if on_opal_client?
def self.acting_user_id
ClientDrivers.opts[:acting_user_id]
end
else
def self.acting_user_id
ClientDrivers.client_drivers_get_acting_user_id
end
end
def self.env
@env = ClientDrivers.env unless @env
@env
end
def self.production?
env == 'production'
end
end
if RUBY_ENGINE == 'opal'
def self.connect(*channels)
channels.each do |channel|
if channel.is_a? Class
IncomingBroadcast.connect_to(channel.name)
elsif channel.is_a?(String) || channel.is_a?(Array)
IncomingBroadcast.connect_to(*channel)
elsif channel.id
IncomingBroadcast.connect_to(channel.class.name, channel.id)
else
raise "cannot connect to model before it has been saved"
end
end
end
def self.connect_session
connect(['Hyperstack::Session', ClientDrivers.opts[:id].split('-').last])
end
def self.action_cable_consumer
ClientDrivers.opts[:action_cable_consumer]
end
class IncomingBroadcast
def self.open_channels
@open_channels ||= Set.new
end
def self.add_connection(channel_name, id = nil)
channel_string = "#{channel_name}#{'-'+id.to_s if id}"
open_channels << channel_string
channel_string
end
def self.connect_to(channel_name, id = nil)
channel_string = add_connection(channel_name, id)
if ClientDrivers.opts[:transport] == :pusher
channel = "#{ClientDrivers.opts[:channel]}-#{channel_string}"
%x{
var channel = #{ClientDrivers.opts[:pusher_api]}.subscribe(#{channel.gsub('::', '==')});
channel.bind('dispatch', #{ClientDrivers.opts[:dispatch]})
channel.bind('pusher:subscription_succeeded', #{lambda {ClientDrivers.get_queued_data("connect-to-transport", channel_string)}})
}
elsif ClientDrivers.opts[:transport] == :action_cable
channel = "#{ClientDrivers.opts[:channel]}-#{channel_string}"
Hyperstack::HTTP.post(ClientDrivers.polling_path('action-cable-auth', channel), headers: { 'X-CSRF-Token' => ClientDrivers.opts[:form_authenticity_token] }).then do |response|
%x{
var fix_opal_0110 = 'return';
#{Hyperstack.action_cable_consumer}.subscriptions.create(
{
channel: "Hyperstack::ActionCableChannel",
client_id: #{ClientDrivers.opts[:id]},
hyperstack_channel: #{channel_string},
authorization: #{response.json[:authorization]},
salt: #{response.json[:salt]}
},
{
connected: function() {
if (#{ClientDrivers.env == 'development'}) { console.log("ActionCable connected to: ", channel_string); }
#{ClientDrivers.complete_connection(channel_string)}
},
received: function(data) {
if (#{ClientDrivers.env == 'development'}) { console.log("ActionCable received: ", data); }
#{ClientDrivers.sync_dispatch(JSON.parse(`JSON.stringify(data)`)['data'])}
}
}
)
}
end
else
Hyperstack::HTTP.get(ClientDrivers.polling_path(:subscribe, channel_string))
end
end
end
end
class ClientDrivers
include Hyperstack::Component::IsomorphicHelpers
def self.sync_dispatch(data)
# TODO old synchromesh double checked at this point to make sure that this client
# expected to recieve from the channel the data was sent on. Was that really needed?
data[:operation].constantize.dispatch_from_server(data[:params])
end
# save the configuration info needed in window.HyperstackOpts
# we keep a list of all channels by session with connections in progress
# for each broadcast we check the list, and add the message to a queue for that
# session. When the client is informed that the connection has completed
# we call the server, this will return ALL the broadcasts (cool) and
# will remove the session from the list.
prerender_footer do |controller|
unless Hyperstack.transport == :none
if defined?(PusherFake)
path = ::Rails.application.routes.routes.detect do |route|
route.app == Hyperstack::Engine ||
(route.app.respond_to?(:app) && route.app.app == Hyperstack::Engine)
end.path.spec
pusher_fake_js = PusherFake.javascript(
auth: { headers: { 'X-CSRF-Token' => controller.send(:form_authenticity_token) } },
authEndpoint: "#{path}/hyperstack-pusher-auth"
)
end
controller.session.delete 'hyperstack-dummy-init' unless controller.session.id
id = "#{SecureRandom.uuid}-#{controller.session.id}"
auto_connections = Hyperstack::AutoConnect.channels(id, controller.acting_user) rescue []
end
config_hash = {
transport: Hyperstack.transport,
id: id,
acting_user_id: (controller.acting_user && controller.acting_user.id),
env: ::Rails.env,
client_logging: Hyperstack.client_logging,
pusher_fake_js: pusher_fake_js,
key: Hyperstack.key,
cluster: Hyperstack.cluster,
encrypted: Hyperstack.encrypted,
channel: Hyperstack.channel,
form_authenticity_token: controller.send(:form_authenticity_token),
seconds_between_poll: Hyperstack.seconds_between_poll,
auto_connect: auto_connections
}
path = ::Rails.application.routes.routes.detect do |route|
# not sure why the second check is needed. It happens in the test app
route.app == Hyperstack::Engine or (route.app.respond_to?(:app) and route.app.app == Hyperstack::Engine)
end
raise 'Hyperstack::Engine mount point not found. Check your config/routes.rb file' unless path
path = path.path.spec
"<script type='text/javascript'>\n"\
"window.HyperstackEnginePath = '#{path}';\n"\
"window.HyperstackOpts = #{config_hash.to_json}\n"\
"</script>\n"
end if RUBY_ENGINE != 'opal'
class << self
attr_reader :opts
end
isomorphic_method(:client_drivers_get_acting_user_id) do |f|
f.send_to_server if RUBY_ENGINE == 'opal'
f.when_on_server { (controller.acting_user && controller.acting_user.id) }
end
isomorphic_method(:env) do |f|
f.when_on_client { opts[:env] }
f.send_to_server
f.when_on_server { ::Rails.env }
end
def self.complete_connection(channel, retries = 10)
get_queued_data('connect-to-transport', channel).fail do
after(0.25) { complete_connection(channel, retries - 1) } unless retries.zero?
end
end
def self.get_queued_data(operation, channel = nil, opts = {})
Hyperstack::HTTP.get(polling_path(operation, channel), opts).then do |response|
response.json.each do |data|
`console.log("simple_poller received: ", data)` if ClientDrivers.env == 'development'
sync_dispatch(data[1])
end
end
end
def self.initialize_client_drivers_on_boot
if @initialized
# 1) skip initialization if already initialized
if on_opal_client? && Hyperstack.action_cable_consumer
# 2) if running action_cable make sure connection is up after pinging the server_up
# action cable closes the connection if files change on the server
Hyperstack::HTTP.get("#{`window.HyperstackEnginePath`}/server_up") do
`#{Hyperstack.action_cable_consumer}.connection.open()` if `#{Hyperstack.action_cable_consumer}.connection.disconnected`
end
end
return
end
@initialized = true
@opts = {}
if on_opal_client?
@opts = Hash.new(`window.HyperstackOpts`)
if opts[:transport] == :pusher
opts[:dispatch] = lambda do |data|
sync_dispatch JSON.parse(`JSON.stringify(#{data})`)
end
if opts[:client_logging] && `window.console && window.console.log`
`Pusher.log = function(message) {window.console.log(message);}`
end
if opts[:pusher_fake_js]
opts[:pusher_api] = `eval(#{opts[:pusher_fake_js]})`
else
h = nil
pusher_api = nil
%x{
h = {
encrypted: #{opts[:encrypted]},
cluster: #{opts[:cluster]},
authEndpoint: window.HyperstackEnginePath+'/hyperstack-pusher-auth',
auth: {headers: {'X-CSRF-Token': #{opts[:form_authenticity_token]}}}
};
pusher_api = new Pusher(#{opts[:key]}, h)
}
opts[:pusher_api] = pusher_api
end
Hyperstack.connect(*opts[:auto_connect])
elsif opts[:transport] == :action_cable
opts[:action_cable_consumer] =
`ActionCable.createConsumer.apply(ActionCable, #{[*opts[:action_cable_consumer_url]]})`
Hyperstack.connect(*opts[:auto_connect])
elsif opts[:transport] == :simple_poller
opts[:auto_connect].each { |channel| IncomingBroadcast.add_connection(*channel) }
every(opts[:seconds_between_poll]) do
get_queued_data(:read, nil)
end
end
end
end
def self.polling_path(to, id = nil)
s = "#{`window.HyperstackEnginePath`}/hyperstack-#{to}/#{opts[:id]}"
s = "#{s}/#{id}" if id
s
end
end
end