You need to sign in or sign up before continuing.

sendproof-core 0.1.0.alpha.1 → 0.1.0.alpha.2

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.
Files changed (124) hide show
  1. checksums.yaml +4 -4
  2. data/lib/sendproof/configuration.rb +31 -0
  3. data/lib/sendproof/data_store.rb +3 -0
  4. data/lib/sendproof/handler.rb +3 -1
  5. data/lib/sendproof/journeys/code_document.rb +305 -0
  6. data/lib/sendproof/journeys.rb +121 -0
  7. data/lib/sendproof/middleware.rb +7 -3
  8. data/lib/sendproof/mongo/engine.rb +121 -24
  9. data/lib/sendproof/mongo/held_session.rb +67 -0
  10. data/lib/sendproof/mongo/store.rb +1 -0
  11. data/lib/sendproof/mongo.rb +1 -0
  12. data/lib/sendproof/mongoid/store.rb +15 -5
  13. data/lib/sendproof/preview_request.rb +4 -1
  14. data/lib/sendproof/preview_sessions.rb +257 -0
  15. data/lib/sendproof/preview_transport.rb +86 -9
  16. data/lib/sendproof/protocol.rb +2 -2
  17. data/lib/sendproof/provider.rb +8 -0
  18. data/lib/sendproof/stores/tables.rb +213 -0
  19. data/lib/sendproof/transaction_control.rb +3 -2
  20. data/lib/sendproof/ui/api.js +2 -1
  21. data/lib/sendproof/ui/app.css +612 -1
  22. data/lib/sendproof/ui/app.js +89 -13
  23. data/lib/sendproof/ui/bar-fit.js +91 -0
  24. data/lib/sendproof/ui/commands.js +27 -4
  25. data/lib/sendproof/ui/dialog.css +125 -0
  26. data/lib/sendproof/ui/dialog.js +191 -0
  27. data/lib/sendproof/ui/fields/lookup-source.js +5 -2
  28. data/lib/sendproof/ui/fields/lookup.js +3 -2
  29. data/lib/sendproof/ui/i18n.js +13 -2
  30. data/lib/sendproof/ui/icons.js +18 -0
  31. data/lib/sendproof/ui/index.html +1 -0
  32. data/lib/sendproof/ui/journeys/compare.js +225 -0
  33. data/lib/sendproof/ui/journeys/expressions.js +89 -0
  34. data/lib/sendproof/ui/journeys/index.js +7 -0
  35. data/lib/sendproof/ui/journeys/run.js +152 -0
  36. data/lib/sendproof/ui/journeys/steps.js +163 -0
  37. data/lib/sendproof/ui/journeys-code.js +193 -0
  38. data/lib/sendproof/ui/journeys-dialog-model.js +172 -0
  39. data/lib/sendproof/ui/journeys-dialogs.js +301 -0
  40. data/lib/sendproof/ui/journeys-model.js +259 -0
  41. data/lib/sendproof/ui/journeys-runs.js +109 -0
  42. data/lib/sendproof/ui/journeys-session.js +135 -0
  43. data/lib/sendproof/ui/journeys-view.js +961 -0
  44. data/lib/sendproof/ui/journeys.js +962 -0
  45. data/lib/sendproof/ui/locales/ar-journeys.js +468 -0
  46. data/lib/sendproof/ui/locales/ar.js +2 -0
  47. data/lib/sendproof/ui/locales/cs-journeys.js +468 -0
  48. data/lib/sendproof/ui/locales/cs.js +2 -0
  49. data/lib/sendproof/ui/locales/da-journeys.js +465 -0
  50. data/lib/sendproof/ui/locales/da.js +2 -0
  51. data/lib/sendproof/ui/locales/de-journeys.js +465 -0
  52. data/lib/sendproof/ui/locales/de.js +2 -0
  53. data/lib/sendproof/ui/locales/el-journeys.js +465 -0
  54. data/lib/sendproof/ui/locales/el.js +2 -0
  55. data/lib/sendproof/ui/locales/en-journeys.js +467 -0
  56. data/lib/sendproof/ui/locales/en.js +2 -0
  57. data/lib/sendproof/ui/locales/es-journeys.js +467 -0
  58. data/lib/sendproof/ui/locales/es.js +2 -0
  59. data/lib/sendproof/ui/locales/fa-journeys.js +465 -0
  60. data/lib/sendproof/ui/locales/fa.js +2 -0
  61. data/lib/sendproof/ui/locales/fi-journeys.js +465 -0
  62. data/lib/sendproof/ui/locales/fi.js +2 -0
  63. data/lib/sendproof/ui/locales/fr-journeys.js +467 -0
  64. data/lib/sendproof/ui/locales/fr.js +2 -0
  65. data/lib/sendproof/ui/locales/he-journeys.js +468 -0
  66. data/lib/sendproof/ui/locales/he.js +2 -0
  67. data/lib/sendproof/ui/locales/hi-journeys.js +465 -0
  68. data/lib/sendproof/ui/locales/hi.js +2 -0
  69. data/lib/sendproof/ui/locales/id-journeys.js +466 -0
  70. data/lib/sendproof/ui/locales/id.js +2 -0
  71. data/lib/sendproof/ui/locales/it-journeys.js +467 -0
  72. data/lib/sendproof/ui/locales/it.js +2 -0
  73. data/lib/sendproof/ui/locales/ja-journeys.js +466 -0
  74. data/lib/sendproof/ui/locales/ja.js +2 -0
  75. data/lib/sendproof/ui/locales/ko-journeys.js +465 -0
  76. data/lib/sendproof/ui/locales/ko.js +2 -0
  77. data/lib/sendproof/ui/locales/nb-journeys.js +465 -0
  78. data/lib/sendproof/ui/locales/nb.js +2 -0
  79. data/lib/sendproof/ui/locales/nl-journeys.js +465 -0
  80. data/lib/sendproof/ui/locales/nl.js +2 -0
  81. data/lib/sendproof/ui/locales/pl-journeys.js +468 -0
  82. data/lib/sendproof/ui/locales/pl.js +2 -0
  83. data/lib/sendproof/ui/locales/pt-BR-journeys.js +467 -0
  84. data/lib/sendproof/ui/locales/pt-BR.js +2 -0
  85. data/lib/sendproof/ui/locales/pt-PT-journeys.js +467 -0
  86. data/lib/sendproof/ui/locales/pt-PT.js +2 -0
  87. data/lib/sendproof/ui/locales/ru-journeys.js +468 -0
  88. data/lib/sendproof/ui/locales/ru.js +2 -0
  89. data/lib/sendproof/ui/locales/sv-journeys.js +465 -0
  90. data/lib/sendproof/ui/locales/sv.js +2 -0
  91. data/lib/sendproof/ui/locales/th-journeys.js +466 -0
  92. data/lib/sendproof/ui/locales/th.js +2 -0
  93. data/lib/sendproof/ui/locales/tr-journeys.js +468 -0
  94. data/lib/sendproof/ui/locales/tr.js +2 -0
  95. data/lib/sendproof/ui/locales/uk-journeys.js +468 -0
  96. data/lib/sendproof/ui/locales/uk.js +2 -0
  97. data/lib/sendproof/ui/locales/vi-journeys.js +466 -0
  98. data/lib/sendproof/ui/locales/vi.js +2 -0
  99. data/lib/sendproof/ui/locales/zh-Hans-journeys.js +466 -0
  100. data/lib/sendproof/ui/locales/zh-Hans.js +2 -0
  101. data/lib/sendproof/ui/locales/zh-Hant-journeys.js +466 -0
  102. data/lib/sendproof/ui/locales/zh-Hant.js +2 -0
  103. data/lib/sendproof/ui/manifest.json +349 -104
  104. data/lib/sendproof/ui/markdown.js +27 -2
  105. data/lib/sendproof/ui/request-editor.js +7 -1
  106. data/lib/sendproof/ui/result-states.js +2 -2
  107. data/lib/sendproof/ui/results.js +41 -14
  108. data/lib/sendproof/ui/router.js +25 -1
  109. data/lib/sendproof/ui/seeded-menu.js +2 -1
  110. data/lib/sendproof/ui/shortcuts-sheet.js +3 -1
  111. data/lib/sendproof/ui/shortcuts.js +6 -0
  112. data/lib/sendproof/ui/sidebar.js +54 -5
  113. data/lib/sendproof/ui/signin.js +6 -3
  114. data/lib/sendproof/ui/styles.css +8 -2
  115. data/lib/sendproof/ui/toast.js +29 -0
  116. data/lib/sendproof/ui/vendor/arazzo-runtime-expression.js +136 -0
  117. data/lib/sendproof/ui/vendor/json-pointer.js +48 -0
  118. data/lib/sendproof/ui/vendor/jsonpath-rfc9535.js +15 -0
  119. data/lib/sendproof/ui/view.js +11 -3
  120. data/lib/sendproof/ui/views.css +7 -0
  121. data/lib/sendproof/version.rb +2 -2
  122. data/lib/sendproof/workbench.rb +11 -1
  123. data/lib/sendproof.rb +2 -0
  124. metadata +55 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b6529a27eec0d1fbd4148f1cffd9e0d8066da654d1be13690af6ce3fe79f12c9
4
- data.tar.gz: 0a94e3230502d6f251fe5053a219c9332b90391eb65dc0ff32616b5176aebc20
3
+ metadata.gz: 4823f18e994cc8625a54a980038c8b3d68f5692025258b5750ba510fc7c0684d
4
+ data.tar.gz: 261d3c857b2f6729ceb87a8ed1ae1d2395eabfe74bd55f10efd36cb67775ad3b
5
5
  SHA512:
6
- metadata.gz: 32af50e0c717af11e2c1dabeb4bcfd1866940d5ac332fd87482139cfd50a82f5c2f69e05fbd84e55aa5c7b9c6322914c842c5192e37c397747d7eed3633a4c0e
7
- data.tar.gz: 7ddd3d9aaae71a86f759b215d54ce6dbd09d49b4c61da8dae1edfc52bb2b496d8216abc24d9cbc135e0ba6fc3d4176e499962d9dd7a662bb28f1fa4ab7716c44
6
+ metadata.gz: d6eb39cb200df8f6537fcbe21fca8d83cec413fc0cc278be159c75769007666276eea5f87cecdebef1765ff82314dce4eb04c7d30938289d607f59d26923d7d1
7
+ data.tar.gz: 6a6e6ec2e6c5f3af1a505f46e5586340b0b36b0c9dfd81caa290ebd0b5912782dfd08f5ad55aa84f19825514e5c54cde812461f6492bcc357b5af870f99f6427
@@ -42,6 +42,7 @@ module Sendproof
42
42
  @auth_providers = []
43
43
  @providers = []
44
44
  @data_stores = []
45
+ @journeys = Journeys.new
45
46
  @preview_operations = []
46
47
  @preview_unavailable = []
47
48
  @trace_ttl = 300
@@ -53,6 +54,36 @@ module Sendproof
53
54
  def api_name = @api_name || "API"
54
55
  def environment = @environment.to_s
55
56
  def framework = @framework || "Rack"
57
+ attr_reader :journeys
58
+
59
+ # Registers a paired Arazzo and expectations file. Relative paths use the host's working directory.
60
+ def journey(path, name: nil)
61
+ journeys.register(path, name:)
62
+ end
63
+
64
+ # Registers a group of code-defined workflows under one Arazzo and expectations URL pair.
65
+ def code_journeys(slug, name:, source_name: nil, &definition)
66
+ journeys.register_code(slug, name:, source_name:, &definition)
67
+ end
68
+
69
+ def load_code_journeys!(app)
70
+ journeys.load_code!(app, self) if enabled?
71
+ end
72
+
73
+ def preview_sessions?(provider = preview_provider)
74
+ provider.respond_to?(:begin_held_preview) &&
75
+ (!provider.respond_to?(:holds_preview?) || provider.holds_preview?) &&
76
+ data_stores.all? { |store| store.describe[:mode].to_s == "guard" || store.respond_to?(:begin_held_preview) }
77
+ end
78
+
79
+ # A Rack application can let its router handle GETs absent from the static preview allowlist.
80
+ def resolve_session_get(path, env)
81
+ marks = unavailable_operations.filter_map { |entry| entry.values_at(:method, :path) if entry[:method] == "GET" }
82
+ OperationMatcher.new(marks).resolve("GET", path) ? :ineligible : :eligible
83
+ end
84
+
85
+ def session_job(&block) = block
86
+ def wait_for_session = yield
56
87
 
57
88
  # Replaces the environments in which the workbench and preview are served. Production is never implied.
58
89
  def environments=(list)
@@ -7,6 +7,9 @@ module Sendproof
7
7
  # A store runs in one of two modes. +:preview+ stores join the Preview: their writes run in a
8
8
  # transaction the hook aborts after the handler. +:guard+ stores can't roll back: reads run and
9
9
  # the first write blocks the Preview before any byte of it reaches the store.
10
+ #
11
+ # For held sessions, a +:preview+ store implements +begin_held_preview(context)+ and returns a
12
+ # part with +begin_step(step, recorder)+, +capture_step(recorder)+, +rewind(step)+ and +close+.
10
13
  class DataStore
11
14
  # @return [String] the store id: +"mongodb"+, +"redis"+ or +"dynamodb"+
12
15
  def system
@@ -12,11 +12,13 @@ module Sendproof
12
12
  #
13
13
  # @param env [Hash] Rack environment of the request being handled
14
14
  # @param eligible [Boolean] whether the endpoint is preview-enabled
15
- # @raise [IneligibleHandler] during a preview when +eligible+ is false (the block does not run)
15
+ # @raise [IneligibleHandler] when a preview requires eligibility and +eligible+ is false
16
16
  def around(env, request: nil, eligible: true, &block)
17
17
  context = env[ENV_KEY]
18
18
  return yield unless context
19
19
 
20
+ # The transport checks the configured previewUnavailable marks before running a session GET.
21
+ eligible ||= context.is_a?(PreviewRequest) && context.session_get?
20
22
  context.around_handler(request: request || Rack::Request.new(env), eligible:, &block)
21
23
  end
22
24
  end
@@ -0,0 +1,305 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module Sendproof
6
+ class Journeys
7
+ # Builds one document pair against the same OpenAPI endpoint clients discover.
8
+ class CodeDocument
9
+ class OpenApiError < ConfigurationError; end
10
+
11
+ HTTP_METHODS = %w[get put post delete options head patch trace query].freeze
12
+
13
+ def self.operations(app, url)
14
+ response = Rack::MockRequest.new(app).get(url.to_s, "HTTP_ACCEPT" => "application/json", "HTTP_HOST" => "localhost")
15
+ raise "HTTP #{response.status}" unless response.ok?
16
+
17
+ document = JSON.parse(response.body)
18
+ paths = document.fetch("paths", {})
19
+ raise "expected an OpenAPI paths object" unless paths.is_a?(Hash)
20
+
21
+ paths.each_with_object({}) do |(path, item), operations|
22
+ item = path_item(document, item)
23
+ next unless item.is_a?(Hash)
24
+
25
+ HTTP_METHODS.each do |method|
26
+ operation = item[method]
27
+ next unless operation.is_a?(Hash)
28
+
29
+ id = operation["operationId"]
30
+ operations[id] = [method.upcase, path] if id.is_a?(String)
31
+ end
32
+ end
33
+ rescue StandardError => error
34
+ raise OpenApiError, "Could not read the OpenAPI document at #{url}: #{error.message}"
35
+ end
36
+
37
+ def self.path_item(document, item)
38
+ reference = item["$ref"] if item.is_a?(Hash)
39
+ return item unless reference.is_a?(String) && reference.start_with?("#/")
40
+
41
+ reference.delete_prefix("#/").split("/").reduce(document) do |node, segment|
42
+ node[segment.gsub("~1", "/").gsub("~0", "~")] if node.is_a?(Hash)
43
+ end
44
+ end
45
+ private_class_method :path_item
46
+
47
+ def initialize(slug, name, source_name, definition)
48
+ @slug = slug
49
+ @name = name
50
+ @source_name = source_name.to_s
51
+ @definition = definition
52
+ end
53
+
54
+ def build(config, operations, ids)
55
+ definitions = Definitions.new(config)
56
+ definitions.instance_eval(&@definition)
57
+ arazzo = {
58
+ "arazzo" => "1.1.0", "info" => { "title" => @name, "version" => "1.0.0" },
59
+ "sourceDescriptions" => [{ "name" => @source_name, "url" => config.open_api_url, "type" => "openapi" }],
60
+ "workflows" => []
61
+ }
62
+ expectations = { "sendproofExpectations" => "1.0", "arazzo" => "#{@slug}.arazzo.json",
63
+ "journeys" => {}, "approvedDifferences" => [] }
64
+ problems = definitions.problems
65
+ approvals = Set.new
66
+
67
+ definitions.journeys.each do |journey|
68
+ found = journey.validate(operations, config)
69
+ found << "Duplicate workflow ID #{journey.id.inspect}." if ids.include?(journey.id)
70
+ records = journey.approvals
71
+ record_ids = records.map { |record| record["id"] }
72
+ if record_ids.uniq.size != record_ids.size || record_ids.any? { |id| approvals.include?(id) }
73
+ found << "Approved difference IDs must be unique within a document."
74
+ end
75
+ if found.empty?
76
+ ids.add(journey.id)
77
+ approvals.merge(record_ids)
78
+ arazzo["workflows"] << journey.workflow
79
+ expectations["journeys"][journey.id] = journey.expectations
80
+ expectations["approvedDifferences"].concat(records)
81
+ else
82
+ problems.concat(found.map { |problem| "#{journey.id}: #{problem}" })
83
+ end
84
+ end
85
+
86
+ entry = Entry.new(@name, "code", arazzo, expectations) unless arazzo["workflows"].empty?
87
+ [entry, problems]
88
+ end
89
+ end
90
+
91
+ class Definitions
92
+ attr_reader :journeys, :problems
93
+
94
+ def initialize(config)
95
+ @config = config
96
+ @journeys = []
97
+ @problems = []
98
+ end
99
+
100
+ def journey(id, name:, description: nil, &definition)
101
+ journey = Definition.new(id.to_s, name, description, @config)
102
+ journey.instance_eval(&definition)
103
+ @journeys << journey
104
+ rescue ConfigurationError => error
105
+ @problems << "#{id}: #{error.message}"
106
+ end
107
+ end
108
+
109
+ class Definition
110
+ attr_reader :id, :workflow
111
+
112
+ def initialize(id, name, description, config)
113
+ @id = id
114
+ @config = config
115
+ @workflow = { "workflowId" => id, "summary" => name, "description" => description }.compact
116
+ @metadata = {}
117
+ @steps = []
118
+ end
119
+
120
+ def group(value) = @metadata["group"] = value
121
+ def run_as(persona) = @metadata["runAs"] = persona
122
+
123
+ def send_only(reason)
124
+ @metadata.merge!("sendOnly" => true, "sendOnlyReason" => reason)
125
+ end
126
+
127
+ # Input keywords are JSON Schema, with requiredness recorded on the containing object.
128
+ def input(name, type:, required: false, **schema)
129
+ inputs = (@workflow["inputs"] ||= { "type" => "object", "properties" => {} })
130
+ name = name.to_s
131
+ raise ConfigurationError, "Duplicate input #{name.inspect}." if inputs["properties"].key?(name)
132
+
133
+ inputs["properties"][name] = { "type" => type.is_a?(Array) ? type.map(&:to_s) : type.to_s }.merge(schema)
134
+ (inputs["required"] ||= []) << name if required
135
+ "$inputs.#{name}"
136
+ end
137
+
138
+ def output(name, expression)
139
+ (@workflow["outputs"] ||= {})[name.to_s] = expression
140
+ end
141
+
142
+ def step(id, operation_id, &definition)
143
+ id = id.to_s
144
+ raise ConfigurationError, "Duplicate step #{id.inspect}." if @steps.any? { |step| step.id == id }
145
+
146
+ step = Step.new(id, operation_id.to_s, @config)
147
+ step.instance_eval(&definition) if definition
148
+ @steps << step
149
+ (@workflow["steps"] ||= []) << step.document
150
+ end
151
+
152
+ def validate(operations, config)
153
+ problems = []
154
+ problems << "Define at least one step." if @steps.empty?
155
+ unavailable = config.unavailable_operations.to_h { |entry| [[entry[:method], entry[:path]], entry[:reason]] }
156
+ inputs = @workflow.dig("inputs", "properties") || {}
157
+ earlier = {}
158
+ @steps.each do |step|
159
+ operation = operations[step.document["operationId"]]
160
+ problems << "Step #{step.id}: unknown operationId #{step.document['operationId'].inspect}." unless operation
161
+ if !@metadata["sendOnly"] && (reason = unavailable[operation] || step.send_only_reason)
162
+ send_only("Step #{step.id} is Send only: #{reason}")
163
+ end
164
+ problems.concat(reference_problems("Step #{step.id}", step.document, inputs, earlier))
165
+ earlier[step.id] = step.document.fetch("outputs", {})
166
+ problems.concat(reference_problems("Step #{step.id} expectations", step.expectations, inputs, earlier))
167
+ end
168
+ problems.concat(reference_problems("Workflow outputs", @workflow["outputs"], inputs, earlier)).uniq
169
+ end
170
+
171
+ def expectations
172
+ steps = @steps.reject { |step| step.expectations.empty? }.to_h { |step| [step.id, step.expectations] }
173
+ @metadata.merge("steps" => steps)
174
+ end
175
+
176
+ def approvals
177
+ @steps.flat_map do |step|
178
+ step.approvals.map { |record| record.merge("journey" => id, "step" => step.id) }
179
+ end
180
+ end
181
+
182
+ private
183
+
184
+ def reference_problems(where, value, inputs, outputs)
185
+ case value
186
+ when Hash then value.values.flat_map { |item| reference_problems(where, item, inputs, outputs) }
187
+ when Array then value.flat_map { |item| reference_problems(where, item, inputs, outputs) }
188
+ when String
189
+ problems = value.scan(/(?:\A|[\s{(])\$inputs\.([\w-]+)/).filter_map do |(name)|
190
+ "#{where}: unknown input #{name.inspect}." unless inputs.key?(name)
191
+ end
192
+ problems + value.scan(/(?:\A|[\s{(])\$steps\.([\w-]+)\.outputs\.([\w-]+)/).filter_map do |step, name|
193
+ if !outputs.key?(step)
194
+ "#{where}: #{step.inspect} is not an earlier step."
195
+ elsif !outputs[step].key?(name)
196
+ "#{where}: step #{step.inspect} has no output #{name.inspect}."
197
+ end
198
+ end
199
+ else []
200
+ end
201
+ end
202
+ end
203
+
204
+ class Step
205
+ attr_reader :id, :document, :expectations, :approvals, :send_only_reason
206
+
207
+ def initialize(id, operation_id, config)
208
+ @id = id
209
+ @config = config
210
+ @document = { "stepId" => id, "operationId" => operation_id }
211
+ @expectations = {}
212
+ @approvals = []
213
+ end
214
+
215
+ def run_as(persona) = @expectations["persona"] = persona
216
+
217
+ def parameter(name, location:, value:)
218
+ (@document["parameters"] ||= []) << { "name" => name.to_s, "in" => location.to_s, "value" => value }
219
+ end
220
+
221
+ def body(payload, content_type: "application/json")
222
+ @document["requestBody"] = { "contentType" => content_type, "payload" => payload }
223
+ end
224
+
225
+ def succeeds_with(status) = success_criterion("$statusCode == #{Integer(status)}")
226
+
227
+ def success_criterion(condition, context: nil, type: nil)
228
+ (@document["successCriteria"] ||= []) << { "condition" => condition, "context" => context, "type" => type }.compact
229
+ end
230
+
231
+ # Returns the Arazzo runtime expression for later steps to use in parameters and bodies.
232
+ def output(name, expression)
233
+ (@document["outputs"] ||= {})[name.to_s] = expression
234
+ "$steps.#{id}.outputs.#{name}"
235
+ end
236
+
237
+ def expect_writes(&definition)
238
+ writes = Writes.new(@config)
239
+ writes.instance_eval(&definition)
240
+ @expectations.merge!(writes.document)
241
+ @send_only_reason = writes.send_only_reason
242
+ end
243
+
244
+ def approve_difference(id:, target:, reason:, approved_by:, approved_on:, kind: "value", expires: nil, link: nil, **values)
245
+ if [id, reason, approved_by, approved_on].any? { |value| value.to_s.strip.empty? }
246
+ raise ConfigurationError, "Step #{@id}: an approved difference needs an ID, reason, approver and approval date."
247
+ end
248
+ unknown = values.keys - %i[expected actual]
249
+ unless unknown.empty?
250
+ raise ConfigurationError, "Step #{@id}: unknown approved difference fields #{unknown.join(', ')}."
251
+ end
252
+
253
+ record = { "id" => id.to_s, "target" => target, "kind" => kind.to_s, "reason" => reason,
254
+ "approvedBy" => approved_by, "approvedOn" => Date.iso8601(approved_on.to_s).iso8601,
255
+ "expires" => expires && Date.iso8601(expires.to_s).iso8601, "link" => link }.compact
256
+ @approvals << record.merge(values)
257
+ rescue Date::Error
258
+ raise ConfigurationError, "Step #{@id}: approved difference dates must use ISO 8601."
259
+ end
260
+ end
261
+
262
+ class Writes
263
+ attr_reader :document, :send_only_reason
264
+
265
+ def initialize(config)
266
+ @config = config
267
+ @document = { "writes" => [], "unlisted" => "fail" }
268
+ end
269
+
270
+ def nothing = @document["effects"] ||= []
271
+
272
+ def sql(table, op, key: nil, values: nil)
273
+ provider = @config.preview_provider
274
+ system = provider.database_system if provider.respond_to?(:database_system)
275
+ write(store: system || "sql", table: table.to_s, op:, key:, values:)
276
+ end
277
+
278
+ def mongo(collection, op, key: nil, values: nil)
279
+ write(store: "mongodb", collection: collection.to_s, op:, key:, values:)
280
+ end
281
+
282
+ def redis(key, op, expiry: nil)
283
+ write(store: "redis", key:, op: op.to_s.upcase, values: expiry.nil? ? nil : { "expiry" => expiry })
284
+ end
285
+
286
+ def write(store:, op:, table: nil, collection: nil, key: nil, values: nil)
287
+ system = store.to_s
288
+ if system == "redis" || @config.data_stores.any? { |hook| hook.system.to_s == system && hook.describe[:mode].to_s == "guard" }
289
+ @send_only_reason ||= "it writes to #{system}, which can't roll back."
290
+ end
291
+ @document["writes"] << { "store" => system, "op" => op.to_s, "table" => table, "collection" => collection,
292
+ "key" => key, "values" => values }.compact
293
+ end
294
+
295
+ def effect(kind, **fields)
296
+ (@document["effects"] ||= []) << fields.merge("kind" => kind.to_s)
297
+ end
298
+
299
+ def email(**fields) = effect("email", **fields)
300
+ def any(type = :any) = { "type" => type.to_s }
301
+ def pattern(value) = { "pattern" => value.is_a?(Regexp) ? value.source : value }
302
+ def changed(from, to) = { "from" => from, "to" => to }
303
+ end
304
+ end
305
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module Sendproof
6
+ # Registered Arazzo and expectations pairs, separate from the workbench's asset directory.
7
+ class Journeys
8
+ autoload :CodeDocument, "sendproof/journeys/code_document"
9
+
10
+ ROUTE = %r{\A/sendproof/journeys/([a-zA-Z0-9._-]+)\.(arazzo|expect)\.json\z}
11
+ SLUG = /\A[a-zA-Z0-9][a-zA-Z0-9._-]*\z/
12
+ Entry = Data.define(:name, :source, :arazzo, :expectations)
13
+
14
+ def initialize
15
+ @entries = {}
16
+ @code = {}
17
+ end
18
+
19
+ def register(path, name: nil)
20
+ path = File.expand_path(path)
21
+ slug = File.basename(path).delete_suffix(".arazzo.json")
22
+ unless path.end_with?(".arazzo.json") && slug.match?(SLUG)
23
+ raise ConfigurationError, "Register a journey named <name>.arazzo.json."
24
+ end
25
+ expected = File.join(File.dirname(path), "#{slug}.expect.json")
26
+ arazzo = JSON.parse(File.read(path))
27
+ expectations = JSON.parse(File.read(expected))
28
+ unless arazzo.is_a?(Hash) && expectations.is_a?(Hash)
29
+ raise ConfigurationError, "Journey files must contain JSON objects."
30
+ end
31
+
32
+ title = name || arazzo.dig("info", "title") || slug
33
+ @entries[slug] = Entry.new(title, "file", arazzo, expectations)
34
+ rescue SystemCallError, JSON::ParserError => error
35
+ raise ConfigurationError, "Could not load the journey pair: #{error.message}"
36
+ end
37
+
38
+ def register_code(slug, name:, source_name:, &definition)
39
+ slug = slug.to_s
40
+ unless slug.match?(SLUG) && !@code.key?(slug) && definition
41
+ raise ConfigurationError, "Register code journeys with a unique document name and a definition block (got #{slug.inspect})."
42
+ end
43
+
44
+ @code[slug] = CodeDocument.new(slug, name, source_name || slug.tr(".", "-"), definition)
45
+ end
46
+
47
+ def code_registered? = !@code.empty?
48
+
49
+ def load_code!(app, config)
50
+ return unless code_registered?
51
+
52
+ files = @entries.select { |_, entry| entry.source == "file" }
53
+ ids = Set.new
54
+ files.each_value do |entry|
55
+ Array(entry.arazzo["workflows"]).each { |flow| ids.add(flow["workflowId"]) if flow.is_a?(Hash) }
56
+ end
57
+ operations = CodeDocument.operations(app, config.open_api_url)
58
+ generated = @code.each_with_object({}) do |(slug, document), entries|
59
+ if files.key?(slug)
60
+ report(config, ["#{slug}: A file journey already uses this document name."])
61
+ next
62
+ end
63
+
64
+ entry, problems = document.build(config, operations, ids)
65
+ report(config, problems)
66
+ entries[slug] = entry if entry
67
+ end
68
+ @entries = files.merge(generated)
69
+ rescue CodeDocument::OpenApiError => error
70
+ report(config, [error.message])
71
+ @entries = files
72
+ end
73
+
74
+ def discovery(base)
75
+ @entries.map do |slug, entry|
76
+ url = "#{base}/sendproof/journeys/#{slug}"
77
+ { name: entry.name, source: entry.source, arazzoUrl: "#{url}.arazzo.json", expectationsUrl: "#{url}.expect.json" }
78
+ end
79
+ end
80
+
81
+ def serve(request, slug, extension)
82
+ return [405, { "allow" => "GET, HEAD" }, []] unless request.get? || request.head?
83
+
84
+ entry = @entries[slug]
85
+ return unless entry
86
+
87
+ document = extension == "arazzo" ? mounted_arazzo(entry.arazzo, request.script_name.to_s) : entry.expectations
88
+ status, headers, body = Protocol.json(200, document, {
89
+ "cache-control" => "no-store", "x-content-type-options" => "nosniff"
90
+ })
91
+ [status, headers, request.head? ? [] : body]
92
+ end
93
+
94
+ private
95
+
96
+ def report(config, problems)
97
+ return if problems.empty?
98
+
99
+ if config.environment.casecmp?("development")
100
+ raise ConfigurationError, "Invalid code journeys:\n#{problems.join("\n")}"
101
+ end
102
+
103
+ problems.each do |problem|
104
+ message = "Sendproof skipped a journey: #{problem}"
105
+ config.logger ? config.logger.warn(message) : warn(message)
106
+ end
107
+ end
108
+
109
+ def mounted_arazzo(document, base)
110
+ sources = document["sourceDescriptions"]
111
+ return document if base.empty? || !sources.is_a?(Array)
112
+
113
+ document.merge("sourceDescriptions" => sources.map do |source|
114
+ next source unless source.is_a?(Hash)
115
+
116
+ url = source["url"]
117
+ url.is_a?(String) && url.start_with?("/") && !url.start_with?("//", "#{base}/") ? source.merge("url" => base + url) : source
118
+ end)
119
+ end
120
+ end
121
+ end
@@ -10,14 +10,18 @@ module Sendproof
10
10
  # request is routed, authenticated and authorized by the host exactly like a real call.
11
11
  class Middleware
12
12
  # @param config [Configuration, nil] a shared configuration; otherwise built from +options+
13
- def initialize(app, config = nil, **options)
13
+ def initialize(app, config = nil, load_code_journeys: true, **options)
14
14
  @app = app
15
15
  @config = config || Configuration.new(**options)
16
16
  @config.validate!
17
- @workbench = Workbench.new(@config)
18
- @preview = PreviewTransport.new(app, @config)
17
+ @config.load_code_journeys!(app) if load_code_journeys
18
+ @sessions = PreviewSessions.new(@config)
19
+ @workbench = Workbench.new(@config, @sessions)
20
+ @preview = PreviewTransport.new(app, @config, @sessions)
19
21
  end
20
22
 
23
+ def close = @sessions.shutdown
24
+
21
25
  def call(env)
22
26
  return @app.call(env) unless @config.enabled?
23
27