labimotion 2.2.0.rc22 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c79a031d59f881b26d04e1acb6863bff76a6164e096068268d7495042d8db0f0
4
- data.tar.gz: 3d84dc19e636a8c57734675e41d58ef16bb821e7d7be34be2cbe7b3196a3b804
3
+ metadata.gz: 5fc8d83e6c643b284cb25c8dc42610d4b42f3e0af1efb8b355f63bb6a4e8212f
4
+ data.tar.gz: f69aff320a11b70bde5e0e5c5d4f4d621795fa8c98e4dc1a318edc8599a8a21c
5
5
  SHA512:
6
- metadata.gz: 4ad9ee1d24b63e2ebdc8a6bf6ca338fe3170644c63bc50cafcd89a660250fef0747375617b394a8174644ead7461f2dcc1d81fa4095e7365e11b07517781af00
7
- data.tar.gz: 103e68dc679f80f3a214946361dc70ad5c1204336f567d17aaae4a9aa32298e56c23f4af4f545f07e27c9cdc8ccaea7bcc00e4978918af0b9d5f9baba6188785
6
+ metadata.gz: 5fec969db1fb1e89052a70d7076c6e6a149e7ce37dec8fe8d2809b9588930a277b2d99895c503a82e69504ea6c2cc8b889245ede972437a9f34d560e26b3c8ae
7
+ data.tar.gz: 9c45faf9b917299fae8fd27f24886388a4b829ed00309a540dc3b0cf2cb7078c2740bc327807bd1374c81902056c66fd0d1b5282e01c5f66a0d6cac3e4e3fb39
@@ -69,6 +69,25 @@ module Labimotion
69
69
  end
70
70
  end
71
71
 
72
+ namespace :create_dataset_klass do
73
+ desc 'create a new, inactive Generic Dataset Klass for an ontology term'
74
+ params do
75
+ requires :ols_term_id, type: String, desc: 'Ontology term ID, e.g. CHMO:0000656'
76
+ requires :label, type: String, desc: 'Label'
77
+ optional :desc, type: String, desc: 'Description; the label when left out'
78
+ end
79
+ post do
80
+ # Datasets are otherwise seeded, never created in the Designer; only the dataset
81
+ # designers that LABIMOTION_ADMIN names may add one.
82
+ authenticate_admin!('datasets')
83
+ error!('401 Unauthorized', 401) unless Labimotion::HubPush.allowed?(current_user)
84
+
85
+ klass = create_dataset_klass(params, current_user)
86
+ { mc: 'ss00', msg: "#{klass.label} was created, inactive.",
87
+ data: Labimotion::DatasetKlassEntity.represent(klass) }
88
+ end
89
+ end
90
+
72
91
  namespace :find_template do
73
92
  desc 'Find best matching template for given OLS term ID'
74
93
  params do
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Labimotion
4
+ ## HubPushAPI
5
+ # The Hub side of handing a dataset template to another Chemotion ELN (see
6
+ # Labimotion::HubPush). Declared under `generic_dataset` beside GenericDatasetAPI; Grape merges
7
+ # both into one route table.
8
+ class HubPushAPI < Grape::API
9
+ resource :generic_dataset do
10
+ namespace :hub_push do
11
+ desc 'whether the current user may create dataset templates and push them to another ELN ' \
12
+ '(LABIMOTION_ADMIN)'
13
+ get :permission do
14
+ { mc: 'ss00', allowed: Labimotion::HubPush.allowed?(current_user) }
15
+ end
16
+
17
+ desc 'have another Chemotion ELN import a dataset template of this Hub'
18
+ params do
19
+ requires :id, type: Integer, desc: 'Dataset Klass ID on this instance'
20
+ requires :url, type: String, desc: 'Base address of the target ELN'
21
+ requires :username, type: String, desc: 'Target ELN account (email or name abbreviation)'
22
+ requires :password, type: String, desc: 'Target ELN password; used once, never stored'
23
+ end
24
+ post do
25
+ error!('401 Unauthorized', 401) unless Labimotion::HubPush.allowed?(current_user)
26
+
27
+ klass = Labimotion::DatasetKlass.find_by(id: params[:id])
28
+ error!('This dataset template does not exist.', 404) if klass.nil?
29
+
30
+ result = Labimotion::HubPush.new(klass: klass, url: params[:url], username: params[:username],
31
+ password: params[:password]).call
32
+ Labimotion::HubPush.audit(current_user, klass, result)
33
+ { mc: 'ss00', msg: result[:message], data: result }
34
+ rescue Labimotion::HubPush::Error => e
35
+ error!(e.message, 422)
36
+ rescue StandardError => e
37
+ Labimotion.log_exception(e, current_user)
38
+ raise e
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -10,6 +10,7 @@ module Labimotion
10
10
  mount Labimotion::GenericDatasetAPI
11
11
  mount Labimotion::SegmentAPI
12
12
  mount Labimotion::LabimotionHubAPI
13
+ mount Labimotion::HubPushAPI
13
14
  mount Labimotion::StandardLayerAPI
14
15
  mount Labimotion::VocabularyAPI
15
16
  mount Labimotion::UserAPI
@@ -49,6 +49,35 @@ module Labimotion
49
49
  raise e
50
50
  end
51
51
 
52
+ # A prefix, a colon and a local ID, as in CHMO:0000656 — the form the dataset picker
53
+ # matches klasses by.
54
+ OLS_TERM_ID = /\A[A-Za-z][A-Za-z0-9_]*:[A-Za-z0-9_.-]+\z/
55
+
56
+ # A new dataset klass starts inactive, so the Hub leaves it out of its list until someone
57
+ # activates it, with an empty template released as its first revision, the way a new
58
+ # element klass starts.
59
+ def create_dataset_klass(params, current_user)
60
+ term = params[:ols_term_id].to_s.strip
61
+ label = params[:label].to_s.strip
62
+ validate_new_dataset_klass!(term, label)
63
+
64
+ uuid = SecureRandom.uuid
65
+ template = { 'uuid' => uuid, 'layers' => {}, 'select_options' => {}, 'klass' => 'DatasetKlass',
66
+ 'pkg' => Labimotion::Utils.pkg(nil) }
67
+ klass = Labimotion::DatasetKlass.create!(
68
+ ols_term_id: term, label: label, desc: params[:desc].to_s.strip.presence || label,
69
+ properties_template: template, properties_release: template, uuid: uuid, released_at: DateTime.now,
70
+ is_active: false, place: (Labimotion::DatasetKlass.with_deleted.maximum(:place) || 0) + 10,
71
+ created_by: current_user.id
72
+ )
73
+ klass.reload
74
+ klass.create_klasses_revision(current_user)
75
+ klass
76
+ rescue StandardError => e
77
+ Labimotion.log_exception(e, current_user)
78
+ raise e
79
+ end
80
+
52
81
  def find_best_match_template(ols_term_id)
53
82
  result = Labimotion::TemplateMatcher.find_best_match(ols_term_id)
54
83
  if result[:template]
@@ -60,6 +89,15 @@ module Labimotion
60
89
 
61
90
  private
62
91
 
92
+ # Soft-deleted klasses still hold their term in the unique index, so they count.
93
+ def validate_new_dataset_klass!(term, label)
94
+ error!("'#{term}' is not an ontology term ID like CHMO:0000656.", 422) unless OLS_TERM_ID.match?(term)
95
+ error!('Enter a label.', 422) if label.empty?
96
+ return unless Labimotion::DatasetKlass.with_deleted.exists?(ols_term_id: term)
97
+
98
+ error!("A dataset template for #{term} already exists.", 422)
99
+ end
100
+
63
101
  def build_template_response(template, match_type, info_messages)
64
102
  response = {
65
103
  error: '',
@@ -0,0 +1,247 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'openssl'
6
+ require 'uri'
7
+
8
+ module Labimotion
9
+ ## HubPush
10
+ # Hands a dataset template of this LabIMotion Hub to another Chemotion ELN that does not
11
+ # have it yet. The target needs nothing new: every step is a route it already serves
12
+ # (labimotion 2.3 included) —
13
+ # 1. POST public/token username + password -> JWT
14
+ # 2. GET generic_dataset/list_klass what the target holds for the term already
15
+ # 3. POST generic_dataset/create_repo_klass the target imports the template by identifier
16
+ # In step 3 the target downloads the template itself, from the Hub it is built against
17
+ # (Labimotion::TemplateHub::TARGET, www.chemotion-repository.net in production), so a push
18
+ # only lands when it is sent from that Hub. The Hub's fetch route serves a template by
19
+ # identifier whether or not it is active, so a template kept inactive here, and so left out
20
+ # of the Hub's list, can still be handed to the instances it is meant for.
21
+ class HubPush
22
+ ENV_KEY = 'LABIMOTION_ADMIN'
23
+ OPEN_TIMEOUT = 10
24
+ READ_TIMEOUT = 60
25
+
26
+ # A refusal the user can act on. Its message is shown to them as is, so it must never
27
+ # carry the password.
28
+ class Error < StandardError; end
29
+
30
+ # Who may create dataset templates and push them to another ELN: LABIMOTION_ADMIN, a comma-
31
+ # or space-separated list of the identifiers a user signs in with — an email (compared
32
+ # case-insensitively, the way Devise stores it) or a name abbreviation (compared exactly).
33
+ # Unset or empty means nobody.
34
+ def self.allowed?(user)
35
+ return false if user.nil?
36
+
37
+ email = user.respond_to?(:email) ? user.email.to_s.downcase : ''
38
+ abbreviation = user.respond_to?(:name_abbreviation) ? user.name_abbreviation.to_s : ''
39
+ admin_entries.any? do |entry|
40
+ entry.include?('@') ? entry.downcase == email : entry == abbreviation
41
+ end
42
+ end
43
+
44
+ # The split never yields an empty entry past the first, and that one is dropped, so an
45
+ # empty email or abbreviation can never match.
46
+ def self.admin_entries
47
+ ENV.fetch(ENV_KEY, '').split(/[\s,;]+/).reject(&:empty?)
48
+ end
49
+
50
+ # The target's base address: http(s) only, no credentials, query or fragment in it, and no
51
+ # trailing slash, so `<base>/api/v1/...` is what gets called. A path is kept for an ELN
52
+ # served below one (https://host/eln).
53
+ def self.base_uri(raw)
54
+ uri = URI.parse(raw.to_s.strip)
55
+ unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
56
+ raise Error, 'Enter the target ELN address, starting with http:// or https://.'
57
+ end
58
+ if uri.userinfo || uri.query || uri.fragment
59
+ raise Error, 'Enter only the address of the target ELN, without credentials, query or fragment.'
60
+ end
61
+
62
+ uri.path = uri.path.sub(%r{/+\z}, '')
63
+ uri
64
+ rescue URI::InvalidURIError
65
+ raise Error, 'The target ELN address is not a valid URL.'
66
+ end
67
+
68
+ # Who sent which template where, for the instance's own log: a push leaves the Hub under
69
+ # someone's name, so it is recorded. Never the credentials.
70
+ def self.audit(user, klass, result, logger: Labimotion.logger)
71
+ logger.info(
72
+ "[HubPush] user #{user&.id} pushed DatasetKlass #{klass.id} (#{klass.ols_term_id}, " \
73
+ "identifier #{klass.identifier}) to #{result[:target_url]}: #{result[:message]}"
74
+ )
75
+ end
76
+
77
+ attr_reader :klass, :base
78
+
79
+ def initialize(klass:, url:, username:, password:)
80
+ @klass = klass
81
+ @base = self.class.base_uri(url)
82
+ @username = username.to_s
83
+ @password = password.to_s
84
+ raise Error, 'Enter the username and password of the target ELN account.' if @username.empty? || @password.empty?
85
+ end
86
+
87
+ def call
88
+ ensure_pushable!
89
+ token = sign_in
90
+ ensure_target_free!(token)
91
+ message = import(token)
92
+ { target_url: base.to_s, label: klass.label, ols_term_id: klass.ols_term_id,
93
+ identifier: klass.identifier, version: klass.version, message: message }
94
+ end
95
+
96
+ private
97
+
98
+ def host
99
+ base.host
100
+ end
101
+
102
+ # The target receives what the Hub serves for the identifier: the released template. A
103
+ # template never released with any layer would arrive empty.
104
+ def ensure_pushable!
105
+ raise Error, "#{klass.label} has no identifier, so the target cannot import it." if klass.identifier.to_s.empty?
106
+
107
+ released = klass.properties_release
108
+ return if released.is_a?(Hash) && released['layers'].is_a?(Hash) && released['layers'].any?
109
+
110
+ raise Error, "#{klass.label} has no released template with layers yet; design and release it in the " \
111
+ 'Designer first.'
112
+ end
113
+
114
+ def sign_in
115
+ response = request(Net::HTTP::Post, 'public/token', body: { username: @username, password: @password })
116
+ raise Error, "#{host} rejected the username or password." if response.code == '401'
117
+
118
+ ensure_success!(response, 'sign in')
119
+ token = parse(response)['token']
120
+ raise Error, "#{host} did not return a sign-in token." if token.to_s.empty?
121
+
122
+ token
123
+ end
124
+
125
+ # create_repo_klass overwrites whatever the target holds for the term. That is wanted for
126
+ # an earlier push of this same template (same identifier: it is brought up to date) and
127
+ # for a never-released placeholder (what seeding leaves for each term); anything else is the
128
+ # target's own template, which a push must not replace.
129
+ def ensure_target_free!(token)
130
+ row = list_target_rows(token).find do |candidate|
131
+ candidate.is_a?(Hash) && candidate['ols_term_id'] == klass.ols_term_id
132
+ end
133
+ return if row.nil? || row['identifier'] == klass.identifier || row['released_at'].to_s.empty?
134
+
135
+ raise Error, "#{host} already has its own dataset template for #{klass.ols_term_id} " \
136
+ "(#{row['label']}); pushing would replace it, so nothing was sent."
137
+ end
138
+
139
+ # `list_klass` is the current route; a target older than it answers 404 and still serves
140
+ # the same list under `list_dataset_klass`, rooted at `klass`.
141
+ def list_target_rows(token)
142
+ response = request(Net::HTTP::Get, 'generic_dataset/list_klass', token: token)
143
+ response = request(Net::HTTP::Get, 'generic_dataset/list_dataset_klass', token: token) if response.code == '404'
144
+ ensure_success!(response, 'list its dataset templates')
145
+ listed = parse(response)
146
+ if listed.key?('mc') && listed['mc'] != 'ss00'
147
+ raise Error, "#{host} could not list its dataset templates: #{listed['msg']}"
148
+ end
149
+
150
+ Array(listed['data'] || listed['klass'])
151
+ end
152
+
153
+ # The target answers 201 either way and reports a failed download as `error`, which on a
154
+ # target that cannot reach this Hub is a bare Ruby message, so the likely cause is named.
155
+ def import(token)
156
+ response = request(Net::HTTP::Post, 'generic_dataset/create_repo_klass',
157
+ token: token, body: { identifier: klass.identifier })
158
+ # Since labimotion 2.4 the target lets only its dataset designers import.
159
+ if response.code == '401'
160
+ raise Error, "#{host} refused the import: the account needs the Dataset Designer right there."
161
+ end
162
+
163
+ ensure_success!(response, 'import the template')
164
+ imported = parse(response)
165
+ if imported['error'].to_s.empty? && imported['status'] == 'success'
166
+ return imported['message'].to_s.empty? ? "#{klass.label} was imported on #{host}." : imported['message']
167
+ end
168
+
169
+ raise Error, "#{host} could not download the template from its LabIMotion Hub " \
170
+ "(#{imported['error'] || imported['message']}). An ELN in production downloads from " \
171
+ 'www.chemotion-repository.net, one in development from http://localhost:3000/; the push ' \
172
+ 'must come from that instance, and the ELN must reach it. Its log/labimotion.log has the cause.'
173
+ end
174
+
175
+ def request(verb, path, body: nil, token: nil)
176
+ uri = base.dup
177
+ uri.path = "#{base.path}/api/v1/#{path}"
178
+ req = verb.new(uri)
179
+ req['Accept'] = 'application/json'
180
+ req['Authorization'] = "Bearer #{token}" if token
181
+ # create_repo_klass forwards its Origin to the Hub, which requires and logs one: the
182
+ # instance that downloads the template, the way its own browser would send it.
183
+ req['Origin'] = origin
184
+ if body
185
+ req['Content-Type'] = 'application/json'
186
+ req.body = body.to_json
187
+ end
188
+ # Net::HTTP does not follow redirects, which is wanted: a redirect would carry the
189
+ # credentials to wherever it points.
190
+ permitting_loads do
191
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
192
+ open_timeout: OPEN_TIMEOUT, read_timeout: READ_TIMEOUT) do |http|
193
+ http.request(req)
194
+ end
195
+ end
196
+ rescue SocketError, SystemCallError, IOError, Timeout::Error, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e
197
+ raise Error, "Cannot reach #{host}: #{e.message}"
198
+ end
199
+
200
+ # The import makes the target call back into this instance, the Hub it downloads from.
201
+ # Without eager loading (development), a request that autoloads waits until no other
202
+ # request is running app code, and this one would sit waiting on the target, which waits
203
+ # on that request, until the target's 10 s timeout. Waiting on the network, it lets loads
204
+ # through, the way Rails asks of code that blocks on another thread.
205
+ def permitting_loads
206
+ interlock = ActiveSupport::Dependencies.interlock if defined?(ActiveSupport::Dependencies.interlock)
207
+ return yield unless interlock
208
+
209
+ # The cop's `&block` form is then flagged for anonymous forwarding, which Ruby 2.7 lacks.
210
+ interlock.permit_concurrent_loads { yield } # rubocop:disable Style/ExplicitBlockArgument
211
+ end
212
+
213
+ def origin
214
+ port = base.port == base.default_port ? '' : ":#{base.port}"
215
+ "#{base.scheme}://#{base.host}#{port}"
216
+ end
217
+
218
+ def ensure_success!(response, doing)
219
+ return if response.is_a?(Net::HTTPSuccess)
220
+
221
+ if response.is_a?(Net::HTTPRedirection)
222
+ raise Error, "#{host} redirected to #{response['location']}; enter that address as the target instead."
223
+ end
224
+
225
+ reason = refusal_text(response)
226
+ raise Error, "#{host} refused to #{doing} (HTTP #{response.code})#{reason.empty? ? '.' : ": #{reason}"}"
227
+ end
228
+
229
+ # The target's own sentence when it sent one: Grape's refusals carry `error`, the
230
+ # labimotion routes `msg`.
231
+ def refusal_text(response)
232
+ body = JSON.parse(response.body.to_s)
233
+ body.is_a?(Hash) ? (body['error'] || body['msg'] || body['message']).to_s : ''
234
+ rescue JSON::ParserError
235
+ ''
236
+ end
237
+
238
+ def parse(response)
239
+ parsed = JSON.parse(response.body.to_s)
240
+ raise JSON::ParserError, 'not an object' unless parsed.is_a?(Hash)
241
+
242
+ parsed
243
+ rescue JSON::ParserError
244
+ raise Error, "#{host} did not answer like a Chemotion ELN (HTTP #{response.code}); check the address."
245
+ end
246
+ end
247
+ end
@@ -2,5 +2,5 @@
2
2
 
3
3
  ## Labimotion Version
4
4
  module Labimotion
5
- VERSION = '2.2.0.rc22'
5
+ VERSION = '2.2.1'
6
6
  end
data/lib/labimotion.rb CHANGED
@@ -23,6 +23,7 @@ module Labimotion
23
23
  autoload :GenericDatasetAPI, 'labimotion/apis/generic_dataset_api'
24
24
  autoload :SegmentAPI, 'labimotion/apis/segment_api'
25
25
  autoload :LabimotionHubAPI, 'labimotion/apis/labimotion_hub_api'
26
+ autoload :HubPushAPI, 'labimotion/apis/hub_push_api'
26
27
  autoload :ConverterAPI, 'labimotion/apis/converter_api'
27
28
  autoload :ExporterAPI, 'labimotion/apis/exporter_api'
28
29
  autoload :StandardLayerAPI, 'labimotion/apis/standard_layer_api'
@@ -85,6 +86,7 @@ module Labimotion
85
86
  autoload :NmrMapper, 'labimotion/libs/nmr_mapper'
86
87
  autoload :NmrMapperRepo, 'labimotion/libs/nmr_mapper_repo' ## for Chemotion Repository
87
88
  autoload :TemplateHub, 'labimotion/libs/template_hub'
89
+ autoload :HubPush, 'labimotion/libs/hub_push'
88
90
  autoload :TemplateMatcher, 'labimotion/libs/template_matcher'
89
91
  autoload :ExportDataset, 'labimotion/libs/export_dataset'
90
92
  autoload :SampleAssociation, 'labimotion/libs/sample_association'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: labimotion
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.0.rc22
4
+ version: 2.2.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Chia-Lin Lin
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2026-07-29 00:00:00.000000000 Z
12
+ date: 2026-11-12 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: caxlsx
@@ -63,6 +63,7 @@ files:
63
63
  - lib/labimotion/apis/generic_dataset_api.rb
64
64
  - lib/labimotion/apis/generic_element_api.rb
65
65
  - lib/labimotion/apis/generic_klass_api.rb
66
+ - lib/labimotion/apis/hub_push_api.rb
66
67
  - lib/labimotion/apis/labimotion_api.rb
67
68
  - lib/labimotion/apis/labimotion_doi_api.rb
68
69
  - lib/labimotion/apis/labimotion_hub_api.rb
@@ -119,6 +120,7 @@ files:
119
120
  - lib/labimotion/libs/dataset_builder.rb
120
121
  - lib/labimotion/libs/export_dataset.rb
121
122
  - lib/labimotion/libs/export_element.rb
123
+ - lib/labimotion/libs/hub_push.rb
122
124
  - lib/labimotion/libs/nmr_mapper.rb
123
125
  - lib/labimotion/libs/properties_handler.rb
124
126
  - lib/labimotion/libs/sample_association.rb
@@ -206,9 +208,9 @@ required_ruby_version: !ruby/object:Gem::Requirement
206
208
  version: '3.4'
207
209
  required_rubygems_version: !ruby/object:Gem::Requirement
208
210
  requirements:
209
- - - ">"
211
+ - - ">="
210
212
  - !ruby/object:Gem::Version
211
- version: 1.3.1
213
+ version: '0'
212
214
  requirements: []
213
215
  rubygems_version: 3.1.6
214
216
  signing_key: