price_waterfall 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.
Files changed (58) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +186 -0
  3. data/LICENSE.txt +21 -0
  4. data/README.md +582 -0
  5. data/lib/price_waterfall/builder/arguments.rb +86 -0
  6. data/lib/price_waterfall/builder.rb +192 -0
  7. data/lib/price_waterfall/conditions/all.rb +18 -0
  8. data/lib/price_waterfall/conditions/any.rb +18 -0
  9. data/lib/price_waterfall/conditions/comparison.rb +142 -0
  10. data/lib/price_waterfall/conditions/compiled.rb +32 -0
  11. data/lib/price_waterfall/conditions/compiler.rb +182 -0
  12. data/lib/price_waterfall/conditions/custom.rb +59 -0
  13. data/lib/price_waterfall/conditions/group.rb +45 -0
  14. data/lib/price_waterfall/conditions/negation.rb +36 -0
  15. data/lib/price_waterfall/conditions/reason.rb +227 -0
  16. data/lib/price_waterfall/configuration_error.rb +8 -0
  17. data/lib/price_waterfall/entry.rb +111 -0
  18. data/lib/price_waterfall/error.rb +24 -0
  19. data/lib/price_waterfall/invalid_amount.rb +7 -0
  20. data/lib/price_waterfall/keys.rb +38 -0
  21. data/lib/price_waterfall/loader/order.rb +51 -0
  22. data/lib/price_waterfall/loader/problems.rb +72 -0
  23. data/lib/price_waterfall/loader/step_entry.rb +114 -0
  24. data/lib/price_waterfall/loader.rb +79 -0
  25. data/lib/price_waterfall/number.rb +149 -0
  26. data/lib/price_waterfall/percentage.rb +77 -0
  27. data/lib/price_waterfall/pipeline.rb +111 -0
  28. data/lib/price_waterfall/registered.rb +87 -0
  29. data/lib/price_waterfall/registry.rb +127 -0
  30. data/lib/price_waterfall/resolver.rb +148 -0
  31. data/lib/price_waterfall/result.rb +200 -0
  32. data/lib/price_waterfall/rounding.rb +119 -0
  33. data/lib/price_waterfall/run.rb +113 -0
  34. data/lib/price_waterfall/step_error.rb +9 -0
  35. data/lib/price_waterfall/step_name.rb +56 -0
  36. data/lib/price_waterfall/steps/amount.rb +50 -0
  37. data/lib/price_waterfall/steps/base.rb +40 -0
  38. data/lib/price_waterfall/steps/callable.rb +48 -0
  39. data/lib/price_waterfall/steps/cents.rb +35 -0
  40. data/lib/price_waterfall/steps/custom.rb +50 -0
  41. data/lib/price_waterfall/steps/override.rb +23 -0
  42. data/lib/price_waterfall/steps/percent.rb +17 -0
  43. data/lib/price_waterfall/steps/percentage_change.rb +26 -0
  44. data/lib/price_waterfall/steps/round.rb +46 -0
  45. data/lib/price_waterfall/steps/skipping.rb +43 -0
  46. data/lib/price_waterfall/steps/step.rb +200 -0
  47. data/lib/price_waterfall/steps/surcharge.rb +17 -0
  48. data/lib/price_waterfall/steps/tiered.rb +95 -0
  49. data/lib/price_waterfall/time_window.rb +93 -0
  50. data/lib/price_waterfall/timestamp.rb +58 -0
  51. data/lib/price_waterfall/user_code.rb +72 -0
  52. data/lib/price_waterfall/values/list.rb +28 -0
  53. data/lib/price_waterfall/values/literal.rb +28 -0
  54. data/lib/price_waterfall/values/path.rb +106 -0
  55. data/lib/price_waterfall/values/source.rb +44 -0
  56. data/lib/price_waterfall/version.rb +6 -0
  57. data/lib/price_waterfall.rb +126 -0
  58. metadata +103 -0
@@ -0,0 +1,200 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Step classes. Each takes the running price in cents and returns the new price and a trace note.
5
+ module Steps
6
+ # Abstract base for all steps: holds the name, the +condition:+ / +skip_if:+ conditions (what
7
+ # the DSL calls +if:+ / +unless:+) and the optional time window, skips the step when they say
8
+ # so, checks the price going in and coming out, and names the step in every error.
9
+ #
10
+ # Errors are handled at two boundaries, building and running. Whatever goes wrong there comes
11
+ # out as a {PriceWaterfall::Error} carrying the step's name: {ConfigurationError} while
12
+ # building, {InvalidAmount} while running, {StepError} when user code raised.
13
+ #
14
+ # Steps are frozen on creation and keep no state between calls, so they are thread-safe.
15
+ class Step
16
+ # Note recorded when a callable +condition:+ skips the step; a data condition
17
+ # says why instead (+skipped (condition: item.qty 4 < 10)+).
18
+ SKIPPED = "skipped (condition)"
19
+ # Note recorded when a callable +skip_if:+ skips the step.
20
+ SKIPPED_IF = "skipped (skip_if)"
21
+
22
+ # @return [Symbol]
23
+ attr_reader :name
24
+ # @return [#call, nil] the step runs only when this returns a truthy value
25
+ attr_reader :condition
26
+ # @return [#call, nil] the step is skipped when this returns a truthy value
27
+ attr_reader :skip_if
28
+ # @return [TimeWindow, nil] when the step is active; +nil+ when it always is
29
+ attr_reader :window
30
+
31
+ class << self
32
+ # Builds the step and freezes it.
33
+ # @return [Step]
34
+ # @raise [ConfigurationError] if the class is abstract, or the arguments don't fit it (an
35
+ # unknown or missing keyword, too many arguments)
36
+ def new(*args, **options, &)
37
+ raise ConfigurationError, "#{self} is abstract; build one of its subclasses" if abstract?
38
+
39
+ begin
40
+ super.freeze
41
+ rescue ArgumentError => e
42
+ raise signature_error(e, args.first)
43
+ end
44
+ end
45
+
46
+ # @return [Boolean] whether this class only exists to be subclassed
47
+ def abstract? = @abstract == true
48
+
49
+ private
50
+
51
+ # Anything raised inside +initialize+ is already a ConfigurationError, so an ArgumentError
52
+ # here means the arguments didn't fit the signature. The step is named as it would have
53
+ # been built ({StepName.utf8}), so +error.step+ matches; a name that isn't text names the class.
54
+ def signature_error(error, name)
55
+ text = StepName.utf8(name)
56
+ return ConfigurationError.new("#{self}: #{error.message}") if text.nil?
57
+
58
+ ConfigurationError.new("step #{text.to_sym.inspect}: #{error.message}", step: text.to_sym)
59
+ end
60
+
61
+ # Marks the class as abstract. Not inherited, so subclasses can be built.
62
+ def abstract! = (@abstract = true)
63
+ end
64
+
65
+ abstract!
66
+
67
+ include Skipping
68
+
69
+ # @param name [Symbol, String]
70
+ # @param condition [#call, Hash, Boolean, nil] callable +(item, ctx)+, a condition described
71
+ # in data (see {Conditions::Compiler}), +true+ or +false+; the DSL's +if:+
72
+ # @param skip_if [#call, Hash, Boolean, nil] the same forms as +condition:+; the DSL's +unless:+
73
+ # @param starts_at [Time, String, nil] the step is skipped before this; see {TimeWindow}
74
+ # @param ends_at [Time, String, nil] the step is skipped from this on; see {TimeWindow}
75
+ # @param clock [#call, nil] callable with no arguments returning the current Time, used when
76
+ # the call is given no +now:+; defaults to +Time.now+
77
+ # @param sources [Hash{Symbol, String => #call}] value sources that data may name with
78
+ # +{ source: "name" }+, each a callable +(item, ctx)+
79
+ # @param operators [Hash{Symbol, String => #call}] operators that data conditions may name
80
+ # with +op: "name"+, each a callable +(value, arg)+
81
+ # @raise [ConfigurationError] if +name+ is blank, a condition or time is invalid, or
82
+ # +sources:+ / +operators:+ is not a Hash or registers a name twice
83
+ def initialize(name, condition: nil, skip_if: nil, starts_at: nil, ends_at: nil, clock: nil,
84
+ sources: {}, operators: {})
85
+ @name = build_name(name)
86
+ configure do
87
+ @sources = Registered.table(sources, "sources")
88
+ operators = Registered.table(operators, "operators")
89
+ @condition = build_condition(condition, "condition", operators)
90
+ @skip_if = build_condition(skip_if, "skip_if", operators)
91
+ @window = TimeWindow.build(starts_at:, ends_at:, clock:)
92
+ end
93
+ end
94
+
95
+ # Runs the step.
96
+ #
97
+ # @param cents [Integer] price before this step
98
+ # @param item [Object] the item being priced, passed to callables
99
+ # @param ctx [Object] the pricing context, passed to callables
100
+ # @param now [Time, nil] the moment to price at, for a time window; +nil+ asks the clock.
101
+ # Inside a {Pipeline} (or another step's call) the run's moment is used unless one is given;
102
+ # a step given its own moment still writes reasons as the pipeline does (+hide_values+).
103
+ # @return [Array(Integer, String)] price after this step and the frozen trace note
104
+ # @raise [InvalidAmount] if the price going in or out, a value from user code, or +now+ is
105
+ # not allowed, or the step's own checks fail unexpectedly; the message names the step
106
+ # @raise [StepError] if user code raises anything, even one of the gem's own errors; the
107
+ # original exception is the +cause+
108
+ def call(cents, item, ctx, now: nil)
109
+ return evaluate(cents, item, ctx).first(2) if nil.equal?(now) && Run.current
110
+
111
+ Run.start(now:, hide_values: Run.hiding_values?) { evaluate(cents, item, ctx).first(2) }
112
+ rescue InvalidAmount => e
113
+ raise if e.step
114
+
115
+ raise InvalidAmount.new("step #{name.inspect}: #{e.message}", step: name)
116
+ end
117
+
118
+ # @api private
119
+ # Runs the step inside the current {Run}, which {Pipeline#call} or {#call} has started.
120
+ # @return [Array(Integer, String, Boolean)] as {#call}, and whether the step was skipped (see
121
+ # {Entry#skipped?})
122
+ # @raise (see #call)
123
+ def evaluate(cents, item, ctx)
124
+ Run.current.next_step
125
+ input!(cents)
126
+ note = skip_note(item, ctx)
127
+ return [cents, note, true] if note
128
+
129
+ applied(apply(cents, item, ctx))
130
+ rescue StepError
131
+ raise
132
+ rescue StandardError => e
133
+ raise InvalidAmount.new("step #{name.inspect}: #{describe_error(e)}", step: name)
134
+ end
135
+
136
+ private
137
+
138
+ def build_name(name) = StepName.check!(name, ConfigurationError, "step name")
139
+
140
+ # @return [Hash] the registered sources, used while subclasses build their inputs
141
+ attr_reader :sources
142
+
143
+ # Only callables, data conditions and booleans are accepted, so a typo such as
144
+ # +condition: :premium?+ or +condition: "false"+ fails at build time instead of being truthy
145
+ # for everyone. The gem's value resolvers are callables but not conditions, so they are
146
+ # rejected too; compiled conditions are accepted.
147
+ def build_condition(value, label, operators)
148
+ return nil if value.nil?
149
+ return Values::Literal.new(value) if [true, false].include?(value)
150
+ return Conditions::Compiler.compile(value, at: label, sources:, operators:) if value.is_a?(Hash)
151
+ return callable_condition(value, label) if value.respond_to?(:call) && condition?(value)
152
+
153
+ raise ConfigurationError, "#{label}: must be a callable (item, ctx), a condition Hash, true or false, " \
154
+ "got #{Conditions::Reason.show(value)}"
155
+ end
156
+
157
+ def condition?(value) = !value.is_a?(Builtin) || value.is_a?(Conditions::Compiled)
158
+
159
+ def callable_condition(value, label)
160
+ Resolver.build(value)
161
+ rescue ConfigurationError => e
162
+ raise ConfigurationError, "#{label}: #{e.message}"
163
+ end
164
+
165
+ # @return [Array(Integer, String), Array(Integer, String, Boolean)] the new price and note, and
166
+ # +true+ when the step had nothing to apply (see {#skip})
167
+ def apply(_cents, _item, _ctx)
168
+ raise NotImplementedError, "#{self.class} must implement #apply"
169
+ end
170
+
171
+ # @return [Array(Integer, String, Boolean)] what {#apply} gave, checked, with a frozen note
172
+ def applied((after, note, skipped))
173
+ [cents!(after, "result"), note.frozen? ? note : note.dup.freeze, skipped == true]
174
+ end
175
+
176
+ # @return [Array(Integer, String, true)] the price unchanged, recorded as skipped:
177
+ # +skipped (reason)+
178
+ def skip(cents, reason) = [cents, "skipped (#{reason})", true]
179
+
180
+ # Calls a resolver, condition or clock; see {UserCode.invoke}. An error from the gem's own code
181
+ # is left for {#call} to report as InvalidAmount.
182
+ def invoke(callable, *) = UserCode.invoke(callable, name, *)
183
+
184
+ # Runs build-time checks, reporting any problem as a ConfigurationError naming the step.
185
+ def configure
186
+ yield
187
+ rescue StandardError => e
188
+ raise ConfigurationError.new("step #{name.inspect}: #{describe_error(e)}", step: name)
189
+ end
190
+
191
+ # The gem's own errors already read well; anything else gets its class name.
192
+ def describe_error(error) = error.is_a?(Error) ? error.message : "#{error.class}: #{error.message}"
193
+
194
+ # Checks the price going in; {Base} ignores it and overrides this.
195
+ def input!(cents) = cents!(cents, "input price")
196
+
197
+ def cents!(value, label) = Cents.check!(value, label)
198
+ end
199
+ end
200
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ module Steps
5
+ # Percentage increase. The surcharge is rounded half up to whole cents before it is added.
6
+ # A +nil+ or zero percentage skips the step. Unlike discounts, it may be above 100%.
7
+ #
8
+ # @example
9
+ # Surcharge.new(:small_order, ->(item, _ctx) { 5 if item[:qty] < 2 })
10
+ # # 4599 at 5% -> 4829, trace note "+230 (5%)"
11
+ class Surcharge < PercentageChange
12
+ private
13
+
14
+ def increase? = true
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ module Steps
5
+ # Percentage discount picked by quantity: the highest tier whose minimum the quantity reaches wins.
6
+ # The step's value is the quantity, a callable +(item, ctx)+ or a literal; +nil+ skips the step.
7
+ # The quantity may be any finite, non-negative number or a numeric String such as "12" (from
8
+ # JSON or params).
9
+ #
10
+ # @example
11
+ # Tiered.new(:volume, { 10 => 5, 50 => 10 }, quantity: ->(item, _ctx) { item[:qty] })
12
+ # # qty 60 on 3500 -> 3150, trace note "-350 (10% at qty >= 50)"
13
+ # # qty 4 -> unchanged, trace note "skipped (qty 4 below 10)"
14
+ class Tiered < Callable
15
+ # @return [Array<Array(Integer, Rational)>] +[min_qty, pct]+ pairs, highest minimum first
16
+ attr_reader :tiers
17
+
18
+ # Also takes +condition:+ / +skip_if:+, see {Step#initialize}.
19
+ #
20
+ # @param name [Symbol, String]
21
+ # @param tiers [Hash{Integer, String, Symbol, Numeric => Integer, Rational, Float, BigDecimal, String}]
22
+ # minimum quantity => percentage; a minimum is any positive whole number, written as
23
+ # +10+, +10.0+, +"10"+, +"+10"+ or +:"10"+
24
+ # @param quantity [#call, Hash, Object] callable +(item, ctx)+, a value description such as
25
+ # +{ item: "qty" }+, or a literal number or numeric String
26
+ # @raise [ConfigurationError] if +tiers+ is empty, a minimum is not a positive integer or is
27
+ # repeated, a percentage is invalid, or +quantity+ is invalid
28
+ def initialize(name, tiers, quantity:, **)
29
+ super(name, quantity, **)
30
+ configure { @tiers = build_tiers(tiers) }
31
+ end
32
+
33
+ private
34
+
35
+ def input_label = "quantity"
36
+
37
+ def apply(cents, item, ctx)
38
+ qty = value(item, ctx)
39
+ return skip(cents, "no quantity") if qty.nil?
40
+
41
+ min, pct = tiers.find { |tier_min, _| qty >= tier_min }
42
+ return skip(cents, "qty #{Number.format(qty)} below #{tiers.last.first}") if min.nil?
43
+ return skip(cents, "0% at qty >= #{min}") if pct.zero?
44
+
45
+ adjusted(cents, Percentage.adjust(cents, pct, suffix: " at qty >= #{min}"))
46
+ end
47
+
48
+ def check_value(qty)
49
+ return nil if qty.nil?
50
+
51
+ number = Number.parse(qty, "quantity")
52
+ return number unless number.negative?
53
+
54
+ raise InvalidAmount, "quantity must be 0 or more, got #{Conditions::Reason.show(qty)}"
55
+ end
56
+
57
+ def build_tiers(tiers)
58
+ unless tiers.is_a?(Hash) && !tiers.empty?
59
+ raise ConfigurationError, "tiers must be a non-empty Hash, got #{Conditions::Reason.show(tiers)}"
60
+ end
61
+
62
+ built = tiers.map { |min, pct| [tier_min(min), tier_pct(min, pct)].freeze }
63
+ check_repeats(built.map(&:first))
64
+ built.sort_by { |min, _| -min }.freeze
65
+ end
66
+
67
+ def check_repeats(minimums)
68
+ repeated, = minimums.tally.find { |_, count| count > 1 }
69
+ raise ConfigurationError, "tier #{repeated} is given more than once" if repeated
70
+ end
71
+
72
+ # Parsed like quantities (Symbols as their String form, as parsed JSON gives them), then
73
+ # required to be a positive whole number.
74
+ def tier_min(min)
75
+ number = parse_tier_min(min)
76
+ return number.to_i if number&.positive? && number == number.to_i
77
+
78
+ raise ConfigurationError, "tier minimum must be a positive Integer, got #{Conditions::Reason.show(min)}"
79
+ end
80
+
81
+ # @return [Integer, Rational, nil] +nil+ when +min+ is not a number at all
82
+ def parse_tier_min(min)
83
+ Number.parse(min.is_a?(Symbol) ? min.to_s : min, "tier minimum")
84
+ rescue InvalidAmount
85
+ nil
86
+ end
87
+
88
+ def tier_pct(min, pct)
89
+ Percentage.parse(pct) || raise(ConfigurationError, "tier #{min}: percentage is missing")
90
+ rescue InvalidAmount => e
91
+ raise ConfigurationError, "tier #{min}: #{e.message}"
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # When a step is active: from +starts_at+ (inclusive) until +ends_at+ (exclusive). Either end may
5
+ # be left open.
6
+ #
7
+ # "Now" is the +now:+ given to {Pipeline#call} or {Steps::Step#call}, so previews and tests can
8
+ # price "as of" any moment; otherwise it comes from the clock, asked once per run (see {Run}).
9
+ class TimeWindow
10
+ # The clock used when none is given.
11
+ DEFAULT_CLOCK = -> { Time.now }
12
+
13
+ # @return [Time, nil]
14
+ attr_reader :starts_at
15
+ # @return [Time, nil]
16
+ attr_reader :ends_at
17
+ # @return [#call] callable with no arguments returning the current Time
18
+ attr_reader :clock
19
+
20
+ # @param starts_at [Time, String, nil] a Time, or an ISO-8601 String with a zone; a date alone
21
+ # ("2026-11-27") or a DateTime is rejected
22
+ # @param ends_at [Time, String, nil] the same forms as +starts_at+
23
+ # @param clock [#call, nil] callable with no arguments returning the current Time
24
+ # @raise [ConfigurationError] if a timestamp is invalid or has no zone, +starts_at+ is not
25
+ # before +ends_at+, or +clock+ is not a callable taking no arguments
26
+ def initialize(starts_at: nil, ends_at: nil, clock: nil)
27
+ @starts_at = configured_time(starts_at, "starts_at")
28
+ @ends_at = configured_time(ends_at, "ends_at")
29
+ if @starts_at && @ends_at && @starts_at >= @ends_at
30
+ raise ConfigurationError, "starts_at must be before ends_at, got #{Conditions::Reason.show(starts_at)} and #{Conditions::Reason.show(ends_at)}"
31
+ end
32
+
33
+ @clock = TimeWindow.check_clock!(clock)
34
+ freeze
35
+ end
36
+
37
+ # The window for a step's settings. Any value other than +nil+ counts as set, so
38
+ # +starts_at: false+ is rejected instead of ignored.
39
+ #
40
+ # @param (see #initialize)
41
+ # @return [TimeWindow, nil] +nil+ when neither end is set; +clock+ is still checked
42
+ # @raise (see #initialize)
43
+ def self.build(starts_at:, ends_at:, clock:)
44
+ return new(starts_at:, ends_at:, clock:) unless starts_at.nil? && ends_at.nil?
45
+
46
+ check_clock!(clock)
47
+ nil
48
+ end
49
+
50
+ # Checks a +clock:+ setting, even for a step without a window, so a mistake never goes unnoticed.
51
+ #
52
+ # @param clock [#call, nil] callable with no arguments returning the current Time
53
+ # @return [#call] the clock, or {DEFAULT_CLOCK} when it is +nil+
54
+ # @raise [ConfigurationError] if +clock+ is not a callable taking no arguments
55
+ def self.check_clock!(clock)
56
+ return DEFAULT_CLOCK if clock.nil?
57
+ unless clock.respond_to?(:call)
58
+ raise ConfigurationError,
59
+ "clock must be callable, got #{Conditions::Reason.show(clock)}"
60
+ end
61
+
62
+ Resolver.check_arity!(clock, 0, "no arguments")
63
+ clock
64
+ end
65
+
66
+ # @param now [Time] the current time, given to the call or from the {#clock}
67
+ # @return [String, nil] the frozen trace note when the step is outside the window, +nil+ when it
68
+ # is active
69
+ # @raise [InvalidAmount] if +now+ is not a Time
70
+ # @example
71
+ # window = TimeWindow.new(starts_at: "2026-11-27T00:00:00Z")
72
+ # window.skip_note(Time.utc(2026, 11, 1)) # => "skipped (not active: starts 2026-11-27T00:00:00Z)"
73
+ def skip_note(now)
74
+ now = Run.time!(now, "clock")
75
+ return "skipped (not active: starts #{starts_at.iso8601})".freeze if starts_at && now < starts_at
76
+ return "skipped (expired #{ends_at.iso8601})".freeze if ends_at && now >= ends_at
77
+
78
+ nil
79
+ end
80
+
81
+ private
82
+
83
+ def configured_time(value, label)
84
+ parse_time(value)
85
+ rescue ArgumentError
86
+ raise ConfigurationError, "#{label} must be a Time or #{Timestamp::FORMAT}; a date alone or a DateTime " \
87
+ "is not accepted, got #{Conditions::Reason.show(value)}"
88
+ end
89
+
90
+ # @raise [ArgumentError] if +value+ is not a Time or a valid ISO-8601 String with a zone
91
+ def parse_time(value) = value.nil? ? nil : Timestamp.parse(value)
92
+ end
93
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module PriceWaterfall
6
+ # Strict parsing of the timestamps configs may contain: time windows (+starts_at:+) and time
7
+ # operands of ordering conditions (+{ ctx: "signup_at", lt: "2026-01-01T00:00:00Z" }+).
8
+ module Timestamp
9
+ # Timestamps must end with a time and a zone (+Z+, +05:30+, +0530+ or +05+), so "midnight"
10
+ # means the same moment on every server. Requiring the time keeps a date alone ("2026-11-27",
11
+ # whose "-27" looks like an offset) out.
12
+ ZONE = /\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}(?::?\d{2})?)\z/i
13
+
14
+ # How a timestamp starts: its date, which {parse} checks was not moved ("2026-02-30" is not March 2).
15
+ DATE = /\A\s*(-?\d+)-(\d\d)-(\d\d)/
16
+
17
+ # What a timestamp String must look like, for error messages.
18
+ FORMAT = "an ISO-8601 String with a zone (Z, +05:30, +0530 or +05) and a real date and time " \
19
+ '(e.g. "2026-11-27T00:00:00Z")'
20
+
21
+ module_function
22
+
23
+ # @param value [Time, String]
24
+ # @return [Time] +value+ itself, or the String parsed
25
+ # @raise [ArgumentError] if +value+ is not a Time or a valid ISO-8601 String with a zone and a
26
+ # date that exists
27
+ # @example
28
+ # Timestamp.parse("2026-11-27T00:00:00Z") # => 2026-11-27 00:00:00 UTC
29
+ # Timestamp.parse("2026-02-30T00:00:00Z") # raises ArgumentError
30
+ def parse(value)
31
+ return value if value.is_a?(Time)
32
+ raise ArgumentError, "not a timestamp" unless value.is_a?(String) && value.valid_encoding? && value.match?(ZONE)
33
+
34
+ time = Time.iso8601(value)
35
+ raise ArgumentError, "no such date" unless [time.year, time.month, time.day] == date_of(value)
36
+
37
+ time
38
+ end
39
+
40
+ # @param value [Object]
41
+ # @return [Boolean] whether +value+ is a String that starts like a date, so is meant as a timestamp
42
+ def date_like?(value) = value.is_a?(String) && value.valid_encoding? && value.match?(DATE)
43
+
44
+ # @param value [Object] a value that was rejected as a timestamp
45
+ # @return [String, nil] advice for a Date or DateTime, which YAML and Rails often give
46
+ # @example
47
+ # Timestamp.hint(Date.new(2026, 1, 1)) # => '; a Date has no zone, so write "2026-01-01T00:00:00Z"'
48
+ def hint(value)
49
+ return "; pass a Time instead (date_time.to_time keeps its time and offset)" if value.is_a?(DateTime)
50
+
51
+ %(; a Date has no zone, so write "#{value.strftime("%F")}T00:00:00Z") if value.is_a?(Date)
52
+ end
53
+
54
+ # @api private
55
+ def date_of(value) = value.match(DATE).captures.map(&:to_i)
56
+ private_class_method :date_of
57
+ end
58
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # @api private
5
+ # Marks the gem's own resolvers and compiled conditions. A step runs these without blaming user
6
+ # code: an error from one of them is the gem's ({InvalidAmount}), not a {StepError}. User code
7
+ # inside them (registered sources and operators, Ruby callables in a description) still runs
8
+ # through {UserCode.call}.
9
+ module Builtin; end
10
+
11
+ # @api private
12
+ # Tells errors from user code apart from the gem's own. {UserCode.call} records each exception
13
+ # raised by user code and lets it through unchanged, so a compiled condition or resolver called
14
+ # directly raises the original exception, while a step can still report it as a {StepError}.
15
+ module UserCode
16
+ # Exceptions raised by user code, held weakly so they are not kept alive. Shared by all threads:
17
+ # each entry is written once, by the thread that raised it, before anything reads it, which is
18
+ # safe under MRI's global VM lock (the Rubies CI runs). Wrapping the exception instead would
19
+ # change its class for callers outside a step.
20
+ RAISED = ObjectSpace::WeakMap.new
21
+
22
+ # Runs a step's resolver, condition or clock. Anything user code raises (the callable itself,
23
+ # or user code inside the gem's own resolvers) becomes a {StepError} naming the step; an error
24
+ # from the gem's own code is raised as it is.
25
+ #
26
+ # @param callable [#call]
27
+ # @param step [Symbol] the step's name
28
+ # @return [Object] whatever +callable+ returns
29
+ # @raise [StepError] if user code raised; its +cause+ is the original exception
30
+ def self.invoke(callable, step, *)
31
+ callable.call(*)
32
+ rescue StandardError => e
33
+ raise unless RAISED.key?(e) || !callable.is_a?(Builtin)
34
+
35
+ raise StepError.new("step #{step.inspect} failed: #{e.class}: #{e.message}", step:)
36
+ end
37
+
38
+ # Runs user code from inside the gem's own code.
39
+ #
40
+ # @param callable [#call]
41
+ # @return [Object] whatever +callable+ returns
42
+ # @raise [StandardError] whatever +callable+ raises, unchanged
43
+ def self.call(callable, *)
44
+ callable.call(*)
45
+ rescue StandardError => e
46
+ RAISED[e] = true
47
+ raise
48
+ end
49
+
50
+ # Runs a Ruby callable given inside a description (a +key:+ or a condition operand) as user code.
51
+ class Callable
52
+ include Builtin
53
+
54
+ # @return [#call] the callable as given
55
+ attr_reader :callable
56
+
57
+ # @param callable [#call] a callable taking +(item, ctx)+
58
+ def initialize(callable)
59
+ @callable = callable
60
+ freeze
61
+ end
62
+
63
+ # @param item [Object]
64
+ # @param ctx [Object]
65
+ # @return [Object] whatever the callable returns
66
+ def call(item, ctx) = UserCode.call(callable, item, ctx)
67
+
68
+ # @return [String] how a trace names a callable
69
+ def label = "callable"
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ module Values
5
+ # A list whose entries are each a literal or a value description, e.g. the operand of +in:+
6
+ # or +between:+ in a condition.
7
+ class List
8
+ include Builtin
9
+
10
+ # @return [Array<#call>] one resolver per entry
11
+ attr_reader :entries
12
+
13
+ # @param entries [Array<#call>]
14
+ def initialize(entries)
15
+ @entries = entries.dup.freeze
16
+ freeze
17
+ end
18
+
19
+ # @param item [Object]
20
+ # @param ctx [Object]
21
+ # @return [Array] each entry resolved
22
+ def call(item, ctx) = entries.map { |entry| entry.call(item, ctx) }
23
+
24
+ # @return [String] how a trace names the list: its entries' labels, +[ctx.lo, 10]+
25
+ def label = "[#{entries.map { |entry| Conditions::Reason.label(entry) }.join(", ")}]"
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Value sources: objects that produce a step input from the item and context.
5
+ module Values
6
+ # A fixed value written straight into the pipeline (+percent :promo, 10+ or +"value": 10+).
7
+ class Literal
8
+ include Builtin
9
+
10
+ # @return [Object] the value returned on every call
11
+ attr_reader :value
12
+
13
+ # @param value [Object]
14
+ def initialize(value)
15
+ @value = value
16
+ freeze
17
+ end
18
+
19
+ # @param _item [Object] ignored
20
+ # @param _ctx [Object] ignored
21
+ # @return [Object] {#value}
22
+ def call(_item, _ctx) = value
23
+
24
+ # @return [String] how a trace shows this value, shortened
25
+ def label = Conditions::Reason.show(value)
26
+ end
27
+ end
28
+ end