graphql-armory 0.1.0.pre5 → 0.1.0.pre7

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.
@@ -39,8 +39,8 @@ module GraphQL
39
39
 
40
40
  # `store:` answers `fetch(id)` with an operation (`body` and `document`) or nil: a Manifest, or your own.
41
41
  # `strict: true` refuses raw queries unless the context holds `armory_allow_raw_query: true`.
42
- def self.use(schema, store:, strict: false)
43
- gate = Gate.build(store: store, strict: strict)
42
+ def self.use(schema, store:, strict: false, sinks: [])
43
+ gate = Gate.build(store: store, strict: strict, sinks: sinks)
44
44
 
45
45
  if schema.singleton_class.include?(Guard)
46
46
  raise ConfigurationError, "#{schema} already uses PersistedQueries (here or in a parent schema): use it once"
@@ -56,13 +56,13 @@ module GraphQL
56
56
  # as it came.
57
57
  class Gate
58
58
  # Wires the app's store with `use`'s defaults; `use` goes through here.
59
- def self.build(store:, strict: false)
60
- new(store: store, strict: strict)
59
+ def self.build(store:, strict: false, sinks: [])
60
+ new(store: store, strict: strict, telemetry: Telemetry.build(sinks: sinks))
61
61
  end
62
62
 
63
63
  # `new` is inert: with no store wired it refuses every request. It checks what it is given, so it never
64
64
  # lets raw queries through without a store either.
65
- def initialize(store: Store::Null.new, strict: true)
65
+ def initialize(store: Store::Null.new, strict: true, telemetry: Telemetry.new)
66
66
  if store.is_a?(Hash) || !store.respond_to?(:fetch)
67
67
  raise ConfigurationError, "store: must answer fetch(id) with an operation or nil, like a Manifest"
68
68
  end
@@ -71,6 +71,7 @@ module GraphQL
71
71
 
72
72
  @store = store
73
73
  @strict = strict
74
+ @telemetry = telemetry
74
75
  end
75
76
 
76
77
  def call(context, text, document)
@@ -79,21 +80,29 @@ module GraphQL
79
80
  if !operation_id.nil?
80
81
  operation = operation_id.is_a?(String) ? @store.fetch(operation_id) : nil
81
82
  if operation.nil?
82
- [UNKNOWN_OPERATION, nil]
83
+ refuse(UNKNOWN_OPERATION, :unknown_operation)
83
84
  elsif document || (text && !same_query?(text, operation))
84
- [MISMATCH, nil]
85
+ refuse(MISMATCH, :mismatch)
85
86
  else
87
+ @telemetry.record(:operation_persisted)
86
88
  [nil, operation.document]
87
89
  end
88
90
  elsif @strict && !(context.respond_to?(:[]) && context[:armory_allow_raw_query] == true)
89
- [RAW_QUERY_REFUSED, nil]
91
+ refuse(RAW_QUERY_REFUSED, :raw_query)
90
92
  else
93
+ @telemetry.record(@strict ? :raw_query_allowed : :raw_query_run) if text || document
91
94
  [nil, nil]
92
95
  end
93
96
  end
94
97
 
95
98
  private
96
99
 
100
+ # The signal says why, never which operation id or query: a client chooses those.
101
+ def refuse(message, reason)
102
+ @telemetry.record(:operation_refused, reason: reason)
103
+ [message, nil]
104
+ end
105
+
97
106
  # Apollo's clients may send the query with its id; graphql-ruby's subscriptions resend it printed.
98
107
  def same_query?(text, operation)
99
108
  text == operation.body || text == operation.document.to_query_string
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module RateLimits
6
+ # What a limiter reads the time from: a callable answering seconds, like `Clock.monotonic`.
7
+ module Clock
8
+ def self.monotonic
9
+ MemoryStore.monotonic_clock
10
+ end
11
+
12
+ # A clock the test moves (`advance`, `now`) and that counts how often it was read: for tests, instead of
13
+ # hand-written fakes.
14
+ class Substitute
15
+ attr_accessor :now
16
+ attr_reader :reads
17
+
18
+ def initialize(now: 0.0)
19
+ @now = now
20
+ @reads = 0
21
+ end
22
+
23
+ def call
24
+ @reads += 1
25
+ @now
26
+ end
27
+
28
+ def advance(seconds)
29
+ @now += seconds
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -28,6 +28,22 @@ module GraphQL
28
28
  end
29
29
  end
30
30
 
31
+ # A root for Query.example whose every field takes `seconds` on `clock` (a Clock::Substitute) before it
32
+ # answers, so a spec decides how long an operation took.
33
+ module Time
34
+ def self.example(clock, resolved = [], seconds: 0.25)
35
+ root = Root.example(resolved)
36
+ Class.new do
37
+ %i[cheap report broken].each do |field|
38
+ define_method(field) do
39
+ clock.advance(seconds)
40
+ root.public_send(field)
41
+ end
42
+ end
43
+ end.new
44
+ end
45
+ end
46
+
31
47
  # A query context naming its client.
32
48
  module Context
33
49
  def self.example(key: "user:1", **context)
@@ -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
@@ -97,6 +97,19 @@ module GraphQL
97
97
  raise ConfigurationError, "store: #{method} answered #{answer.inspect}: it must answer [true or false, #{meaning}]"
98
98
  end
99
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
+
100
113
  def store_error_handler(handler)
101
114
  return ->(error, _query) { warn("graphql-armory rate limit store failed, query let through: #{error.class}: #{error.message}") } if handler.nil?
102
115
  raise ConfigurationError, "on_store_error: must be a callable that takes the error and the query" unless handler.respond_to?(:call)
@@ -110,7 +123,9 @@ end
110
123
 
111
124
  require "graphql/armory/rate_limits/memory_store"
112
125
  require "graphql/armory/rate_limits/store"
126
+ require "graphql/armory/rate_limits/clock"
113
127
  require "graphql/armory/rate_limits/redis_store"
114
128
  require "graphql/armory/rate_limits/points"
115
129
  require "graphql/armory/rate_limits/concurrency"
130
+ require "graphql/armory/rate_limits/time"
116
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.pre5"
5
+ VERSION = "0.1.0.pre7"
6
6
  end
7
7
  end
@@ -10,8 +10,10 @@ 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"
17
18
  require "graphql/armory/rate_limits"
19
+ require "graphql/armory/keyset"
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.pre5
4
+ version: 0.1.0.pre7
5
5
  platform: ruby
6
6
  authors:
7
7
  - Israel
@@ -43,8 +43,10 @@ files:
43
43
  - README.md
44
44
  - docs/authorization.md
45
45
  - docs/encrypted-ids.md
46
+ - docs/keyset-connections.md
46
47
  - docs/persisted-queries.md
47
48
  - docs/rate-limiting.md
49
+ - docs/telemetry.md
48
50
  - lib/graphql-armory.rb
49
51
  - lib/graphql/armory.rb
50
52
  - lib/graphql/armory/authorization.rb
@@ -75,7 +77,6 @@ files:
75
77
  - lib/graphql/armory/authorization/rspec.rb
76
78
  - lib/graphql/armory/authorization/rule.rb
77
79
  - lib/graphql/armory/authorization/scope.rb
78
- - lib/graphql/armory/authorization/telemetry.rb
79
80
  - lib/graphql/armory/encoder.rb
80
81
  - lib/graphql/armory/encoder/default.rb
81
82
  - lib/graphql/armory/encoder/legacy.rb
@@ -84,17 +85,22 @@ files:
84
85
  - lib/graphql/armory/encoder/versioned.rb
85
86
  - lib/graphql/armory/ids.rb
86
87
  - lib/graphql/armory/ids/controls.rb
88
+ - lib/graphql/armory/keyset.rb
89
+ - lib/graphql/armory/keyset/controls.rb
87
90
  - lib/graphql/armory/persisted_queries.rb
88
91
  - lib/graphql/armory/persisted_queries/controls.rb
89
92
  - lib/graphql/armory/persisted_queries/manifest.rb
90
93
  - lib/graphql/armory/persisted_queries/store.rb
91
94
  - lib/graphql/armory/rate_limits.rb
95
+ - lib/graphql/armory/rate_limits/clock.rb
92
96
  - lib/graphql/armory/rate_limits/concurrency.rb
93
97
  - lib/graphql/armory/rate_limits/controls.rb
94
98
  - lib/graphql/armory/rate_limits/memory_store.rb
95
99
  - lib/graphql/armory/rate_limits/points.rb
96
100
  - lib/graphql/armory/rate_limits/redis_store.rb
97
101
  - lib/graphql/armory/rate_limits/store.rb
102
+ - lib/graphql/armory/rate_limits/time.rb
103
+ - lib/graphql/armory/telemetry.rb
98
104
  - lib/graphql/armory/version.rb
99
105
  - lib/tasks/graphql_armory.rake
100
106
  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