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.
- checksums.yaml +7 -0
- data/.rubocop.yml +20 -0
- data/.yardopts +3 -0
- data/CHANGELOG.md +37 -0
- data/CODE_OF_CONDUCT.md +10 -0
- data/LICENSE.txt +201 -0
- data/README.md +352 -0
- data/Rakefile +46 -0
- data/Steepfile +7 -0
- data/config.ru +6 -0
- data/exe/fhir-stub-server +25 -0
- data/lib/fhir_stub_server/fhir_role.rb +62 -0
- data/lib/fhir_stub_server/http_server.rb +35 -0
- data/lib/fhir_stub_server/includes.rb +69 -0
- data/lib/fhir_stub_server/paging.rb +51 -0
- data/lib/fhir_stub_server/pairs.rb +162 -0
- data/lib/fhir_stub_server/rack_app.rb +38 -0
- data/lib/fhir_stub_server/replay.rb +37 -0
- data/lib/fhir_stub_server/request.rb +35 -0
- data/lib/fhir_stub_server/responses.rb +59 -0
- data/lib/fhir_stub_server/sources.rb +139 -0
- data/lib/fhir_stub_server/stub.rb +57 -0
- data/lib/fhir_stub_server/unmatched.rb +32 -0
- data/lib/fhir_stub_server/validator.rb +73 -0
- data/lib/fhir_stub_server/version.rb +5 -0
- data/lib/fhir_stub_server/webmock_adapter.rb +53 -0
- data/lib/fhir_stub_server.rb +66 -0
- data/sig/fhir_stub_server.rbs +273 -0
- metadata +92 -0
data/Rakefile
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'bundler/gem_tasks'
|
|
4
|
+
require 'rspec/core/rake_task'
|
|
5
|
+
require 'rubocop/rake_task'
|
|
6
|
+
require 'reek/rake/task'
|
|
7
|
+
|
|
8
|
+
RSpec::Core::RakeTask.new(:spec)
|
|
9
|
+
|
|
10
|
+
RuboCop::RakeTask.new(:rubocop)
|
|
11
|
+
|
|
12
|
+
Reek::Rake::Task.new(:reek) do |task|
|
|
13
|
+
task.source_files = 'lib/**/*.rb'
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Flay's and flog's own Rake tasks are not used: FlayTask reads the score before
|
|
17
|
+
# analysing (always 0), FlogTask crashes when lib/ has no methods yet.
|
|
18
|
+
desc 'Fail on any duplicated code in lib/ above flay\'s default mass'
|
|
19
|
+
task :flay do
|
|
20
|
+
require 'flay'
|
|
21
|
+
flay = Flay.run(%w[lib])
|
|
22
|
+
flay.analyze
|
|
23
|
+
next if flay.total.zero?
|
|
24
|
+
|
|
25
|
+
flay.report
|
|
26
|
+
abort "Flay found duplication: score #{flay.total} > 0"
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
desc 'Fail when a method in lib/ scores above 20 in flog'
|
|
30
|
+
task :flog do
|
|
31
|
+
require 'flog_cli'
|
|
32
|
+
flog = FlogCLI.new(continue: true, quiet: true, methods: true)
|
|
33
|
+
flog.flog(*Dir['lib/**/*.rb'])
|
|
34
|
+
name, score = flog.max_method
|
|
35
|
+
abort "Flog score for #{name} is too high: #{score.round(1)} > 20" if score&.>(20)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
desc 'Type-check lib/ against sig/ with Steep'
|
|
39
|
+
task :steep do
|
|
40
|
+
sh 'steep check'
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
desc 'Run all code quality tools'
|
|
44
|
+
task quality: %i[rubocop reek flay flog steep]
|
|
45
|
+
|
|
46
|
+
task default: %i[spec quality]
|
data/Steepfile
ADDED
data/config.ru
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
# Scenario replay: serves one Scenario's Stub on a random port of 127.0.0.1 until interrupted.
|
|
5
|
+
require 'fhir_stub_server'
|
|
6
|
+
|
|
7
|
+
abort 'Usage: fhir-stub-server <config.yml>' unless ARGV.one?
|
|
8
|
+
$stdout.sync = true
|
|
9
|
+
|
|
10
|
+
begin
|
|
11
|
+
FHIRStubServer.require_gem('puma', 'fhir-stub-server')
|
|
12
|
+
stub = FHIRStubServer.load(ARGV.first)
|
|
13
|
+
rescue FHIRStubServer::Error => error
|
|
14
|
+
abort error.message
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
replay = FHIRStubServer::Replay.new(stub)
|
|
18
|
+
server = FHIRStubServer::HTTPServer.new(replay)
|
|
19
|
+
base_url = server.start
|
|
20
|
+
puts "FHIR base URL: #{base_url}/fhir"
|
|
21
|
+
puts "Validator base URL: #{base_url}/validator" if stub.validator?
|
|
22
|
+
|
|
23
|
+
%w[INT TERM].each { |signal| trap(signal) { server.stop } }
|
|
24
|
+
server.wait
|
|
25
|
+
replay.log_unused_pairs
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FHIRStubServer
|
|
4
|
+
# Answers FHIR requests from `fhir.pairs` and Demo Data, the way Stub expects of a role:
|
|
5
|
+
# [answered_by, response, { report name => entries }].
|
|
6
|
+
# @api private
|
|
7
|
+
class FHIRRole
|
|
8
|
+
def initialize(config, demo_data, model, dir)
|
|
9
|
+
@pairs = Pairs.load(config['pairs'].to_a, Pairs.fhirpath(demo_data, model), dir)
|
|
10
|
+
@reads = Sources.reads(demo_data)
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# A Pair first, so it can override a read; then a built-in read; then a miss, reported with
|
|
14
|
+
# the Pair it most likely meant.
|
|
15
|
+
def answer(request)
|
|
16
|
+
found = Pairs.answer(@pairs, request) || read_answer(request)
|
|
17
|
+
return [found[0], found[1], {}] if found
|
|
18
|
+
|
|
19
|
+
miss = { request:, **Pairs.near_miss(@pairs, request), suggested_request: FHIRRole.config(Request.key(request)) }
|
|
20
|
+
[:miss, Responses.not_found(request), { unmatched: [miss] }]
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# One entry per Pair, in config order, for Stub#unused_pairs.
|
|
24
|
+
def pairs = FHIRRole.listed(@pairs)
|
|
25
|
+
|
|
26
|
+
# Each `select` or `include` that yielded nothing, in config order, for Stub#empty_selects.
|
|
27
|
+
def empty_selects = @pairs.flat_map { |pair| pair[:empty_selects] }
|
|
28
|
+
|
|
29
|
+
# One `{ role:, pair:, request: }` per Pair: where it is written and its request.
|
|
30
|
+
def self.listed(pairs)
|
|
31
|
+
pairs.map { |pair| { role: :fhir, pair: pair[:where], request: config(pair[:key]) } }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# A key as the config writes a Pair's `request`: `method` only when not GET, a single value
|
|
35
|
+
# unwrapped, the form `body` only for `POST .../_search`.
|
|
36
|
+
def self.config(key)
|
|
37
|
+
method = key[:method]
|
|
38
|
+
{ 'method' => (method unless method == 'GET'), 'path' => key[:path],
|
|
39
|
+
'query' => config_values(key[:query]), 'body' => config_values(key[:form]) }.compact
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def self.config_values(params)
|
|
43
|
+
params = params.to_h
|
|
44
|
+
params.transform_values { |values| values.one? ? values.first : values } unless params.empty?
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
private_class_method :config_values
|
|
48
|
+
|
|
49
|
+
# The path of a GET without query parameters, which a built-in read may answer; nil for
|
|
50
|
+
# anything else, so a read that gains a parameter is a miss unless a Pair declares it.
|
|
51
|
+
def self.read_path(request)
|
|
52
|
+
request[:path] if request[:method] == 'GET' && request[:query].empty?
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
private
|
|
56
|
+
|
|
57
|
+
def read_answer(request)
|
|
58
|
+
resource = @reads[FHIRRole.read_path(request)]
|
|
59
|
+
[:demo_data, Responses.fhir(200, resource)] if resource
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
FHIRStubServer.require_gem('puma', 'FHIRStubServer::HTTPServer')
|
|
4
|
+
|
|
5
|
+
module FHIRStubServer
|
|
6
|
+
# Serves a Stub (through a RackApp) or any Rack app, such as a Replay, over HTTP with Puma on a
|
|
7
|
+
# random free port of 127.0.0.1, in a background thread: for `inferno execute` runs and
|
|
8
|
+
# Scenario replay.
|
|
9
|
+
class HTTPServer
|
|
10
|
+
def initialize(stub_or_app, **rack_app_options)
|
|
11
|
+
app = case stub_or_app
|
|
12
|
+
when Stub then RackApp.new(stub_or_app, **rack_app_options)
|
|
13
|
+
else stub_or_app
|
|
14
|
+
end
|
|
15
|
+
@server = Puma::Server.new(app)
|
|
16
|
+
@thread = nil # set by #start
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Returns the server's base URL; a RackApp puts the FHIR and validator roles under their base paths.
|
|
20
|
+
def start
|
|
21
|
+
@server.add_tcp_listener('127.0.0.1', 0)
|
|
22
|
+
@thread = @server.run
|
|
23
|
+
"http://127.0.0.1:#{@server.connected_ports.first}"
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Blocks until #stop, which may be called from a signal trap.
|
|
27
|
+
def wait
|
|
28
|
+
@thread&.join
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def stop
|
|
32
|
+
@server.stop(true)
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FHIRStubServer
|
|
4
|
+
# Splices the `{ from: <path> }` entries of a Pair list (`fhir.pairs`, `validator.pairs`): the
|
|
5
|
+
# file holds a YAML list of Pairs, which may itself have `from:` entries. Paths in a file,
|
|
6
|
+
# `from:` and `body_file` alike, are relative to that file.
|
|
7
|
+
# @api private
|
|
8
|
+
class Includes
|
|
9
|
+
# Each Pair as [pair, dir, where]: the directory of the file it is written in, and where it is
|
|
10
|
+
# written, e.g. `fhir.pairs[3]` or `fhir.pairs[3] (shared/patient.yml[7])`, paths relative to `dir`.
|
|
11
|
+
def self.splice(entries, name, dir)
|
|
12
|
+
new(name, dir).pairs(entries)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def initialize(name, dir)
|
|
16
|
+
@name = name
|
|
17
|
+
@root = File.expand_path(dir)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# `trail` lists [file, index] of each entry leading here; the config's own list has no file.
|
|
21
|
+
def pairs(entries, file = nil, trail = [])
|
|
22
|
+
dir = file ? File.dirname(file) : @root
|
|
23
|
+
entries.each_with_index.flat_map do |entry, index|
|
|
24
|
+
at = [*trail, [file, index]] #: trail
|
|
25
|
+
entry_pairs(entry, dir, at)
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def entry_pairs(entry, dir, at)
|
|
32
|
+
return included(from_path(entry, dir, at), at) if entry.is_a?(Hash) && entry.key?('from')
|
|
33
|
+
|
|
34
|
+
[[entry, dir, where(at)]] #: Array[spliced]
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def from_path(include, dir, at)
|
|
38
|
+
from = include['from']
|
|
39
|
+
raise Error, "#{where(at)}: an include is { from: <path> } only" unless include.size == 1 && from.is_a?(String)
|
|
40
|
+
|
|
41
|
+
File.expand_path(from, dir)
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def included(file, at)
|
|
45
|
+
entries = read(file, at)
|
|
46
|
+
return pairs(entries, file, at) if entries.is_a?(Array)
|
|
47
|
+
|
|
48
|
+
raise Error, "#{where(at)}: #{relative(file)} must hold a list of Pairs"
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def read(file, at)
|
|
52
|
+
raise Error, "including #{relative(file)} again is a cycle" if at.any? { |(seen)| seen == file }
|
|
53
|
+
|
|
54
|
+
FHIRStubServer.parse_file(file, :yaml)
|
|
55
|
+
rescue Error => error
|
|
56
|
+
raise Error, "#{where(at)}: #{error.message}"
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def where(at)
|
|
60
|
+
(_, index), *included = at
|
|
61
|
+
files = included.map { |file, position| "#{relative(file.to_s)}[#{position}]" }
|
|
62
|
+
["#{@name}[#{index}]", ("(#{files.join(' > ')})" unless files.empty?)].compact.join(' ')
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def relative(file)
|
|
66
|
+
Pathname(file).relative_path_from(@root).to_s
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FHIRStubServer
|
|
4
|
+
# A `select` Pair's `page_size: n` splits its matches into pages of n. The first page answers
|
|
5
|
+
# the Pair's request, the next ones are GETs of continuation URLs below the FHIR base,
|
|
6
|
+
# /_page/<the Pair's index in the list>/<page>, which each page's `next` link names.
|
|
7
|
+
# @api private
|
|
8
|
+
module Paging
|
|
9
|
+
# Page 1 is the Pair's own request, so a continuation URL names page 2 or later.
|
|
10
|
+
PATH = %r{\A/_page/(\d+)/([2-9]|[1-9]\d+)\z}
|
|
11
|
+
|
|
12
|
+
# [index, page] of the first Pair whose request the key matches (page 1) or of the Pair and
|
|
13
|
+
# page a continuation URL names; nil for neither.
|
|
14
|
+
def self.locate(pairs, key)
|
|
15
|
+
index = pairs.index { |pair| pair[:key] == key }
|
|
16
|
+
index ? page(index, 1) : continued(key)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def self.continued(key)
|
|
20
|
+
found = PATH.match(key[:path]) if key[:method] == 'GET' && key[:query].empty?
|
|
21
|
+
index, number = found&.captures.to_a.map(&:to_i)
|
|
22
|
+
page(index, number) if index && number
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def self.page(index, number) = [index, { number:, path: "/_page/#{index}" }]
|
|
26
|
+
|
|
27
|
+
def self.body(config, results, where)
|
|
28
|
+
matches = results.fetch('select', [])
|
|
29
|
+
pages = split(matches, results.fetch('include', []), size(config, matches, where))
|
|
30
|
+
->(request, page) { Responses.searchset(request, pages, page) }
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# The response's `page_size`; without one, all matches on one page (one more, as each_slice rejects 0).
|
|
34
|
+
def self.size(config, matches, where)
|
|
35
|
+
size = config['page_size']
|
|
36
|
+
return matches.size + 1 unless size
|
|
37
|
+
return size if size.is_a?(Integer) && size.positive?
|
|
38
|
+
|
|
39
|
+
raise Error, "#{where}: page_size must be a positive integer"
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Each page's [matches, includes], `size` matches each and the includes on the first page,
|
|
43
|
+
# each fullUrl once; and the total of all matches, which every page carries.
|
|
44
|
+
def self.split(matches, includes, size)
|
|
45
|
+
first, *rest = matches.each_slice(size).to_a
|
|
46
|
+
{ total: matches.size, entries: [[first.to_a, includes.uniq - matches], *rest.map { |slice| [slice, []] }] }
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
private_class_method :continued, :page, :size, :split
|
|
50
|
+
end
|
|
51
|
+
end
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FHIRStubServer
|
|
4
|
+
# Loads `fhir.pairs`: each Pair is one expected request and the response configured for it.
|
|
5
|
+
#
|
|
6
|
+
# - request: { method: POST, path: /Patient/_search, query: { ... }, body: { family: Smith } }
|
|
7
|
+
# response: { status: 200, body_file: bundle.json }
|
|
8
|
+
#
|
|
9
|
+
# The response has exactly one body kind: `body_file` (literal JSON), `resource` (a FHIRPath
|
|
10
|
+
# expression yielding exactly one resource) or `select` (FHIRPath, answered as a searchset;
|
|
11
|
+
# an optional `include` adds resources with search.mode include, an optional `page_size` pages
|
|
12
|
+
# the matches, see Paging). Expressions run once, over a collection Bundle of all Demo Data
|
|
13
|
+
# with the FHIR model of its version (see Sources), when the Stub is built. An empty `select`
|
|
14
|
+
# or `include` is listed in Stub#empty_selects, unless the response says `expect_empty: true`.
|
|
15
|
+
#
|
|
16
|
+
# `path` is relative to the FHIR base and required; `method` defaults to GET, `status` to 200.
|
|
17
|
+
# `query` and `body` map names to a value or a list of values. `body` is the form body and
|
|
18
|
+
# only counts for `POST .../_search`; other writes match whatever body they send.
|
|
19
|
+
# When several Pairs match a request, the first one answers. An entry `{ from: <path> }` is
|
|
20
|
+
# replaced by the Pairs of that file (see Includes).
|
|
21
|
+
# @api private
|
|
22
|
+
module Pairs
|
|
23
|
+
BODY_KINDS = %w[body_file select resource].freeze
|
|
24
|
+
|
|
25
|
+
def self.load(pairs, fhirpath, dir)
|
|
26
|
+
Includes.splice(pairs, 'fhir.pairs', dir).map do |pair, pair_dir, where|
|
|
27
|
+
build(with_dir(pair, pair_dir), fhirpath, where)
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# A lambda evaluating an expression over all Demo Data, with fhirpath-rb's `model` (e.g. `r4`).
|
|
32
|
+
def self.fhirpath(demo_data, model)
|
|
33
|
+
bundle = { 'resourceType' => 'Bundle', 'type' => 'collection',
|
|
34
|
+
'entry' => demo_data.values.map { |resource| { 'resource' => resource } } }
|
|
35
|
+
->(expression) { Fhirpath.evaluate(bundle, expression, {}, model) }
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# The Pair with its `body_file` relative to `dir`.
|
|
39
|
+
def self.with_dir(pair, dir)
|
|
40
|
+
response = pair['response'].to_h
|
|
41
|
+
file = response['body_file']
|
|
42
|
+
file ? pair.merge('response' => response.merge('body_file' => File.expand_path(file, dir))) : pair
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# [where, response] of the first Pair matching the request, or of the Pair whose continuation
|
|
46
|
+
# URL it is while that page exists (see Paging); nil when none does.
|
|
47
|
+
def self.answer(pairs, request)
|
|
48
|
+
index, page = Paging.locate(pairs, Request.key(request))
|
|
49
|
+
pair = pairs[index] if index
|
|
50
|
+
body = pair && page && pair[:body].call(request, page)
|
|
51
|
+
[pair[:where], Responses.raw(pair[:status], body)] if pair && body
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# The Pair an unmatched request most likely meant: same method and path, fewest
|
|
55
|
+
# differing parameters, the first on a tie. Differences are keyed by parameter name: expected
|
|
56
|
+
# holds the Pair's values (nil: extra in the request), actual the request's (nil: missing).
|
|
57
|
+
def self.near_miss(pairs, request)
|
|
58
|
+
where, differences = candidates(pairs, Request.key(request)).min_by { |candidate| candidate.last.size }
|
|
59
|
+
{ nearest_pair: where, differences: differences || {} }
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# [where, differences] for each Pair with the request's method and path.
|
|
63
|
+
def self.candidates(pairs, key)
|
|
64
|
+
pairs.filter_map do |pair|
|
|
65
|
+
pair_key = pair[:key]
|
|
66
|
+
[pair[:where], differences(pair_key, key)] if pair_key.slice(:method, :path) == key.slice(:method, :path)
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Query and form body differences in one Hash; a name differing in both keeps the form body's.
|
|
71
|
+
def self.differences(pair_key, request_key)
|
|
72
|
+
diff(pair_key[:query], request_key[:query]).merge(diff(pair_key[:form].to_h, request_key[:form].to_h))
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def self.diff(expected, actual)
|
|
76
|
+
(expected.keys | actual.keys).sort.filter_map do |name|
|
|
77
|
+
values = { expected: expected[name], actual: actual[name] }
|
|
78
|
+
[name, values] unless values[:expected] == values[:actual]
|
|
79
|
+
end.to_h
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def self.build(pair, fhirpath, where)
|
|
83
|
+
key = Request.key(request(pair['request'].to_h, where))
|
|
84
|
+
response = pair['response'].to_h
|
|
85
|
+
body, empty_selects = body(response, fhirpath, where)
|
|
86
|
+
{ key:, status: response.fetch('status', 200), body:, where:, empty_selects: }
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# The Pair's request, normalized exactly like an incoming one.
|
|
90
|
+
def self.request(config, where)
|
|
91
|
+
path = config['path'].to_s
|
|
92
|
+
raise Error, "#{where}: the request needs a path starting with /" unless path.start_with?('/')
|
|
93
|
+
|
|
94
|
+
Request.build(
|
|
95
|
+
role: :fhir, method: config.fetch('method', 'GET').upcase, base_url: '', path:,
|
|
96
|
+
query: URI.encode_www_form(config['query'].to_h), body: URI.encode_www_form(config['body'].to_h)
|
|
97
|
+
)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# A lambda building the body of a matched request's page (from 1; nil past the last), and its
|
|
101
|
+
# Stub#empty_selects entries. Only a searchset needs the request: its URLs use its base URL.
|
|
102
|
+
def self.body(config, fhirpath, where)
|
|
103
|
+
return [literal_body(config, fhirpath, where), []] unless body_kind(config, where) == 'select'
|
|
104
|
+
|
|
105
|
+
expressions = config.slice('select', 'include').compact # `include: ~` is no expression
|
|
106
|
+
results = expressions.transform_values { |expression| evaluate(expression, fhirpath, where) }
|
|
107
|
+
[Paging.body(config, results, where), empty_selects(config, results, where)]
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# One entry per `select` or `include` that yielded nothing; none when the response expects that.
|
|
111
|
+
def self.empty_selects(config, results, where)
|
|
112
|
+
return [] if config['expect_empty']
|
|
113
|
+
|
|
114
|
+
results.filter_map { |name, found| { role: :fhir, pair: where, expression: config[name] } if found.empty? }
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# The fixed body of a `body_file` or `resource` response.
|
|
118
|
+
def self.literal_body(config, fhirpath, where)
|
|
119
|
+
body = if config.key?('body_file')
|
|
120
|
+
FHIRStubServer.read_file(config['body_file'])
|
|
121
|
+
else
|
|
122
|
+
JSON.generate(one_resource(evaluate(config['resource'], fhirpath, where), where))
|
|
123
|
+
end
|
|
124
|
+
->(_request, page) { body if page[:number] == 1 }
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def self.body_kind(config, where)
|
|
128
|
+
kinds = BODY_KINDS & config.keys
|
|
129
|
+
raise Error, "#{where}: the response needs exactly one of #{BODY_KINDS.join(', ')}" unless kinds.one?
|
|
130
|
+
|
|
131
|
+
searchset_only = (%w[include page_size] & config.compact.keys).first unless kinds == ['select']
|
|
132
|
+
raise Error, "#{where}: #{searchset_only} needs select" if searchset_only
|
|
133
|
+
|
|
134
|
+
kinds.first
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def self.evaluate(expression, fhirpath, where)
|
|
138
|
+
return [] unless expression
|
|
139
|
+
|
|
140
|
+
resources_only(fhirpath.call(expression), "#{where}: #{expression}")
|
|
141
|
+
rescue StandardError => error # a Fhirpath::Error, or a fhirpath-rb bug such as a TypeError
|
|
142
|
+
raise if error.is_a?(Error) # from resources_only, already labelled
|
|
143
|
+
|
|
144
|
+
raise Error, "#{where}: #{expression}: #{error.class}: #{error.message}"
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def self.resources_only(results, label)
|
|
148
|
+
return results if results.all? { |result| result.is_a?(Hash) && result['resourceType'] }
|
|
149
|
+
|
|
150
|
+
raise Error, "#{label} must yield resources only"
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def self.one_resource(results, where)
|
|
154
|
+
return results.first if results.one?
|
|
155
|
+
|
|
156
|
+
raise Error, "#{where}: resource must yield exactly one resource, got #{results.size}"
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
private_class_method :with_dir, :candidates, :differences, :diff, :build, :request, :body, :empty_selects,
|
|
160
|
+
:literal_body, :body_kind, :evaluate, :resources_only, :one_resource
|
|
161
|
+
end
|
|
162
|
+
end
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FHIRStubServer
|
|
4
|
+
# A Rack app serving a Stub: the FHIR role under `fhir_base_path`, the validator role under
|
|
5
|
+
# `validator_base_path` when the Stub has a validator block. Requests outside these get a
|
|
6
|
+
# plain 404 and are not recorded.
|
|
7
|
+
# Needs no rack gem: it only reads the Rack env.
|
|
8
|
+
class RackApp
|
|
9
|
+
def initialize(stub, fhir_base_path: '/fhir', validator_base_path: '/validator')
|
|
10
|
+
@stub = stub
|
|
11
|
+
@base_paths = { fhir: fhir_base_path, validator: (validator_base_path if stub.validator?) }
|
|
12
|
+
.compact.transform_values { |path| path.chomp('/') }
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def call(env)
|
|
16
|
+
role, base_path = base_path_for(env['PATH_INFO'])
|
|
17
|
+
return [404, { 'content-type' => 'text/plain' }, ['Not Found']] unless role && base_path
|
|
18
|
+
|
|
19
|
+
status, headers, body = @stub.respond(RackApp.stub_request(env, role, base_path))
|
|
20
|
+
[status, headers, [body]]
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def base_path_for(path)
|
|
24
|
+
@base_paths.find { |_, base_path| path.match?(%r{\A#{Regexp.escape(base_path)}(?=/|\z)}) }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def self.stub_request(env, role, base_path)
|
|
28
|
+
host = env['HTTP_HOST'] || "#{env['SERVER_NAME']}:#{env['SERVER_PORT']}"
|
|
29
|
+
Request.build(
|
|
30
|
+
role:, method: env['REQUEST_METHOD'],
|
|
31
|
+
base_url: "#{env['rack.url_scheme']}://#{host}#{env['SCRIPT_NAME']}#{base_path}",
|
|
32
|
+
path: env['PATH_INFO'].delete_prefix(base_path),
|
|
33
|
+
query: env['QUERY_STRING'].to_s,
|
|
34
|
+
body: env['rack.input']&.read
|
|
35
|
+
)
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FHIRStubServer
|
|
4
|
+
# Scenario replay: one Scenario's Stub served on its own, to point Inferno's UI at. A RackApp
|
|
5
|
+
# that logs the load-time skips and empty selects at start and each unmatched request as it
|
|
6
|
+
# arrives; drift fails nothing. Used by `fhir-stub-server`, which also calls #log_unused_pairs on
|
|
7
|
+
# shutdown, and `config.ru`.
|
|
8
|
+
class Replay
|
|
9
|
+
def initialize(stub, log = $stderr)
|
|
10
|
+
@stub = stub
|
|
11
|
+
@rack_app = RackApp.new(stub)
|
|
12
|
+
@log = log
|
|
13
|
+
@lock = Mutex.new # Puma serves requests on several threads; each miss is logged once
|
|
14
|
+
stub.served.select { |entry| entry[:kind] == :load }
|
|
15
|
+
.each { |entry| log.puts "Skipped #{entry[:skipped]}: #{entry[:reason]}" }
|
|
16
|
+
stub.empty_selects.each { |entry| log.puts format('Empty %<pair>s: %<expression>s', entry) }
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def call(env)
|
|
20
|
+
@lock.synchronize { logging_misses { @rack_app.call(env) } }
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Once no request can arrive.
|
|
24
|
+
def log_unused_pairs
|
|
25
|
+
report = @stub.unused_pairs_report
|
|
26
|
+
@log.puts report unless report.empty?
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def logging_misses
|
|
32
|
+
unmatched = @stub.unmatched
|
|
33
|
+
logged = unmatched.size
|
|
34
|
+
yield.tap { unmatched.drop(logged).each { |miss| @log.puts Unmatched.describe(miss) } }
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FHIRStubServer
|
|
4
|
+
# The request Hash Stub#respond takes, built the same way by every adapter and for every Pair,
|
|
5
|
+
# and what a request and a Pair must share to match.
|
|
6
|
+
# @api private
|
|
7
|
+
module Request
|
|
8
|
+
# Turns the raw values an adapter reads (query and body as strings) into a request: path
|
|
9
|
+
# percent-decoded, query as { name => sorted values } (repeats kept, order ignored), the body
|
|
10
|
+
# as UTF-8 (Rack hands it over as binary) and an empty body as nil.
|
|
11
|
+
def self.build(raw)
|
|
12
|
+
body = raw[:body].to_s.dup.force_encoding(Encoding::UTF_8)
|
|
13
|
+
{
|
|
14
|
+
role: raw[:role], method: raw[:method], base_url: raw[:base_url],
|
|
15
|
+
path: URI.decode_uri_component(raw[:path]), query: parse_query(raw[:query]),
|
|
16
|
+
body: (body unless body.empty?)
|
|
17
|
+
}
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Raw non-ASCII bytes (a form body sent as UTF-8) are percent-encoded first:
|
|
21
|
+
# URI.decode_www_form rejects them.
|
|
22
|
+
def self.parse_query(query)
|
|
23
|
+
ascii = query.b.gsub(/[^\x00-\x7F]/n) { |byte| format('%%%02X', byte.ord) }
|
|
24
|
+
URI.decode_www_form(ascii).group_by(&:first).sort.to_h { |name, pairs| [name, pairs.map(&:last).sort] }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Method, path, query and, for `POST .../_search`, the form body (nil otherwise).
|
|
28
|
+
def self.key(request)
|
|
29
|
+
method = request[:method]
|
|
30
|
+
path = request[:path]
|
|
31
|
+
form = parse_query(request[:body].to_s) if method == 'POST' && path.end_with?('/_search')
|
|
32
|
+
{ method:, path:, query: request[:query], form: }
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module FHIRStubServer
|
|
4
|
+
# Builds the Rack-style [status, headers, body] responses the Stub returns.
|
|
5
|
+
# @api private
|
|
6
|
+
module Responses
|
|
7
|
+
CONTENT_TYPE = 'application/fhir+json'
|
|
8
|
+
|
|
9
|
+
def self.fhir(status, resource)
|
|
10
|
+
raw(status, JSON.generate(resource))
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def self.raw(status, body)
|
|
14
|
+
[status, { 'content-type' => CONTENT_TYPE }, body]
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# The JSON body of a searchset's `page` (see Paging), nil past the last one. `total` counts the
|
|
18
|
+
# matches of all pages; every page but the last links the `next`.
|
|
19
|
+
def self.searchset(request, pages, page)
|
|
20
|
+
number = page[:number]
|
|
21
|
+
(matches, includes), following = pages[:entries].values_at(number - 1, number)
|
|
22
|
+
return unless matches
|
|
23
|
+
|
|
24
|
+
base_url = request[:base_url]
|
|
25
|
+
JSON.generate({
|
|
26
|
+
'resourceType' => 'Bundle', 'type' => 'searchset', 'total' => pages[:total],
|
|
27
|
+
'link' => links(request, ("#{base_url}#{page[:path]}/#{number + 1}" if following)),
|
|
28
|
+
'entry' => entries(base_url, matches, 'match') + entries(base_url, includes, 'include')
|
|
29
|
+
})
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def self.links(request, next_url)
|
|
33
|
+
query = URI.encode_www_form(request[:query])
|
|
34
|
+
self_url = ["#{request[:base_url]}#{request[:path]}", query].reject(&:empty?).join('?')
|
|
35
|
+
[{ 'relation' => 'self', 'url' => self_url }, ({ 'relation' => 'next', 'url' => next_url } if next_url)].compact
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def self.entries(base_url, resources, mode)
|
|
39
|
+
resources.map do |resource|
|
|
40
|
+
{ 'fullUrl' => "#{base_url}/#{resource['resourceType']}/#{resource['id']}",
|
|
41
|
+
'resource' => resource, 'search' => { 'mode' => mode } }
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# What Inferno's validator client reads: the issues of the first outcome.
|
|
46
|
+
def self.validation(issues)
|
|
47
|
+
[200, { 'content-type' => 'application/json' },
|
|
48
|
+
JSON.generate({ 'sessionId' => 'stub', 'outcomes' => [{ 'issues' => issues }] })]
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def self.not_found(request)
|
|
52
|
+
fhir(404, {
|
|
53
|
+
'resourceType' => 'OperationOutcome',
|
|
54
|
+
'issue' => [{ 'severity' => 'error', 'code' => 'not-found',
|
|
55
|
+
'diagnostics' => "No Pair or Demo Data for #{request[:method]} #{request[:path]}" }]
|
|
56
|
+
})
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|