1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
6 include ActiveModel::Validations
7 include ActiveModel::Conversion
8 include ActiveModel::Serialization
9 include ActiveModel::Dirty
10 include ActiveModel::AttributeAssignment
11 extend ActiveModel::Naming
13 Column = Struct.new("Column", :name)
15 attr_accessor :attribute_sortkey
16 attr_accessor :create_params
18 class Error < StandardError; end
21 class Hash < ActiveModel::Type::Value
32 (value.class == String) ? ::JSON.parse(value) : value
36 class Array < ActiveModel::Type::Value
47 (value.class == String) ? ::JSON.parse(value) : value
52 def self.arvados_api_client
53 ArvadosApiClient.new_or_current
56 def arvados_api_client
57 ArvadosApiClient.new_or_current
60 def self.uuid_infix_object_kind
61 @@uuid_infix_object_kind ||=
64 arvados_api_client.discovery[:schemas].each do |name, schema|
65 if schema[:uuidPrefix]
66 infix_kind[schema[:uuidPrefix]] =
67 'arvados#' + name.to_s.camelcase(:lower)
71 # Recognize obsolete types.
73 merge('mxsvm' => 'arvados#pipelineTemplate', # Pipeline
74 'uo14g' => 'arvados#pipelineInstance', # PipelineInvocation
75 'ldvyl' => 'arvados#group') # Project
79 def initialize raw_params={}, create_params={}
80 self.class.permit_attribute_params(raw_params)
81 @create_params = create_params
82 @attribute_sortkey ||= {
85 'owner_uuid' => '002',
86 'event_type' => '100',
87 'link_class' => '100',
88 'group_class' => '100',
91 'object_uuid' => '102',
93 'description' => '104',
94 'properties' => '150',
96 'created_at' => '200',
97 'modified_at' => '201',
98 'modified_by_user_uuid' => '202',
99 'modified_by_client_uuid' => '203',
102 @loaded_attributes = {}
103 attributes = self.class.columns.map { |c| [c.name.to_sym, nil] }.to_h.merge(raw_params)
104 attributes.symbolize_keys.each do |name, value|
105 send("#{name}=", value)
109 # The ActiveModel::Dirty API was changed on Rails 5.2
110 # See: https://github.com/rails/rails/commit/c3675f50d2e59b7fc173d7b332860c4b1a24a726#diff-aaddd42c7feb0834b1b5c66af69814d3
111 def mutations_from_database
112 @mutations_from_database ||= ActiveModel::NullMutationTracker.instance
116 @discovered_columns = [] if !defined?(@discovered_columns)
117 return @discovered_columns if @discovered_columns.andand.any?
118 @attribute_info ||= {}
119 schema = arvados_api_client.discovery[:schemas][self.to_s.to_sym]
120 return @discovered_columns if schema.nil?
121 schema[:properties].each do |k, coldef|
126 if coldef[:type] == coldef[:type].downcase
127 # boolean, integer, etc.
128 @discovered_columns << column(k, coldef[:type])
131 @discovered_columns << column(k, coldef[:type], coldef[:type].constantize.new)
134 @attribute_info[k] = coldef
141 # dup method doesn't reset the uuid attr
142 @uuid.nil? || @new_record || false
145 def initialize_dup(other)
151 def self.column(name, sql_type = nil, default = nil, null = true)
152 caster = case sql_type
154 ActiveModel::Type::Integer
155 when 'string', 'text'
156 ActiveModel::Type::String
158 ActiveModel::Type::Float
160 ActiveModel::Type::DateTime
162 ActiveModel::Type::Boolean
164 ArvadosBase::Type::Hash
166 ArvadosBase::Type::Array
168 ArvadosBase::Type::Hash
170 raise ArvadosBase::Error.new("Type unknown: #{sql_type}")
172 define_method "#{name}=" do |val|
173 val = default if val.nil?
174 casted_value = caster.new.cast(val)
175 attribute_will_change!(name) if send(name) != casted_value
176 set_attribute_after_cast(name, casted_value)
178 Column.new(name.to_s)
181 def set_attribute_after_cast(name, casted_value)
182 instance_variable_set("@#{name}", casted_value)
189 Rails.logger.debug "BUG: access non-loaded attribute #{attr_name}"
194 def []=(attr_name, attr_val)
195 send("#{attr_name}=", attr_val)
198 def self.attribute_info
203 def self.find(uuid, opts={})
204 if uuid.class != String or uuid.length < 27 then
205 raise 'argument to find() must be a uuid string. Acceptable formats: warehouse locator or string with format xxxxx-xxxxx-xxxxxxxxxxxxxxx'
208 if self == ArvadosBase
209 # Determine type from uuid and defer to the appropriate subclass.
210 return resource_class_for_uuid(uuid).find(uuid, opts)
213 # Only do one lookup on the API side per {class, uuid, workbench
214 # request} unless {cache: false} is given via opts.
215 cache_key = "request_#{Thread.current.object_id}_#{self.to_s}_#{uuid}"
216 if opts[:cache] == false
217 Rails.cache.write cache_key, arvados_api_client.api(self, '/' + uuid)
219 hash = Rails.cache.fetch cache_key do
220 arvados_api_client.api(self, '/' + uuid)
222 new.private_reload(hash)
225 def self.find?(*args)
226 find(*args) rescue nil
229 def self.order(*args)
230 ArvadosResourceList.new(self).order(*args)
233 def self.filter(*args)
234 ArvadosResourceList.new(self).filter(*args)
237 def self.where(*args)
238 ArvadosResourceList.new(self).where(*args)
241 def self.limit(*args)
242 ArvadosResourceList.new(self).limit(*args)
245 def self.select(*args)
246 ArvadosResourceList.new(self).select(*args)
249 def self.with_count(*args)
250 ArvadosResourceList.new(self).with_count(*args)
253 def self.distinct(*args)
254 ArvadosResourceList.new(self).distinct(*args)
257 def self.include_trash(*args)
258 ArvadosResourceList.new(self).include_trash(*args)
261 def self.recursive(*args)
262 ArvadosResourceList.new(self).recursive(*args)
265 def self.eager(*args)
266 ArvadosResourceList.new(self).eager(*args)
270 ArvadosResourceList.new(self)
273 def self.permit_attribute_params raw_params
274 # strong_parameters does not provide security in Workbench: anyone
275 # who can get this far can just as well do a call directly to our
276 # database (Arvados) with the same credentials we use.
278 # The following permit! is necessary even with
279 # "ActionController::Parameters.permit_all_parameters = true",
280 # because permit_all does not permit nested attributes.
281 if !raw_params.is_a? ActionController::Parameters
282 raw_params = ActionController::Parameters.new(raw_params)
287 def self.create raw_params={}, create_params={}
288 x = new(permit_attribute_params(raw_params), create_params)
293 def self.create! raw_params={}, create_params={}
294 x = new(permit_attribute_params(raw_params), create_params)
300 self.name.underscore.pluralize.downcase
303 def update_attributes raw_params={}
304 assign_attributes(self.class.permit_attribute_params(raw_params))
308 def update_attributes! raw_params={}
309 assign_attributes(self.class.permit_attribute_params(raw_params))
315 self.class.columns.each do |col|
316 # Non-nil serialized values must be sent because we can't tell
317 # whether they've changed. Other than that, any given attribute
318 # is either unchanged (in which case there's no need to send its
319 # old value in the update/create command) or has been added to
320 # #changed by ActiveRecord's #attr= method.
321 if changed.include? col.name or
322 ([Hash, Array].include?(attributes[col.name].class) and
323 @loaded_attributes[col.name])
324 obdata[col.name.to_sym] = self.send col.name
328 postdata = { self.class.to_s.underscore => obdata }
330 postdata['_method'] = 'PUT'
332 resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
335 @create_params = @create_params.to_unsafe_hash if @create_params.is_a? ActionController::Parameters
336 postdata.merge!(@create_params)
338 resp = arvados_api_client.api(self.class, '', postdata)
340 return false if !resp[:etag] || !resp[:uuid]
342 # set read-only non-database attributes
346 # attributes can be modified during "save" -- we should update our copies
347 resp.keys.each do |attr|
348 if self.respond_to? "#{attr}=".to_sym
349 self.send(attr.to_s + '=', resp[attr.to_sym])
360 self.save or raise Exception.new("Save failed")
364 (!new_record? && !destroyed?) ? true : false
368 !(new_record? || etag || uuid)
373 postdata = { '_method' => 'DELETE' }
374 resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
375 resp[:etag] && resp[:uuid] && resp
383 o.merge!(args.pop) if args[-1].is_a? Hash
384 o[:link_class] ||= args.shift
385 o[:name] ||= args.shift
386 o[:tail_uuid] = self.uuid
388 return all_links.select do |m|
393 if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
401 @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
402 @links = arvados_api_client.unpack_api_response(@links)
406 return @all_links if @all_links
407 res = arvados_api_client.api Link, '', {
410 tail_kind: self.kind,
415 @all_links = arvados_api_client.unpack_api_response(res)
419 private_reload(self.uuid)
422 def private_reload(uuid_or_hash)
423 raise "No such object" if !uuid_or_hash
424 if uuid_or_hash.is_a? Hash
427 hash = arvados_api_client.api(self.class, '/' + uuid_or_hash)
430 @loaded_attributes[k.to_s] = true
431 if self.respond_to?(k.to_s + '=')
432 self.send(k.to_s + '=', v)
434 # When ArvadosApiClient#schema starts telling us what to expect
435 # in API responses (not just the server side database
436 # columns), this sort of awfulness can be avoided:
437 self.instance_variable_set('@' + k.to_s, v)
438 if !self.respond_to? k
439 singleton = class << self; self end
440 singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
454 def initialize_copy orig
460 kv = self.class.columns.collect {|c| c.name}.map {|key| [key, send(key)]}
464 def attributes_for_display
465 self.attributes.reject { |k,v|
466 attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
468 attribute_sortkey[k] or k
472 def class_for_display
473 self.class.to_s.underscore.humanize
476 def self.class_for_display
477 self.to_s.underscore.humanize
480 # Array of strings that are names of attributes that should be rendered as textile.
481 def textile_attributes
486 current_user.andand.is_active && api_exists?(:create)
489 def self.goes_in_projects?
493 # can this class of object be copied into a project?
494 # override to false on indivudal model classes for which this should not be true
495 def self.copies_to_projects?
496 self.goes_in_projects?
500 (current_user and current_user.is_active and
501 (current_user.is_admin or
502 current_user.uuid == self.owner_uuid or
504 (respond_to?(:writable_by) ?
505 writable_by.include?(current_user.uuid) :
506 (ArvadosBase.find(owner_uuid).writable_by.include? current_user.uuid rescue false)))) or false
513 def self.api_exists?(method)
514 arvados_api_client.discovery[:resources][self.to_s.underscore.pluralize.to_sym].andand[:methods].andand[method]
517 # Array of strings that are the names of attributes that can be edited
519 def editable_attributes
520 self.class.columns.map(&:name) -
521 %w(created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at)
524 def attribute_editable?(attr, ever=nil)
525 if not editable_attributes.include?(attr.to_s)
527 elsif not (current_user.andand.is_active)
530 current_user.is_admin
538 def self.resource_class_for_uuid(uuid, opts={})
539 if uuid.is_a? ArvadosBase
542 unless uuid.is_a? String
545 if opts[:class].is_a? Class
548 if uuid.match(/^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/)
552 uuid.match(/^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/) do |re|
553 resource_class ||= arvados_api_client.
554 kind_class(self.uuid_infix_object_kind[re[1]])
556 if opts[:referring_object] and
557 opts[:referring_attr] and
558 opts[:referring_attr].match(/_uuid$/)
559 resource_class ||= arvados_api_client.
560 kind_class(opts[:referring_object].
561 attributes[opts[:referring_attr].
562 sub(/_uuid$/, '_kind')])
567 def resource_param_name
568 self.class.to_s.underscore
571 def friendly_link_name lookup=nil
572 (name if self.respond_to? :name) || default_name
576 self.class_for_display
583 def self.default_name
584 self.to_s.underscore.humanize
588 (self.class.to_s.pluralize + 'Controller').constantize
592 self.class.to_s.tableize
595 # Placeholder for name when name is missing or empty
597 if self.respond_to? :name
598 "New #{class_for_display.downcase}"
605 ArvadosBase.find(owner_uuid) rescue nil
616 def self.current_user
617 Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
618 Thread.current[:user]
621 self.class.current_user