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