graphql-armory 0.1.0.pre4 → 0.1.0.pre6

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.
@@ -0,0 +1,209 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module RateLimits
6
+ # Charges each client the wall-clock milliseconds its operations take, against a bucket of milliseconds per
7
+ # client that refills over a window:
8
+ #
9
+ # use GraphQL::Armory::RateLimits::Time, store: GraphQL::Armory::RateLimits::MemoryStore.new,
10
+ # limit: 10_000, window: 60, soft: false
11
+ #
12
+ # A query analyzer asks the store for the client's balance before the operation runs and refuses it, before any
13
+ # field resolves, when none is left. A trace measures the multiplex with a monotonic clock and charges the
14
+ # elapsed milliseconds when it ends, even when it raises. A running operation is never interrupted: the one
15
+ # that spends the last milliseconds finishes, and the next is refused. Soft mode (the default) charges and
16
+ # records but refuses nothing. What happened is in `context[:rate_limit_time]`.
17
+ class Time
18
+ CONTEXT_KEY = :rate_limit_time
19
+ NAMESPACE = :graphql_armory
20
+
21
+ def self.use(schema, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
22
+ build(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, clock: clock, extensions: extensions).install(schema)
23
+ end
24
+
25
+ # HTTP headers for the budget a result recorded: `RateLimit-Time-Limit` and `RateLimit-Time-Remaining` in
26
+ # milliseconds, and `RateLimit-Time-Reset` (seconds until the bucket is full again). Prefixed so they never
27
+ # clash with the `Points` headers. Empty when the query had no limit.
28
+ def self.headers(result)
29
+ info = result.context.namespace(NAMESPACE)[:time]
30
+ return {} unless info && info[:limit] && info[:remaining]
31
+
32
+ {
33
+ "RateLimit-Time-Limit" => info[:limit].to_s,
34
+ "RateLimit-Time-Remaining" => info[:remaining].to_s,
35
+ "RateLimit-Time-Reset" => Points.reset_in(info).to_s
36
+ }
37
+ end
38
+
39
+ # Wires the app's store with `use`'s defaults (soft mode); `use` goes through here.
40
+ def self.build(store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
41
+ new(store: store, limit: limit, window: window, soft: soft, key: key, on_store_error: on_store_error, clock: clock, extensions: extensions)
42
+ end
43
+
44
+ # `new` is inert: with no store wired it refuses every query. It checks every setting, so no partial
45
+ # configuration lets a query through either.
46
+ def initialize(store: Store::Null.new, limit: 1, window: 60, soft: false, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false)
47
+ unless Settings.store_answers?(store, take: %i[cost limit window force])
48
+ raise ConfigurationError, "store: must answer take(key, cost:, limit:, window:, force:), like a MemoryStore"
49
+ end
50
+
51
+ @store = store
52
+ @limit = Settings.wired_limit(limit, store)
53
+ @window = Settings.seconds(:window, window)
54
+ @soft = Settings.wired_soft(soft, store)
55
+ @key = Settings.key_reader(key)
56
+ @on_store_error = Settings.store_error_handler(on_store_error)
57
+ @clock = Settings.clock(clock)
58
+ now # a clock that answers anything but a finite number fails here, not by charging nothing
59
+ @extensions = Settings.extensions(extensions)
60
+ @trace = measuring_trace
61
+ end
62
+
63
+ # Adds the analyzer and the trace to the schema.
64
+ def install(schema)
65
+ time = self
66
+ schema.query_analyzer(Class.new(Analyzer) { define_method(:time) { time } })
67
+ schema.trace_with(@trace)
68
+ end
69
+
70
+ # The refusal for a client with no milliseconds left, or nil to let the operation run (and be charged).
71
+ def call(query)
72
+ unless query.current_trace.is_a?(@trace)
73
+ raise ConfigurationError, "this query runs with its own trace (context[:trace]), so Time could never charge it: remove context[:trace] or add trace_with to that trace"
74
+ end
75
+
76
+ key = Settings.key_for(@key, query)
77
+ limit = Settings.limit_for(@limit, key, query)
78
+ if limit.nil?
79
+ record(query, key: key, limit: nil, remaining: nil, limited: false)
80
+ return nil
81
+ end
82
+
83
+ answer = begin
84
+ @store.take(key, cost: 0, limit: limit, window: @window, force: false)
85
+ rescue StandardError => error
86
+ # Fail open, and still measure: the charge may find the store back.
87
+ query.context[CONTEXT_KEY] = nil
88
+ @on_store_error.call(error, query)
89
+ owe(query, key, limit)
90
+ return nil
91
+ end
92
+ _taken, remaining = Settings.checked(answer, :take, "the Integer milliseconds left")
93
+
94
+ limited = remaining.zero?
95
+ info = record(query, key: key, limit: limit, remaining: remaining, limited: limited)
96
+ extension = announce(query, info) if @extensions
97
+ return refusal(limit) if limited && !@soft
98
+
99
+ owe(query, key, limit, info, extension)
100
+ nil
101
+ end
102
+
103
+ # The clock's reading, for the trace. A reading that is not a finite number would make the charge
104
+ # impossible, so it raises instead of letting operations run uncharged.
105
+ def now
106
+ reading = @clock.call
107
+ return reading if reading.is_a?(Numeric) && reading.finite?
108
+
109
+ raise ConfigurationError, "clock: answered #{reading.inspect}: it must answer a finite number of seconds"
110
+ end
111
+
112
+ # Charges the elapsed time since `started`, split equally among the queries of the multiplex that ran.
113
+ def charge(multiplex, started)
114
+ return if started.nil?
115
+
116
+ # A clock that stands still or goes backwards charges nothing.
117
+ seconds = [now - started, 0].max
118
+ # Each limiter takes only its own debts: a schema may `use` several, with different stores and keys.
119
+ owed = multiplex.queries.filter_map do |query|
120
+ debt = query.context.namespace(NAMESPACE)[:time_charges]&.delete(self)
121
+ [query, debt] if debt
122
+ end
123
+ return if owed.empty?
124
+
125
+ share = (seconds * 1000 / owed.size.to_f).ceil
126
+ # Every query is charged even if one hook raises; the first such error is raised afterwards.
127
+ failure = nil
128
+ owed.each do |query, debt|
129
+ charge_one(query, debt, share)
130
+ rescue StandardError => error
131
+ failure ||= error
132
+ end
133
+ raise failure if failure
134
+ end
135
+
136
+ private
137
+
138
+ def charge_one(query, debt, cost)
139
+ answer = @store.take(debt[:key], cost: cost, limit: debt[:limit], window: @window, force: true)
140
+ _taken, remaining = Settings.checked(answer, :take, "the Integer milliseconds left")
141
+ settle(query, debt, cost, remaining)
142
+ rescue StandardError => error
143
+ @on_store_error.call(error, query)
144
+ end
145
+
146
+ # What the client has left once the charge is in, in the record and in the extensions announced earlier.
147
+ def settle(query, debt, cost, remaining)
148
+ info = (debt[:info] || base_record(key: debt[:key], limit: debt[:limit], limited: false)).merge(remaining: remaining, elapsed: cost)
149
+ query.context.namespace(NAMESPACE)[:time] = info
150
+ query.context[CONTEXT_KEY] = info
151
+ debt[:extension]&.merge!("remaining" => remaining, "elapsed" => cost, "resetIn" => Points.reset_in(info))
152
+ end
153
+
154
+ # Per query and per limiter, not in the context hash: queries of a multiplex may share one hash, and a
155
+ # schema may use several limiters.
156
+ def owe(query, key, limit, info = nil, extension = nil)
157
+ charges = (query.context.namespace(NAMESPACE)[:time_charges] ||= {})
158
+ charges[self] = { key: key, limit: limit, info: info, extension: extension }
159
+ end
160
+
161
+ def record(query, **info)
162
+ info = base_record(**info)
163
+ query.context.namespace(NAMESPACE)[:time] = info
164
+ query.context[CONTEXT_KEY] = info
165
+ end
166
+
167
+ # `elapsed` is nil until the operation ends and is charged; it stays nil for a refused one.
168
+ def base_record(key:, limit:, limited:, remaining: nil)
169
+ { key: key, limit: limit, remaining: remaining, elapsed: nil, window: @window, soft: @soft, limited: limited }
170
+ end
171
+
172
+ # The budget before the run; the charge completes the same hash, which the response already holds.
173
+ def announce(query, info)
174
+ extension = { "limit" => info[:limit], "remaining" => info[:remaining], "resetIn" => Points.reset_in(info) }
175
+ query.context.response_extensions["rateLimitTime"] = extension
176
+ end
177
+
178
+ def refusal(limit)
179
+ retry_after = [(@window / limit.to_f).ceil, 1].max
180
+ GraphQL::AnalysisError.new(
181
+ "Rate limit exceeded: this client used its #{limit} ms of processing time every #{@window} seconds. Retry in #{retry_after} seconds.",
182
+ extensions: { "code" => "RATE_LIMITED", "limit" => limit, "retryAfter" => retry_after }
183
+ )
184
+ end
185
+
186
+ # One module per limiter, so the trace reads this limiter's clock and charges this limiter's store.
187
+ def measuring_trace
188
+ time = self
189
+ Module.new do
190
+ # `define_method` does not forward the block implicitly, as `def` with `super` does.
191
+ define_method(:execute_multiplex) do |multiplex:, &block|
192
+ started = time.now
193
+ super(multiplex: multiplex, &block)
194
+ ensure
195
+ time.charge(multiplex, started)
196
+ end
197
+ end
198
+ end
199
+
200
+ # Asks for the balance during analysis, before anything runs.
201
+ class Analyzer < GraphQL::Analysis::Analyzer
202
+ def result
203
+ time.(query)
204
+ end
205
+ end
206
+ end
207
+ end
208
+ end
209
+ end
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ # Rate limits built for GraphQL, where requests differ wildly in cost. Each client is named by
6
+ # `context[:rate_limit_key]` (or a `key:` callable) and limited through a store: `MemoryStore` for tests and
7
+ # a single process, a shared store for several processes.
8
+ module RateLimits
9
+ class ConfigurationError < Armory::Error; end
10
+
11
+ KEY = :rate_limit_key
12
+
13
+ # The settings every limiter shares, checked at boot.
14
+ module Settings
15
+ module_function
16
+
17
+ def key_reader(key)
18
+ return ->(query) { query.context[KEY] } if key.nil?
19
+ raise ConfigurationError, "key: must be a callable that takes the query, got #{key.inspect}" unless key.respond_to?(:call)
20
+
21
+ key
22
+ end
23
+
24
+ def key_for(reader, query)
25
+ key = reader.call(query)
26
+ return key if key.is_a?(String) && !key.empty?
27
+
28
+ raise ConfigurationError, "no client key for this query: put a non-empty String in context[:#{KEY}], or give the limiter a key: callable"
29
+ end
30
+
31
+ def soft(value)
32
+ raise ConfigurationError, "soft: must be true or false, got #{value.inspect}" unless value == true || value == false
33
+
34
+ value
35
+ end
36
+
37
+ # A limit callable may answer nil (no limit for that key), so on the Null store it could let queries through.
38
+ def wired_limit(value, store)
39
+ limit(value)
40
+ raise ConfigurationError, "a limit: callable needs a store: on the Null store a nil answer would let queries run unlimited" if value.respond_to?(:call) && store.is_a?(Store::Null)
41
+
42
+ value
43
+ end
44
+
45
+ # Soft mode counts but never refuses, so on the Null store it would let everything through uncounted.
46
+ def wired_soft(value, store)
47
+ soft(value)
48
+ raise ConfigurationError, "soft: true needs a store: the Null store counts nothing, so every query would run unlimited" if value && store.is_a?(Store::Null)
49
+
50
+ value
51
+ end
52
+
53
+ def limit(limit)
54
+ return limit if limit.respond_to?(:call) || positive_integer?(limit)
55
+
56
+ raise ConfigurationError, "limit: must be a positive Integer, or a callable taking the key and the query, got #{limit.inspect}"
57
+ end
58
+
59
+ def limit_for(limit, key, query)
60
+ return limit unless limit.respond_to?(:call)
61
+
62
+ answer = limit.call(key, query)
63
+ return answer if answer.nil? || positive_integer?(answer)
64
+
65
+ raise ConfigurationError, "limit: answered #{answer.inspect} for #{key}: it must answer a positive Integer, or nil for no limit"
66
+ end
67
+
68
+ def positive_integer?(value)
69
+ value.is_a?(Integer) && value.positive?
70
+ end
71
+
72
+ def seconds(name, value)
73
+ return value if value.is_a?(Numeric) && value.positive? && value.finite?
74
+
75
+ raise ConfigurationError, "#{name}: must be a positive number of seconds, got #{value.inspect}"
76
+ end
77
+
78
+ # Whether `store` answers each method with the keywords this gem passes, so a wrong signature fails at
79
+ # boot instead of failing open on every query.
80
+ def store_answers?(store, methods)
81
+ methods.all? do |name, keywords|
82
+ next false unless store.respond_to?(name)
83
+
84
+ parameters = store.method(name).parameters
85
+ next false unless parameters.any? { |type, _| %i[req opt rest].include?(type) } # the key
86
+ next true if parameters.any? { |type, _| type == :keyrest }
87
+
88
+ (keywords - parameters.select { |type, _| type == :key || type == :keyreq }.map(&:last)).empty?
89
+ end
90
+ end
91
+
92
+ # A store answer that is not [true or false, a whole number] would let queries through: 0 is truthy.
93
+ def checked(answer, method, meaning)
94
+ granted, count = answer if answer.is_a?(Array) && answer.size == 2
95
+ return answer if (granted == true || granted == false) && count.is_a?(Integer) && !count.negative?
96
+
97
+ raise ConfigurationError, "store: #{method} answered #{answer.inspect}: it must answer [true or false, #{meaning}]"
98
+ end
99
+
100
+ def extensions(value)
101
+ raise ConfigurationError, "extensions: must be true or false, got #{value.inspect}" unless value == true || value == false
102
+
103
+ value
104
+ end
105
+
106
+ # A callable answering seconds, like `Clock.monotonic`.
107
+ def clock(value)
108
+ raise ConfigurationError, "clock: must be a callable answering seconds, got #{value.inspect}" unless value.respond_to?(:call)
109
+
110
+ value
111
+ end
112
+
113
+ def store_error_handler(handler)
114
+ return ->(error, _query) { warn("graphql-armory rate limit store failed, query let through: #{error.class}: #{error.message}") } if handler.nil?
115
+ raise ConfigurationError, "on_store_error: must be a callable that takes the error and the query" unless handler.respond_to?(:call)
116
+
117
+ handler
118
+ end
119
+ end
120
+ end
121
+ end
122
+ end
123
+
124
+ require "graphql/armory/rate_limits/memory_store"
125
+ require "graphql/armory/rate_limits/store"
126
+ require "graphql/armory/rate_limits/clock"
127
+ require "graphql/armory/rate_limits/redis_store"
128
+ require "graphql/armory/rate_limits/points"
129
+ require "graphql/armory/rate_limits/concurrency"
130
+ require "graphql/armory/rate_limits/time"
131
+ require "graphql/armory/rate_limits/controls"
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ # Records what a module decided (a request allowed, an ID refused, an operation run) and hands it to its sinks.
6
+ # A sink is anything that responds to `call(signal, data)`: a lambda that logs, a metrics client, or
7
+ # `Telemetry::Notifications`. Never put record attributes, IDs, keys or queries in `data`: a client chooses
8
+ # those, and they would end up in the app's logs.
9
+ class Telemetry
10
+ class ConfigurationError < Armory::Error; end
11
+
12
+ def self.build(sinks: [])
13
+ new(sinks: sinks)
14
+ end
15
+
16
+ def initialize(sinks: [])
17
+ # Messages name a class, never `inspect` a value: a metrics client holds its API key.
18
+ raise ConfigurationError, "sinks: must be an Array of callables taking (signal, data), got #{sinks.class}" unless sinks.is_a?(Array)
19
+
20
+ sinks.each do |sink|
21
+ raise ConfigurationError, "sinks: must be an Array of callables taking (signal, data), found a #{sink.class}" unless sink.respond_to?(:call)
22
+ next unless sink.respond_to?(:available?) && !sink.available?
23
+
24
+ raise ConfigurationError, "sink #{sink.is_a?(Module) ? sink.name : sink.class} is not available: the library it reports to is not loaded"
25
+ end
26
+
27
+ @sinks = sinks.dup.freeze
28
+ end
29
+
30
+ # Every sink gets the same frozen data, so one sink (or a subscriber) cannot change what the next one sees.
31
+ def record(signal, **data)
32
+ return nil if @sinks.empty?
33
+
34
+ data = data.to_h { |key, value| [key, value.is_a?(String) ? value.dup.freeze : value] }.freeze
35
+ @sinks.each { |sink| sink.call(signal, data) }
36
+ nil
37
+ end
38
+
39
+ # Reports every signal as an ActiveSupport::Notifications event named "<signal>.graphql_armory", with the
40
+ # signal's data as payload: `sinks: [GraphQL::Armory::Telemetry::Notifications]`.
41
+ module Notifications
42
+ def self.available?
43
+ defined?(::ActiveSupport::Notifications) ? true : false
44
+ end
45
+
46
+ def self.call(signal, data)
47
+ ::ActiveSupport::Notifications.instrument("#{signal}.graphql_armory", data.dup) # ActiveSupport may add keys to its payload
48
+ end
49
+ end
50
+
51
+ # Keeps what was recorded and fails when told, for tests.
52
+ class Substitute
53
+ attr_reader :recorded
54
+
55
+ def initialize
56
+ @recorded = []
57
+ @failure = nil
58
+ end
59
+
60
+ # Raises `error` from every `record` until `recover`, like a sink that cannot reach its service.
61
+ def fail_with(error)
62
+ @failure = error
63
+ end
64
+
65
+ def recover
66
+ @failure = nil
67
+ end
68
+
69
+ def record(signal, **data)
70
+ raise @failure if @failure
71
+
72
+ @recorded << [signal, data]
73
+ nil
74
+ end
75
+
76
+ def recorded?(signal)
77
+ @recorded.any? { |recorded_signal, _| recorded_signal == signal }
78
+ end
79
+ end
80
+ end
81
+ end
82
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module GraphQL
4
4
  module Armory
5
- VERSION = "0.1.0.pre4"
5
+ VERSION = "0.1.0.pre6"
6
6
  end
7
7
  end
@@ -10,7 +10,9 @@ module GraphQL
10
10
  end
11
11
  end
12
12
 
13
+ require "graphql/armory/telemetry"
13
14
  require "graphql/armory/encoder"
14
15
  require "graphql/armory/authorization"
15
16
  require "graphql/armory/ids"
16
17
  require "graphql/armory/persisted_queries"
18
+ require "graphql/armory/rate_limits"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: graphql-armory
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0.pre4
4
+ version: 0.1.0.pre6
5
5
  platform: ruby
6
6
  authors:
7
7
  - Israel
@@ -44,6 +44,8 @@ files:
44
44
  - docs/authorization.md
45
45
  - docs/encrypted-ids.md
46
46
  - docs/persisted-queries.md
47
+ - docs/rate-limiting.md
48
+ - docs/telemetry.md
47
49
  - lib/graphql-armory.rb
48
50
  - lib/graphql/armory.rb
49
51
  - lib/graphql/armory/authorization.rb
@@ -74,14 +76,28 @@ files:
74
76
  - lib/graphql/armory/authorization/rspec.rb
75
77
  - lib/graphql/armory/authorization/rule.rb
76
78
  - lib/graphql/armory/authorization/scope.rb
77
- - lib/graphql/armory/authorization/telemetry.rb
78
79
  - lib/graphql/armory/encoder.rb
79
80
  - lib/graphql/armory/encoder/default.rb
80
81
  - lib/graphql/armory/encoder/legacy.rb
82
+ - lib/graphql/armory/encoder/null.rb
83
+ - lib/graphql/armory/encoder/substitute.rb
81
84
  - lib/graphql/armory/encoder/versioned.rb
82
85
  - lib/graphql/armory/ids.rb
86
+ - lib/graphql/armory/ids/controls.rb
83
87
  - lib/graphql/armory/persisted_queries.rb
88
+ - lib/graphql/armory/persisted_queries/controls.rb
84
89
  - lib/graphql/armory/persisted_queries/manifest.rb
90
+ - lib/graphql/armory/persisted_queries/store.rb
91
+ - lib/graphql/armory/rate_limits.rb
92
+ - lib/graphql/armory/rate_limits/clock.rb
93
+ - lib/graphql/armory/rate_limits/concurrency.rb
94
+ - lib/graphql/armory/rate_limits/controls.rb
95
+ - lib/graphql/armory/rate_limits/memory_store.rb
96
+ - lib/graphql/armory/rate_limits/points.rb
97
+ - lib/graphql/armory/rate_limits/redis_store.rb
98
+ - lib/graphql/armory/rate_limits/store.rb
99
+ - lib/graphql/armory/rate_limits/time.rb
100
+ - lib/graphql/armory/telemetry.rb
85
101
  - lib/graphql/armory/version.rb
86
102
  - lib/tasks/graphql_armory.rake
87
103
  homepage: https://github.com/israelb/graphql-armory
@@ -1,42 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module GraphQL
4
- module Armory
5
- module Authorization
6
- # Records what happened (allowed, denied, bypassed, scoped) and hands it to its sinks.
7
- # A sink is anything that responds to `call(signal, data)`. Never put record attributes in `data`.
8
- class Telemetry
9
- def self.build(sinks: [])
10
- new(sinks: sinks)
11
- end
12
-
13
- def initialize(sinks: [])
14
- @sinks = sinks
15
- end
16
-
17
- def record(signal, **data)
18
- @sinks.each { |sink| sink.call(signal, data) }
19
- nil
20
- end
21
-
22
- # Keeps what was recorded, for tests.
23
- class Substitute
24
- attr_reader :recorded
25
-
26
- def initialize
27
- @recorded = []
28
- end
29
-
30
- def record(signal, **data)
31
- @recorded << [signal, data]
32
- nil
33
- end
34
-
35
- def recorded?(signal)
36
- @recorded.any? { |recorded_signal, _| recorded_signal == signal }
37
- end
38
- end
39
- end
40
- end
41
- end
42
- end