reason_me_this 0.1.0 → 0.3.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.
@@ -2,6 +2,8 @@ require 'json'
2
2
  require 'fileutils'
3
3
  require 'optparse'
4
4
  require 'reason_me_this'
5
+ require 'reason_me_this/blueprint/ruby'
6
+ require 'reason_me_this/blueprint/yaml'
5
7
  require 'reason_me_this/cli/output'
6
8
 
7
9
  module ReasonMeThis
@@ -16,18 +18,29 @@ module ReasonMeThis
16
18
  guide print the guide to building a blueprint
17
19
  describe list step types with examples and the functions formulas can call
18
20
  check BLUEPRINT list problems with a blueprint file
19
- test BLUEPRINT CASES run each case's facts and compare the expected outputs
21
+ test BLUEPRINT [CASES] run each case's facts and compare the expected outputs
20
22
  run BLUEPRINT [--facts FILE] [--calculation NAME] [--trace]
21
23
  run a blueprint file; facts come from FILE or standard input
22
24
 
23
25
  Publish and run definitions:
24
26
  push NAME BLUEPRINT [CASES] save a definition's draft, checked and tested
25
- publish NAME publish the draft as the next version
26
- run NAME [--version N|draft] [...] run a definition, or a shipped blueprint, by name
27
+ publish NAME [--effective-from DATE] [--no-live]
28
+ publish the draft as the next version
29
+ run NAME [--version N|draft|--on DATE] [...]
30
+ run a definition, or a shipped blueprint, by name
31
+ schema NAME [--version N|draft|--on DATE] [--calculation NAME]
32
+ print JSON Schemas for a calculation's inputs and outputs
27
33
  list list the definitions and their published versions
28
- pull NAME [--dir DIR] write DIR/NAME/blueprint.yml and cases.yml
34
+ pull NAME [--dir DIR] [--ruby] write DIR/NAME/blueprint.yml and cases.yml; --ruby writes blueprint.rb
29
35
 
30
- A BLUEPRINT ending in .yml or .yaml or containing a / is a file; anything else is a name.
36
+ Keep a blueprint as Ruby:
37
+ ruby BLUEPRINT write a YAML blueprint file as the Ruby that builds it, beside it
38
+
39
+ A BLUEPRINT ending in .yml, .yaml or .rb or containing a / is a file; anything else is a name. A .rb file
40
+ is run, and the ReasonMeThis::Blueprint it ends with is sent as YAML, with the examples it gives as its
41
+ cases when no CASES file is named.
42
+ --on YYYY-MM-DD picks the version in effect that day. publish --effective-from makes the new version take
43
+ effect on that day (today by default); --no-live keeps the version that is live now live, so the new one waits.
31
44
  Every command but guide and describe needs RMT_API_KEY (create one at #{KEYS}).
32
45
  RMT_API_URL defaults to #{HOSTED}.
33
46
 
@@ -35,10 +48,14 @@ module ReasonMeThis
35
48
  --json answer in JSON (the default when output is not a terminal)
36
49
  --text answer in text (the default at a terminal)
37
50
 
38
- Exit codes: 0 success, 1 a run failed, 2 the blueprint has problems, 3 a case failed, 64 usage,
39
- 69 the service could not be reached, 77 the service refused the key
51
+ Exit codes: 0 success, 1 a run failed or the service has no such definition or version (404, 410),
52
+ 2 the blueprint has problems, 3 a case failed, 64 usage, 69 the service could not be reached,
53
+ 77 the service refused the key
40
54
  TEXT
41
55
 
56
+ class Unreadable < Error
57
+ end
58
+
42
59
  WORKFLOW = <<~MARKDOWN.freeze
43
60
  # Building a blueprint
44
61
 
@@ -59,13 +76,17 @@ module ReasonMeThis
59
76
  was reached when a value surprises you.
60
77
  8. `rmt push NAME BLUEPRINT CASES` saves it as the draft of the definition NAME, and `rmt publish NAME`
61
78
  makes the draft the next version, which applications call. A draft with problems or a failing case
62
- is refused.
79
+ is refused. `--effective-from DATE` makes it take effect on that day, and `--no-live` keeps the live
80
+ version live.
81
+ 9. `rmt run NAME --facts FACTS.json` runs the live version; `--version draft` tries the draft first, and
82
+ `--on DATE` runs the version in effect that day. `rmt schema NAME` prints the JSON Schemas of its facts
83
+ and outputs, for a validator.
63
84
 
64
85
  Every command prints JSON to standard output when it is not a terminal, which is how an agent runs it,
65
- and text at a terminal; `--json` or `--text` chooses either way. Exit codes: 0 success, 1 a run failed,
66
- 2 the blueprint has problems, 3 a case failed, 64 usage, 69 the service could not be reached, 77 the
67
- service refused the key. A blueprint imports others by name (`imports: [rates]`, `rates@2`,
68
- `rates@draft`), never by path.
86
+ and text at a terminal; `--json` or `--text` chooses either way. Exit codes: 0 success, 1 a run failed
87
+ or the service has no such definition or version, 2 the blueprint has problems, 3 a case failed,
88
+ 64 usage, 69 the service could not be reached, 77 the service refused the key. A blueprint imports
89
+ others by name (`imports: [rates]`, `rates@2`, `rates@draft`), never by path.
69
90
 
70
91
  MARKDOWN
71
92
 
@@ -93,6 +114,8 @@ module ReasonMeThis
93
114
  rescue OptionParser::ParseError, Errno::ENOENT => e
94
115
  @err.puts(e.message)
95
116
  usage
117
+ rescue Unreadable, Blueprint::Ruby::Unwritable => e
118
+ answered(:problems, {'problems' => [e.message]}, 2)
96
119
  end
97
120
 
98
121
  private
@@ -100,7 +123,7 @@ module ReasonMeThis
100
123
  def dispatch(command, argv)
101
124
  case command
102
125
  when 'guide', 'describe', 'list' then send(command)
103
- when 'check', 'test', 'run', 'push', 'publish', 'pull' then argv.first ? send(command, argv) : usage
126
+ when 'check', 'test', 'run', 'schema', 'push', 'publish', 'pull', 'ruby' then argv.first ? send(command, argv) : usage
104
127
  else usage
105
128
  end
106
129
  end
@@ -122,30 +145,35 @@ module ReasonMeThis
122
145
  end
123
146
 
124
147
  def check(argv)
125
- on_service(:post, '/check', {yaml: File.read(argv.first)}) do |_status, answer|
148
+ on_service(:post, '/check', {yaml: blueprint(argv.first)}) do |_status, answer|
126
149
  answered(:problems, answer.slice('problems'), answer['problems'].any? ? 2 : 0)
127
150
  end
128
151
  end
129
152
 
130
153
  def test(argv)
131
- return usage unless argv[1]
154
+ cases = cases(*argv.first(2)) or return usage
132
155
 
133
- on_service(:post, '/check', {yaml: File.read(argv[0]), cases: File.read(argv[1])}) { |_status, answer| answered(:report, answer, proven(answer)) }
156
+ on_service(:post, '/check', {yaml: blueprint(argv[0]), cases:}) { |_status, answer| answered(:report, answer, proven(answer)) }
134
157
  end
135
158
 
136
159
  def run(argv)
137
160
  options = {}
138
161
  OptionParser.new do |parser|
139
162
  parser.on('--facts FILE') { |file| options[:facts] = file }
140
- parser.on('--calculation NAME') { |name| options[:calculation] = name }
141
- parser.on('--version VERSION') { |version| options[:version] = version }
163
+ choosing(parser, options)
142
164
  parser.on('--trace') { options[:trace] = true }
143
165
  end.parse!(argv)
144
166
  facts = read_facts(options) or return 1
145
- body = {facts:, **options.slice(:calculation, :version, :trace)}
167
+ body = {facts:, **options.slice(:calculation, :version, :on, :trace)}
146
168
  return ran(:post, "/definitions/#{argv.first}/run", body, options) unless path?(argv.first)
147
169
 
148
- ran(:post, '/try', {yaml: File.read(argv.first), **body.except(:version)}, options)
170
+ ran(:post, '/try', {yaml: blueprint(argv.first), **body.except(:version, :on)}, options)
171
+ end
172
+
173
+ def choosing(parser, options)
174
+ parser.on('--calculation NAME') { |name| options[:calculation] = name }
175
+ parser.on('--version VERSION') { |version| options[:version] = version }
176
+ parser.on('--on DATE') { |day| options[:on] = day }
149
177
  end
150
178
 
151
179
  def ran(method, path, body, options)
@@ -165,16 +193,36 @@ module ReasonMeThis
165
193
  nil
166
194
  end
167
195
 
196
+ def schema(argv)
197
+ options = {}
198
+ OptionParser.new { |parser| choosing(parser, options) }.parse!(argv)
199
+ query = options.empty? ? '' : "?#{URI.encode_www_form(options)}"
200
+ on_service(:get, "/definitions/#{argv.first}/schema#{query}") do |status, answer|
201
+ status == 200 ? print_schema(answer) : answered(:refusal, answer, 1)
202
+ end
203
+ end
204
+
205
+ # A JSON Schema is JSON, so it prints as JSON at a terminal too.
206
+ def print_schema(schema)
207
+ @out.puts(JSON.pretty_generate(schema))
208
+ 0
209
+ end
210
+
168
211
  def push(argv)
169
- name, blueprint, cases = argv
170
- return usage unless blueprint
212
+ name, file, cases = argv
213
+ return usage unless file
171
214
 
172
- body = {yaml: File.read(blueprint), cases: cases ? File.read(cases) : ''}
215
+ body = {yaml: blueprint(file), cases: cases(file, cases) || ''}
173
216
  on_service(:put, "/definitions/#{name}", body) { |_status, answer| answered(:report, answer, proven(answer)) }
174
217
  end
175
218
 
176
219
  def publish(argv)
177
- on_service(:post, "/definitions/#{argv.first}/publish") do |status, answer|
220
+ options = {}
221
+ OptionParser.new do |parser|
222
+ parser.on('--effective-from DATE') { |day| options[:effective_from] = day }
223
+ parser.on('--[no-]live') { |live| options[:live] = live }
224
+ end.parse!(argv)
225
+ on_service(:post, "/definitions/#{argv.first}/publish", (options unless options.empty?)) do |status, answer|
178
226
  status == 201 ? answered(:published, answer, 0, name: argv.first) : answered(:report, answer, proven(answer))
179
227
  end
180
228
  end
@@ -185,15 +233,51 @@ module ReasonMeThis
185
233
 
186
234
  def pull(argv)
187
235
  options = {dir: '.'}
188
- OptionParser.new { |parser| parser.on('--dir DIR') { |dir| options[:dir] = dir } }.parse!(argv)
236
+ OptionParser.new do |parser|
237
+ parser.on('--dir DIR') { |dir| options[:dir] = dir }
238
+ parser.on('--ruby') { options[:ruby] = true }
239
+ end.parse!(argv)
189
240
  name = argv.first
190
241
  on_service(:get, "/definitions/#{name}") do |status, answer|
191
242
  next answered(:refusal, answer, 1) unless status == 200
192
243
 
193
- write_new({'blueprint.yml' => answer['yaml'], 'cases.yml' => answer['cases']}.transform_keys { |file| File.join(options[:dir], name, file) })
244
+ kept = options[:ruby] ? {'blueprint.rb' => as_ruby(answer['yaml'], name)} : {'blueprint.yml' => answer['yaml']}
245
+ write_new({**kept, 'cases.yml' => answer['cases']}.transform_keys { |file| File.join(options[:dir], name, file) })
194
246
  end
195
247
  end
196
248
 
249
+ def ruby(argv)
250
+ path = argv.first
251
+ name = File.basename(path, '.*')
252
+ name = File.basename(File.dirname(File.expand_path(path))) if name == 'blueprint'
253
+ write_new({"#{path.sub(/\.ya?ml\z/, '')}.rb" => as_ruby(File.read(path), name)})
254
+ end
255
+
256
+ def as_ruby(yaml, name)
257
+ Blueprint::Ruby.write(Blueprint::Yaml.read(yaml), name)
258
+ rescue Psych::SyntaxError => e
259
+ raise Unreadable.new("The blueprint is not valid YAML: #{e.message}")
260
+ end
261
+
262
+ def blueprint(path) = path.end_with?('.rb') ? built(path).yaml : File.read(path)
263
+
264
+ # The cases file, or without one the examples a Ruby file gives.
265
+ def cases(blueprint, path = nil)
266
+ return File.read(path) if path
267
+
268
+ built(blueprint).cases_yaml if blueprint.end_with?('.rb')
269
+ end
270
+
271
+ # A Ruby file is run for the blueprint it ends with.
272
+ def built(path)
273
+ built = Module.new.module_eval(File.read(path), path)
274
+ return built if built.is_a?(Blueprint)
275
+
276
+ raise Unreadable.new("#{path} should end with the blueprint it builds, a ReasonMeThis::Blueprint, not #{built.inspect}")
277
+ rescue ScriptError, StandardError => e
278
+ raise e.is_a?(Unreadable) ? e : Unreadable.new("#{path} could not be run: #{e.class}: #{e.message}")
279
+ end
280
+
197
281
  def write_new(files)
198
282
  existing = files.keys.select { |path| File.exist?(path) }
199
283
  return answered(:problems, {'problems' => existing.map { |path| "#{path} already exists" }}, 1) if existing.any?
@@ -223,7 +307,7 @@ module ReasonMeThis
223
307
  answer['failed'].to_i.positive? ? 3 : 0
224
308
  end
225
309
 
226
- def path?(argument) = argument.end_with?('.yml', '.yaml') || argument.include?('/')
310
+ def path?(argument) = argument.end_with?('.yml', '.yaml', '.rb') || argument.include?('/')
227
311
 
228
312
  def answered(kind, answer, code, context = {})
229
313
  @output.show(kind, answer, **context)
@@ -1,3 +1,11 @@
1
1
  module ReasonMeThis
2
- Configuration = Struct.new(:url, :api_key, :connection)
2
+ Configuration = Struct.new(:url, :api_key, :connection, :engine, :blueprints) do
3
+ def hooks = @hooks ||= []
4
+
5
+ def after_reasoning(&hook) = hooks << hook
6
+
7
+ def event_handlers = @event_handlers ||= []
8
+
9
+ def on_event(&handler) = event_handlers << handler
10
+ end
3
11
  end
@@ -0,0 +1,25 @@
1
+ module ReasonMeThis
2
+ # The engines that run blueprints in this process, with no service. They are licensed separately: an engine's
3
+ # own package provides reason_me_this/engines/NAME, which registers how to build its connection.
4
+ module Engines
5
+ NAME = /\A[a-z0-9_]+\z/
6
+ @builders = {}
7
+
8
+ def self.register(name, &builder) = @builders[name.to_sym] = builder
9
+
10
+ def self.connection(name, blueprints: nil)
11
+ raise Error.new("an engine is named in lowercase letters, digits and underscores, not #{name}") unless NAME.match?(name.to_s)
12
+
13
+ @builders.fetch(name.to_sym) { load(name) }.call(blueprints:)
14
+ end
15
+
16
+ def self.load(name)
17
+ require "reason_me_this/engines/#{name}"
18
+ @builders.fetch(name.to_sym)
19
+ rescue LoadError => e
20
+ raise EngineMissing.new("the #{name} engine could not be loaded: #{e.message}. It is licensed separately; add the gems you were " \
21
+ 'given to your Gemfile, or configure a url to use the service')
22
+ end
23
+ private_class_method :load
24
+ end
25
+ end
@@ -2,9 +2,13 @@ module ReasonMeThis
2
2
  class Error < StandardError; end
3
3
  class Unauthorized < Error; end
4
4
  class NotFound < Error; end
5
+ class Gone < Error; end
5
6
  class StepFailed < Error; end
6
7
  class Timeout < Error; end
7
8
  class Unreachable < Error; end
9
+ class InvalidSignature < Error; end
10
+ class EngineMissing < Error; end
11
+ class Unsupported < Error; end
8
12
 
9
13
  class Refused < Error
10
14
  attr_reader :report
@@ -21,6 +25,10 @@ module ReasonMeThis
21
25
  def message = "the facts have problems: #{problems.join('; ')}"
22
26
  end
23
27
 
28
+ class InvalidRequest < Refused
29
+ def message = problems.join('; ')
30
+ end
31
+
24
32
  class Rejected < Refused
25
33
  def message
26
34
  failed = "#{report[:failed]} cases failed" if report[:failed].to_i.positive?
@@ -1,3 +1,36 @@
1
1
  module ReasonMeThis
2
- Explanation = Data.define(:outputs, :steps)
2
+ Event = Data.define(:name, :data) do
3
+ def self.read(event) = new(name: event[:name].to_sym, data: event.fetch(:data, {}))
4
+ end
5
+
6
+ Explanation = Data.define(:outputs, :steps, :version, :events) do
7
+ def initialize(outputs:, steps:, version: nil, events: []) = super
8
+
9
+ def at(path)
10
+ names = path.to_s.split('.')
11
+ return outputs[names.first] if names.one? && outputs.to_h.key?(names.first.to_sym)
12
+
13
+ found(steps, names) { raise Error.new("no step #{path} in the trace") }
14
+ end
15
+
16
+ private
17
+
18
+ def found(list, names, &missing)
19
+ step = list.find { |each| each[:step].to_s == names.first } or return missing.call
20
+ rest = names.drop(1)
21
+ return step[:value] if rest.empty?
22
+ return step[:rows].map { |row| found(row, rest, &missing) } if step[:rows]
23
+ return found(step[:steps], rest, &missing) if step[:steps]
24
+
25
+ within(step[:value], rest, &missing)
26
+ end
27
+
28
+ def within(value, names, &missing)
29
+ return value if names.empty?
30
+ return value.map { |row| within(row, names, &missing) } if value.is_a?(Array)
31
+ return missing.call unless value.is_a?(Hash) && value.key?(names.first.to_sym)
32
+
33
+ within(value[names.first.to_sym], names.drop(1), &missing)
34
+ end
35
+ end
3
36
  end
@@ -3,12 +3,20 @@ module ReasonMeThis
3
3
  def self.included(base) = base.extend(ClassMethods)
4
4
 
5
5
  module ClassMethods
6
- def reasons(name, with:, calculation: nil, &facts)
6
+ def reasons(name, with:, calculation: nil, &)
7
+ reasoned[name] = Recipe.build(with:, calculation:, &)
8
+ keep_receipts if reasoned[name].receipts
7
9
  {name => :run, "#{name}_explained": :explain}.each do |method, call|
8
- define_method(method) do |*args|
9
- reasonings[[method, args]] ||= reason_me_this_client.public_send(call, with, instance_exec(*args, &facts), calculation:)
10
- end
10
+ define_method(method) { |*args| reasonings[[method, args]] ||= reasoning(self.class.reasoned.fetch(name), call, args) }
11
11
  end
12
+ define_method(:"#{name}!") { |*args| reason!(name, args) }
13
+ end
14
+
15
+ def reasoned = @reasoned ||= superclass.respond_to?(:reasoned) ? superclass.reasoned.dup : {}
16
+
17
+ def keep_receipts
18
+ require 'reason_me_this/receipt'
19
+ has_many :reason_me_this_receipts, as: :record, class_name: 'ReasonMeThis::Receipt' unless reflect_on_association(:reason_me_this_receipts)
12
20
  end
13
21
  end
14
22
 
@@ -17,5 +25,45 @@ module ReasonMeThis
17
25
  private
18
26
 
19
27
  def reasonings = @reasonings ||= {}
28
+
29
+ def reason!(name, args)
30
+ recipe = self.class.reasoned.fetch(name)
31
+ facts = instance_exec(*args, &recipe.facts)
32
+ explained = reason_me_this_client.explain(recipe.blueprint, facts, calculation: recipe.calculation)
33
+ transactionally do
34
+ recipe.savings.each { |saving| saving.apply(self, explained) }
35
+ save! if respond_to?(:save!)
36
+ recipe.hooks.each { |hook| instance_exec(explained, &hook) }
37
+ ReasonMeThis.configuration.hooks.each { |hook| hook.call(self, name, explained) }
38
+ keep_receipt(recipe, name, facts, explained) if recipe.receipts
39
+ end
40
+ committed { announce(recipe, name, explained) }
41
+ explained
42
+ end
43
+
44
+ def announce(recipe, name, explained)
45
+ explained.events.each do |event|
46
+ recipe.handlers.fetch(event.name, []).each { |handler| instance_exec(event, explained, &handler) }
47
+ ReasonMeThis.configuration.event_handlers.each { |handler| handler.call(self, name, event) }
48
+ end
49
+ end
50
+
51
+ def reasoning(recipe, call, args)
52
+ reason_me_this_client.public_send(call, recipe.blueprint, instance_exec(*args, &recipe.facts), calculation: recipe.calculation)
53
+ end
54
+
55
+ def keep_receipt(recipe, name, facts, explained)
56
+ reason_me_this_receipts.create!(reasoning: name, blueprint: recipe.blueprint, version: explained.version, calculation: recipe.calculation,
57
+ facts: Values.text(facts), outputs: Values.text(explained.outputs.to_h), steps: Values.text(explained.steps),
58
+ events: Values.text(explained.events.map(&:to_h)))
59
+ end
60
+
61
+ def transactionally(&) = self.class.respond_to?(:transaction) ? self.class.transaction(&) : yield
62
+
63
+ # Inside a transaction the caller opened, after_all_transactions_commit waits for it to commit, and never
64
+ # runs if it rolls back. Outside one, or without Active Record, the block runs now.
65
+ def committed(&)
66
+ defined?(ActiveRecord) && ActiveRecord.respond_to?(:after_all_transactions_commit) ? ActiveRecord.after_all_transactions_commit(&) : yield
67
+ end
20
68
  end
21
69
  end
@@ -0,0 +1,9 @@
1
+ require 'active_record'
2
+
3
+ module ReasonMeThis
4
+ class Receipt < ActiveRecord::Base
5
+ self.table_name = 'reason_me_this_receipts'
6
+
7
+ belongs_to :record, polymorphic: true
8
+ end
9
+ end
@@ -0,0 +1,35 @@
1
+ module ReasonMeThis
2
+ Recipe = Data.define(:blueprint, :calculation, :facts, :savings, :hooks, :handlers, :receipts) do
3
+ def self.build(with:, calculation:, &steps)
4
+ builder = Recipe::Builder.new
5
+ builder.instance_eval(&steps) if steps
6
+ new(blueprint: with, calculation:, facts: builder.facts || proc { {} }, savings: builder.savings, hooks: builder.hooks, handlers: builder.handlers,
7
+ receipts: builder.receipts)
8
+ end
9
+ end
10
+
11
+ class Recipe
12
+ class Builder
13
+ attr_reader :savings, :hooks, :handlers, :receipts
14
+
15
+ def initialize
16
+ @savings = []
17
+ @hooks = []
18
+ @handlers = {}
19
+ end
20
+
21
+ def facts(&given)
22
+ @facts = given if given
23
+ @facts
24
+ end
25
+
26
+ def saves(**) = savings << Saving.of(**)
27
+
28
+ def after(&hook) = hooks << hook
29
+
30
+ def on(event, &handler) = (handlers[event.to_sym] ||= []) << handler
31
+
32
+ def keeps_receipts = @receipts = true
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,30 @@
1
+ module ReasonMeThis
2
+ Saving = Data.define(:on, :into, :from, :by, :columns) do
3
+ def self.of(on: nil, into: nil, from: nil, by: nil, **columns) = new(on:, into:, from:, by:, columns:)
4
+
5
+ def apply(record, explained)
6
+ return rows(record.public_send(into), Array(explained.at(from))) if into
7
+
8
+ target = on ? record.public_send(on) : record
9
+ columns.each { |column, source| target.public_send(:"#{column}=", stored(target, column, value(source, explained))) }
10
+ target.save! if on
11
+ end
12
+
13
+ private
14
+
15
+ def value(source, explained) = source.respond_to?(:call) ? source.call(explained) : explained.at(source)
16
+
17
+ def stored(target, column, value)
18
+ json = target.respond_to?(:type_for_attribute) && target.type_for_attribute(column.to_s).type == :json
19
+ json ? Values.text(value) : value
20
+ end
21
+
22
+ def rows(association, found)
23
+ found.each do |row|
24
+ child = association.find_or_initialize_by(by => row[by])
25
+ child.assign_attributes(columns.empty? ? row.slice(*child.attribute_names.map(&:to_sym)) : columns.transform_values { |key| row[key.to_sym] })
26
+ child.save!
27
+ end
28
+ end
29
+ end
30
+ end
@@ -7,6 +7,7 @@ module ReasonMeThis
7
7
  module Values
8
8
  NUMBER = /\A-?\d+(\.\d+)?\z/
9
9
  DATE = /\A\d{4}-\d{2}-\d{2}\z/
10
+ TIME = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})\z/
10
11
 
11
12
  module_function
12
13
 
@@ -15,6 +16,7 @@ module ReasonMeThis
15
16
  case leaf
16
17
  when NUMBER then BigDecimal(leaf)
17
18
  when DATE then date(leaf)
19
+ when TIME then time(leaf)
18
20
  else leaf
19
21
  end
20
22
  end
@@ -31,12 +33,28 @@ module ReasonMeThis
31
33
  end
32
34
  end
33
35
 
36
+ def text(value)
37
+ deep(value) do |leaf|
38
+ case leaf
39
+ when BigDecimal then leaf.frac.zero? ? leaf.to_i.to_s : leaf.to_s('F')
40
+ when Date, Time then leaf.iso8601
41
+ else leaf
42
+ end
43
+ end
44
+ end
45
+
34
46
  def date(text)
35
47
  Date.iso8601(text)
36
48
  rescue Date::Error
37
49
  text
38
50
  end
39
51
 
52
+ def time(text)
53
+ Time.iso8601(text)
54
+ rescue ArgumentError
55
+ text
56
+ end
57
+
40
58
  def deep(value, &)
41
59
  case value
42
60
  when Hash then value.to_h { |key, item| [key.is_a?(String) ? key.to_sym : key, deep(item, &)] }
@@ -1,3 +1,3 @@
1
1
  module ReasonMeThis
2
- VERSION = '0.1.0'.freeze
2
+ VERSION = '0.3.0'.freeze
3
3
  end
@@ -0,0 +1,29 @@
1
+ require 'json'
2
+ require 'openssl'
3
+
4
+ module ReasonMeThis
5
+ # Checks a delivery the service posted to a webhook: the RMT-Signature header is t=<unix time>,v1=<hex
6
+ # HMAC-SHA256 of "<t>.<body>" with the subscription's secret>. A delivery signed more than tolerance seconds
7
+ # from now is refused, so a captured one cannot be replayed later.
8
+ module Webhook
9
+ TOLERANCE = 300
10
+
11
+ module_function
12
+
13
+ def verify(body, signature, secret, now: Time.now, tolerance: TOLERANCE)
14
+ delivered = payload(body, signature, secret, now:, tolerance:)
15
+ Event.new(name: delivered[:event].to_sym, data: delivered.fetch(:data, {}))
16
+ end
17
+
18
+ def payload(body, signature, secret, now: Time.now, tolerance: TOLERANCE)
19
+ at, given = signature.to_s.split(',').to_h { |part| part.split('=', 2) }.values_at('t', 'v1')
20
+ raise InvalidSignature.new('the delivery is not signed') unless at && given
21
+ raise InvalidSignature.new("the delivery was signed more than #{tolerance} seconds from now") if (now.to_i - at.to_i).abs > tolerance
22
+
23
+ expected = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{at}.#{body}")
24
+ raise InvalidSignature.new('the signature does not match') unless OpenSSL.secure_compare(expected, given)
25
+
26
+ Values.read(JSON.parse(body, symbolize_names: true))
27
+ end
28
+ end
29
+ end