fhir_stub_server 0.1.0

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.
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FHIRStubServer
4
+ # Loads Demo Data from an ordered list of Sources into one `Type/id` index; later Sources win.
5
+ # A Source is `package: <FHIR NPM package .tgz>` or `bundle: <Bundle .json>`.
6
+ # @api private
7
+ module Sources
8
+ MODELS = { '1.0' => 'dstu2', '3.0' => 'stu3', '4.0' => 'r4', '5.0' => 'r5' }.freeze
9
+
10
+ # Returns the index, the load-time #served entries for resources skipped for having no id,
11
+ # and the fhirpath-rb model of the packages' FHIR version. Source paths are relative to `dir`.
12
+ def self.load(sources, dir)
13
+ loaded = sources.map { |source| located_resources(source, dir) }
14
+ kept, skipped = loaded.flat_map(&:first).partition { |_, resource| resource['id'] }
15
+ [index(kept), skipped_entries(skipped), model(loaded.filter_map(&:last))]
16
+ end
17
+
18
+ # The model every package stating FHIR versions supports, in the first one's order; R4 when
19
+ # none states any, as a Bundle carries none.
20
+ def self.model(stated)
21
+ stated = stated.reject { |_, versions| versions.empty? }
22
+ common = stated.map { |path, versions| models(path, versions) }.reduce(:&) || ['r4']
23
+ common.first || raise(no_common_version(stated))
24
+ end
25
+
26
+ def self.no_common_version(stated)
27
+ packages = stated.map { |path, versions| "#{path} (#{versions.join(', ')})" }
28
+ Error.new("Demo Data packages share no FHIR version: #{packages.join(', ')}")
29
+ end
30
+
31
+ # The models for a package's FHIR versions, skipping versions without one.
32
+ def self.models(path, versions)
33
+ models = versions.filter_map { |version| MODELS[version.to_s[/\A\d+\.\d+/].to_s] }
34
+ return models unless models.empty?
35
+
36
+ raise Error, "#{path}: FHIR #{versions.join(', ')} has no FHIRPath model"
37
+ end
38
+
39
+ def self.index(located)
40
+ located.to_h { |_, resource| [key(resource), resource] }
41
+ end
42
+
43
+ def self.skipped_entries(skipped)
44
+ skipped.map { |location, _| { kind: :load, skipped: location, reason: 'resource without id' } }
45
+ end
46
+
47
+ # What the built-in reads answer: `/<Type>/<id>` for every resource, and `/metadata` for the
48
+ # one CapabilityStatement with a `server` rest mode (an IG's responder), when there is one.
49
+ def self.reads(demo_data)
50
+ reads = demo_data.transform_keys { |key| "/#{key}" }
51
+ metadata = server_capability_statement(demo_data.values)
52
+ metadata ? reads.merge('/metadata' => metadata) : reads
53
+ end
54
+
55
+ def self.server_capability_statement(resources)
56
+ servers = resources.select { |resource| server?(resource) }
57
+ return servers.first unless servers.size > 1
58
+
59
+ raise Error, "Demo Data has several server CapabilityStatements (#{servers.map { |cs| cs['id'] }.join(', ')}); " \
60
+ '/metadata needs at most one'
61
+ end
62
+
63
+ def self.server?(resource)
64
+ resource['resourceType'] == 'CapabilityStatement' &&
65
+ resource['rest'].to_a.any? { |rest| rest['mode'] == 'server' }
66
+ end
67
+
68
+ def self.key(resource)
69
+ "#{resource['resourceType']}/#{resource['id']}"
70
+ end
71
+
72
+ # A Source's resources as [location, resource] pairs, the location naming the file, and for
73
+ # a package [path, the FHIR versions it states].
74
+ def self.located_resources(source, dir)
75
+ package, bundle = source.values_at('package', 'bundle').map { |path| File.expand_path(path, dir) if path }
76
+ return package_resources(package) if package
77
+ return [bundle_resources(bundle), nil] if bundle
78
+
79
+ raise Error, "Unknown Source: #{source.inspect}"
80
+ end
81
+
82
+ # Every JSON file with a resourceType: examples and conformance resources alike. Anything
83
+ # else (.index.json, openapi/, xml/, empty files) is not a resource and is left out; of
84
+ # package.json only `fhirVersions` counts. Bundles stay whole.
85
+ def self.package_resources(path)
86
+ files = json_files(path)
87
+ resources = files.filter_map do |name, json|
88
+ ["#{path} (#{name})", json] if json.key?('resourceType')
89
+ end #: Array[located]
90
+ [no_duplicates(resources), [path, Array(files.to_h['package/package.json'].to_h['fhirVersions'])]]
91
+ end
92
+
93
+ def self.json_files(path)
94
+ Zlib::GzipReader.wrap(StringIO.new(FHIRStubServer.read_file(path).b)) { |archive| tar_json_files(archive) }
95
+ rescue Zlib::Error, Gem::Package::TarInvalidError => error
96
+ raise Error, "#{path}: not a FHIR package .tgz (#{error.message})"
97
+ end
98
+
99
+ def self.tar_json_files(archive)
100
+ Gem::Package::TarReader.new(archive).filter_map do |entry|
101
+ name = entry.full_name
102
+ json = json(entry) if name.end_with?('.json')
103
+ [name, json] if json.is_a?(Hash)
104
+ end
105
+ end
106
+
107
+ def self.json(entry)
108
+ JSON.parse(entry.read.to_s)
109
+ rescue JSON::ParserError
110
+ nil
111
+ end
112
+
113
+ def self.bundle_resources(path)
114
+ entries = FHIRStubServer.parse_file(path, :json)['entry'].to_a
115
+ # An entry without a resource (a delete in a transaction) adds nothing.
116
+ entries.each_with_index.filter_map do |entry, index|
117
+ resource = entry['resource']
118
+ ["#{path} (entry[#{index}])", resource] if resource
119
+ end
120
+ end
121
+
122
+ # Tar order is not meaningful, so two files with one `Type/id` in a package are an error.
123
+ def self.no_duplicates(located)
124
+ key, copies = duplicate(located)
125
+ raise Error, "#{key} is in both #{copies.map(&:first).join(' and ')}" if copies
126
+
127
+ located
128
+ end
129
+
130
+ def self.duplicate(located)
131
+ located.select { |_, resource| resource['id'] }.group_by { |_, resource| key(resource) }
132
+ .find { |_, copies| copies.size > 1 }
133
+ end
134
+
135
+ private_class_method :model, :no_common_version, :models, :index, :skipped_entries, :server_capability_statement,
136
+ :server?, :key, :located_resources, :package_resources, :json_files, :tar_json_files, :json,
137
+ :bundle_resources, :no_duplicates, :duplicate
138
+ end
139
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FHIRStubServer
4
+ # Hands each request to its role (FHIRRole or Validator) and records what answered it.
5
+ # Adapters build the request Hash and send the [status, headers, body] response back.
6
+ class Stub
7
+ # File paths in the config are relative to `dir`, by default the working directory.
8
+ def initialize(config, dir: '.')
9
+ fhir = config['fhir'].to_h
10
+ demo_data, served, model = Sources.load(fhir['sources'].to_a, dir)
11
+ validator = config['validator']
12
+ @validator = validator ? true : false
13
+ @roles = { fhir: FHIRRole.new(fhir, demo_data, model, dir), validator: Validator.new(validator.to_h, dir) }
14
+ @reports = { served:, unmatched: [], context_mismatches: [] }
15
+ end
16
+
17
+ def served = @reports[:served]
18
+ def unmatched = @reports[:unmatched]
19
+ def context_mismatches = @reports[:context_mismatches]
20
+
21
+ # #unmatched as one line per miss (see Unmatched.describe), empty when there is none:
22
+ # a readable failure message for `expect(stub.unmatched).to be_empty, stub.unmatched_report`.
23
+ def unmatched_report = unmatched.map { |miss| Unmatched.describe(miss) }.join("\n")
24
+
25
+ # One `{ role:, pair:, request: }` per Pair no request was answered by, in config order:
26
+ # `pair` names where it is written, `request` the request it matches, shaped like a
27
+ # `suggested_request` (for a validator Pair, its profile and resource).
28
+ def unused_pairs
29
+ used = served.to_set { |entry| entry[:answered_by] }
30
+ @roles.values.flat_map(&:pairs).reject { |entry| used.include?(entry[:pair]) }
31
+ end
32
+
33
+ # #unused_pairs as one line per Pair, empty when there is none.
34
+ def unused_pairs_report
35
+ unused_pairs.map { |entry| entry.values_at(:pair, :request) }
36
+ .map { |pair, request| "Unused #{pair}: #{JSON.generate(request)}" }.join("\n")
37
+ end
38
+
39
+ # One `{ role:, pair:, expression: }` per `select` or `include` that yielded nothing when the
40
+ # Stub was built, in config order, but for Pairs whose response says `expect_empty: true`.
41
+ # Usually a typo: the search then answers an empty searchset.
42
+ def empty_selects = @roles[:fhir].empty_selects
43
+
44
+ # Whether the config has a `validator:` block; without one the adapters route only the FHIR role.
45
+ def validator? = @validator
46
+
47
+ # #served starts with the load-time entries; each request adds `answered_by`: where the
48
+ # answering Pair is written (see Includes), :demo_data or :miss. The role builds the report
49
+ # entries; Stub only appends them.
50
+ def respond(request)
51
+ answered_by, response, reports = @roles.fetch(request[:role]).answer(request)
52
+ served << { kind: :request, request:, answered_by: }
53
+ reports.each { |name, entries| @reports.fetch(name).concat(entries) }
54
+ response
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FHIRStubServer
4
+ # One line per #unmatched entry, for Replay's log and Stub#unmatched_report.
5
+ module Unmatched
6
+ # The request, its nearest Pair and the differing parameters, then the suggested request as
7
+ # JSON, which is valid YAML: it pastes into the config after `- request:` (`- ` for a
8
+ # validator Pair, adding `issues`).
9
+ def self.describe(miss)
10
+ request = miss[:request]
11
+ nearest = miss[:nearest_pair]
12
+ near = "; nearest #{nearest}: #{differences(miss[:differences])}" if nearest
13
+ line = ["#{request[:role]} #{request[:method]} #{request[:path]}", URI.encode_www_form(request[:query])]
14
+ "Unmatched #{line.reject(&:empty?).join('?')}#{near}#{suggestion(miss)}"
15
+ end
16
+
17
+ def self.differences(differences)
18
+ differences.map { |name, values| "#{name} expected #{values[:expected].inspect}, got #{values[:actual].inspect}" }
19
+ .join('; ')
20
+ end
21
+
22
+ # A validator suggestion is a whole Pair but `issues`, so it is labelled `pair`.
23
+ def self.suggestion(miss)
24
+ suggested = miss[:suggested_request]
25
+ return '' unless suggested
26
+
27
+ "; #{miss[:request][:role] == :validator ? 'pair' : 'request'}: #{JSON.generate(suggested)}"
28
+ end
29
+
30
+ private_class_method :differences, :suggestion
31
+ end
32
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FHIRStubServer
4
+ # Answers Inferno's validator calls from the `validator:` block, the way Stub expects of a role:
5
+ #
6
+ # pairs: [{ profile: au-core-patient, resource: Patient/p1, issues: [...] }]
7
+ # expected_context: { sv: 4.0.1 }
8
+ #
9
+ # A call is matched on the profile (`filesToValidate[0].fileName` without `.json`) and the
10
+ # `Type/id` of the file's content; `sessionId` is ignored. `pairs` may include files (see Includes).
11
+ # @api private
12
+ class Validator
13
+ def initialize(config, dir)
14
+ @pairs = Includes.splice(config['pairs'].to_a, 'validator.pairs', dir).map do |pair, _dir, where|
15
+ [pair.values_at('profile', 'resource'), pair['issues'].to_a, where]
16
+ end
17
+ @expected_context = config['expected_context'].to_h
18
+ end
19
+
20
+ # A context mismatch is reported, but a matching Pair still answers.
21
+ def answer(request)
22
+ key, context = Validator.call(request)
23
+ reports = { context_mismatches: mismatches(context, request) }
24
+ pair = matching_pair(key)
25
+ return [pair.last, Responses.validation(pair[1]), reports] if pair
26
+
27
+ [:miss, Responses.not_found(request), { **reports, unmatched: [Validator.miss(request, key)] }]
28
+ end
29
+
30
+ # One entry per Pair, in config order, for Stub#unused_pairs.
31
+ def pairs = @pairs.map { |key, _issues, where| { role: :validator, pair: where, request: Validator.config(key) } }
32
+
33
+ # No near miss: validator Pairs have no parameters to compare. The suggestion is the Pair
34
+ # without its `issues`; nil when the request is no validate call.
35
+ def self.miss(request, key)
36
+ { request:, nearest_pair: nil, differences: {}, suggested_request: key && config(key) }
37
+ end
38
+
39
+ # The key as the config writes a Pair, without its `issues`.
40
+ def self.config(key) = %w[profile resource].zip(key).to_h.compact
41
+
42
+ # [[profile, Type/id], context] of a `POST /validate`; nil for any other request.
43
+ def self.call(request)
44
+ return unless request[:method] == 'POST' && request[:path] == '/validate'
45
+
46
+ body = JSON.parse(request[:body].to_s)
47
+ [key(body.dig('filesToValidate', 0)), body['cliContext'] || body['validationContext'] || {}]
48
+ rescue JSON::ParserError, TypeError, NoMethodError # not shaped like an Inferno validate call
49
+ nil
50
+ end
51
+
52
+ def self.key(file)
53
+ resource = JSON.parse(file['fileContent'])
54
+ [file['fileName'].delete_suffix('.json'), "#{resource['resourceType']}/#{resource['id']}"]
55
+ end
56
+
57
+ private_class_method :key
58
+
59
+ private
60
+
61
+ def matching_pair(key) = @pairs.find { |pair| pair.first == key }
62
+
63
+ # Only the listed keys count, each compared exactly; a request that is no validate call has none.
64
+ def mismatches(context, request)
65
+ return [] unless context
66
+
67
+ @expected_context.filter_map do |key, expected|
68
+ actual = context[key]
69
+ { request:, key:, expected:, actual: } unless actual == expected
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FHIRStubServer
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ FHIRStubServer.require_gem('webmock', 'FHIRStubServer::WebMockAdapter')
4
+
5
+ module FHIRStubServer
6
+ # Sends requests WebMock intercepts under the given base URLs to a Stub, for in-process runs.
7
+ # Requests outside these base URLs are left to WebMock (and `disable_net_connect!`), as are
8
+ # validator calls when the Stub has no validator block.
9
+ module WebMockAdapter
10
+ def self.install(stub, fhir_base_url:, validator_base_url: nil)
11
+ WebMock.enable! # a plain `require 'webmock'` intercepts nothing; webmock/rspec enables it
12
+ keep_repeated_query_parameters
13
+ { fhir: fhir_base_url, validator: (validator_base_url if stub.validator?) }.compact.each do |role, base_url|
14
+ route(stub, role, base_url.chomp('/'))
15
+ end
16
+ end
17
+
18
+ # Restores the query notation `install` replaced. The catch-all stubs stay until WebMock resets.
19
+ def self.uninstall
20
+ return unless instance_variable_defined?(:@previous_notation)
21
+
22
+ WebMock::Config.instance.query_values_notation = remove_instance_variable(:@previous_notation)
23
+ end
24
+
25
+ # The default notation parses the query into a Hash and keeps only the last of repeated
26
+ # parameters (`date=ge2020&date=le2021`). Global: hash_including query stubs stop matching.
27
+ def self.keep_repeated_query_parameters
28
+ config = WebMock::Config.instance
29
+ # The default is nil, so whether the variable is defined tells if `install` already ran.
30
+ @previous_notation = config.query_values_notation unless instance_variable_defined?(:@previous_notation)
31
+ config.query_values_notation = :flat_array
32
+ end
33
+
34
+ def self.route(stub, role, base_url)
35
+ WebMock.stub_request(:any, %r{\A#{Regexp.escape(base_url)}(?=[/?]|\z)}).to_return do |request|
36
+ status, headers, body = stub.respond(stub_request(request, role, base_url))
37
+ { status:, headers:, body: }
38
+ end
39
+ end
40
+
41
+ def self.stub_request(request, role, base_url)
42
+ uri = request.uri
43
+ Request.build(
44
+ role:, method: request.method.to_s.upcase, base_url:,
45
+ path: uri.path.delete_prefix(URI(base_url).path),
46
+ query: uri.query.to_s,
47
+ body: request.body
48
+ )
49
+ end
50
+
51
+ private_class_method :keep_repeated_query_parameters, :route, :stub_request
52
+ end
53
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fhirpath'
4
+ require 'json'
5
+ require 'pathname'
6
+ require 'rubygems/package'
7
+ require 'stringio'
8
+ require 'uri'
9
+ require 'yaml'
10
+ require 'zlib'
11
+ require_relative 'fhir_stub_server/version'
12
+
13
+ # A strict stub for the FHIR server and validator used by FHIR test kits.
14
+ module FHIRStubServer
15
+ # Base class for every error the gem raises, including config errors at build time.
16
+ class Error < StandardError; end
17
+
18
+ # Builds a Stub from a YAML config file, or from the `server:` block of a kit's scenario.yml.
19
+ # Source paths and `body_file`s are relative to the file.
20
+ def self.load(path)
21
+ document = parse_file(path, :yaml)
22
+ config = document.is_a?(Hash) ? document.fetch('server', document) : document
23
+ raise Error, "#{path}: the config must be a mapping" unless config.is_a?(Hash)
24
+
25
+ Stub.new(config, dir: File.dirname(path))
26
+ end
27
+
28
+ # For the adapters' optional dependencies, which the consuming kit's Gemfile supplies.
29
+ def self.require_gem(name, needed_by)
30
+ require name
31
+ rescue LoadError => error
32
+ raise Error, "#{needed_by} needs the #{name} gem: add it to your Gemfile (#{error.message})"
33
+ end
34
+
35
+ # Reads a file named in the config, so a missing one fails when the Stub is built.
36
+ def self.read_file(path)
37
+ File.read(path)
38
+ rescue SystemCallError => error # missing, a directory, unreadable
39
+ raise Error, "Cannot read #{path}: #{error.message}"
40
+ end
41
+
42
+ # Reads a JSON or YAML file named in the config: invalid content fails when the Stub is built.
43
+ def self.parse_file(path, format)
44
+ text = read_file(path)
45
+ format == :yaml ? YAML.safe_load(text, aliases: true) : JSON.parse(text)
46
+ rescue JSON::ParserError, Psych::Exception => error
47
+ raise Error, "#{path}: not valid #{format.upcase} (#{error.message})"
48
+ end
49
+
50
+ # Loaded on first use, so the core requires neither webmock nor puma.
51
+ autoload :WebMockAdapter, 'fhir_stub_server/webmock_adapter'
52
+ autoload :HTTPServer, 'fhir_stub_server/http_server'
53
+ end
54
+
55
+ require_relative 'fhir_stub_server/fhir_role'
56
+ require_relative 'fhir_stub_server/includes'
57
+ require_relative 'fhir_stub_server/pairs'
58
+ require_relative 'fhir_stub_server/paging'
59
+ require_relative 'fhir_stub_server/rack_app'
60
+ require_relative 'fhir_stub_server/replay'
61
+ require_relative 'fhir_stub_server/request'
62
+ require_relative 'fhir_stub_server/responses'
63
+ require_relative 'fhir_stub_server/sources'
64
+ require_relative 'fhir_stub_server/stub'
65
+ require_relative 'fhir_stub_server/unmatched'
66
+ require_relative 'fhir_stub_server/validator'