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