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.
- checksums.yaml +4 -4
- data/README.md +323 -16
- data/lib/generators/reason_me_this/receipts_generator.rb +17 -0
- data/lib/generators/reason_me_this/templates/create_reason_me_this_receipts.rb.tt +16 -0
- data/lib/reason_me_this/blueprint/calculation.rb +110 -0
- data/lib/reason_me_this/blueprint/fields.rb +50 -0
- data/lib/reason_me_this/blueprint/ruby.rb +217 -0
- data/lib/reason_me_this/blueprint/rules.rb +22 -0
- data/lib/reason_me_this/blueprint/step.rb +25 -0
- data/lib/reason_me_this/blueprint/yaml.rb +40 -0
- data/lib/reason_me_this/blueprint.rb +87 -0
- data/lib/reason_me_this/cli/output.rb +15 -2
- data/lib/reason_me_this/cli.rb +111 -27
- data/lib/reason_me_this/configuration.rb +9 -1
- data/lib/reason_me_this/engines.rb +25 -0
- data/lib/reason_me_this/errors.rb +8 -0
- data/lib/reason_me_this/explanation.rb +34 -1
- data/lib/reason_me_this/model.rb +52 -4
- data/lib/reason_me_this/receipt.rb +9 -0
- data/lib/reason_me_this/recipe.rb +35 -0
- data/lib/reason_me_this/saving.rb +30 -0
- data/lib/reason_me_this/values.rb +18 -0
- data/lib/reason_me_this/version.rb +1 -1
- data/lib/reason_me_this/webhook.rb +29 -0
- data/lib/reason_me_this.rb +61 -14
- metadata +17 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: b588faa6d905ef02f7aaf13b1458594f812b360b0a47f8c804d846f6ef98c9c2
|
|
4
|
+
data.tar.gz: 3ca4a8ddb96775b492f587f280fed1a866d89741794989dcfd01b9129ed8a840
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 77dd54b9b13e0bc5ef968fc4916ea0df1462e00dabe4d4c6481158a1a1d97b7f6f78e8aa2778b46f57b2d14ff38a25782798ded273d326d717660df1791cc6bd
|
|
7
|
+
data.tar.gz: d7bbf1fe7be1dc22823c91f204303a2ae6aadc614518a21676b494f5815f259965591d76927bf5f27e113acefc924972c940ab1f6187c3ffec5bbaf9bffe8fa9
|
data/README.md
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
The Ruby client for [Reason Me This](https://reason-me-this.com). It runs, explains, pushes and publishes definitions over HTTP
|
|
4
4
|
and keeps every number exact on the way out and on the way back.
|
|
5
5
|
|
|
6
|
-
It
|
|
6
|
+
It speaks HTTP and needs nothing beyond Ruby's standard library. With a licensed engine installed it can
|
|
7
|
+
instead run blueprints in your own process, with no service: see [Without the service](#without-the-service).
|
|
7
8
|
|
|
8
9
|
## Install
|
|
9
10
|
|
|
@@ -22,13 +23,24 @@ rmt guide # how to build a blueprint
|
|
|
22
23
|
rmt check bill.yml # exit 2 while it has problems
|
|
23
24
|
rmt test bill.yml cases.yml # exit 3 while a case fails
|
|
24
25
|
rmt push bill bill.yml cases.yml && rmt publish bill
|
|
26
|
+
rmt publish bill --effective-from 2027-01-01 --no-live
|
|
25
27
|
echo '{"plan": "flat_rate"}' | rmt run bill --trace
|
|
28
|
+
echo '{"plan": "flat_rate"}' | rmt run bill --on 2026-07-01
|
|
29
|
+
rmt schema bill --calculation bill # JSON Schemas of its facts and outputs
|
|
26
30
|
rmt run electricity_bill --facts facts.json # a shipped blueprint, by name
|
|
31
|
+
rmt ruby bill.yml # write bill.rb, the same blueprint in Ruby
|
|
32
|
+
rmt pull bill --ruby # bill/blueprint.rb in place of blueprint.yml
|
|
33
|
+
rmt check bill.rb && rmt push bill bill.rb # a .rb file is run and sent as the YAML it builds
|
|
34
|
+
rmt test bill.rb # with the examples it gives as its cases
|
|
27
35
|
```
|
|
28
36
|
|
|
29
37
|
`check`, `test` and `run` on a file send its text to the service and save nothing. Exit codes: 0 success,
|
|
30
|
-
1 a run failed, 2 problems, 3 a case failed, 64 usage, 69 the service could
|
|
31
|
-
refused. `rmt help` lists every command. `RMT_API_URL` points it at another
|
|
38
|
+
1 a run failed or no such definition or version, 2 problems, 3 a case failed, 64 usage, 69 the service could
|
|
39
|
+
not be reached, 77 the key was refused. `rmt help` lists every command. `RMT_API_URL` points it at another
|
|
40
|
+
service. `rmt run` and `rmt schema` take the live version, `--version N` or `draft`, or `--on YYYY-MM-DD` for
|
|
41
|
+
the version in effect that day. `rmt publish` takes `--effective-from YYYY-MM-DD` (today by default) and
|
|
42
|
+
`--no-live`, which keeps the live version live so the new one waits. `rmt schema` prints JSON even at a
|
|
43
|
+
terminal.
|
|
32
44
|
|
|
33
45
|
## Configure
|
|
34
46
|
|
|
@@ -56,7 +68,8 @@ answer.to_h
|
|
|
56
68
|
| Option | Means |
|
|
57
69
|
| --- | --- |
|
|
58
70
|
| `calculation:` | which calculation in the definition to run |
|
|
59
|
-
| `version:` | a published version number, `"latest"` (the default) or `"draft"` |
|
|
71
|
+
| `version:` | a published version number, `"latest"` (the default, the live version) or `"draft"` |
|
|
72
|
+
| `on:` | a `Date`: run the version in effect that day, rather than the live one. Not with a version number |
|
|
60
73
|
| `trace:` | `true` answers as `explain` does |
|
|
61
74
|
|
|
62
75
|
`"sales_commission@3"` pins the name to published version 3. A `version:` given as well wins over the pin.
|
|
@@ -69,6 +82,7 @@ The service sends numbers as strings so they stay exact. An answer reads them ba
|
|
|
69
82
|
| --- | --- |
|
|
70
83
|
| `"55830"`, `"0.8"`, `"-12.5"` | `BigDecimal` |
|
|
71
84
|
| `"2026-07-01"` | `Date` |
|
|
85
|
+
| `"2026-11-02T16:00:00+11:00"`, `"2026-11-02T05:00:00Z"` | `Time`, keeping its offset |
|
|
72
86
|
| any other string, number, `true`, `false`, `null` | as sent |
|
|
73
87
|
| an object | a hash with symbol keys, its values read the same way |
|
|
74
88
|
|
|
@@ -87,19 +101,140 @@ explained = ReasonMeThis.explain("sales_commission", facts, calculation: :year)
|
|
|
87
101
|
|
|
88
102
|
explained.outputs # an answer, as run gives
|
|
89
103
|
explained.steps # each step with its value, in the order they ran
|
|
104
|
+
explained.events # what the answer set off: [Event(name: :quota_hit, data: {over_by: BigDecimal("1200")})]
|
|
90
105
|
```
|
|
91
106
|
|
|
107
|
+
A blueprint names its events beside its outputs (see the engine's Events guide). Only a traced run lists
|
|
108
|
+
them; a plain `run` answers the outputs alone.
|
|
109
|
+
|
|
92
110
|
## Manage definitions
|
|
93
111
|
|
|
94
112
|
```ruby
|
|
95
113
|
ReasonMeThis.push("bill", yaml: File.read("bill.yml"), cases: File.read("cases.yml"))
|
|
96
114
|
# => {problems: [], passed: 4, failed: 0, cases: [...]}
|
|
97
115
|
|
|
98
|
-
ReasonMeThis.publish("bill") # => 4,
|
|
99
|
-
ReasonMeThis.
|
|
100
|
-
|
|
116
|
+
ReasonMeThis.publish("bill") # => {version: 4, effective_from: Date(2026-11-08), live_version: 4}
|
|
117
|
+
ReasonMeThis.publish("bill", effective_from: Date.new(2027, 1, 1), live: false)
|
|
118
|
+
# => {version: 5, effective_from: Date(2027-01-01), live_version: 4}
|
|
119
|
+
ReasonMeThis.definitions
|
|
120
|
+
# => [{name: "bill", published_version: 5, live_version: 4, live_pinned: true,
|
|
121
|
+
# versions: [{number: 1, effective_from: Date(2026-07-01), retired: false, published_at: Time(...)}, ...], updated_at: Time(...)}]
|
|
122
|
+
ReasonMeThis.definition("bill") # => {name: "bill", yaml: "...", cases: "...", published_version: 5, live_version: 4, ...}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
`publish` takes `effective_from:`, the day the new version takes effect (today by default), and `live: false`
|
|
126
|
+
to leave the version that is live now live, so the new one waits until it is made live on the service.
|
|
127
|
+
It answers what the service does: the new version, the day it takes effect and the live version. It used
|
|
128
|
+
to answer the version number alone; read that as `publish("bill")[:version]`.
|
|
129
|
+
|
|
130
|
+
## Blueprints in Ruby
|
|
131
|
+
|
|
132
|
+
A blueprint can be written in Ruby instead of YAML. `ReasonMeThis::Blueprint.define` builds the same
|
|
133
|
+
document a blueprint file holds, so it is pushed, checked and run exactly as one is.
|
|
134
|
+
|
|
135
|
+
```ruby
|
|
136
|
+
ROOM_HIRE = ReasonMeThis::Blueprint.define do
|
|
137
|
+
table :rates, [{period: "daytime", hourly: 60}, {period: "evening", hourly: 80}]
|
|
138
|
+
|
|
139
|
+
calculation :hire do
|
|
140
|
+
inputs do
|
|
141
|
+
number :hours
|
|
142
|
+
string :period, default: "daytime", one_of: {table: :rates, column: :period}
|
|
143
|
+
boolean :member, default: false
|
|
144
|
+
list :extras, default: [] do
|
|
145
|
+
string :item
|
|
146
|
+
number :price
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
lookup :hourly, table: :rates, where: {period: :period}, value: :hourly
|
|
151
|
+
formula :cost, "hours * hourly + SUM(PLUCK(extras, price))"
|
|
152
|
+
rules :discount, pick: :highest, otherwise: 0 do
|
|
153
|
+
rule :member, "member", value: 10
|
|
154
|
+
rule :long_hire, "hours >= 8", value: 15
|
|
155
|
+
end
|
|
156
|
+
formula :total, "ROUND(cost * (100 - discount) / 100, 2)"
|
|
157
|
+
formula(:deposit, "ROUND(total * 0.2, 2)").when("total > 200", else: 0)
|
|
158
|
+
|
|
159
|
+
outputs :total, :discount
|
|
160
|
+
output :deposit, type: :number
|
|
161
|
+
event :long_hire, "hours >= 8", data: [:total]
|
|
162
|
+
|
|
163
|
+
example "a member for two hours", facts: {hours: 2, member: true}, expect: {total: 108, discount: 10}
|
|
164
|
+
end
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
ReasonMeThis.prove(ROOM_HIRE) # raises Rejected while it has problems or an example fails
|
|
168
|
+
ReasonMeThis.push("room_hire", yaml: ROOM_HIRE.yaml, cases: ROOM_HIRE.cases_yaml) # to the service
|
|
169
|
+
File.write("config/blueprints/room_hire/blueprint.yml", ROOM_HIRE.yaml) # or for a local engine
|
|
170
|
+
ROOM_HIRE.to_h # the document, with text keys
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
- Names are symbols, and formulas and conditions are text, or a plain number or true or false.
|
|
174
|
+
- An input is written by its type: `number`, `string`, `date`, `time`, `boolean` or `list`, with `default:`,
|
|
175
|
+
`optional:` and, on a number or a string, `one_of:`. A block on a `list` gives the fields of each row. `input :name,
|
|
176
|
+
:type, key: value` writes an input of any other type or with any other key.
|
|
177
|
+
- A step is written by its type, name first: `formula`, `rules`, `lookup`, `decide`, `run`, `repeat`, `sum`,
|
|
178
|
+
`group`, `compare` and `slice`, each taking the keys the blueprint format gives it. `step :name, :type, spec`
|
|
179
|
+
writes a step of any other type.
|
|
180
|
+
- `.when(condition, else: formula)` on any step makes it conditional.
|
|
181
|
+
- `import "rates"` at the top imports a blueprint by name or path.
|
|
182
|
+
- `example "name", facts: {...}, expect: {...}` in a calculation is a worked example of it: the outputs those
|
|
183
|
+
facts should give, any of them, and with `events:` the events they should set off. `cases` is every example
|
|
184
|
+
as the list a cases file holds, and `cases_yaml` is that file. They are no part of `to_h` or `yaml`.
|
|
185
|
+
- `ReasonMeThis.prove(blueprint)` checks the blueprint and runs its examples without saving anything. It
|
|
186
|
+
answers the report, or raises `ReasonMeThis::Rejected` with it when the blueprint has problems or an
|
|
187
|
+
example fails, so a spec or a build step that calls it keeps an unproven blueprint out.
|
|
188
|
+
- The YAML is written with decimals exact (`BigDecimal("0.1")` stays `0.1`), dates as dates and no aliases.
|
|
189
|
+
The first calculation is the default.
|
|
190
|
+
- The service or the engine still does the checking: a formula that cannot be read or a name that does not
|
|
191
|
+
exist is a problem reported by `push`, or raised when a local engine runs it.
|
|
192
|
+
|
|
193
|
+
### From YAML, and with rmt
|
|
194
|
+
|
|
195
|
+
`rmt ruby bill.yml` writes `bill.rb` beside it, and `rmt pull bill --ruby` pulls a definition as
|
|
196
|
+
`bill/blueprint.rb`. The Ruby builds the same document the YAML holds, with a method for each input and
|
|
197
|
+
step; one that no method can say, such as a custom step, is written with `step` or `input`, so nothing is
|
|
198
|
+
lost. Comments in the YAML are not carried over. In Ruby it is
|
|
199
|
+
`ReasonMeThis::Blueprint::Ruby.write(ReasonMeThis::Blueprint::Yaml.read(yaml), "bill")`.
|
|
200
|
+
|
|
201
|
+
Wherever `rmt` takes a blueprint file it takes a `.rb` one: `check`, `test`, `run` and `push` run the file
|
|
202
|
+
and send the YAML of the `ReasonMeThis::Blueprint` it ends with. `rmt test bill.rb` and `rmt push bill bill.rb`
|
|
203
|
+
send the examples the file gives as its cases; a cases file named after it is sent in their place.
|
|
204
|
+
|
|
205
|
+
### With Sorbet
|
|
206
|
+
|
|
207
|
+
Every method carries an RBS comment signature and every block binds `self`, so a blueprint type checks in
|
|
208
|
+
a `# typed: strict` file with nothing added, once `tapioca gem reason_me_this` has written the gem's RBI
|
|
209
|
+
and Sorbet runs with `--parser=prism --enable-experimental-rbs-comments`. Annotate the constant:
|
|
210
|
+
|
|
211
|
+
```ruby
|
|
212
|
+
# typed: strict
|
|
213
|
+
|
|
214
|
+
ROOM_HIRE = ReasonMeThis::Blueprint.define do
|
|
215
|
+
calculation :hire do
|
|
216
|
+
inputs { nummber :hours } # Method `nummber` does not exist on `ReasonMeThis::Blueprint::Fields`
|
|
217
|
+
lookup :hourly, table: "rates" # Expected `Symbol` but found `String("rates")` for argument `table`
|
|
218
|
+
end
|
|
219
|
+
end #: ReasonMeThis::Blueprint
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Sorbet checks the shape: the methods, their keys and the kinds of value they take. It does not read a
|
|
223
|
+
formula or know which names exist; that stays with the service or the engine.
|
|
224
|
+
|
|
225
|
+
## Schema
|
|
226
|
+
|
|
227
|
+
```ruby
|
|
228
|
+
schema = ReasonMeThis.schema("bill", calculation: :invoice) # also version: 3, "bill@3" or on: Date
|
|
229
|
+
schema["inputs"] # a JSON Schema (draft 2020-12) of the facts: types, enum, default, required
|
|
230
|
+
schema["outputs"] # a JSON Schema of the outputs, with the types the blueprint declares
|
|
231
|
+
schema["version"] # the version it describes
|
|
101
232
|
```
|
|
102
233
|
|
|
234
|
+
The schemas come back as the service sent them, with string keys (`"$schema"`) and no values read as
|
|
235
|
+
numbers or dates, so they can go straight to a JSON Schema validator. They describe the JSON: a number fact
|
|
236
|
+
is a JSON number and a number output exact text, as the service sends it.
|
|
237
|
+
|
|
103
238
|
## Errors
|
|
104
239
|
|
|
105
240
|
Every error is a `ReasonMeThis::Error`, with a message in plain words.
|
|
@@ -108,11 +243,16 @@ Every error is a `ReasonMeThis::Error`, with a message in plain words.
|
|
|
108
243
|
| --- | --- |
|
|
109
244
|
| `Unauthorized` | the service refused the API key (401) |
|
|
110
245
|
| `NotFound` | no such definition or version (404) |
|
|
246
|
+
| `Gone` | the version asked for is retired (410) |
|
|
111
247
|
| `InvalidFacts` | the facts have problems (422); `#problems` lists them |
|
|
248
|
+
| `InvalidRequest` | the service refused what was asked rather than the facts (422): a day that is not a date, both `version:` and `on:`, or a schema of a calculation it cannot give (the service marks these `refused: "request"`; an older one is read by its wording); the message is the service's |
|
|
112
249
|
| `StepFailed` | a step failed while running (422); the message says which |
|
|
113
250
|
| `Timeout` | the run took too long on the service (503) |
|
|
114
251
|
| `Unreachable` | the service could not be reached: refused, DNS, or timed out |
|
|
115
|
-
| `
|
|
252
|
+
| `InvalidSignature` | `Webhook.verify` was given a delivery that is unsigned, signed with another secret, or too old |
|
|
253
|
+
| `Rejected` | `push`, `publish` or `prove` was refused: problems in the definition or failing cases; `#report` has them |
|
|
254
|
+
| `EngineMissing` | a client was given an `engine` whose gems are not installed |
|
|
255
|
+
| `Unsupported` | a client with an `engine` was asked for something only the service does, such as `push` |
|
|
116
256
|
|
|
117
257
|
```ruby
|
|
118
258
|
begin
|
|
@@ -124,23 +264,151 @@ end
|
|
|
124
264
|
|
|
125
265
|
## In a model
|
|
126
266
|
|
|
127
|
-
`ReasonMeThis::Model` works in any class, ActiveRecord or not.
|
|
267
|
+
`ReasonMeThis::Model` works in any class, ActiveRecord or not. Each `reasons` block is one recipe: how to
|
|
268
|
+
build the facts, and, for `!`, what to save and what to run after.
|
|
128
269
|
|
|
129
270
|
```ruby
|
|
130
|
-
class
|
|
271
|
+
class Round < ApplicationRecord
|
|
131
272
|
include ReasonMeThis::Model
|
|
132
273
|
|
|
133
|
-
|
|
134
|
-
|
|
274
|
+
belongs_to :golfer
|
|
275
|
+
has_many :hole_scores
|
|
276
|
+
|
|
277
|
+
reasons :result, with: "golf_whs_golfer" do
|
|
278
|
+
facts { {record: golfer.rounds.scored.last(20).map(&:to_fact), holes: holes.map(&:to_fact), played: played_on} }
|
|
279
|
+
|
|
280
|
+
saves differential: "gross_differential", daily_handicap: "card.daily_handicap"
|
|
281
|
+
saves into: :hole_scores, from: "card.scored", by: :hole
|
|
282
|
+
saves on: :golfer, handicap_index: "new_ga_handicap"
|
|
283
|
+
after { |explained| golfer.handicap_changes.create!(to: explained.at("new_ga_handicap")) }
|
|
284
|
+
on(:handicap_cut) { |event| HandicapMailer.cut(golfer, event.data).deliver_later }
|
|
285
|
+
keeps_receipts
|
|
286
|
+
end
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
round.result # run and read; saves nothing, remembered on this round
|
|
290
|
+
round.result_explained # the same, with every step
|
|
291
|
+
round.result! # run with every step, then save, in one transaction, then handle its events
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
`facts` runs on the record and takes the method's arguments: `facts { |year| ... }` makes `rep.statement(2026)`.
|
|
295
|
+
|
|
296
|
+
### What `!` saves
|
|
297
|
+
|
|
298
|
+
| Declaration | Writes |
|
|
299
|
+
| --- | --- |
|
|
300
|
+
| `saves column: "path"` | the value at `path` into a column of this record |
|
|
301
|
+
| `saves on: :golfer, column: "path"` | into a column of an associated record, and saves it |
|
|
302
|
+
| `saves into: :hole_scores, from: "path", by: :hole` | each row of the list at `path` into the association, matched on `hole`, so a second run updates rather than duplicates. Columns the child has are filled from the row's fields of the same name; give `column: :field` pairs to choose |
|
|
303
|
+
|
|
304
|
+
### Picking values
|
|
305
|
+
|
|
306
|
+
Each `saves column: source` takes its value from a path, or from a lambda for anything a path cannot say:
|
|
307
|
+
|
|
308
|
+
| Source | Gives |
|
|
309
|
+
| --- | --- |
|
|
310
|
+
| `"total_paid"` | an output |
|
|
311
|
+
| `"card.daily_handicap"` | a step inside a chained calculation |
|
|
312
|
+
| `"by_quarter"` | a whole list, for a JSON column |
|
|
313
|
+
| `"by_quarter.payout"` | one field from every row, as a list |
|
|
314
|
+
| `->(explained) { explained.at("by_quarter").last[:payout] }` | anything worked out from the explanation, such as one row |
|
|
315
|
+
|
|
316
|
+
```ruby
|
|
317
|
+
reasons :statement, with: "sales_commission@3", calculation: :year do
|
|
318
|
+
facts { |year| {...} }
|
|
319
|
+
saves total_paid: "total_paid", quarters: "by_quarter", payouts: "by_quarter.payout"
|
|
320
|
+
saves q4_payout: ->(explained) { explained.at("by_quarter").last[:payout] }
|
|
321
|
+
end
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
A decimal or integer column gets the exact number. A JSON column gets values written as the service
|
|
325
|
+
writes them (`"5000"`, `"0.8"`, `"2026-01-01"`), so nothing is lost to floats. `explained.at(path)` reads
|
|
326
|
+
the same paths, and an `after` hook can save anything else: `after { |explained| update!(...) }`.
|
|
327
|
+
|
|
328
|
+
Everything happens in one transaction with the record's own `save!`: a refusal from the service, an
|
|
329
|
+
invalid record or a hook that raises leaves nothing written.
|
|
330
|
+
|
|
331
|
+
### Hooks and events
|
|
332
|
+
|
|
333
|
+
A recipe has two kinds of hook, for two jobs:
|
|
334
|
+
|
|
335
|
+
| | `after { \|explained\| ... }` | `on(:name) { \|event, explained\| ... }` |
|
|
336
|
+
| --- | --- | --- |
|
|
337
|
+
| For | writing more data, all or nothing with the saves | acting on what the rules decided: mail, jobs, calls to other services |
|
|
338
|
+
| Runs | on every `!`, inside the transaction, after the saves | for each event the answer set off, once the transaction has committed |
|
|
339
|
+
| When it raises | nothing is written | the saves stand; the error reaches the caller |
|
|
340
|
+
|
|
341
|
+
`after` is where to save anything `saves` cannot say, such as a new row: `after { |explained| update!(...) }`.
|
|
342
|
+
Because it runs inside the transaction, a job enqueued or a mail sent there can go out for a run that then
|
|
343
|
+
rolls back. Put those in `on`, against an event the blueprint names, so the condition is tested by the
|
|
344
|
+
blueprint's cases and the action waits for the commit. When `!` runs inside a transaction of your own, `on`
|
|
345
|
+
waits for that one to commit too, and never runs if it rolls back (Rails 7.2 or later; before that it runs
|
|
346
|
+
as soon as `!` has saved).
|
|
347
|
+
|
|
348
|
+
To act for every reasoning, in tables or jobs of your own, add a hook to the configuration:
|
|
349
|
+
|
|
350
|
+
```ruby
|
|
351
|
+
ReasonMeThis.configure do |config|
|
|
352
|
+
config.after_reasoning do |record, name, explained| # inside the transaction
|
|
353
|
+
CalculationLog.create!(subject: record, reasoning: name, version: explained.version, stableford: explained.at("stableford"))
|
|
354
|
+
end
|
|
355
|
+
|
|
356
|
+
config.on_event do |record, name, event| # once it has committed
|
|
357
|
+
EventRelayJob.perform_later(record, name.to_s, event.name.to_s, event.data)
|
|
135
358
|
end
|
|
136
359
|
end
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
`on` acts on runs your app makes through a model. For events from any run of a published version, wherever
|
|
363
|
+
it came from, subscribe on the service instead (see [Webhooks](#webhooks)).
|
|
364
|
+
|
|
365
|
+
### Receipts
|
|
366
|
+
|
|
367
|
+
`keeps_receipts` writes a `ReasonMeThis::Receipt` for every `!`: the reasoning, the blueprint and the
|
|
368
|
+
version that ran, the calculation, and the facts, outputs, steps and events as the service showed them, so a
|
|
369
|
+
result can be explained long after the rules change. Add the table once:
|
|
137
370
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
371
|
+
```sh
|
|
372
|
+
bin/rails generate reason_me_this:receipts
|
|
373
|
+
bin/rails db:migrate
|
|
141
374
|
```
|
|
142
375
|
|
|
143
|
-
|
|
376
|
+
```ruby
|
|
377
|
+
round.reason_me_this_receipts.last.version # => "3"
|
|
378
|
+
round.reason_me_this_receipts.last.steps # the whole working, as it was
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
## Webhooks
|
|
382
|
+
|
|
383
|
+
The service can act on events itself. In the app's **Subscriptions** page, subscribe to a blueprint's
|
|
384
|
+
events, then either post them to a webhook or run another blueprint on their data. Every run of a published
|
|
385
|
+
version through the API delivers, whoever made it. **Deliveries** lists each one and sends a failed one again.
|
|
386
|
+
|
|
387
|
+
A webhook gets a JSON POST, signed with a secret shown once when the subscription is made:
|
|
388
|
+
|
|
389
|
+
```json
|
|
390
|
+
{"id": "evt_6f1c...", "event": "quota_hit", "definition": "commission", "version": 3, "calculation": "year",
|
|
391
|
+
"data": {"rep": "42", "over_by": "1200"}, "ran_at": "2026-11-06T10:30:00Z", "chain": ["commission@3"]}
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
`Webhook.verify` checks the `RMT-Signature` header and reads the body as an event, with exact values:
|
|
395
|
+
|
|
396
|
+
```ruby
|
|
397
|
+
class RmtWebhooksController < ActionController::API
|
|
398
|
+
def create
|
|
399
|
+
event = ReasonMeThis::Webhook.verify(request.raw_post, request.headers["RMT-Signature"], ENV["RMT_WEBHOOK_SECRET"])
|
|
400
|
+
QuotaHitJob.perform_later(event.data) if event.name == :quota_hit
|
|
401
|
+
head :no_content
|
|
402
|
+
rescue ReasonMeThis::InvalidSignature
|
|
403
|
+
head :unauthorized
|
|
404
|
+
end
|
|
405
|
+
end
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
`Webhook.payload` gives the whole body (`id`, `definition`, `version`, `chain` and the rest) instead. A
|
|
409
|
+
delivery signed more than five minutes from now is refused, so a captured one cannot be replayed. Use `id` to
|
|
410
|
+
ignore a delivery you have already handled: one that got no 2xx is sent again, up to nine times over about a
|
|
411
|
+
day.
|
|
144
412
|
|
|
145
413
|
## More than one service
|
|
146
414
|
|
|
@@ -161,6 +429,40 @@ class Rep < ApplicationRecord
|
|
|
161
429
|
end
|
|
162
430
|
```
|
|
163
431
|
|
|
432
|
+
## Without the service
|
|
433
|
+
|
|
434
|
+
The engine that runs blueprints on the service is licensed separately. With it installed, a client runs
|
|
435
|
+
blueprint files in your own process: no URL, no key, and nothing sent anywhere.
|
|
436
|
+
|
|
437
|
+
```ruby
|
|
438
|
+
ReasonMeThis.configure do |config|
|
|
439
|
+
config.engine = :rust # the engine on its native calculator
|
|
440
|
+
config.blueprints = "config/blueprints" # config/blueprints/hall_hire/blueprint.yml, as rmt pull writes it
|
|
441
|
+
end
|
|
442
|
+
|
|
443
|
+
ReasonMeThis.run("hall_hire", {sessions: [{from: Time.iso8601("2026-11-02T16:00:00+11:00"), to: Time.iso8601("2026-11-02T22:00:00+11:00")}]})
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
`run`, `explain`, `schema`, `definitions` and `definition` answer as they do from the service, with the
|
|
447
|
+
same values and the same errors, so models, receipts and hooks work unchanged. A client of its own takes
|
|
448
|
+
the same options: `ReasonMeThis::Client.new(engine: :rust, blueprints: "config/blueprints")`.
|
|
449
|
+
|
|
450
|
+
- This gem does not depend on the engine. Add the engine gems you were given to your
|
|
451
|
+
Gemfile. Without them, a client given an engine raises `ReasonMeThis::EngineMissing` when it is
|
|
452
|
+
built, saying what could not be loaded. The configured client is built on its first use, so call
|
|
453
|
+
`ReasonMeThis.default` in the initializer to find out at boot.
|
|
454
|
+
- A name is a folder in `blueprints` holding `blueprint.yml`, with `cases.yml` beside it if you keep one.
|
|
455
|
+
A name the folder does not have is looked for among the blueprints the engine ships, and an `imports:`
|
|
456
|
+
by name is found the same way. Without `blueprints`, only the shipped ones run.
|
|
457
|
+
- A blueprint file has no versions. `version:`, `on:` and a pinned name such as `"bill@3"` are refused with
|
|
458
|
+
`InvalidRequest` rather than ignored, and an explanation's `version` is `"local"`. An import pinned to a
|
|
459
|
+
version, `rates@3`, is not found.
|
|
460
|
+
- `push` and `publish` raise `ReasonMeThis::Unsupported`: edit the files, and use the service to publish.
|
|
461
|
+
- A blueprint is read and checked on its first run and kept until a file in the folder is added, removed
|
|
462
|
+
or changed.
|
|
463
|
+
- The engine is chosen for the whole process, not for each client, and a run has no time limit.
|
|
464
|
+
- A client takes a `url` or an `engine`, not both. The `rmt` CLI always uses the service.
|
|
465
|
+
|
|
164
466
|
## In tests
|
|
165
467
|
|
|
166
468
|
A client talks through a connection: anything with `request(method, path, body)` that answers
|
|
@@ -196,4 +498,9 @@ out by the service from the rep's deals. See its README.
|
|
|
196
498
|
bundle install
|
|
197
499
|
bundle exec rspec
|
|
198
500
|
bundle exec rubocop
|
|
501
|
+
SRB_SKIP_GEM_RBIS=1 bundle exec srb tc
|
|
199
502
|
```
|
|
503
|
+
|
|
504
|
+
The specs of a local engine are skipped unless the engine is in the bundle. To run them, write a
|
|
505
|
+
gemfile of your own that evaluates this one and adds the engine gems, such as `gemfiles/engine.gemfile`
|
|
506
|
+
(`gemfiles/` is ignored by git), and run `BUNDLE_GEMFILE=gemfiles/engine.gemfile bundle exec rspec`.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
require 'rails/generators'
|
|
2
|
+
require 'rails/generators/active_record'
|
|
3
|
+
|
|
4
|
+
module ReasonMeThis
|
|
5
|
+
module Generators
|
|
6
|
+
class ReceiptsGenerator < Rails::Generators::Base
|
|
7
|
+
include ActiveRecord::Generators::Migration
|
|
8
|
+
|
|
9
|
+
source_root File.expand_path('templates', __dir__)
|
|
10
|
+
desc 'Adds the reason_me_this_receipts table, where reasonings that keep receipts record what ran and how.'
|
|
11
|
+
|
|
12
|
+
def create_migration_file
|
|
13
|
+
migration_template 'create_reason_me_this_receipts.rb.tt', File.join(db_migrate_path, 'create_reason_me_this_receipts.rb')
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
class CreateReasonMeThisReceipts < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
|
|
2
|
+
def change
|
|
3
|
+
create_table :reason_me_this_receipts do |t|
|
|
4
|
+
t.references :record, polymorphic: true, null: false
|
|
5
|
+
t.string :reasoning, null: false
|
|
6
|
+
t.string :blueprint, null: false
|
|
7
|
+
t.string :version
|
|
8
|
+
t.string :calculation
|
|
9
|
+
t.json :facts, null: false
|
|
10
|
+
t.json :outputs, null: false
|
|
11
|
+
t.json :steps, null: false
|
|
12
|
+
t.json :events, null: false
|
|
13
|
+
t.datetime :created_at, null: false
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# typed: strict
|
|
2
|
+
|
|
3
|
+
module ReasonMeThis
|
|
4
|
+
class Blueprint
|
|
5
|
+
# A calculation: its inputs, its steps in the order they run, and what it hands back.
|
|
6
|
+
class Calculation
|
|
7
|
+
#: -> void
|
|
8
|
+
def initialize
|
|
9
|
+
@inputs = Fields.new #: Fields
|
|
10
|
+
@steps = [] #: Array[Step]
|
|
11
|
+
@outputs = [] #: Array[Symbol | Hash[Symbol, untyped]]
|
|
12
|
+
@events = [] #: Array[Hash[Symbol, untyped]]
|
|
13
|
+
@examples = [] #: Array[Hash[Symbol, untyped]]
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
#: Array[Hash[Symbol, untyped]]
|
|
17
|
+
attr_reader :examples
|
|
18
|
+
|
|
19
|
+
#: { () [self: Fields] -> void } -> void
|
|
20
|
+
def inputs(&block)
|
|
21
|
+
@inputs.instance_eval(&block)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
#: (Symbol, String | Numeric | bool) -> Step
|
|
25
|
+
def formula(name, expression) = step(name, :formula, expression)
|
|
26
|
+
|
|
27
|
+
#: (Symbol, ?pick: Symbol, ?otherwise: (String | Numeric | bool)?) { () [self: Rules] -> void } -> Step
|
|
28
|
+
def rules(name, pick: :first, otherwise: nil, &block)
|
|
29
|
+
rules = Rules.new
|
|
30
|
+
rules.instance_eval(&block)
|
|
31
|
+
step(name, :rules, {pick:, otherwise:, rules: rules.to_a}.compact)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
#: (Symbol, table: Symbol, ?where: Hash[Symbol, Symbol], ?value: Symbol?, ?on: Symbol?, ?band: Hash[Symbol, Symbol]?,
|
|
35
|
+
#| ?default: (String | Numeric | bool)?) -> Step
|
|
36
|
+
def lookup(name, table:, where: {}, value: nil, on: nil, band: nil, default: nil)
|
|
37
|
+
step(name, :lookup, {table:, where:, value:, on:, band:, default:}.compact)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
#: (Symbol, table: Symbol, given: Hash[Symbol, Symbol], hit: Symbol, ?value: Symbol?, ?default: (String | Numeric | bool)?) -> Step
|
|
41
|
+
def decide(name, table:, given:, hit:, value: nil, default: nil)
|
|
42
|
+
step(name, :decide, {table:, given:, hit:, value:, default:}.compact)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
#: (Symbol, Symbol, ?over: Symbol?, ?with: Hash[Symbol, String | Numeric | bool]?, ?position: Symbol?, ?carry: Hash[Symbol, Symbol]?,
|
|
46
|
+
#| ?start: Hash[Symbol, String | Numeric | bool]?, ?earlier: Symbol?, ?update: bool) -> Step
|
|
47
|
+
def run(name, calculation, over: nil, with: nil, position: nil, carry: nil, start: nil, earlier: nil, update: false)
|
|
48
|
+
step(name, :run, {calculation:, over:, with:, position:, carry:, start:, earlier:, update: update || nil}.compact)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
#: (Symbol, Symbol, ?times: (String | Integer)?, ?until: Symbol?, ?limit: Integer?, ?with: Hash[Symbol, String | Numeric | bool]?,
|
|
52
|
+
#| ?position: Symbol?, ?carry: Hash[Symbol, Symbol]?, ?start: Hash[Symbol, String | Numeric | bool]?, ?earlier: Symbol?) -> Step
|
|
53
|
+
def repeat(name, calculation, times: nil, until: nil, limit: nil, with: nil, position: nil, carry: nil, start: nil, earlier: nil)
|
|
54
|
+
spec = {calculation:, times:, until: binding.local_variable_get(:until), limit:, with:, position:, carry:, start:, earlier:}
|
|
55
|
+
step(name, :repeat, spec.compact)
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
#: (Symbol, Symbol, of: Symbol) -> Step
|
|
59
|
+
def sum(name, output, of:) = step(name, :sum, {output:, of:})
|
|
60
|
+
|
|
61
|
+
#: (Symbol, of: Symbol, by: Array[Symbol], ?sum: Array[Symbol]?) -> Step
|
|
62
|
+
def group(name, of:, by:, sum: nil) = step(name, :group, {of:, by:, sum:}.compact)
|
|
63
|
+
|
|
64
|
+
#: (Symbol, Array[Symbol], ?pick: Symbol) -> Step
|
|
65
|
+
def compare(name, steps, pick: :highest) = step(name, :compare, {steps:, pick:})
|
|
66
|
+
|
|
67
|
+
#: (Symbol, ?from: String?, ?to: String?, ?over: Symbol?, ?without: untyped, ?at_hours: (Array[Integer] | String)?, ?at_times: String?,
|
|
68
|
+
#| ?within: untyped, ?after: untyped) -> Step
|
|
69
|
+
def slice(name, from: nil, to: nil, over: nil, without: nil, at_hours: nil, at_times: nil, within: nil, after: nil)
|
|
70
|
+
step(name, :slice, {from:, to:, over:, without:, at_hours:, at_times:, within:, after:}.compact)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# A step of a type this gem has no method for, such as one a licensed engine adds.
|
|
74
|
+
#: (Symbol, Symbol, untyped) -> Step
|
|
75
|
+
def step(name, type, spec)
|
|
76
|
+
step = Step.new(name, type, spec)
|
|
77
|
+
@steps << step
|
|
78
|
+
step
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
#: (*Symbol) -> void
|
|
82
|
+
def outputs(*names)
|
|
83
|
+
@outputs.concat(names)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# An output held to a type: a run fails when the value is of another, or blank without optional.
|
|
87
|
+
#: (Symbol, ?type: Symbol?, ?optional: bool) -> void
|
|
88
|
+
def output(name, type: nil, optional: false)
|
|
89
|
+
@outputs << {name:, type:, optional: optional || nil}.compact
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# An event set off when the condition is true, carrying the outputs unless data names what it carries.
|
|
93
|
+
#: (Symbol, String, ?data: Array[Symbol]?) -> void
|
|
94
|
+
def event(name, condition, data: nil)
|
|
95
|
+
@events << {name:, when: condition, data:}.compact
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# A worked example: facts with the outputs they should give, any of them, and the events they should set off.
|
|
99
|
+
#: (String, expect: Hash[Symbol, untyped], ?facts: Hash[Symbol, untyped], ?events: Array[Symbol]?) -> void
|
|
100
|
+
def example(name, expect:, facts: {}, events: nil)
|
|
101
|
+
@examples << {name:, facts:, expect:, events:}.compact
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
#: -> Hash[Symbol, untyped]
|
|
105
|
+
def to_h
|
|
106
|
+
{inputs: @inputs.to_h, steps: @steps.map(&:to_h), outputs: @outputs, events: @events}.reject { |key, held| key != :steps && held.empty? }
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# typed: strict
|
|
2
|
+
|
|
3
|
+
module ReasonMeThis
|
|
4
|
+
class Blueprint
|
|
5
|
+
# The inputs of a calculation, or the fields of each row of a list. A field of a row takes no default.
|
|
6
|
+
class Fields
|
|
7
|
+
#: -> void
|
|
8
|
+
def initialize
|
|
9
|
+
@fields = {} #: Hash[Symbol, Hash[Symbol, untyped]]
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
#: (Symbol, ?default: untyped, ?optional: bool, ?one_of: (Array[String] | Hash[Symbol, Symbol])?) -> void
|
|
13
|
+
def number(name, default: nil, optional: false, one_of: nil) = field(name, :number, default:, optional:, one_of:)
|
|
14
|
+
|
|
15
|
+
#: (Symbol, ?default: untyped, ?optional: bool, ?one_of: (Array[String] | Hash[Symbol, Symbol])?) -> void
|
|
16
|
+
def string(name, default: nil, optional: false, one_of: nil) = field(name, :string, default:, optional:, one_of:)
|
|
17
|
+
|
|
18
|
+
#: (Symbol, ?default: untyped, ?optional: bool) -> void
|
|
19
|
+
def date(name, default: nil, optional: false) = field(name, :date, default:, optional:)
|
|
20
|
+
|
|
21
|
+
#: (Symbol, ?default: untyped, ?optional: bool) -> void
|
|
22
|
+
def time(name, default: nil, optional: false) = field(name, :time, default:, optional:)
|
|
23
|
+
|
|
24
|
+
#: (Symbol, ?default: bool?, ?optional: bool) -> void
|
|
25
|
+
def boolean(name, default: nil, optional: false) = field(name, :boolean, default:, optional:)
|
|
26
|
+
|
|
27
|
+
# With a block, the fields each row must have. Without one, the list takes anything.
|
|
28
|
+
#: (Symbol, ?default: Array[untyped]?, ?optional: bool) ?{ () [self: Fields] -> void } -> void
|
|
29
|
+
def list(name, default: nil, optional: false, &block)
|
|
30
|
+
row = Fields.new
|
|
31
|
+
row.instance_eval(&block) if block
|
|
32
|
+
field(name, :list, default:, optional:, of: (row.to_h if block))
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# An input of a type, or with a key, this gem has no method for.
|
|
36
|
+
#: (Symbol, Symbol, **untyped) -> void
|
|
37
|
+
def input(name, type, **keys)
|
|
38
|
+
@fields[name] = {type:, **keys}
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
#: -> Hash[Symbol, Hash[Symbol, untyped]]
|
|
42
|
+
def to_h = @fields
|
|
43
|
+
|
|
44
|
+
private
|
|
45
|
+
|
|
46
|
+
#: (Symbol, Symbol, **untyped) -> void
|
|
47
|
+
def field(name, type, **keys) = input(name, type, **keys.compact.reject { |key, held| key == :optional && !held })
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|