d7ffd9c792420396b9251d15d103014330b5a93e
[arvados.git] / apps / workbench / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include ArvadosApiClientHelper
3   include ApplicationHelper
4
5   respond_to :html, :json, :js
6   protect_from_forgery
7
8   ERROR_ACTIONS = [:render_error, :render_not_found]
9
10   around_filter :thread_clear
11   around_filter :thread_with_mandatory_api_token, except: ERROR_ACTIONS
12   around_filter :thread_with_optional_api_token
13   before_filter :check_user_agreements, except: ERROR_ACTIONS
14   before_filter :check_user_notifications, except: ERROR_ACTIONS
15   before_filter :find_object_by_uuid, except: [:index, :choose] + ERROR_ACTIONS
16   theme :select_theme
17
18   begin
19     rescue_from Exception,
20     :with => :render_exception
21     rescue_from ActiveRecord::RecordNotFound,
22     :with => :render_not_found
23     rescue_from ActionController::RoutingError,
24     :with => :render_not_found
25     rescue_from ActionController::UnknownController,
26     :with => :render_not_found
27     rescue_from ::AbstractController::ActionNotFound,
28     :with => :render_not_found
29   end
30
31   def unprocessable(message=nil)
32     @errors ||= []
33
34     @errors << message if message
35     render_error status: 422
36   end
37
38   def render_error(opts)
39     opts = {status: 500}.merge opts
40     respond_to do |f|
41       # json must come before html here, so it gets used as the
42       # default format when js is requested by the client. This lets
43       # ajax:error callback parse the response correctly, even though
44       # the browser can't.
45       f.json { render opts.merge(json: {success: false, errors: @errors}) }
46       f.html { render opts.merge(controller: 'application', action: 'error') }
47     end
48   end
49
50   def render_exception(e)
51     logger.error e.inspect
52     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
53     if @object.andand.errors.andand.full_messages.andand.any?
54       @errors = @object.errors.full_messages
55     else
56       @errors = [e.to_s]
57     end
58     self.render_error status: 422
59   end
60
61   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
62     logger.error e.inspect
63     @errors = ["Path not found"]
64     self.render_error status: 404
65   end
66
67   def find_objects_for_index
68     @limit ||= 200
69     if params[:limit]
70       @limit = params[:limit].to_i
71     end
72
73     @offset ||= 0
74     if params[:offset]
75       @offset = params[:offset].to_i
76     end
77
78     @filters ||= []
79     if params[:filters]
80       filters = params[:filters]
81       if filters.is_a? String
82         filters = Oj.load filters
83       end
84       @filters += filters
85     end
86
87     @objects ||= model_class
88     @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
89   end
90
91   def render_index
92     respond_to do |f|
93       f.json { render json: @objects }
94       f.html {
95         if params['tab_pane']
96           comparable = self.respond_to? :compare
97           render(partial: 'show_' + params['tab_pane'].downcase,
98                  locals: { comparable: comparable, objects: @objects })
99         else
100           render
101         end
102       }
103       f.js { render }
104     end
105   end
106
107   def index
108     find_objects_for_index if !@objects
109     render_index
110   end
111
112   helper_method :next_page_offset
113   def next_page_offset
114     if @objects.respond_to?(:result_offset) and
115         @objects.respond_to?(:result_limit) and
116         @objects.respond_to?(:items_available)
117       next_offset = @objects.result_offset + @objects.result_limit
118       if next_offset < @objects.items_available
119         next_offset
120       else
121         nil
122       end
123     end
124   end
125
126   def show
127     if !@object
128       return render_not_found("object not found")
129     end
130     respond_to do |f|
131       f.json { render json: @object.attributes.merge(href: url_for(@object)) }
132       f.html {
133         if params['tab_pane']
134           comparable = self.respond_to? :compare
135           render(partial: 'show_' + params['tab_pane'].downcase,
136                  locals: { comparable: comparable, objects: @objects })
137         elsif request.method.in? ['GET', 'HEAD']
138           render
139         else
140           redirect_to params[:return_to] || @object
141         end
142       }
143       f.js { render }
144     end
145   end
146
147   def choose
148     params[:limit] ||= 40
149     if !@objects
150       if params[:project_uuid] and !params[:project_uuid].empty?
151         @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
152       end
153       find_objects_for_index if !@objects
154     end
155     respond_to do |f|
156       if params[:partial]
157         f.json {
158           render json: {
159             content: render_to_string(partial: "choose_rows.html",
160                                       formats: [:html],
161                                       locals: {
162                                         multiple: params[:multiple]
163                                       }),
164             next_page_href: @next_page_href
165           }
166         }
167       end
168       f.js {
169         render partial: 'choose', locals: {multiple: params[:multiple]}
170       }
171     end
172   end
173
174   def render_content
175     if !@object
176       return render_not_found("object not found")
177     end
178   end
179
180   def new
181     @object = model_class.new
182   end
183
184   def update
185     @updates ||= params[@object.resource_param_name.to_sym]
186     @updates.keys.each do |attr|
187       if @object.send(attr).is_a? Hash
188         if @updates[attr].is_a? String
189           @updates[attr] = Oj.load @updates[attr]
190         end
191         if params[:merge] || params["merge_#{attr}".to_sym]
192           # Merge provided Hash with current Hash, instead of
193           # replacing.
194           @updates[attr] = @object.send(attr).with_indifferent_access.
195             deep_merge(@updates[attr].with_indifferent_access)
196         end
197       end
198     end
199     if @object.update_attributes @updates
200       show
201     else
202       self.render_error status: 422
203     end
204   end
205
206   def create
207     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
208     @new_resource_attrs ||= {}
209     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
210     @object ||= model_class.new @new_resource_attrs, params["options"]
211     if @object.save
212       respond_to do |f|
213         f.json { render json: @object.attributes.merge(href: url_for(@object)) }
214         f.html {
215           redirect_to @object
216         }
217         f.js { render }
218       end
219     else
220       self.render_error status: 422
221     end
222   end
223
224   # Clone the given object, merging any attribute values supplied as
225   # with a create action.
226   def copy
227     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
228     @new_resource_attrs ||= {}
229     @object = @object.dup
230     @object.update_attributes @new_resource_attrs
231     if not @new_resource_attrs[:name] and @object.respond_to? :name
232       if @object.name and @object.name != ''
233         @object.name = "Copy of #{@object.name}"
234       else
235         @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
236       end
237     end
238     @object.save!
239     show
240   end
241
242   def destroy
243     if @object.destroy
244       respond_to do |f|
245         f.json { render json: @object }
246         f.html {
247           redirect_to(params[:return_to] || :back)
248         }
249         f.js { render }
250       end
251     else
252       self.render_error status: 422
253     end
254   end
255
256   def current_user
257     return Thread.current[:user] if Thread.current[:user]
258
259     if Thread.current[:arvados_api_token]
260       if session[:user]
261         if session[:user][:is_active] != true
262           Thread.current[:user] = User.current
263         else
264           Thread.current[:user] = User.new(session[:user])
265         end
266       else
267         Thread.current[:user] = User.current
268       end
269     else
270       logger.error "No API token in Thread"
271       return nil
272     end
273   end
274
275   def model_class
276     controller_name.classify.constantize
277   end
278
279   def breadcrumb_page_name
280     (@breadcrumb_page_name ||
281      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
282      action_name)
283   end
284
285   def index_pane_list
286     %w(Recent)
287   end
288
289   def show_pane_list
290     %w(Attributes Advanced)
291   end
292
293   protected
294
295   def redirect_to_login
296     respond_to do |f|
297       f.html {
298         if request.method.in? ['GET', 'HEAD']
299           redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
300         else
301           flash[:error] = "Either you are not logged in, or your session has timed out. I can't automatically log you in and re-attempt this request."
302           redirect_to :back
303         end
304       }
305       f.json {
306         @errors = ['You do not seem to be logged in. You did not supply an API token with this request, and your session (if any) has timed out.']
307         self.render_error status: 422
308       }
309     end
310     false  # For convenience to return from callbacks
311   end
312
313   def using_specific_api_token(api_token)
314     start_values = {}
315     [:arvados_api_token, :user].each do |key|
316       start_values[key] = Thread.current[key]
317     end
318     Thread.current[:arvados_api_token] = api_token
319     Thread.current[:user] = nil
320     begin
321       yield
322     ensure
323       start_values.each_key { |key| Thread.current[key] = start_values[key] }
324     end
325   end
326
327   def find_object_by_uuid
328     if params[:id] and params[:id].match /\D/
329       params[:uuid] = params.delete :id
330     end
331     if not model_class
332       @object = nil
333     elsif params[:uuid].is_a? String
334       if params[:uuid].empty?
335         @object = nil
336       else
337         if (model_class != Link and
338             resource_class_for_uuid(params[:uuid]) == Link)
339           @name_link = Link.find(params[:uuid])
340           @object = model_class.find(@name_link.head_uuid)
341         else
342           @object = model_class.find(params[:uuid])
343         end
344       end
345     else
346       @object = model_class.where(uuid: params[:uuid]).first
347     end
348   end
349
350   def thread_clear
351     Thread.current[:arvados_api_token] = nil
352     Thread.current[:user] = nil
353     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
354     yield
355     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
356   end
357
358   def thread_with_api_token(login_optional = false)
359     begin
360       try_redirect_to_login = true
361       if params[:api_token]
362         try_redirect_to_login = false
363         Thread.current[:arvados_api_token] = params[:api_token]
364         # Before copying the token into session[], do a simple API
365         # call to verify its authenticity.
366         if verify_api_token
367           session[:arvados_api_token] = params[:api_token]
368           u = User.current
369           session[:user] = {
370             uuid: u.uuid,
371             email: u.email,
372             first_name: u.first_name,
373             last_name: u.last_name,
374             is_active: u.is_active,
375             is_admin: u.is_admin,
376             prefs: u.prefs
377           }
378           if !request.format.json? and request.method.in? ['GET', 'HEAD']
379             # Repeat this request with api_token in the (new) session
380             # cookie instead of the query string.  This prevents API
381             # tokens from appearing in (and being inadvisedly copied
382             # and pasted from) browser Location bars.
383             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
384           else
385             yield
386           end
387         else
388           @errors = ['Invalid API token']
389           self.render_error status: 401
390         end
391       elsif session[:arvados_api_token]
392         # In this case, the token must have already verified at some
393         # point, but it might have been revoked since.  We'll try
394         # using it, and catch the exception if it doesn't work.
395         try_redirect_to_login = false
396         Thread.current[:arvados_api_token] = session[:arvados_api_token]
397         begin
398           yield
399         rescue ArvadosApiClient::NotLoggedInException
400           try_redirect_to_login = true
401         end
402       else
403         logger.debug "No token received, session is #{session.inspect}"
404       end
405       if try_redirect_to_login
406         unless login_optional
407           redirect_to_login
408         else
409           # login is optional for this route so go on to the regular controller
410           Thread.current[:arvados_api_token] = nil
411           yield
412         end
413       end
414     ensure
415       # Remove token in case this Thread is used for anything else.
416       Thread.current[:arvados_api_token] = nil
417     end
418   end
419
420   def thread_with_mandatory_api_token
421     thread_with_api_token(true) do
422       if Thread.current[:arvados_api_token]
423         yield
424       elsif session[:arvados_api_token]
425         # Expired session. Clear it before refreshing login so that,
426         # if this login procedure fails, we end up showing the "please
427         # log in" page instead of getting stuck in a redirect loop.
428         session.delete :arvados_api_token
429         redirect_to_login
430       else
431         render 'users/welcome'
432       end
433     end
434   end
435
436   # This runs after thread_with_mandatory_api_token in the filter chain.
437   def thread_with_optional_api_token
438     if Thread.current[:arvados_api_token]
439       # We are already inside thread_with_mandatory_api_token.
440       yield
441     else
442       # We skipped thread_with_mandatory_api_token. Use the optional version.
443       thread_with_api_token(true) do
444         yield
445       end
446     end
447   end
448
449   def verify_api_token
450     begin
451       Link.where(uuid: 'just-verifying-my-api-token')
452       true
453     rescue ArvadosApiClient::NotLoggedInException
454       false
455     end
456   end
457
458   def ensure_current_user_is_admin
459     unless current_user and current_user.is_admin
460       @errors = ['Permission denied']
461       self.render_error status: 401
462     end
463   end
464
465   def check_user_agreements
466     if current_user && !current_user.is_active
467       if not current_user.is_invited
468         return render 'users/inactive'
469       end
470       signatures = UserAgreement.signatures
471       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
472       @required_user_agreements = UserAgreement.all.map do |ua|
473         if not @signed_ua_uuids.index ua.uuid
474           Collection.find(ua.uuid)
475         end
476       end.compact
477       if @required_user_agreements.empty?
478         # No agreements to sign. Perhaps we just need to ask?
479         current_user.activate
480         if !current_user.is_active
481           logger.warn "#{current_user.uuid.inspect}: " +
482             "No user agreements to sign, but activate failed!"
483         end
484       end
485       if !current_user.is_active
486         render 'user_agreements/index'
487       end
488     end
489     true
490   end
491
492   def select_theme
493     return Rails.configuration.arvados_theme
494   end
495
496   @@notification_tests = []
497
498   @@notification_tests.push lambda { |controller, current_user|
499     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
500       return nil
501     end
502     return lambda { |view|
503       view.render partial: 'notifications/ssh_key_notification'
504     }
505   }
506
507   #@@notification_tests.push lambda { |controller, current_user|
508   #  Job.limit(1).where(created_by: current_user.uuid).each do
509   #    return nil
510   #  end
511   #  return lambda { |view|
512   #    view.render partial: 'notifications/jobs_notification'
513   #  }
514   #}
515
516   @@notification_tests.push lambda { |controller, current_user|
517     Collection.limit(1).where(created_by: current_user.uuid).each do
518       return nil
519     end
520     return lambda { |view|
521       view.render partial: 'notifications/collections_notification'
522     }
523   }
524
525   @@notification_tests.push lambda { |controller, current_user|
526     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
527       return nil
528     end
529     return lambda { |view|
530       view.render partial: 'notifications/pipelines_notification'
531     }
532   }
533
534   def check_user_notifications
535     return if params['tab_pane']
536
537     @notification_count = 0
538     @notifications = []
539
540     if current_user
541       @showallalerts = false
542       @@notification_tests.each do |t|
543         a = t.call(self, current_user)
544         if a
545           @notification_count += 1
546           @notifications.push a
547         end
548       end
549     end
550
551     if @notification_count == 0
552       @notification_count = ''
553     end
554   end
555
556   helper_method :all_projects
557   def all_projects
558     @all_projects ||= Group.
559       filter([['group_class','in',['project','folder']]]).order('name')
560   end
561
562   helper_method :my_projects
563   def my_projects
564     return @my_projects if @my_projects
565     @my_projects = []
566     root_of = {}
567     all_projects.each do |g|
568       root_of[g.uuid] = g.owner_uuid
569       @my_projects << g
570     end
571     done = false
572     while not done
573       done = true
574       root_of = root_of.each_with_object({}) do |(child, parent), h|
575         if root_of[parent]
576           h[child] = root_of[parent]
577           done = false
578         else
579           h[child] = parent
580         end
581       end
582     end
583     @my_projects = @my_projects.select do |g|
584       root_of[g.uuid] == current_user.uuid
585     end
586   end
587
588   helper_method :projects_shared_with_me
589   def projects_shared_with_me
590     my_project_uuids = my_projects.collect &:uuid
591     all_projects.reject { |x| x.uuid.in? my_project_uuids }
592   end
593
594   helper_method :recent_jobs_and_pipelines
595   def recent_jobs_and_pipelines
596     (Job.limit(10) |
597      PipelineInstance.limit(10)).
598       sort_by do |x|
599       x.finished_at || x.started_at || x.created_at rescue x.created_at
600     end
601   end
602
603   helper_method :my_project_tree
604   def my_project_tree
605     build_project_trees
606     @my_project_tree
607   end
608
609   helper_method :shared_project_tree
610   def shared_project_tree
611     build_project_trees
612     @shared_project_tree
613   end
614
615   def build_project_trees
616     return if @my_project_tree and @shared_project_tree
617     parent_of = {current_user.uuid => 'me'}
618     all_projects.each do |ob|
619       parent_of[ob.uuid] = ob.owner_uuid
620     end
621     children_of = {false => [], 'me' => [current_user]}
622     all_projects.each do |ob|
623       if ob.owner_uuid != current_user.uuid and
624           not parent_of.has_key? ob.owner_uuid
625         parent_of[ob.uuid] = false
626       end
627       children_of[parent_of[ob.uuid]] ||= []
628       children_of[parent_of[ob.uuid]] << ob
629     end
630     buildtree = lambda do |children_of, root_uuid=false|
631       tree = {}
632       children_of[root_uuid].andand.each do |ob|
633         tree[ob] = buildtree.call(children_of, ob.uuid)
634       end
635       tree
636     end
637     sorted_paths = lambda do |tree, depth=0|
638       paths = []
639       tree.keys.sort_by { |ob|
640         ob.is_a?(String) ? ob : ob.friendly_link_name
641       }.each do |ob|
642         paths << {object: ob, depth: depth}
643         paths += sorted_paths.call tree[ob], depth+1
644       end
645       paths
646     end
647     @my_project_tree =
648       sorted_paths.call buildtree.call(children_of, 'me')
649     @shared_project_tree =
650       sorted_paths.call({'Shared with me' =>
651                           buildtree.call(children_of, false)})
652   end
653
654   helper_method :get_object
655   def get_object uuid
656     if @get_object.nil? and @objects
657       @get_object = @objects.each_with_object({}) do |object, h|
658         h[object.uuid] = object
659       end
660     end
661     @get_object ||= {}
662     @get_object[uuid]
663   end
664
665   helper_method :project_breadcrumbs
666   def project_breadcrumbs
667     crumbs = []
668     current = @name_link || @object
669     while current
670       if current.is_a?(Group) and current.group_class.in?(['project','folder'])
671         crumbs.prepend current
672       end
673       if current.is_a? Link
674         current = Group.find?(current.tail_uuid)
675       else
676         current = Group.find?(current.owner_uuid)
677       end
678     end
679     crumbs
680   end
681
682   helper_method :current_project_uuid
683   def current_project_uuid
684     if @object.is_a? Group and @object.group_class.in?(['project','folder'])
685       @object.uuid
686     elsif @name_link.andand.tail_uuid
687       @name_link.tail_uuid
688     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
689       @object.owner_uuid
690     else
691       nil
692     end
693   end
694
695   # helper method to get links for given object or uuid
696   helper_method :links_for_object
697   def links_for_object object_or_uuid
698     raise ArgumentError, 'No input argument' unless object_or_uuid
699     preload_links_for_objects([object_or_uuid])
700     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
701     @all_links_for[uuid] ||= []
702   end
703
704   # helper method to preload links for given objects and uuids
705   helper_method :preload_links_for_objects
706   def preload_links_for_objects objects_and_uuids
707     @all_links_for ||= {}
708
709     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
710     return @all_links_for if objects_and_uuids.empty?
711
712     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
713
714     # if already preloaded for all of these uuids, return
715     if not uuids.select { |x| @all_links_for[x].nil? }.any?
716       return @all_links_for
717     end
718
719     uuids.each do |x|
720       @all_links_for[x] = []
721     end
722
723     # TODO: make sure we get every page of results from API server
724     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
725       @all_links_for[link.head_uuid] << link
726     end
727     @all_links_for
728   end
729
730   # helper method to get a certain number of objects of a specific type
731   # this can be used to replace any uses of: "dataclass.limit(n)"
732   helper_method :get_n_objects_of_class
733   def get_n_objects_of_class dataclass, size
734     @objects_map_for ||= {}
735
736     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
737     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
738
739     # if the objects_map_for has a value for this dataclass, and the
740     # size used to retrieve those objects is equal, return it
741     size_key = "#{dataclass.name}_size"
742     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
743         (@objects_map_for[size_key] == size)
744       return @objects_map_for[dataclass.name]
745     end
746
747     @objects_map_for[size_key] = size
748     @objects_map_for[dataclass.name] = dataclass.limit(size)
749   end
750
751   # helper method to get collections for the given uuid
752   helper_method :collections_for_object
753   def collections_for_object uuid
754     raise ArgumentError, 'No input argument' unless uuid
755     preload_collections_for_objects([uuid])
756     @all_collections_for[uuid] ||= []
757   end
758
759   # helper method to preload collections for the given uuids
760   helper_method :preload_collections_for_objects
761   def preload_collections_for_objects uuids
762     @all_collections_for ||= {}
763
764     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
765     return @all_collections_for if uuids.empty?
766
767     # if already preloaded for all of these uuids, return
768     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
769       return @all_collections_for
770     end
771
772     uuids.each do |x|
773       @all_collections_for[x] = []
774     end
775
776     # TODO: make sure we get every page of results from API server
777     Collection.where(uuid: uuids).each do |collection|
778       @all_collections_for[collection.uuid] << collection
779     end
780     @all_collections_for
781   end
782
783   # helper method to get log collections for the given log
784   helper_method :log_collections_for_object
785   def log_collections_for_object log
786     raise ArgumentError, 'No input argument' unless log
787
788     preload_log_collections_for_objects([log])
789
790     uuid = log
791     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
792     if fixup && fixup.size>1
793       uuid = fixup[1]
794     end
795
796     @all_log_collections_for[uuid] ||= []
797   end
798
799   # helper method to preload collections for the given uuids
800   helper_method :preload_log_collections_for_objects
801   def preload_log_collections_for_objects logs
802     @all_log_collections_for ||= {}
803
804     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
805     return @all_log_collections_for if logs.empty?
806
807     uuids = []
808     logs.each do |log|
809       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
810       if fixup && fixup.size>1
811         uuids << fixup[1]
812       else
813         uuids << log
814       end
815     end
816
817     # if already preloaded for all of these uuids, return
818     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
819       return @all_log_collections_for
820     end
821
822     uuids.each do |x|
823       @all_log_collections_for[x] = []
824     end
825
826     # TODO: make sure we get every page of results from API server
827     Collection.where(uuid: uuids).each do |collection|
828       @all_log_collections_for[collection.uuid] << collection
829     end
830     @all_log_collections_for
831   end
832
833   # helper method to get object of a given dataclass and uuid
834   helper_method :object_for_dataclass
835   def object_for_dataclass dataclass, uuid
836     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
837     preload_objects_for_dataclass(dataclass, [uuid])
838     @objects_for[uuid]
839   end
840
841   # helper method to preload objects for given dataclass and uuids
842   helper_method :preload_objects_for_dataclass
843   def preload_objects_for_dataclass dataclass, uuids
844     @objects_for ||= {}
845
846     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
847     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
848
849     return @objects_for if uuids.empty?
850
851     # if already preloaded for all of these uuids, return
852     if not uuids.select { |x| @objects_for[x].nil? }.any?
853       return @objects_for
854     end
855
856     dataclass.where(uuid: uuids).each do |obj|
857       @objects_for[obj.uuid] = obj
858     end
859     @objects_for
860   end
861
862 end