graphql-armory 0.1.0.pre13 → 0.1.0.pre14

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 (137) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +17 -0
  3. data/README.md +5 -5
  4. data/docs/authorization.md +4 -0
  5. data/docs/encrypted-ids.md +24 -2
  6. data/docs/persisted-queries.md +4 -0
  7. data/docs/rate-limiting.md +23 -0
  8. data/docs/response-caching.md +590 -0
  9. data/docs/subscriptions.md +261 -0
  10. data/docs/telemetry.md +39 -1
  11. data/docs/versioning.md +4 -0
  12. data/lib/graphql/armory/authorization/authorize.rb +3 -0
  13. data/lib/graphql/armory/authorization/scope.rb +2 -0
  14. data/lib/graphql/armory/caching/audit/command.rb +51 -0
  15. data/lib/graphql/armory/caching/audit/context_class.rb +117 -0
  16. data/lib/graphql/armory/caching/audit/declarations.rb +166 -0
  17. data/lib/graphql/armory/caching/audit/own_checks.rb +150 -0
  18. data/lib/graphql/armory/caching/audit/public_rules.rb +158 -0
  19. data/lib/graphql/armory/caching/audit/report.rb +113 -0
  20. data/lib/graphql/armory/caching/audit.rb +136 -0
  21. data/lib/graphql/armory/caching/base.rb +118 -0
  22. data/lib/graphql/armory/caching/canonical.rb +138 -0
  23. data/lib/graphql/armory/caching/charge.rb +86 -0
  24. data/lib/graphql/armory/caching/codec.rb +108 -0
  25. data/lib/graphql/armory/caching/context_methods.rb +88 -0
  26. data/lib/graphql/armory/caching/controls/app_schema.rb +70 -0
  27. data/lib/graphql/armory/caching/controls/context.rb +30 -0
  28. data/lib/graphql/armory/caching/controls/operations.rb +37 -0
  29. data/lib/graphql/armory/caching/controls/schema.rb +123 -0
  30. data/lib/graphql/armory/caching/controls/store.rb +16 -0
  31. data/lib/graphql/armory/caching/controls/walk_schema.rb +197 -0
  32. data/lib/graphql/armory/caching/controls.rb +19 -0
  33. data/lib/graphql/armory/caching/digester.rb +48 -0
  34. data/lib/graphql/armory/caching/errors.rb +16 -0
  35. data/lib/graphql/armory/caching/gate/admission.rb +67 -0
  36. data/lib/graphql/armory/caching/gate/signals.rb +65 -0
  37. data/lib/graphql/armory/caching/gate/store_check.rb +60 -0
  38. data/lib/graphql/armory/caching/gate/substitute.rb +61 -0
  39. data/lib/graphql/armory/caching/gate.rb +384 -0
  40. data/lib/graphql/armory/caching/integration/guard.rb +55 -0
  41. data/lib/graphql/armory/caching/integration/install.rb +262 -0
  42. data/lib/graphql/armory/caching/integration/query.rb +42 -0
  43. data/lib/graphql/armory/caching/integration.rb +141 -0
  44. data/lib/graphql/armory/caching/keyer.rb +208 -0
  45. data/lib/graphql/armory/caching/memory_store.rb +164 -0
  46. data/lib/graphql/armory/caching/nulls.rb +121 -0
  47. data/lib/graphql/armory/caching/purge.rb +98 -0
  48. data/lib/graphql/armory/caching/record_keys.rb +109 -0
  49. data/lib/graphql/armory/caching/recorder/context.rb +178 -0
  50. data/lib/graphql/armory/caching/recorder/log.rb +142 -0
  51. data/lib/graphql/armory/caching/recorder/null.rb +24 -0
  52. data/lib/graphql/armory/caching/recorder/shared_writes.rb +58 -0
  53. data/lib/graphql/armory/caching/recorder/substitute.rb +119 -0
  54. data/lib/graphql/armory/caching/recorder.rb +34 -0
  55. data/lib/graphql/armory/caching/redis_store/scripts.rb +159 -0
  56. data/lib/graphql/armory/caching/redis_store.rb +162 -0
  57. data/lib/graphql/armory/caching/rspec.rb +25 -0
  58. data/lib/graphql/armory/caching/schema_identity.rb +102 -0
  59. data/lib/graphql/armory/caching/store/null.rb +31 -0
  60. data/lib/graphql/armory/caching/store/substitute.rb +144 -0
  61. data/lib/graphql/armory/caching/store.rb +34 -0
  62. data/lib/graphql/armory/caching/tags.rb +39 -0
  63. data/lib/graphql/armory/caching/values/decision.rb +45 -0
  64. data/lib/graphql/armory/caching/values/declaration.rb +114 -0
  65. data/lib/graphql/armory/caching/values/entry.rb +108 -0
  66. data/lib/graphql/armory/caching/values/key.rb +39 -0
  67. data/lib/graphql/armory/caching/values/lookup.rb +35 -0
  68. data/lib/graphql/armory/caching/values/policy.rb +44 -0
  69. data/lib/graphql/armory/caching/viewer.rb +112 -0
  70. data/lib/graphql/armory/caching/walk/directives.rb +45 -0
  71. data/lib/graphql/armory/caching/walk/relay.rb +54 -0
  72. data/lib/graphql/armory/caching/walk/run.rb +130 -0
  73. data/lib/graphql/armory/caching/walk/tally.rb +38 -0
  74. data/lib/graphql/armory/caching/walk.rb +46 -0
  75. data/lib/graphql/armory/caching.rb +69 -0
  76. data/lib/graphql/armory/encoder/legacy.rb +14 -0
  77. data/lib/graphql/armory/encoder/null.rb +14 -1
  78. data/lib/graphql/armory/encoder/substitute.rb +54 -2
  79. data/lib/graphql/armory/encoder/versioned.rb +36 -0
  80. data/lib/graphql/armory/encoder.rb +80 -1
  81. data/lib/graphql/armory/persisted_queries.rb +8 -1
  82. data/lib/graphql/armory/rate_limits/cached_charge.rb +43 -0
  83. data/lib/graphql/armory/rate_limits/concurrency.rb +12 -5
  84. data/lib/graphql/armory/rate_limits/invalid_queries.rb +3 -2
  85. data/lib/graphql/armory/rate_limits/points.rb +21 -9
  86. data/lib/graphql/armory/rate_limits/time.rb +15 -8
  87. data/lib/graphql/armory/rate_limits.rb +9 -0
  88. data/lib/graphql/armory/subscriptions/ably/key.rb +49 -0
  89. data/lib/graphql/armory/subscriptions/ably/publisher.rb +132 -0
  90. data/lib/graphql/armory/subscriptions/ably/token_request.rb +42 -0
  91. data/lib/graphql/armory/subscriptions/ably/webhook.rb +96 -0
  92. data/lib/graphql/armory/subscriptions/ably.rb +126 -0
  93. data/lib/graphql/armory/subscriptions/audit.rb +92 -0
  94. data/lib/graphql/armory/subscriptions/controls/dependencies.rb +37 -0
  95. data/lib/graphql/armory/subscriptions/controls/event_log.rb +30 -0
  96. data/lib/graphql/armory/subscriptions/controls/id.rb +26 -0
  97. data/lib/graphql/armory/subscriptions/controls/record.rb +34 -0
  98. data/lib/graphql/armory/subscriptions/controls/schema.rb +187 -0
  99. data/lib/graphql/armory/subscriptions/controls/viewer.rb +99 -0
  100. data/lib/graphql/armory/subscriptions/controls.rb +19 -0
  101. data/lib/graphql/armory/subscriptions/core/channels.rb +93 -0
  102. data/lib/graphql/armory/subscriptions/core/clock.rb +40 -0
  103. data/lib/graphql/armory/subscriptions/core/controls.rb +29 -0
  104. data/lib/graphql/armory/subscriptions/core/delivery.rb +250 -0
  105. data/lib/graphql/armory/subscriptions/core/settings.rb +182 -0
  106. data/lib/graphql/armory/subscriptions/core/trigger.rb +63 -0
  107. data/lib/graphql/armory/subscriptions/core/viewer.rb +153 -0
  108. data/lib/graphql/armory/subscriptions/core/write.rb +172 -0
  109. data/lib/graphql/armory/subscriptions/core.rb +200 -0
  110. data/lib/graphql/armory/subscriptions/errors.rb +30 -0
  111. data/lib/graphql/armory/subscriptions/http/null.rb +17 -0
  112. data/lib/graphql/armory/subscriptions/http/substitute.rb +56 -0
  113. data/lib/graphql/armory/subscriptions/http.rb +93 -0
  114. data/lib/graphql/armory/subscriptions/memory_store.rb +115 -0
  115. data/lib/graphql/armory/subscriptions/pusher/signature.rb +45 -0
  116. data/lib/graphql/armory/subscriptions/pusher.rb +192 -0
  117. data/lib/graphql/armory/subscriptions/redis_store/scripts.rb +115 -0
  118. data/lib/graphql/armory/subscriptions/redis_store.rb +157 -0
  119. data/lib/graphql/armory/subscriptions/store/null.rb +23 -0
  120. data/lib/graphql/armory/subscriptions/store/substitute.rb +155 -0
  121. data/lib/graphql/armory/subscriptions/store.rb +38 -0
  122. data/lib/graphql/armory/subscriptions/topic.rb +253 -0
  123. data/lib/graphql/armory/subscriptions/transport/null.rb +28 -0
  124. data/lib/graphql/armory/subscriptions/transport/substitute.rb +150 -0
  125. data/lib/graphql/armory/subscriptions/transport.rb +41 -0
  126. data/lib/graphql/armory/subscriptions/values/capabilities.rb +50 -0
  127. data/lib/graphql/armory/subscriptions/values/message.rb +31 -0
  128. data/lib/graphql/armory/subscriptions/values/outcome.rb +42 -0
  129. data/lib/graphql/armory/subscriptions/values/record.rb +176 -0
  130. data/lib/graphql/armory/subscriptions/webhook_app.rb +31 -0
  131. data/lib/graphql/armory/subscriptions.rb +33 -0
  132. data/lib/graphql/armory/telemetry.rb +8 -4
  133. data/lib/graphql/armory/version.rb +1 -1
  134. data/lib/graphql/armory/versioning/integration.rb +2 -1
  135. data/lib/graphql/armory.rb +2 -0
  136. data/lib/tasks/graphql_armory.rake +9 -0
  137. metadata +110 -1
@@ -0,0 +1,262 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ module Integration
7
+ # The installer behind `use GraphQL::Armory::Caching` (docs/response-caching.md "Installing"): checks every option at boot,
8
+ # refuses a second `use` in one hierarchy and a `rescue_from` registered before it, builds the gate, and prepends
9
+ # the guard. PersistedQueries is checked at the first request, not here: the two `use` lines may come in either
10
+ # order.
11
+ module Install
12
+ # `gate:` is internal: specs inject a `Gate::Substitute`. Without it the real gate is built from the settings.
13
+ def self.call(schema, gate: nil, **options)
14
+ if schema.singleton_class.include?(Guard)
15
+ raise ConfigurationError, "#{schema} already uses GraphQL::Armory::Caching (here or in a parent schema): use it once"
16
+ end
17
+ if Handlers.registered?(schema)
18
+ raise ConfigurationError, "#{schema} registered a rescue_from handler before `use GraphQL::Armory::Caching`, which cannot wrap it: " \
19
+ "a run that handler answered could be stored. Move `use GraphQL::Armory::Caching` above `rescue_from`"
20
+ end
21
+
22
+ settings = Settings.build(**options)
23
+ gate ||= build_gate(schema, settings)
24
+ unless gate.respond_to?(:call) && gate.respond_to?(:store)
25
+ raise ConfigurationError, "gate: must answer call(queries, engine:) and store(query, decision, result), found a #{gate.class}"
26
+ end
27
+
28
+ schema.instance_variable_set(:@armory_caching, settings.bind(gate))
29
+ schema.singleton_class.prepend(Guard)
30
+ schema.context_class(schema.context_class)
31
+ schema.query_class(schema.query_class)
32
+ end
33
+
34
+ # The seam the integration wires to the real gate: `Gate.build(schema, **settings.to_h)`, which
35
+ # receives the checked options plus the one `digester:` and `telemetry:` every part shares.
36
+ def self.build_gate(schema, settings)
37
+ raise NotImplementedError, "#{schema}: Caching::Gate.build is not defined" unless Gate.respond_to?(:build)
38
+
39
+ Gate.build(schema, **settings.to_h)
40
+ end
41
+ private_class_method :build_gate
42
+ end
43
+
44
+ # The checked `use` options, frozen, read through `schema.armory_caching` by the gate, the keyer, `Purge` and
45
+ # the audit. `digester` is the one keyed digester for keys and tags (from `encoder:`, or a per-process key), so
46
+ # what `purge` digests matches what the gate stored; `telemetry` is built from `sinks:` and `on_sink_error:`.
47
+ class Settings
48
+ DEFAULT_VIEWER_ID = ->(principal) { principal.id }
49
+ ANONYMOUS = %i[uncacheable shared].freeze
50
+ MAX_VIEWER_TTL = 300
51
+ REDIS_STORE = "GraphQL::Armory::Caching::RedisStore"
52
+ STORE_METHODS = %i[lookup write purge purge_all].freeze
53
+ SEALING = %i[seal open mac].freeze
54
+
55
+ FIELDS = %i[store encoder release viewer viewer_id anonymous anonymous_reason vary max_ttl max_viewer_ttl max_entry_bytes
56
+ neutral_keys context_methods own_checks extensions sinks on_sink_error on_store_error digester telemetry].freeze
57
+
58
+ attr_reader(*FIELDS, :gate)
59
+
60
+ def self.build(store: nil, encoder: nil, release: nil, viewer: nil, viewer_id: nil, anonymous: :uncacheable, anonymous_reason: nil,
61
+ vary: {}, max_ttl: 3600, max_viewer_ttl: MAX_VIEWER_TTL, max_entry_bytes: 262_144, neutral_keys: {}, context_methods: {},
62
+ own_checks: {}, extensions: false, sinks: [], on_sink_error: nil, on_store_error: nil)
63
+ check_store(store)
64
+ check_encoder(encoder, store)
65
+ raise ConfigurationError, "release: must be a non-empty String (the deploy, e.g. ENV.fetch(\"GIT_SHA\"))" unless text?(release)
66
+
67
+ check_viewer(viewer, viewer_id)
68
+ check_anonymous(anonymous, anonymous_reason, viewer)
69
+ new(store: store, encoder: encoder, release: release.dup.freeze, viewer: viewer, viewer_id: viewer_id || DEFAULT_VIEWER_ID,
70
+ anonymous: anonymous, anonymous_reason: anonymous_reason&.dup&.freeze, vary: check_vary(vary),
71
+ max_ttl: positive(:max_ttl, max_ttl), max_viewer_ttl: viewer_ttl(max_viewer_ttl), max_entry_bytes: positive(:max_entry_bytes, max_entry_bytes),
72
+ neutral_keys: reasons(:neutral_keys, neutral_keys, viewer), context_methods: reasons(:context_methods, context_methods, nil).transform_keys(&:to_sym).freeze,
73
+ own_checks: check_own_checks(own_checks), extensions: boolean(:extensions, extensions), sinks: sinks, on_sink_error: on_sink_error, on_store_error: callable(:on_store_error, on_store_error),
74
+ digester: encoder ? Digester.build(encoder: encoder) : Digester.new, telemetry: telemetry(sinks, on_sink_error))
75
+ end
76
+
77
+ def initialize(store: Store::Null.new, encoder: nil, release: nil, viewer: nil, viewer_id: DEFAULT_VIEWER_ID, anonymous: :uncacheable,
78
+ anonymous_reason: nil, vary: {}, max_ttl: 3600, max_viewer_ttl: MAX_VIEWER_TTL, max_entry_bytes: 262_144, neutral_keys: {},
79
+ context_methods: {}, own_checks: {}, extensions: false, sinks: [], on_sink_error: nil, on_store_error: nil, digester: Digester.new,
80
+ telemetry: Telemetry.new, gate: nil)
81
+ @store = store
82
+ @encoder = encoder
83
+ @release = release
84
+ @viewer = viewer
85
+ @viewer_id = viewer_id
86
+ @anonymous = anonymous
87
+ @anonymous_reason = anonymous_reason
88
+ @vary = vary
89
+ @max_ttl = max_ttl
90
+ @max_viewer_ttl = max_viewer_ttl
91
+ @max_entry_bytes = max_entry_bytes
92
+ @neutral_keys = neutral_keys
93
+ @context_methods = context_methods
94
+ @own_checks = own_checks
95
+ @extensions = extensions
96
+ @sinks = sinks
97
+ @on_sink_error = on_sink_error
98
+ @on_store_error = on_store_error
99
+ @digester = digester
100
+ @telemetry = telemetry
101
+ @gate = gate
102
+ freeze
103
+ end
104
+
105
+ # The same settings with the gate that decides for them.
106
+ def bind(gate)
107
+ self.class.new(**to_h, gate: gate)
108
+ end
109
+
110
+ # Every field but the gate, as keywords: what `Gate.build(schema, **settings.to_h)` receives.
111
+ def to_h
112
+ FIELDS.to_h { |field| [field, public_send(field)] }
113
+ end
114
+
115
+ def inspect = "#<#{self.class.name} release=#{release.inspect}>"
116
+
117
+ def self.check_store(store)
118
+ raise ConfigurationError, "store: is required (a MemoryStore, or a RedisStore with encoder:)" if store.nil?
119
+ raise ConfigurationError, "store: Store::Null is a cache that stores nothing: pass a MemoryStore or a RedisStore" if store.is_a?(Store::Null)
120
+ return if STORE_METHODS.all? { |name| store.respond_to?(name) }
121
+
122
+ raise ConfigurationError, "store: must answer lookup, write, purge and purge_all, like a MemoryStore; found a #{store.class}"
123
+ end
124
+
125
+ # Named, never loaded: RedisStore is its own unit, and a subclass counts too.
126
+ def self.check_encoder(encoder, store)
127
+ if encoder.nil?
128
+ return unless store.class.ancestors.any? { |ancestor| ancestor.name == REDIS_STORE }
129
+
130
+ raise ConfigurationError, "encoder: is required with RedisStore: entries in Redis are sealed and their keys digested with it (an Encoder subclass)"
131
+ end
132
+
133
+ if [Encoder::Null, Encoder::Legacy].any? { |plain| encoder.is_a?(Module) && encoder <= plain }
134
+ raise ConfigurationError, "encoder: #{encoder.name} does not encrypt: pass an Encoder subclass with a key"
135
+ end
136
+ return if SEALING.all? { |name| encoder.respond_to?(name) }
137
+
138
+ raise ConfigurationError, "encoder: must seal entries (seal, open and mac), like an Encoder subclass with a key; found a #{encoder.class}"
139
+ end
140
+
141
+ def self.check_viewer(viewer, viewer_id)
142
+ unless viewer.nil? || ((viewer.is_a?(Symbol) || viewer.is_a?(String)) && !viewer.empty?)
143
+ raise ConfigurationError, "viewer: must be the context key that holds the principal (a Symbol or a String), or nil"
144
+ end
145
+ return if viewer_id.nil?
146
+ raise ConfigurationError, "viewer_id: needs viewer:, the context key it reads the principal from" if viewer.nil?
147
+
148
+ callable(:viewer_id, viewer_id)
149
+ end
150
+
151
+ def self.check_anonymous(anonymous, reason, viewer)
152
+ raise ConfigurationError, "anonymous: must be one of #{ANONYMOUS.map(&:inspect).join(", ")}, got #{anonymous.inspect}" unless ANONYMOUS.include?(anonymous)
153
+
154
+ if anonymous == :shared
155
+ raise ConfigurationError, "anonymous: :shared needs viewer:, the key whose absence makes a request anonymous" if viewer.nil?
156
+ raise ConfigurationError, "anonymous: :shared needs anonymous_reason:, a non-empty String the audit lists" unless text?(reason)
157
+ elsif !reason.nil?
158
+ raise ConfigurationError, "anonymous_reason: goes with anonymous: :shared only"
159
+ end
160
+ end
161
+
162
+ # name => context key (its value enters the key whole) or a callable taking no arguments.
163
+ def self.check_vary(vary)
164
+ raise ConfigurationError, "vary: must be a Hash of name => context key or callable taking no arguments" unless vary.is_a?(Hash)
165
+
166
+ vary.each do |name, source|
167
+ raise ConfigurationError, "vary: names must be non-empty Symbols or Strings" unless key?(name)
168
+ next if key?(source)
169
+ raise ConfigurationError, "vary: #{name} must be a context key (Symbol or String) or a callable" unless source.respond_to?(:call)
170
+ raise ConfigurationError, "vary: #{name} must be a callable that takes no arguments (read Current or I18n, not the context)" unless no_arguments?(source)
171
+ end
172
+ names = vary.keys.map(&:to_s)
173
+ raise ConfigurationError, "vary: names a value twice (#{names.find { |name| names.count(name) > 1 }})" unless names.uniq.size == names.size
174
+
175
+ vary.dup.freeze
176
+ end
177
+
178
+ # key => reason, each reason a non-empty String the audit lists.
179
+ def self.reasons(option, declared, viewer)
180
+ raise ConfigurationError, "#{option}: must be a Hash of name => reason" unless declared.is_a?(Hash)
181
+
182
+ declared.each do |name, reason|
183
+ raise ConfigurationError, "#{option}: names must be non-empty Symbols or Strings" unless key?(name)
184
+ raise ConfigurationError, "#{option}: #{name} needs a reason, a non-empty String" unless text?(reason)
185
+ end
186
+ if !viewer.nil? && declared.key?(viewer)
187
+ raise ConfigurationError, "neutral_keys: cannot hold the viewer key #{viewer.inspect}: a shared answer that reads it depends on the viewer"
188
+ end
189
+
190
+ declared.transform_values { |reason| reason.dup.freeze }.freeze
191
+ end
192
+
193
+ # For the audit only, Authorization's shape: `{ Types::Invoice => { visible?: "reason" } }`. Changes nothing at runtime.
194
+ def self.check_own_checks(own_checks)
195
+ raise ConfigurationError, "own_checks: must be a Hash of class => { method name => reason }" unless own_checks.is_a?(Hash)
196
+
197
+ own_checks.each do |owner, methods|
198
+ raise ConfigurationError, "own_checks: keys must be classes or modules, found a #{owner.class}" unless owner.is_a?(Module)
199
+ raise ConfigurationError, "own_checks: #{owner} must map method names to reasons" unless methods.is_a?(Hash)
200
+
201
+ reasons("own_checks: #{owner}", methods, nil)
202
+ end
203
+ own_checks.dup.freeze
204
+ end
205
+
206
+ def self.positive(option, value)
207
+ raise ConfigurationError, "#{option}: must be a positive Integer, got #{value.inspect}" unless value.is_a?(Integer) && value.positive?
208
+
209
+ value
210
+ end
211
+
212
+ def self.viewer_ttl(value)
213
+ positive(:max_viewer_ttl, value)
214
+ raise ConfigurationError, "max_viewer_ttl: is at most #{MAX_VIEWER_TTL} seconds, got #{value}" if value > MAX_VIEWER_TTL
215
+
216
+ value
217
+ end
218
+
219
+ def self.boolean(option, value)
220
+ raise ConfigurationError, "#{option}: must be true or false, got #{value.inspect}" unless [true, false].include?(value)
221
+
222
+ value
223
+ end
224
+
225
+ def self.callable(option, value)
226
+ raise ConfigurationError, "#{option}: must be a callable, found a #{value.class}" unless value.nil? || value.respond_to?(:call)
227
+
228
+ value
229
+ end
230
+
231
+ def self.telemetry(sinks, on_sink_error)
232
+ Telemetry.build(sinks: sinks, on_sink_error: on_sink_error)
233
+ rescue Telemetry::ConfigurationError => error
234
+ raise ConfigurationError, error.message
235
+ end
236
+
237
+ def self.text?(value)
238
+ value.is_a?(String) && !value.strip.empty?
239
+ end
240
+
241
+ def self.key?(value)
242
+ (value.is_a?(Symbol) || value.is_a?(String)) && !value.empty?
243
+ end
244
+
245
+ # A lambda or method with no required parameter, or a block proc that names none.
246
+ def self.no_arguments?(callable)
247
+ target = callable.is_a?(Proc) || callable.is_a?(Method) ? callable : callable.method(:call)
248
+ parameters = target.parameters
249
+ return false if parameters.any? { |type, _| %i[req keyreq].include?(type) }
250
+
251
+ !(target.is_a?(Proc) && !target.lambda? && parameters.any?)
252
+ rescue NameError
253
+ false
254
+ end
255
+
256
+ private_class_method :check_store, :check_encoder, :check_viewer, :check_anonymous, :check_vary, :check_own_checks, :reasons, :positive, :viewer_ttl,
257
+ :boolean, :callable, :telemetry, :text?, :key?, :no_arguments?
258
+ end
259
+ end
260
+ end
261
+ end
262
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ module Integration
7
+ # Included in the schema's query class (`Guard#query_class`).
8
+ #
9
+ # - `current_trace`: the guard builds queries before the multiplex exists, and graphql-ruby memoizes a standalone
10
+ # trace for a query traced then (`query.rb` `current_trace`). Before the multiplex is bound this answers the
11
+ # context's `:trace` or a throwaway trace, unmemoized, so the run traces with the multiplex.
12
+ # - `result`: a hit's query never ran; `query.result` answers the hit's Result instead of running it.
13
+ module Query
14
+ WRAPPERS = {}.compare_by_identity
15
+ LOCK = Mutex.new
16
+
17
+ # A subclass of `klass` that includes this module, the same one for the same `klass` every time, and `klass`
18
+ # itself when it already includes it.
19
+ def self.wrap(klass)
20
+ return klass if klass.include?(self)
21
+
22
+ hooks = self
23
+ LOCK.synchronize do
24
+ WRAPPERS[klass] ||= Class.new(klass) { include hooks }
25
+ end
26
+ end
27
+
28
+ def current_trace
29
+ return super if multiplex
30
+
31
+ context[:trace] || schema.new_trace(multiplex: nil, query: self)
32
+ end
33
+
34
+ def result
35
+ hit = executed? ? nil : Integration.hit_result(self)
36
+ hit || super
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # graphql-ruby's hooks, through its public extension points only (docs/response-caching.md "Installing"):
7
+ #
8
+ # - `Guard`, prepended on the schema's singleton class: `multiplex` and `multiplex_next` (every request sent through
9
+ # `execute`, `execute_next`, `multiplex` and `multiplex_next`), `context_class`, `query_class` and `rescue_from`.
10
+ # - `Query`, included in the schema's query class: `current_trace` before the multiplex and `result` on a hit.
11
+ # - `Install`, behind `Caching.use`, and `Purge`, behind `Caching.purge`.
12
+ module Integration
13
+ def self.install(schema, **options)
14
+ Install.(schema, **options)
15
+ end
16
+
17
+ def self.purge(schema, all: false, viewer: nil, tag: nil, type: nil)
18
+ Purge.(schema, all: all, viewer: viewer, tag: tag, type: type)
19
+ end
20
+
21
+ # One `multiplex`/`multiplex_next` call (4.2): builds each options Hash into a query the way `run_all` would and
22
+ # marks it, hands every query of the call to the gate in order, answers its hits, runs the misses and passes
23
+ # together through `run` (the engine's `super`) and offers each miss's result to the gate. Results come back in
24
+ # the order the queries were given.
25
+ def self.call(schema, queries, engine:, &run)
26
+ check_request(schema)
27
+ settings = schema.armory_caching
28
+ built = queries.map { |options| options.is_a?(Hash) ? build(schema, options) : options }
29
+ decisions = settings.gate.(built, engine: engine)
30
+ check_decisions(decisions, built)
31
+
32
+ results = Array.new(built.size)
33
+ runnable = []
34
+ built.each_with_index do |query, index|
35
+ answer = decisions[index].hit? ? hit_result(query) : nil
36
+ answer ? results[index] = answer : runnable << index
37
+ end
38
+ unless runnable.empty?
39
+ ran = run.call(runnable.map { |index| built[index] })
40
+ runnable.each_with_index { |index, position| results[index] = ran[position] }
41
+ end
42
+
43
+ runnable.each { |index| settings.gate.store(built[index], decisions[index], results[index]) if decisions[index].miss? }
44
+ results
45
+ end
46
+
47
+ # The Result the gate answered a hit with. Only for a query the guard built: the gate never decides on another,
48
+ # and a hit whose Result is missing runs uncached rather than being answered from anything else.
49
+ def self.hit_result(query)
50
+ context = query.context
51
+ RecordKeys.guard_built?(context) ? RecordKeys.hit_result(context) : nil
52
+ end
53
+
54
+ # Options that change what a query runs or sees in ways the gate cannot read back from the query through public
55
+ # readers (a `warden:` on a schema without visibility profiles, an app validator, a root object). A query built
56
+ # with any of them set is left unmarked, so the gate passes it through (`:built_query`). `execute_next` sends
57
+ # `warden: nil` and `root_value: nil` on every request: only a value counts.
58
+ UNMARKED_OPTIONS = %i[warden static_validator root_value use_visibility_profile].freeze
59
+
60
+ # The same construction `run_all` makes for an options Hash, so PersistedQueries, Versioning and the recorder
61
+ # decide here, before the gate looks at the query.
62
+ def self.build(schema, options)
63
+ query = schema.query_class.new(schema, nil, **options)
64
+ RecordKeys.guard_built!(query.context) if markable?(options)
65
+ query
66
+ end
67
+
68
+ def self.markable?(options)
69
+ UNMARKED_OPTIONS.none? { |name| !options[name].nil? } && options[:validate] != false
70
+ end
71
+
72
+ def self.check_request(schema)
73
+ unless schema.respond_to?(:armory_persisted_queries)
74
+ raise ConfigurationError, "#{schema} uses GraphQL::Armory::Caching without GraphQL::Armory::PersistedQueries: only persisted " \
75
+ "operations are cached. Add `use GraphQL::Armory::PersistedQueries` to the schema"
76
+ end
77
+
78
+ unwrapped = Handlers.unwrapped(schema)
79
+ return unless unwrapped
80
+
81
+ raise ConfigurationError, "#{unwrapped} registered a rescue_from handler after GraphQL::Armory::Caching was installed on #{schema}, " \
82
+ "where caching cannot wrap it: a run that handler answered could be stored. Register it on #{schema}"
83
+ end
84
+
85
+ def self.check_decisions(decisions, queries)
86
+ return if decisions.is_a?(Array) && decisions.size == queries.size && decisions.all?(Decision)
87
+
88
+ raise Error, "the cache gate must answer one Decision per query, in order"
89
+ end
90
+ private_class_method :markable?, :check_request, :check_decisions
91
+
92
+ # The `rescue_from` handlers: each one registered after `use` is wrapped, so a run a handler answered is flagged
93
+ # (`RecordKeys.rescued!`) and never stored. A handler caching cannot wrap is refused: before `use` at boot, on a
94
+ # parent after `use` at the first request.
95
+ module Handlers
96
+ MARK = :@armory_caching_rescue
97
+
98
+ def self.wrap(handler)
99
+ wrapper = proc do |*arguments|
100
+ context = arguments.find { |argument| argument.is_a?(GraphQL::Query::Context) }
101
+ RecordKeys.rescued!(context) if context
102
+ handler.call(*arguments)
103
+ end
104
+ wrapper.instance_variable_set(MARK, true)
105
+ wrapper
106
+ end
107
+
108
+ # Whether the schema or a parent registered any handler (read through the public `error_handlers`).
109
+ def self.registered?(schema)
110
+ hierarchy(schema).any? { |member| handlers_in(member.error_handlers).any? }
111
+ end
112
+
113
+ # The schema of the hierarchy holding a handler that is not a wrapper, or nil.
114
+ def self.unwrapped(schema)
115
+ hierarchy(schema).find { |member| handlers_in(member.error_handlers).any? { |handler| !handler.instance_variable_defined?(MARK) } }
116
+ end
117
+
118
+ def self.hierarchy(schema)
119
+ members = []
120
+ member = schema
121
+ while member.respond_to?(:error_handlers)
122
+ members << member
123
+ member = member.superclass
124
+ end
125
+ members
126
+ end
127
+
128
+ def self.handlers_in(node)
129
+ node[:subclass_handlers].each_value.flat_map { |entry| [entry[:handler], *handlers_in(entry)].compact }
130
+ end
131
+ private_class_method :hierarchy, :handlers_in
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
137
+
138
+ require "graphql/armory/caching/integration/install"
139
+ require "graphql/armory/caching/integration/guard"
140
+ require "graphql/armory/caching/integration/query"
141
+ require "graphql/armory/caching/purge"
@@ -0,0 +1,208 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # Builds a request's `Key`: a keyed digest over the canonical JSON of every input the answer may depend
7
+ # on that graphql-ruby can see, so no component is ever in clear and none can forge a separator:
8
+ #
9
+ # ["armory-cache/2", release, schema name, schema digest, engine, document digest, selected operation name,
10
+ # declared variables, version label, visibility profile, max_depth, max_complexity, scope, viewer, vary]
11
+ #
12
+ # keyer = Keyer.build(release: ENV.fetch("GIT_SHA"), digester: Digester.build(encoder: AppEncoder),
13
+ # viewer: :current_user, vary: { locale: :locale, tenant: -> { Current.tenant&.id } })
14
+ # keyer.(query, policy, engine: :interpreter) # => Key, or Policy.refused(reason)
15
+ # keyer.covered_keys(policy) # => [:current_user, :locale]: the context reads the key holds
16
+ # keyer.viewer_tag_for(user) # => the digest of the viewer's purge tag (`:anonymous` too)
17
+ #
18
+ # Refusals: the policy's own (a refused policy is answered as it is), `:unconfigured` (an inert keyer), `:operation`
19
+ # (no operation selected), `:variables` (a declared variable's value is not JSON), `:viewer_unconfigured` and
20
+ # `:anonymous` (a `:viewer` policy with no `viewer:` key, or an anonymous request under `anonymous: :uncacheable`),
21
+ # `:vary_value` (a `vary:` value of a type the key cannot hold), `:version` (a refused version), `:schema_unprintable`
22
+ # (graphql-ruby cannot print the schema: graphql before 2.6 with json 3.x). A principal the key
23
+ # cannot name (an anonymous class, a bad id) raises `ConfigurationError`: that is the app's setup, not the client's.
24
+ #
25
+ # The engine comes from the caller (the gate is told it per `multiplex` call): a query does not know it before it runs.
26
+ # `new` is inert: it refuses every key, like `Keyer::Null`.
27
+ class Keyer
28
+ FORMAT = "armory-cache/2"
29
+ ENGINES = %i[interpreter next].freeze
30
+
31
+ # Validates `use`'s `release:`, `viewer:`, `viewer_id:`, `anonymous:`, `anonymous_reason:` and `vary:`; the
32
+ # `digester:` is the one the gate digests tags and purges with, so a viewer tag here matches a purge.
33
+ def self.build(release:, digester:, viewer: nil, viewer_id: Viewer::DEFAULT_ID, anonymous: :uncacheable, anonymous_reason: nil, vary: {})
34
+ raise ConfigurationError, "release: must be a non-empty String (the deploy's identity, such as the git SHA)" unless release.is_a?(String) && !release.strip.empty?
35
+ raise ConfigurationError, "digester: must answer call(string) with a keyed hex digest (a Caching::Digester)" unless digester.respond_to?(:call)
36
+
37
+ new(release: release.dup.freeze,
38
+ digester: digester,
39
+ viewer: Viewer.build(key: viewer, id: viewer_id, anonymous: anonymous, anonymous_reason: anonymous_reason),
40
+ vary: Vary.build(vary))
41
+ end
42
+
43
+ attr_reader :schema_identity
44
+
45
+ def initialize(release: nil, digester: nil, viewer: Viewer.new, vary: Vary.new, schema_identity: SchemaIdentity.new)
46
+ @release = release
47
+ @digester = digester
48
+ @viewer = viewer
49
+ @vary = vary
50
+ @schema_identity = schema_identity
51
+ end
52
+
53
+ def call(query, policy, engine:)
54
+ raise ArgumentError, "engine: must be one of #{ENGINES.inspect}, got #{engine.inspect}" unless ENGINES.include?(engine)
55
+ return policy unless policy.cacheable?
56
+ return Policy.refused(:unconfigured) unless configured?
57
+
58
+ operation = query.selected_operation
59
+ return Policy.refused(:operation) if operation.nil?
60
+
61
+ variables = refusing(:variables) { Canonical.variables(operation, query.provided_variables) }
62
+ return variables if variables.is_a?(Policy)
63
+
64
+ viewer = nil
65
+ if policy.scope == :viewer
66
+ viewer = @viewer.(query.context)
67
+ return viewer if viewer.is_a?(Policy)
68
+ end
69
+
70
+ vary = refusing(:vary_value) { @vary.(query.context) }
71
+ return vary if vary.is_a?(Policy)
72
+
73
+ label = version_label(query)
74
+ return label if label.is_a?(Policy)
75
+
76
+ profile = profile_name(query)
77
+ schema = query.schema
78
+ schema_digest = begin
79
+ @schema_identity.schema_digest(schema, label, profile)
80
+ rescue SchemaIdentity::Unprintable
81
+ return Policy.refused(:schema_unprintable)
82
+ end
83
+ components = [
84
+ FORMAT, @release, schema.name, schema_digest, engine.to_s,
85
+ @schema_identity.document_digest(query.document), operation.name, variables, label,
86
+ profile.nil? ? nil : Canonical.typed(profile), limit(query.max_depth, :max_depth), limit(query.max_complexity, :max_complexity),
87
+ policy.scope.to_s, viewer&.component, vary
88
+ ]
89
+
90
+ Key.new(digest: @digester.(Canonical.json(components)), scope: policy.scope, viewer_tag: viewer && @digester.(viewer.tag))
91
+ end
92
+
93
+ # The context keys a `:viewer` or `:public` run may read because the key holds their whole value: the `viewer:` key
94
+ # for a `:viewer` policy only, and each `vary:` entry given as a context key. A `vary:` callable covers nothing.
95
+ def covered_keys(policy)
96
+ keys = @vary.context_keys
97
+ keys = [@viewer.key, *keys] if policy.scope == :viewer && !@viewer.key.nil?
98
+ keys.uniq.freeze
99
+ end
100
+
101
+ # The `viewer:` context key (nil when none is configured): covered for `:viewer` policies only.
102
+ def viewer_key = @viewer.key
103
+
104
+ # The `vary:` entries given as context keys, sorted by name: each is covered for every policy. Callables are not.
105
+ def vary_context_keys = @vary.context_keys.freeze
106
+
107
+ # The keyed digest of a principal's purge tag (or of every anonymous request, `:anonymous`): what `Key#viewer_tag`
108
+ # holds for that principal, so a purge finds its entries.
109
+ def viewer_tag_for(principal)
110
+ raise ConfigurationError, "this keyer is not built: Keyer.build(release:, digester:, ...)" unless configured?
111
+
112
+ @digester.(@viewer.tag(principal))
113
+ end
114
+
115
+ def inspect = "#<#{self.class.name} viewer=#{@viewer.key.inspect} vary=#{@vary.names.inspect}>"
116
+
117
+ private
118
+
119
+ def configured?
120
+ !@release.nil? && !@digester.nil?
121
+ end
122
+
123
+ def refusing(reason)
124
+ yield
125
+ rescue Canonical::Unsupported
126
+ Policy.refused(reason)
127
+ end
128
+
129
+ # The resolved label (`Versioning.version`), not the client's raw value; nil on a schema without Versioning.
130
+ def version_label(query)
131
+ return nil unless query.schema.respond_to?(:armory_versioning)
132
+
133
+ Versioning.version(query.context).label
134
+ rescue Versioning::RefusedVersionError
135
+ Policy.refused(:version)
136
+ end
137
+
138
+ # The named `Schema::Visibility` profile the query runs under, or nil (a dynamic profile, or the Warden).
139
+ def profile_name(query)
140
+ profile = query.respond_to?(:visibility_profile) ? query.visibility_profile : nil
141
+ profile.respond_to?(:name) ? profile.name : nil
142
+ end
143
+
144
+ def limit(value, name)
145
+ return value if value.nil? || value.is_a?(Integer) || (value.is_a?(Float) && value.finite?)
146
+
147
+ raise ConfigurationError, "#{name} is a #{value.class}: the key holds an Integer, a finite Float or nil"
148
+ end
149
+
150
+ # `vary:`: name => context key (its whole value enters the key and covers that key) or name => callable taking no
151
+ # arguments (for inputs graphql-ruby cannot see, such as `Current` or `I18n.locale`; it covers nothing). Values
152
+ # enter the key with their type, sorted by name; an absent context key is not a nil one.
153
+ class Vary
154
+ Entry = Struct.new(:name, :source, keyword_init: true) do
155
+ def context_key? = source.is_a?(Symbol) || source.is_a?(String)
156
+ end
157
+
158
+ def self.build(vary)
159
+ raise ConfigurationError, "vary: must be a Hash of name => context key or callable" unless vary.is_a?(Hash)
160
+
161
+ entries = vary.map do |name, source|
162
+ unless (name.is_a?(Symbol) || name.is_a?(String)) && !name.to_s.empty?
163
+ raise ConfigurationError, "vary: names must be non-empty Symbols or Strings, got #{name.inspect}"
164
+ end
165
+
166
+ Entry.new(name: name.to_s.freeze, source: source(name, source))
167
+ end
168
+ duplicate = entries.map(&:name).tally.find { |_, count| count > 1 }
169
+ raise ConfigurationError, "vary: names #{duplicate.first.inspect} twice (as a Symbol and a String)" if duplicate
170
+
171
+ new(entries.sort_by(&:name))
172
+ end
173
+
174
+ def self.source(name, source)
175
+ return source if (source.is_a?(Symbol) || source.is_a?(String)) && !source.to_s.empty?
176
+
177
+ arity = if source.respond_to?(:arity) then source.arity
178
+ elsif source.respond_to?(:call) then source.method(:call).arity
179
+ end
180
+ return source if [0, -1].include?(arity)
181
+
182
+ raise ConfigurationError, "vary: #{name.inspect} must be a context key (Symbol or String) or a callable taking no arguments"
183
+ end
184
+ private_class_method :source
185
+
186
+ def initialize(entries = [])
187
+ @entries = entries.freeze
188
+ end
189
+
190
+ def names = @entries.map(&:name)
191
+
192
+ def context_keys = @entries.select(&:context_key?).map(&:source)
193
+
194
+ # `[[name, typed value], ...]`; raises `Canonical::Unsupported` for a value of another type.
195
+ def call(context)
196
+ @entries.map do |entry|
197
+ value = if !entry.context_key? then Canonical.typed(entry.source.call)
198
+ elsif context.key?(entry.source) then Canonical.typed(context[entry.source])
199
+ else ["absent"]
200
+ end
201
+ [entry.name, value]
202
+ end
203
+ end
204
+ end
205
+ end
206
+ end
207
+ end
208
+ end