hyper-operation 1.0.alpha1.8 → 1.0.0.lap28

Sign up to get free protection for your applications and to get access to all the features.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +2 -7
  3. data/.travis.yml +9 -21
  4. data/CODE_OF_CONDUCT.md +49 -0
  5. data/DOCS-POLICIES.md +582 -0
  6. data/DOCS.md +869 -0
  7. data/Gemfile +1 -5
  8. data/LICENSE.txt +21 -0
  9. data/README.md +77 -0
  10. data/Rakefile +2 -1
  11. data/dciy.toml +3 -0
  12. data/hyper-operation.gemspec +15 -19
  13. data/lib/hyper-operation.rb +6 -10
  14. data/lib/hyper-operation/api.rb +4 -8
  15. data/lib/hyper-operation/boot.rb +2 -3
  16. data/lib/hyper-operation/delay_and_interval.rb +9 -0
  17. data/lib/hyper-operation/engine.rb +2 -2
  18. data/lib/hyper-operation/exception.rb +4 -30
  19. data/lib/hyper-operation/filters/acting_user.rb +1 -1
  20. data/lib/hyper-operation/http.rb +2 -2
  21. data/lib/hyper-operation/promise.rb +2 -32
  22. data/lib/hyper-operation/railway.rb +1 -1
  23. data/lib/hyper-operation/railway/dispatcher.rb +5 -8
  24. data/lib/hyper-operation/railway/params_wrapper.rb +2 -2
  25. data/lib/hyper-operation/railway/run.rb +49 -58
  26. data/lib/hyper-operation/railway/validations.rb +3 -10
  27. data/lib/hyper-operation/server_op.rb +20 -46
  28. data/lib/hyper-operation/transport/action_cable.rb +8 -8
  29. data/lib/hyper-operation/transport/client_drivers.rb +55 -96
  30. data/lib/hyper-operation/transport/connection.rb +136 -58
  31. data/lib/hyper-operation/transport/{hyperstack.rb → hyperloop.rb} +15 -28
  32. data/lib/hyper-operation/transport/{hyperstack_controller.rb → hyperloop_controller.rb} +53 -59
  33. data/lib/hyper-operation/transport/policy.rb +49 -50
  34. data/lib/hyper-operation/version.rb +2 -2
  35. data/lib/sources/{hyperstack → hyperloop}/pusher.js +0 -0
  36. metadata +73 -94
  37. data/lib/hyper-operation/async_sleep.rb +0 -23
  38. data/lib/hyper-operation/transport/connection_adapter/active_record.rb +0 -113
  39. data/lib/hyper-operation/transport/connection_adapter/active_record/auto_create.rb +0 -26
  40. data/lib/hyper-operation/transport/connection_adapter/active_record/connection.rb +0 -47
  41. data/lib/hyper-operation/transport/connection_adapter/active_record/queued_message.rb +0 -42
  42. data/lib/hyper-operation/transport/connection_adapter/redis.rb +0 -94
  43. data/lib/hyper-operation/transport/connection_adapter/redis/connection.rb +0 -85
  44. data/lib/hyper-operation/transport/connection_adapter/redis/queued_message.rb +0 -34
  45. data/lib/hyper-operation/transport/connection_adapter/redis/redis_record.rb +0 -158
  46. data/lib/hyper-operation/transport/policy_diagnostics.rb +0 -106
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 89a7c07b2cab1760bb41bcff159333e5ea985d8eca22329f4a39f7890d295e5f
4
- data.tar.gz: 5955718c34bba9f9af227ea92e0d0869a4f21c131deccd2ad2f0e707c97b8219
3
+ metadata.gz: d00d9782994ad17467b5727e4de407152824f59ef7efc8f35d279815b972387e
4
+ data.tar.gz: 8a5fec5f246395cd01bb9bf88d504191b128b2c380fd75df888c67fd63f2ee10
5
5
  SHA512:
6
- metadata.gz: 215aaf6fa7aa4084551d000b96a5dcf62c1839ff346fd8e0c75b6c66eea32274867e93eca3d1f485ccef0ed0f2cbc5e7442da994016a8446d49daa8156c51832
7
- data.tar.gz: 18944dce11ebdbd25616d2b4a0d7565ea2ddbbf033ba78f36608102220e95278433f4a7b5e4241032758fda4f5b7a5bec99cb6d1236501f4c6ee729b17bd2736
6
+ metadata.gz: 88c7f4e4fff15b2412f14c3c9eddc302ec40550c69ccbccbbf9b3f503b316acafd0ab441c7458cf0dac368e4109c952576245a62561947486cad3eaa28b9f1c6
7
+ data.tar.gz: d47e4290512aba19e747fa09135056220498248e0bb77a674a58d2b2b713bed6e7b0612a3f8c21abac09b5524dd668e673c9d1a95e17c166d69df9dd51098ce4
data/.gitignore CHANGED
@@ -5,14 +5,13 @@ capybara-*.html
5
5
  /tmp
6
6
  /db/*.sqlite3
7
7
  /db/*.sqlite3-journal
8
- /spec/test_app/db/*.sqlite3
9
- /spec/test_app/db/*.sqlite3-journal
10
8
  /public/system
11
9
  /coverage/
12
10
  /spec/tmp
13
11
  **.orig
14
12
  rerun.txt
15
13
  pickle-email-*.html
14
+ Gemfile.lock
16
15
 
17
16
  # TODO Comment out these rules if you are OK with secrets being uploaded to the repo
18
17
  config/initializers/secret_token.rb
@@ -52,8 +51,4 @@ bower.json
52
51
 
53
52
  .idea
54
53
  .vscode
55
- *.iml
56
-
57
- # ignore Gemfile.locks https://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
58
- /spec/test_app/Gemfile.lock
59
- /Gemfile.lock
54
+ *.iml
data/.travis.yml CHANGED
@@ -1,34 +1,22 @@
1
- dist: trusty
2
1
  language: ruby
3
- cache: bundler
4
2
  rvm:
5
- - 2.4.4
6
- - 2.5.1
7
- - ruby-head
3
+ - ruby
8
4
  services:
9
5
  - mysql
10
- - redis-server
11
6
  env:
12
- - DRIVER=google-chrome TZ=Europe/Berlin
13
- matrix:
14
- fast_finish: true
15
- allow_failures:
16
- - rvm: ruby-head
7
+ - HYPER_DEV_GEM_SOURCE="https://gems.ruby-hyperloop.org" TZ=Europe/Berlin
17
8
  before_install:
18
- - if [[ "$DRIVER" == "google-chrome" ]]; then wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -; fi
19
- - if [[ "$DRIVER" == "google-chrome" ]]; then echo "deb http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee /etc/apt/sources.list.d/google-chrome.list; fi
20
- - if [[ "$DRIVER" == "google-chrome" ]]; then sudo apt-get update -qq && sudo apt-get install -qq -y google-chrome-stable; fi
9
+ - sudo apt-get install -y fonts-liberation
10
+ - wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
11
+ - sudo dpkg -i google-chrome*.deb
21
12
  - gem install bundler
22
13
  before_script:
23
14
  - cd spec/test_app
24
- - bundle install --jobs=3 --retry=3
25
- - bundle exec rails db:setup
15
+ - bundle update
16
+ - rails db:setup
26
17
  - cd ../../
27
- - if [[ "$DRIVER" == "google-chrome" ]]; then bundle exec chromedriver-update; fi
28
- - if [[ "$DRIVER" == "google-chrome" ]]; then ls -lR ~/.chromedriver-helper/; fi
29
- - if [[ "$DRIVER" == "google-chrome" ]]; then bundle exec chromedriver --version; fi
30
- - if [[ "$DRIVER" == "google-chrome" ]]; then google-chrome --version; fi
31
- - if [[ "$DRIVER" == "google-chrome" ]]; then which google-chrome; fi
18
+ - chromedriver-update
19
+ - ls -lR ~/.chromedriver-helper/
32
20
  script: bundle exec rspec
33
21
  gemfile:
34
22
  - gemfiles/opal_0_11_react-rails_2_4.gemfile
@@ -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 mitch@catprint.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/DOCS-POLICIES.md ADDED
@@ -0,0 +1,582 @@
1
+ # Hyperloop Policies
2
+
3
+ ## Authorization
4
+
5
+ Access to your Isomorphic Models is controlled by *Policies* that describe how the current *acting_user* and *channels* may access your Models.
6
+
7
+ Each browser session has an *acting_user* (which may be nil) and you will define `create`, `update`, and `destroy` policies giving (or denying) the `acting_user` the ability to do these operations.
8
+
9
+ Read and *broadcast* access is defined based on *channels* which are connected based again on the current `acting_user`. Read access is initiated when a specific browser tries to read a record attribute, and broadcasts are initiated whenever a model changes.
10
+
11
+ An application can have several channels and each channel and each active record model can have different policies to determine which attributes are sent when a record changes.
12
+
13
+ For example a Todo application might have an *instance* of a channel for each currently logged in user; an instance of a channel for each team if that team has one or more logged in users; and a general `AdminUser` channel shared by all administrators that are logged in.
14
+
15
+ Lets say a specific `Todo` changes, which is part of team id 123's Todo list, and users 7 and 8 who are members of that team are currently logged in as well as two of the `AdminUsers`.
16
+
17
+ When the `Todo` changes we want all the attributes of the `Todo` broadcast on team 123's channel, as well on the `AdminUser`'s channel. Now lets say User 7 sends User 8 a private message, adding a new record to the `Message` model. This update should only be sent to user 7 and user 8's private channels, as well as to the AdminUser channel.
18
+
19
+ We can define all these policies by creating the following classes:
20
+
21
+ ```ruby
22
+ class UserPolicy # defines policies for the User class
23
+ # The regulate_instance_connections method enables instances of the User
24
+ # class to be treated as a channel.
25
+
26
+ # The policy is defined by a block that is executed in the context of the
27
+ # current acting_user.
28
+
29
+ # For our User instance connection the policy is that there must be a
30
+ # logged-in user, and the connection is made to that user:
31
+ regulate_instance_connections { self }
32
+ # If there is no logged in user self will be nil, and no connection will be
33
+ # made.
34
+ end
35
+
36
+ class TeamPolicy # defines policies for the Team class
37
+ # Users can only connect to Teams that they belong to
38
+ regulate_instance_connections { teams }
39
+ end
40
+
41
+ class AdminUserPolicy
42
+ # All AdminUsers share the same connection so we setup a class wide
43
+ # connection available to any users who are admins.
44
+ regulate_class_connection { admin? }
45
+
46
+ # The AdminUser channel will receive all attributes
47
+ # of all records, unless the attribute is named :password
48
+ regulate_all_broadcasts do |policy|
49
+ policy.send_all_but(:password)
50
+ end
51
+ end
52
+
53
+ class TodoPolicy
54
+ # Policies can be established for models that are not channels as well.
55
+
56
+ # The regulate_broadcast method will describe what attributes to send
57
+ # when a Todo model changes.
58
+
59
+ # The blocks of broadcast policies run in the context of the changed model
60
+ # so we have access to all the models methods. In this case Todo
61
+ # belongs to a Team through the 'team' relationship.
62
+ regulate_broadcast do |policy|
63
+ # send all Todo attributes to the todo's team channel
64
+ policy.send_all.to(team)
65
+ end
66
+ end
67
+
68
+ class MessagePolicy
69
+ # Broadcast policies can be arbitrarily complex. In this case we
70
+ # want to broadcast the entire message to the sender and the
71
+ # recipient's instance channels.
72
+ # In addition if the message is not private, then we want to send to all
73
+ # the team instance channels that are shared between the sender and
74
+ # recipient's teams.
75
+ regulate_broadcast do |policy|
76
+ policy.send_all.to(sender, recipient)
77
+ policy.send_all.to(sender.teams.merge(recipient.teams)) unless private?
78
+ end
79
+ end
80
+ ```
81
+
82
+ Before we begin using these channels and policies we need to first define the Reactive-Record `acting_user` method in our ApplicationController:
83
+
84
+ ```ruby
85
+ class ApplicationController < ActionController::Base
86
+ def acting_user
87
+ # The acting_user method should return nil, or some object that corresponds to a
88
+ # logged in user. Specifics will depend on your application and whatever other
89
+ # authentication mechanisms you are using.
90
+ @acting_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id])
91
+ end
92
+ end
93
+ end
94
+ ```
95
+
96
+ Note that `acting_user` is also used by ReactiveRecord's permission system.
97
+
98
+ Our entire set of policies is defined in 29 lines of code of which 8 actually execute the policies. Our existing classes form the foundation, and we simply add Hyperloop specific policy directives. Pretty sweet huh?
99
+
100
+ ### Details
101
+
102
+ Hyperloop uses *Policies* to *regulate* what *connections* are opened between clients and the server and what data is distributed over those connections.
103
+
104
+ Connections are made on *channels* of data flowing between the server and a number of clients. Each channel is associated with either a class or an instance of a class. Typically the channel class represents an entity (or is associated with an entity) that can be authenticated like a `User`, an `AdminUser`, or a `Team` of users. A channel associated with the class itself broadcasts data that is received by any member of that class. A channel associated with an instance is for data that is available only to that specific instance.
105
+
106
+ As Models on the server change (i.e. created, updated, or destroyed) the changes are broadcast over open channels. What specific attributes are sent (if any) is determined by broadcast policies.
107
+
108
+ Broadcast policies can be associated with Models. As the Model changes the broadcast policy will regulate what attributes of the changed model will be sent over which channels.
109
+
110
+ Broadcast policies can also be associated with a channel and will regulate *all* model changes over specific channels. In other words this is just a convenient way to associate a common policy with *all* Models.
111
+
112
+ Note that Models that are associated with channels can also broadcast their changes on the same or different channels.
113
+
114
+ #### Defining Policies and Policy Classes
115
+
116
+ The best way to define policies is to use a *Policy Class*. A policy class has the same class name as the class it is regulating, with `Policy` added to the end. Policy classes are compatible with `Pundit`, and you can add regular pundit policies as well.
117
+
118
+ Policies are defined using four methods:
119
+ + `regulate_class_connection` controls connections to the class channels,
120
+ + `regulate_instance_connections` controls connections to instance channels,
121
+ + `regulate_broadcast` controls what data will be sent when a model or object changes and,
122
+ + `regulate_all_broadcasts` controls what data will be sent of some channels when any model changes.
123
+
124
+ In addition `always_allow_connection` is short hand for `regulate_class_connection { true }`
125
+
126
+ A policy class can be defined for which there is no regulated class. This is useful for application wide connections, which are typically open even if no one is logged in:
127
+
128
+ ```ruby
129
+ #app/policies/application.rb
130
+ class ApplicationPolicy
131
+ regulate_class_connection { true }
132
+ end
133
+ ```
134
+
135
+ Note that by default policy classes go in the `app/policies` directory. Hyperloop will require all the files in this directory.
136
+
137
+ If you wish, you can also add policies directly in your Models by including the `Hyperloop::PolicyMethods` module in your model. You can then use the `regulate_class_connection`, `regulate_instance_connections`, `regulate_all_broadcasts` and `regulate_broadcast` methods directly in the model.
138
+
139
+ ```ruby
140
+ class User < ActiveRecord::Base
141
+ include Hyperloop::PolicyMethods
142
+ regulate_class_connection ...
143
+ regulate_instance_connections ...
144
+ regulate_all_broadcasts ...
145
+ regulate_broadcast ...
146
+ end
147
+ ```
148
+
149
+ Normally the policy methods are regulating the class with the prefix as the policy, but you can override this by providing specific class names to the policy method. This allows you to group several different class policies together, and to reuse policies:
150
+
151
+ ```ruby
152
+ class ApplicationPolicy
153
+ regulate_connection { ... } # Application is assumed
154
+ regulate_class_connection(User) { ... }
155
+ # regulate_class_connection, regulate_instance_connections and
156
+ # regulate_all_broadcasts can take a list of channels.
157
+ regulate_all_broadcasts(User, Application)
158
+ # regulate_broadcast takes a list of object classes which
159
+ # may also be channels.
160
+ regulate_broadcast(Todo, Message, User) { ... }
161
+ end
162
+ ```
163
+
164
+ #### Channels and connection policies
165
+
166
+ Any ruby class that has a connection policy is a Hyperloop channel. The fully scoped name of the class becomes the root of the channel name.
167
+
168
+ The purpose of having channels is to restrict what gets broadcast when models change, therefore typically channels represent *connections* to
169
+
170
+ + the application, or some function within the application
171
+ + or some class which is *authenticated* like a User or Administrator,
172
+ + instances of those classes,
173
+ + or instances of related classes.
174
+
175
+ So a channel that is connected to the User class would get information readable by any logged-in user, while a channel that is connected to a specific User instance would get information readable by that specific user.
176
+
177
+ The `regulate_class_connection` takes a block that will execute in the context of the current acting_user (which may be nil), and if the block returns any truthy value, the connection will be made.
178
+
179
+ The `regulate_instance_connections` likewise takes a block that is executed in the context of the current acting_user. The block may do one of following:
180
+
181
+ + raise an error meaning the connection cannot be made
182
+ + return a falsy value also meaning the connection cannot be made
183
+ + return a single object meaning the connection can be made to that object
184
+ + return a enumerable of objects meaning the connection can made to any member of the enumerable
185
+
186
+ Note that the object (or objects) returned are expected to be of the same class as the regulated policy.
187
+
188
+ ```ruby
189
+ # Create a class connection only if the acting_user is non-nil (i.e. logged in:)
190
+ regulate_class_connection { self }
191
+ # Always open the connection:
192
+ regulate_class_connection { true }
193
+ # Which can be shortened to:
194
+ always_allow_connection
195
+ # Create a class level connection if the acting_user is an admin:
196
+ regulate_class_connection { admin? }
197
+ # Create an instance connection for the current user:
198
+ regulate_instance_connections { self }
199
+ # Create an instance connection for the current user if the user is an admin:
200
+ regulate_instance_connections { self if admin? }
201
+ # create an instance_connection to the users' group
202
+ regulate_instance_connections { group }
203
+ # create an instance connection for any team the user belongs to
204
+ regulate_instance_connections { teams }
205
+ ```
206
+
207
+ #### Class Names Instances and IDs
208
+
209
+ While establishing connections, classes are represented as their fully scoped name, and instances are represented as the class name plus the result of calling `id` on the instance.
210
+
211
+ Typically connections are made to ActiveRecord models, and if those are in the `app/hyperloop/models` folder everything will work fine.
212
+
213
+ ## Acting User
214
+
215
+ Hyperloop looks for an `acting_user` method typically defined in the ApplicationController and would normally pick up the current session user, and return an appropriate object.
216
+
217
+ ```ruby
218
+ class ApplicationController < ActiveController::Base
219
+ def acting_user
220
+ @acting_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id])
221
+ end
222
+ end
223
+ end
224
+ ```
225
+
226
+ #### Automatic Connection
227
+
228
+ Connections to channels available to the current `acting_user` are automatically made on the initial page load. This behavior can be turned off with the `auto_connect` option.
229
+
230
+ ```ruby
231
+ class TeamPolicy
232
+ # Allow current users to establish connections to any teams they are
233
+ # members of, but disable_auto_connect
234
+ regulate_instance_connections(auto_connect: false) { teams }
235
+ end
236
+ ```
237
+
238
+ Its important to consider turning off automatic connections for cases like the above where the user is likely to be a member of many teams. Typically the client application will want to dynamically determine which specific teams to connect to given the current state of the application.
239
+
240
+ ### Manually Connecting to Channels
241
+
242
+ Normally the client will automatically connect to the available channels when a page loads, but you can also
243
+ manually connect on the client in response to some user action like logging in, or the user deciding to
244
+ display a specific team status on their dashboard.
245
+
246
+ To manually connect a client use the `Hyperloop.connect` method.
247
+
248
+ The `connect` method takes any number of arguments each of which is either a class, an object, a String or Array.
249
+
250
+ If the argument is a class then the connection will be made to the matching class channel on the server.
251
+
252
+ ```ruby
253
+ # connect the client to the AdminUser class channel
254
+ Hyperloop.connect(AdminUser)
255
+ # if the connection is successful the client will begin getting updates on the
256
+ # AdminUser class channel
257
+ ```
258
+
259
+ If the argument is an object then a connection will be made to the matching object on the server.
260
+
261
+ ```ruby
262
+ # assume current_user is an instance of class User
263
+ Hyperloop.connect(current_user)
264
+ # current_user.id is used to establish which User instance to connect to on the
265
+ # server
266
+ ```
267
+
268
+ The argument can also be a string, which matches the name of a class on the server
269
+
270
+ ```ruby
271
+ Hyperloop.connect('AdminUser')
272
+ # same as AdminUser class
273
+ ```
274
+
275
+ or the argument can be an array with a string and the id:
276
+
277
+ ```ruby
278
+ Hyperloop.connect(['User', current_user.id])
279
+ # same as saying current_user
280
+ ```
281
+
282
+ You can make several connections at once as well:
283
+ ```ruby
284
+ Hyperloop.connect(AdminUser, current_user)
285
+ ```
286
+
287
+ Finally falsy values are ignored.
288
+
289
+ You can also send `connect` directly to ActiveRecord models:
290
+
291
+ ```ruby
292
+ AdminUser.connect! # same as Hyperloop.connect(AdminUser)
293
+ current_user.connect! # same as Hyperloop.connect(current_user)
294
+ ```
295
+
296
+ #### Connection Sequence Summary
297
+
298
+ For class connections:
299
+
300
+ 1. The client calls `Hyperloop.connect`.
301
+ 2. Hyperloop sends the channel name to the server.
302
+ 3. Hyperloop has its own controller which will determine the `acting_user`,
303
+ 4. and call the channel's `regulate_class_connection` method.
304
+ 5. If `regulate_class_connection` returns a truthy value then the connection is made,
305
+ 6. otherwise a 500 error is returned.
306
+
307
+ For instance connections:
308
+
309
+ 1. The process is the same but the channel name and id are sent to the server.
310
+ 2. The Hyperloop controller will do a `find` of the id passed to get the instance,
311
+ 3. and if successful `regulate_instance_connections` is called,
312
+ 4. which must return an either the same instance, or an enumerable with that instance as a member.
313
+ 5. Otherwise a 500 error is returned.
314
+
315
+ Note that the same sequence is used for auto connections and manually invoked connections.
316
+
317
+ #### Disconnecting
318
+
319
+ Calling `Hyperloop.disconnect(channel)` or `channel.disconnect!` will disconnect from the channel.
320
+
321
+ ## Broadcasting and Broadcast Policies
322
+
323
+ Broadcast policies can be defined for channels using the `regulate_all_broadcasts` method, and for individual objects (typically ActiveRecord models) using the `regulate_broadcast` method. A `regulate_all_broadcasts` policy is essentially a `regulate_broadcast` that will be run for every record that changes in the system.
324
+
325
+ After an ActiveRecord Model change is committed, all active class channels run their channel broadcast policies, and then the instance broadcast policy associated with the changing Model is run. So for any change there may be multiple channel broadcast policies involved, but only one (at most) regulate_broadcast.
326
+
327
+ The result is that each channel may get a filtered copy of the record which is broadcast on that channel.
328
+
329
+ The purpose of the policies then is to determine which channel sees what. Each broadcast policy receives the instance of the policy which responds to the following methods
330
+
331
+ + `send_all`: send all the attributes of the record.
332
+ + `send_only`: send only the listed attributes of the record.
333
+ + `send_all_but`: send all the attributes except the ones listed.
334
+
335
+ The result of the `send...` method is then directed to the set of channels using the `to` method:
336
+
337
+ ```ruby
338
+ policy.send_all_but(:password).to(AdminUser)
339
+ ```
340
+
341
+ Within channel broadcast policies the channel is assumed to be the channel in question:
342
+
343
+ ```ruby
344
+ class AdminUserPolicy
345
+ regulate_all_broadcasts do |policy|
346
+ policy.send_all_but(:password) #.to(AdminUser) is not needed.
347
+ end
348
+ end
349
+ ```
350
+
351
+ The `to` method can take any number of arguments:
352
+
353
+ + a class naming a channel,
354
+ + an object that is instance channel,
355
+ + an ActiveRecord collection,
356
+ + any falsy value which will be ignored,
357
+ + or an array that will be flattened and merged with the other arguments.
358
+
359
+ The broadcast policy executes in the context of the model that has just changed, so the policy can use all the methods of that model, especially relationships. For example:
360
+
361
+ ```ruby
362
+ class Message < ActiveRecord::Base
363
+ belongs_to :sender, class: "User"
364
+ belongs_to :recipient, class: "User"
365
+ end
366
+
367
+ class MessagePolicy
368
+ regulate_broadcast do |policy|
369
+ # send all attributes to both the sender, and recipient User instance channels
370
+ policy.send_all.to(sender, recipient)
371
+ # send all attributes to intersection
372
+ policy.send_all.to(sender.teams.merge(recipient.teams)) unless private?
373
+ end
374
+ end
375
+ ```
376
+
377
+ It is possible that the same channel may be sent a record from different policies, in this case the minimum set of attributes will be sent regardless of the order of the send operations. For example:
378
+
379
+ ```ruby
380
+ policy.send_all_but(:password).to(MyChannel)
381
+ # ... later
382
+ policy.send_all.to(MyChannel)
383
+ # MyChannel gets everything but the password
384
+ ```
385
+
386
+ or even
387
+
388
+ ```ruby
389
+ policy.send_only(:foo, :bar).to(MyChannel)
390
+ policy.send_only(:baz).to(MyChannel)
391
+ # MyChannel gets nothing
392
+ ```
393
+
394
+ Keep in mind that the broadcast policies are sent a copy of the policy object so you can use helper methods in your policies. Also you can add policy specific methods to your models using `class_eval` thus keeping policy logic out of your models.
395
+
396
+ So we could for example we can rewrite the above MessagePolicy like this:
397
+
398
+ ```ruby
399
+ class MessagePolicy
400
+ Message.class_eval do
401
+ scope :teams_for_policy, -> () { sender.teams.merge(recipient.teams) }
402
+ end
403
+ def teams # the obj method returns the instance being regulated
404
+ [obj.sender, obj.recipient, !obj.private? && obj.teams_for_policy]
405
+ end
406
+ regulate_broadcast { |policy| policy.send_all.to(policy.teams) }
407
+ end
408
+ ```
409
+
410
+ ## Regulating Scopes
411
+
412
+ Consider the following expression (evaluated on the client)
413
+
414
+ ```ruby
415
+ Order.for_vip_customers.count
416
+ ```
417
+
418
+ Even though the policy system will prevent us from looking into the actual attributes of any record, a malicioius hacker can find private information about our data if the above expression is not secured. Moreover a DOS attack could be formed by repeatedly attempting to perform a variant of `Order.all`.
419
+
420
+ To prevent this scopes and relationships can also be regulated. A scope and relationship regulation is a proc that will return either a truthy or falsy value or calls the `denied!` method. The proc is evaluated in the context of the relationship object, and the `acting_user` method is available for the proc's use in making decisions.
421
+
422
+ All the scopes in a chain are evaluated together, and permission is granted or denied as follows:
423
+
424
+ + If *any* of the regulations in a chain of scopes calls `denied!` then the remote request is aborted;
425
+ + If *any* of the regulations in a chain of scopes returns a truthy value then access is granted to the entire chain;
426
+ + If *none* of the regulations in a chain of scopes returns a truthy value then the request is aborted.
427
+
428
+ Example:
429
+
430
+ ```ruby
431
+ class Order < ApplicationRecord
432
+ regulate_scope(:for_vip_customers) { denied! unless acting_user.admin? }
433
+ regulate_scope(:active) { acting_user.admin? }
434
+ end
435
+
436
+ class User < ApplicationRecord
437
+ regulate_relationship(:orders) { self == acting_user }
438
+ end
439
+
440
+ # in component code
441
+
442
+ user.orders.count # valid if user is the acting user because the orders regulation returned true
443
+ # but will raise error if acting_user is not == user
444
+ user.orders.active.count # valid if user is the acting user or if current user is an administrator
445
+ user.orders.for_vip_customers # fails unless acting user is an admin
446
+ ```
447
+
448
+ By default all relationships and scopes (including `all` and `unscoped` have a regulation that returns nil, so unless you explicitly provide a regulation that returns true, the client can not access any scopes.
449
+
450
+ There are some short hand ways to define regulations as well:
451
+
452
+ #### Constant Regulations
453
+
454
+ If the regulation always does the same thing you can specify what to do without the block:
455
+
456
+ ```ruby
457
+ regulate_scope my_scope: :always_allow # any truthy value works
458
+ regulate_scope my_scope: :denied! # :deny or :denied work as well
459
+ regulate_relationship many_of_those: :denied! # works the same on relationships
460
+ ```
461
+
462
+ Always denying a regulation effectively makes it inaccessible except on the server.
463
+
464
+ Likewise be careful of always returning true for a scope, as this means that a hacker only needs
465
+ to include this scope in the chain to gain access to the chain. So just make sure that scopes that return
466
+ true, narrow the scope down to something you would not mind anybody seeing.
467
+
468
+ For development you can easily access everything (except regulations that explicitly invoke denied!) simply by doing this:
469
+
470
+ ```ruby
471
+ class ApplicationRecord < ActiveRecord::Base
472
+ regulate_scope all: :always_allow if Rails.env.development?
473
+ regulate_scope unscoped: :always_allow if Rails.env.development?
474
+ end
475
+ ```
476
+
477
+ #### Regulations directly on scopes and has_many relationships
478
+
479
+ You can also directly add the regulation where you declare the scope or relationship using the `regulate:` option.
480
+
481
+ ```ruby
482
+ # here is a handy scope to add to ApplicationRecord that you can attach to
483
+ # any scope chain to give admin's full access
484
+ scope :admin, ->() {}, regulate: -> () { acting_user.admin? || denied! }
485
+
486
+ # customers can always see their orders, otherwise we return nil meaning "don't know yet"
487
+ has_many :orders, regulate: -> () { acting_user == self }
488
+ ```
489
+
490
+ ## Regulating server_method and finder_method methods
491
+
492
+ The server or finder method proc will be executed in the context of the appropriate object (a record for server_method, and a relationship collection for finder_method.) Attached to this object will be the current `acting_user` method, and a `denied!` method.
493
+
494
+ You can use these methods to restrict access to server and finder methods.
495
+
496
+ ```ruby
497
+ server_method :unit_cost do
498
+ denied! unless acting_user.admin? # only admin's can see this
499
+ # continue on calculating the unit cost
500
+ end
501
+ ```
502
+
503
+ ## Browser Initiated Change policies
504
+
505
+ To allow code in the browser to create, update or destroy a model, there must be a change access policy defined for that operation.
506
+
507
+ Each change access policy executes a block in the context of the record that will be accessed. The current value of `acting_user` is also defined for the life of the block.
508
+
509
+ If the block returns a truthy value access will be allowed, otherwise if the block returns a falsy value or raises an exception, access will be denied.
510
+
511
+ In the below examples we assume that your user model responds to `admin?` but this is not built into Hyperloop.
512
+
513
+ ```ruby
514
+ class TodoPolicy
515
+ # allow creation to any logged in user
516
+ allow_create { acting_user }
517
+ # only allow the owner, author any any admin to update a todo
518
+ allow_update { acting_user == owner || acting_user == author || acting_user.admin? }
519
+ # don't allow Todo's to be destroyed
520
+ # this is the default behavior so its not actually needed
521
+ allow_destroy { false }
522
+ end
523
+ ```
524
+
525
+ There are several variants of the access policy method:
526
+
527
+ ```ruby
528
+ class ConfigDataPolicy
529
+ allow_change(on: [:create, :update, :destroy]) { acting_user.admin? }
530
+ # which can be shortened to:
531
+ allow_change { acting_user.admin? }
532
+ end
533
+ ```
534
+
535
+ ```ruby
536
+ class ApplicationPolicy
537
+ # do any thing to all models unless we are in production! Be careful!
538
+ allow_change(to: :all) { true } unless Rails.env.production?
539
+ # and always allow admins to destroy models globally:
540
+ allow_change(to: :all, on: :destroy) { acting_user.admin? }
541
+ # which is the same as saying:
542
+ allow_destroy(to: :all) { acting_user.admin? }
543
+ # you can create model specific policies in the Application Policy as well.
544
+ # Here we allow the author of a message to destroy the message within 5
545
+ # minutes of creation.
546
+ allow_destroy(to: Message) do
547
+ return true if acting_user == author && created_at > 5.minutes.ago
548
+ return true if acting_user.admin?
549
+ end
550
+ end
551
+ ```
552
+
553
+ Note that there is no `allow_read` method. Read access is granted if this browser would have the attribute broadcast to it.
554
+
555
+ ## Method Summary and Name Space Conflicts
556
+
557
+ Policy classes (and the Hyperloop::PolicyMethods module) define the following class methods:
558
+
559
+ + `regulate_connection`
560
+ + `regulate_all_broadcasts`
561
+ + `regulate_broadcast`
562
+
563
+ As well as the following instance methods:
564
+ + `send_all`
565
+ + `send_all_but`
566
+ + `send_only`
567
+ + `obj`
568
+
569
+ To avoid name space conflicts with your classes, Hyperloop policy classes (and the Hyperloop::PolicyMethods module) maintain class and instance `attr_accessor`s named `synchromesh_internal_policy_object`. The above methods call methods of the same name in the appropriate internal policy object.
570
+
571
+ You may thus freely redefine of the class and instance methods if you have name space conflicts
572
+
573
+ ```ruby
574
+ class ProductionCenterPolicy < MyPolicyClass
575
+ # MyPolicyClass already defines our version of obj
576
+ # so we will call it 'this'
577
+ def this
578
+ synchromesh_internal_policy_object.obj
579
+ end
580
+ ...
581
+ end
582
+ ```