Project

General

Profile

Hacking Workbench » History » Version 12

Tom Clegg, 08/19/2014 01:50 PM

1 1 Tom Clegg
h1. Hacking Workbench
2
3
{{toc}}
4
5
h2. Source tree layout
6
7
Everything is in @/apps/workbench@.
8
9
Key pieces to know about before going much further:
10
11
|/|Usual Rails project layout|
12
|/app/controllers/application_controller.rb|Controller superclass with authentication setup, error handling, and generic CRUD actions|
13
|/app/controllers/*.rb|Actions other than generic CRUD (users#activity, jobs#generate_provenance, ...)|
14
|/app/models/arvados_base.rb|Default Arvados model behavior and ActiveRecord-like accessors and introspection features|
15
|/app/models/arvados_resource_list.rb|ActiveRelation-like class (what you get from Model.where() etc.)|
16
17 12 Tom Clegg
h2. Background resources
18
19
Workbench is a Rails 4 application.
20
21
* "Getting started with Rails":http://guides.rubyonrails.org/getting_started.html at rubyonrails.org
22
* "AJAX in Rails 3.1":http://blog.madebydna.com/all/code/2011/12/05/ajax-in-rails-3.html blog post (still relevant in Rails 4)
23
24 1 Tom Clegg
h2. Unlike a typical Rails project...
25
26 7 Peter Amstutz
* ActiveRecord in Workbench doesn't talk to the database directly, but instead queries the Arvados API as REST client.
27
* The Arvados query API is somewhat limited and doesn't accept SQL statements, so Workbench has to work harder to get what it needs.
28 1 Tom Clegg
* Workbench itself only has the privileges of the Workbench user: when making Arvados API calls, it uses the API token provided by the user.
29
30
h2. Unlike what you might expect...
31
32
* Workbench doesn't use the Ruby SDK. It uses a sort of baked-in Rails SDK.
33
** TODO: move it out of Workbench into a gem.
34
** TODO: use the Ruby SDK under the hood.
35
36
h2. Running in development mode
37
38 2 Misha Zatsman
h3. SSL certificates
39
40 4 Tom Clegg
You can get started quickly with SSL by generating a self-signed certificate:
41 1 Tom Clegg
42
 openssl req -new -x509 -nodes -out ~/self-signed.pem -keyout ~/self-signed.key -days 3650 -subj '/CN=arvados.example.com'
43
44
Alternatively, download a set from the bottom of the [[API server]] page.
45 2 Misha Zatsman
46
h3. Download and configure
47 1 Tom Clegg
48 2 Misha Zatsman
Follow "these instructions":http://doc.arvados.org/install/install-workbench-app.html to download the source and configure your workbench instance.
49 3 Misha Zatsman
50 4 Tom Clegg
h3. Start the server
51 1 Tom Clegg
52 4 Tom Clegg
Save something like the following at @~/bin/workbench@, make it executable[1], make sure @~/bin@ is in your path[2]:
53 1 Tom Clegg
54
 #!/bin/sh
55
set -e
56
cd ~/arvados/apps/workbench
57
export RAILS_ENV=development
58 5 Tom Clegg
bundle install --path=vendor/bundle
59 4 Tom Clegg
exec bundle exec passenger start -p 3031 --ssl --ssl-certificate ~/self-signed.pem --ssl-certificate-key ~/self-signed.key
60 1 Tom Clegg
61
The first time you run the above it will take a while to install all the ruby gems. In particular @Installing nokogiri@ takes a while
62
63
Once you see:
64
65
 =============== Phusion Passenger Standalone web server started ===============
66
67
You can visit your server at:
68
69 4 Tom Clegg
 @https://{ip-or-host}:3031/@
70
71 6 Misha Zatsman
You can kill your server with @ctrl-C@ but if you get disconnected from the terminal, it will continue running. You can kill it by running
72
73
 @ps x |grep nginx |grep master@
74
75
And then
76
77
 @kill ####@
78
79
Replacing #### with the number in the left column returned by ps
80
81 4 Tom Clegg
fn1. @chmod +x ~/bin/workbench@
82
83
fn2. In Debian systems, the default .profile adds ~/bin to your path, but only if it exists when you log in. If you just created ~/bin, doing @exec bash -login@ or @source .profile@ should make ~/bin appear in your path.
84
85
h2. Running tests
86
87
The test suite brings up an API server in test mode, and runs browser tests with Firefox.
88
89
Make sure API server has its dependencies in place.
90
91
<pre>
92 5 Tom Clegg
(cd ../../services/api && RAILS_ENV=test bundle install --path=vendor/bundle)
93 4 Tom Clegg
</pre>
94
95
Install headless testing tools.
96
97
<pre>
98
sudo apt-get install xvfb iceweasel
99
</pre>
100
101
(Install firefox instead of iceweasel if you're not using Debian.)
102
103 10 Tom Clegg
Install phantomjs. (See http://phantomjs.org/download.html for latest version.)
104
105
<pre>
106
wget -P /tmp https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7-linux-x86_64.tar.bz2
107
sudo tar -C /usr/local -xjf /tmp/phantomjs-1.9.7-linux-x86_64.tar.bz2
108
sudo ln -s ../phantomjs-1.9.7-linux-x86_64/bin/phantomjs /usr/local/bin/
109
</pre>
110
111 4 Tom Clegg
Run the test suite.
112
113
<pre>
114
RAILS_ENV=test bundle exec rake test
115 1 Tom Clegg
</pre>
116 9 Tom Clegg
117
To aid debugging, when an integration test fails (or skips) a screenshot is automatically saved in @arvados/apps/workbench/tmp/workbench-fail-1.png@, etc.
118
119 1 Tom Clegg
h2. Loading state from API into models
120
121
If your model makes an API call that returns the new state of an object, load the new attributes into the local model with @private_reload@:
122
123
<pre><code class="ruby">
124
  api_response = $arvados_api_client.api(...)
125
  private_reload api_response
126
</code></pre>
127
128
h2. Features
129
130
h3. Authentication
131
132
ApplicationController uses an around_filter to make sure the user is logged in, redirect to Arvados to complete the login procedure if not, and store the user's API token in Thread.current[:arvados_api_token] if so.
133
134
The @current_user@ helper returns User.current if the user is logged in, otherwise nil. (Generally, only special pages like "welcome" and "error" get displayed to users who aren't logged in.)
135
136
h3. Default filter behavior
137
138
@before_filter :find_object_by_uuid@
139
140
* This is enabled by default, @except :index, :create@.
141
* It renames the @:id@ param to @:uuid@. (The Rails default routing rules use @:id@ to accept params in path components, but @params[:uuid]@ makes more sense everywhere else in our code.)
142
* If you define a collection method (where there's no point looking up an object with the :id supplied in the request), skip this.
143
144
<pre><code class="ruby">
145
  skip_before_filter :find_object_by_uuid, only: [:action_that_takes_no_uuid_param]
146
</code></pre>
147
148
h3. Error handling
149
150
ApplicationController has a render_error method that shows a standard error page. (It's not very good, but it's better than a default Rails stack trace.)
151
152
In a controller you get there like this
153
154
<pre><code class="ruby">
155
  @errors = ['I could not achieve what you wanted.']
156
  render_error status: 500
157
</code></pre>
158
159
You can also do this, anywhere
160
161
<pre><code class="ruby">
162
  raise 'My spoon is too big.'
163
</code></pre>
164
165
The @render_error@ method sends JSON or HTML to the client according to the Accept header in the request (it sends JSON if JavaScript was requested), so reasonable things happen whether or not the request is AJAX.
166
167
h2. Development patterns
168
169
h3. Add a model
170
171
Currently, when the API provides a new model, we need to generate a corresponding model in Workbench: it's not smart enough to pick up the list of models from the API server's discovery document.
172
173
_(Need to fill in details here)_
174
# @rails generate model ....@
175
# Delete migration
176 8 Peter Amstutz
# Change base class to ArvadosBase
177
# @rails generate controller ...@ 
178 1 Tom Clegg
179
Model _attributes_, on the other hand, are populated automatically.
180
181
h3. Add a configuration knob
182
183
Same situation as API server. See [[Hacking API Server]].
184
185
h3. Add an API method
186
187
Workbench is not yet smart enough to look in the discovery document for supported API methods. You need to add a method to the appropriate model class before you can use it in the Workbench app.
188
189
h3. Writing tests
190
191
(TODO)
192
193
h3. AJAX using Rails UJS (remote:true with JavaScript response)
194
195
This pattern is the best way to make a button/link that invokes an asynchronous action on the Workbench server side, i.e., before/without navigating away from the current page.
196
197
# Add <code class="ruby">remote: true</code> to a link or button. This makes Rails put a <code class="html">data-remote="true"</code> attribute in the HTML element. Say, in @app/views/fizz_buzzes/index.html.erb@:
198
<pre><code class="ruby">
199
<%= link_to "Blurfl", blurfl_fizz_buzz_url(id: @object.uuid), {class: 'btn btn-primary', remote: true} %>
200
</code></pre>
201
# Ensure the targeted action responds appropriately to both "js" and "html" requests. At minimum:
202
<pre><code class="ruby">
203
class FizzBuzzesController
204
  #...
205
  def blurfl
206
    @howmany = 1
207
    #...
208
    respond_to do |format|
209
      format.js
210
      format.html
211
    end
212
  end
213
end
214
</code></pre>
215
# The @html@ view is used if this is a normal page load (presumably this means the client has turned off JS).
216
#* @app/views/fizz_buzz/blurfl.html.erb@
217
<pre><code>
218
<p>I am <%= @howmany %></p>
219
</code></pre>
220
# The @js@ view is used if this is an AJAX request. It renders as JavaScript code which will be executed in the browser. Say, in @app/views/fizz_buzz/blurfl.js.erb@:
221
<pre><code class="javascript">
222
window.alert('I am <%= @howmany %>');
223
</code></pre>
224
# The browser opens an alert box:
225
<pre>
226
I am 1
227
</pre>
228
# A common task is to render a partial and use it to update part of the page. Say the partial is in @app/views/fizz_buzz/_latest_news.html.erb@:
229
<pre><code class="javascript">
230
var new_content = "<%= escape_javascript(render partial: 'latest_news') %>";
231
if ($('div#latest-news').html() != new_content)
232
   $('div#latest-news').html(new_content);
233
</code></pre>
234
235
*TODO: error handling*
236
237
h3. AJAX invoked from custom JavaScript (JSON response)
238
239
(and error handling)
240
241
h3. Add JavaScript triggers and fancy behavior
242
243
Some guidelines for implementing stuff nicely in JavaScript:
244
* Don't rely on the DOM being loaded before your script is loaded.
245
** If you need to inspect/alter the DOM as soon as it's loaded, make a setup function that fires on "document ready" and "ajax:complete".
246
** jQuery's delegated event pattern can help keep your code clean. See http://api.jquery.com/on/
247
<pre><code class="javascript">
248
// worse:
249
$('table.fizzbuzzer tr').
250
    on('mouseover', function(e, xhr) {
251
        console.log("This only works if the table exists when this setup script is executed.");
252
    });
253
// better:
254
$(document).
255
    on('mouseover', 'table.fizzbuzzer tr', function(e, xhr) {
256
        console.log("This works even if the table appears (or has the fizzbuzzer class added) later.");
257
    });
258
</code></pre>
259
260
* If your code really only makes sense for a particular view, rather than embedding @<script>@ tags in the middle of the page,
261
** use this:
262
<pre><code class="ruby">
263
<% content_for :js do %>
264
console.log("hurray, this goes in HEAD");
265
<% end %>
266
</code></pre>
267
** or, if your code should run after [most of] the DOM is loaded:
268
<pre><code class="ruby">
269
<% content_for :footer_js do %>
270
console.log("hurray, this runs at the bottom of the BODY element in the default layout.");
271
<% end %>
272
</code></pre>
273
274
* Don't just write JavaScript on the @fizz_buzzes/blurfl@ page and rely on the fact that the only @table@ element on the page is the one you want to attach your special behavior to. Instead, add a class to the table, and use a jQuery selector to attach special behavior to it.
275
** In @app/views/fizz_buzzes/blurfl.html.erb@
276
<pre>
277
<table class="fizzbuzzer">
278
 <tr>
279
  <td>fizz</td><td>buzz</td>
280
 </tr>
281
</table>
282
</pre>
283
** In @app/assets/javascripts/fizz_buzzes.js@
284
<pre><code class="javascript">
285
<% content_for :js do %>
286
$(document).on('mouseover', 'table.fizzbuzzer tr', function() {
287
    console.log('buzz');
288
});
289
<% end %>
290
</code></pre>
291
** Advantage: You can reuse the special behavior in other tables/pages/classes
292
** Advantage: The JavaScript can get compiled, minified, cached in the browser, etc., instead of being rendered with every page view
293
** Advantage: The JavaScript code is available regardless of how the content got into the DOM (regular page view, partial update with AJAX)
294
295 11 Tom Clegg
h3. Invoking chooser
296
297
Example from @app/views/projects/_show_contents.html.erb@:
298
299
<pre>
300
    <%= link_to(
301
          choose_collections_path(
302
            title: 'Add data to project:',
303
            multiple: true,
304
            action_name: 'Add',
305
            action_href: actions_path(id: @object.uuid),
306
            action_method: 'post',
307
            action_data: {selection_param: 'selection[]', copy_selections_into_project: @object.uuid, success: 'page-refresh'}.to_json),
308
          { class: "btn btn-primary btn-sm", remote: true, method: 'get', data: {'event-after-select' => 'page-refresh'} }) do %>
309
      <i class="fa fa-fw fa-plus"></i> Add data...
310
    <% end %>
311
</pre>
312
313
Tour:
314 1 Tom Clegg
315
(TODO)
316
317
h3. Tabs/panes on index & show pages
318
319
(TODO)
320
321
h3. User notifications
322
323
(TODO)
324
325
h3. Customizing breadcrumbs
326
327
(TODO)
328
329
h3. Making a page accessible before login
330
331
(TODO)
332
333
h3. Making a page accessible to non-active users
334
335
(TODO)