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)
110 @discovered_columns = [] if !defined?(@discovered_columns)
111 return @discovered_columns if @discovered_columns.andand.any?
112 @attribute_info ||= {}
113 schema = arvados_api_client.discovery[:schemas][self.to_s.to_sym]
114 return @discovered_columns if schema.nil?
115 schema[:properties].each do |k, coldef|
120 if coldef[:type] == coldef[:type].downcase
121 # boolean, integer, etc.
122 @discovered_columns << column(k, coldef[:type])
125 @discovered_columns << column(k, coldef[:type], coldef[:type].constantize.new)
128 @attribute_info[k] = coldef
135 # dup method doesn't reset the uuid attr
136 @uuid.nil? || @new_record || false
139 def initialize_dup(other)
145 def self.column(name, sql_type = nil, default = nil, null = true)
146 caster = case sql_type
148 ActiveModel::Type::Integer
149 when 'string', 'text'
150 ActiveModel::Type::String
152 ActiveModel::Type::Float
154 ActiveModel::Type::DateTime
156 ActiveModel::Type::Boolean
158 ArvadosBase::Type::Hash
160 ArvadosBase::Type::Array
162 ArvadosBase::Type::Hash
164 raise ArvadosBase::Error.new("Type unknown: #{sql_type}")
166 define_method "#{name}=" do |val|
167 val = default if val.nil?
168 casted_value = caster.new.cast(val)
169 attribute_will_change!(name) if send(name) != casted_value
170 set_attribute_after_cast(name, casted_value)
172 Column.new(name.to_s)
175 def set_attribute_after_cast(name, casted_value)
176 instance_variable_set("@#{name}", casted_value)
183 Rails.logger.debug "BUG: access non-loaded attribute #{attr_name}"
188 def []=(attr_name, attr_val)
189 send("#{attr_name}=", attr_val)
192 def self.attribute_info
197 def self.find(uuid, opts={})
198 if uuid.class != String or uuid.length < 27 then
199 raise 'argument to find() must be a uuid string. Acceptable formats: warehouse locator or string with format xxxxx-xxxxx-xxxxxxxxxxxxxxx'
202 if self == ArvadosBase
203 # Determine type from uuid and defer to the appropriate subclass.
204 return resource_class_for_uuid(uuid).find(uuid, opts)
207 # Only do one lookup on the API side per {class, uuid, workbench
208 # request} unless {cache: false} is given via opts.
209 cache_key = "request_#{Thread.current.object_id}_#{self.to_s}_#{uuid}"
210 if opts[:cache] == false
211 Rails.cache.write cache_key, arvados_api_client.api(self, '/' + uuid)
213 hash = Rails.cache.fetch cache_key do
214 arvados_api_client.api(self, '/' + uuid)
216 new.private_reload(hash)
219 def self.find?(*args)
220 find(*args) rescue nil
223 def self.order(*args)
224 ArvadosResourceList.new(self).order(*args)
227 def self.filter(*args)
228 ArvadosResourceList.new(self).filter(*args)
231 def self.where(*args)
232 ArvadosResourceList.new(self).where(*args)
235 def self.limit(*args)
236 ArvadosResourceList.new(self).limit(*args)
239 def self.select(*args)
240 ArvadosResourceList.new(self).select(*args)
243 def self.with_count(*args)
244 ArvadosResourceList.new(self).with_count(*args)
247 def self.distinct(*args)
248 ArvadosResourceList.new(self).distinct(*args)
251 def self.include_trash(*args)
252 ArvadosResourceList.new(self).include_trash(*args)
255 def self.recursive(*args)
256 ArvadosResourceList.new(self).recursive(*args)
259 def self.eager(*args)
260 ArvadosResourceList.new(self).eager(*args)
264 ArvadosResourceList.new(self)
267 def self.permit_attribute_params raw_params
268 # strong_parameters does not provide security in Workbench: anyone
269 # who can get this far can just as well do a call directly to our
270 # database (Arvados) with the same credentials we use.
272 # The following permit! is necessary even with
273 # "ActionController::Parameters.permit_all_parameters = true",
274 # because permit_all does not permit nested attributes.
275 if !raw_params.is_a? ActionController::Parameters
276 raw_params = ActionController::Parameters.new(raw_params)
281 def self.create raw_params={}, create_params={}
282 x = new(permit_attribute_params(raw_params), create_params)
287 def self.create! raw_params={}, create_params={}
288 x = new(permit_attribute_params(raw_params), create_params)
294 self.name.underscore.pluralize.downcase
297 def update_attributes raw_params={}
298 assign_attributes(self.class.permit_attribute_params(raw_params))
302 def update_attributes! raw_params={}
303 assign_attributes(self.class.permit_attribute_params(raw_params))
309 self.class.columns.each do |col|
310 # Non-nil serialized values must be sent because we can't tell
311 # whether they've changed. Other than that, any given attribute
312 # is either unchanged (in which case there's no need to send its
313 # old value in the update/create command) or has been added to
314 # #changed by ActiveRecord's #attr= method.
315 if changed.include? col.name or
316 ([Hash, Array].include?(attributes[col.name].class) and
317 @loaded_attributes[col.name])
318 obdata[col.name.to_sym] = self.send col.name
322 postdata = { self.class.to_s.underscore => obdata }
324 postdata['_method'] = 'PUT'
326 resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
329 @create_params = @create_params.to_unsafe_hash if @create_params.is_a? ActionController::Parameters
330 postdata.merge!(@create_params)
332 resp = arvados_api_client.api(self.class, '', postdata)
334 return false if !resp[:etag] || !resp[:uuid]
336 # set read-only non-database attributes
340 # attributes can be modified during "save" -- we should update our copies
341 resp.keys.each do |attr|
342 if self.respond_to? "#{attr}=".to_sym
343 self.send(attr.to_s + '=', resp[attr.to_sym])
354 self.save or raise Exception.new("Save failed")
358 (!new_record? && !destroyed?) ? true : false
362 !(new_record? || etag || uuid)
367 postdata = { '_method' => 'DELETE' }
368 resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
369 resp[:etag] && resp[:uuid] && resp
377 o.merge!(args.pop) if args[-1].is_a? Hash
378 o[:link_class] ||= args.shift
379 o[:name] ||= args.shift
380 o[:tail_uuid] = self.uuid
382 return all_links.select do |m|
387 if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
395 @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
396 @links = arvados_api_client.unpack_api_response(@links)
400 return @all_links if @all_links
401 res = arvados_api_client.api Link, '', {
404 tail_kind: self.kind,
409 @all_links = arvados_api_client.unpack_api_response(res)
413 private_reload(self.uuid)
416 def private_reload(uuid_or_hash)
417 raise "No such object" if !uuid_or_hash
418 if uuid_or_hash.is_a? Hash
421 hash = arvados_api_client.api(self.class, '/' + uuid_or_hash)
424 @loaded_attributes[k.to_s] = true
425 if self.respond_to?(k.to_s + '=')
426 self.send(k.to_s + '=', v)
428 # When ArvadosApiClient#schema starts telling us what to expect
429 # in API responses (not just the server side database
430 # columns), this sort of awfulness can be avoided:
431 self.instance_variable_set('@' + k.to_s, v)
432 if !self.respond_to? k
433 singleton = class << self; self end
434 singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
448 def initialize_copy orig
454 kv = self.class.columns.collect {|c| c.name}.map {|key| [key, send(key)]}
458 def attributes_for_display
459 self.attributes.reject { |k,v|
460 attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
462 attribute_sortkey[k] or k
466 def class_for_display
467 self.class.to_s.underscore.humanize
470 def self.class_for_display
471 self.to_s.underscore.humanize
474 # Array of strings that are names of attributes that should be rendered as textile.
475 def textile_attributes
480 current_user.andand.is_active && api_exists?(:create)
483 def self.goes_in_projects?
487 # can this class of object be copied into a project?
488 # override to false on indivudal model classes for which this should not be true
489 def self.copies_to_projects?
490 self.goes_in_projects?
494 (current_user and current_user.is_active and
495 (current_user.is_admin or
496 current_user.uuid == self.owner_uuid or
498 (respond_to?(:writable_by) ?
499 writable_by.include?(current_user.uuid) :
500 (ArvadosBase.find(owner_uuid).writable_by.include? current_user.uuid rescue false)))) or false
507 def self.api_exists?(method)
508 arvados_api_client.discovery[:resources][self.to_s.underscore.pluralize.to_sym].andand[:methods].andand[method]
511 # Array of strings that are the names of attributes that can be edited
513 def editable_attributes
514 self.class.columns.map(&:name) -
515 %w(created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at)
518 def attribute_editable?(attr, ever=nil)
519 if not editable_attributes.include?(attr.to_s)
521 elsif not (current_user.andand.is_active)
524 current_user.is_admin
532 def self.resource_class_for_uuid(uuid, opts={})
533 if uuid.is_a? ArvadosBase
536 unless uuid.is_a? String
539 if opts[:class].is_a? Class
542 if uuid.match(/^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/)
546 uuid.match(/^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/) do |re|
547 resource_class ||= arvados_api_client.
548 kind_class(self.uuid_infix_object_kind[re[1]])
550 if opts[:referring_object] and
551 opts[:referring_attr] and
552 opts[:referring_attr].match(/_uuid$/)
553 resource_class ||= arvados_api_client.
554 kind_class(opts[:referring_object].
555 attributes[opts[:referring_attr].
556 sub(/_uuid$/, '_kind')])
561 def resource_param_name
562 self.class.to_s.underscore
565 def friendly_link_name lookup=nil
566 (name if self.respond_to? :name) || default_name
570 self.class_for_display
577 def self.default_name
578 self.to_s.underscore.humanize
582 (self.class.to_s.pluralize + 'Controller').constantize
586 self.class.to_s.tableize
589 # Placeholder for name when name is missing or empty
591 if self.respond_to? :name
592 "New #{class_for_display.downcase}"
599 ArvadosBase.find(owner_uuid) rescue nil
610 def self.current_user
611 Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
612 Thread.current[:user]
615 self.class.current_user