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,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ class Gate
7
+ # What the gate reports for each query: one signal through Telemetry, and the controller's record
8
+ # `{ status:, reason:, scope:, ttl:, age: }` in `context[:response_cache]` (docs/response-caching.md "Signals").
9
+ #
10
+ # No signal and no record holds a key, a viewer, a variable, a document, an operation id or name, or a tag:
11
+ # only reasons, scopes, TTLs, ages, the store operation and an error's class name.
12
+ class Signals
13
+ def initialize(telemetry)
14
+ @telemetry = telemetry
15
+ end
16
+
17
+ def hit(query, entry, now, limited:)
18
+ @telemetry.record(:cache_hit, context: query.context, scope: entry.scope)
19
+ write(query, status: :hit, reason: limited ? :rate_limited : nil, scope: entry.scope, ttl: entry.ttl, age: entry.age(now))
20
+ end
21
+
22
+ def stored(query, scope, ttl)
23
+ @telemetry.record(:cache_stored, context: query.context, scope: scope, ttl: ttl)
24
+ write(query, status: :stored, scope: scope, ttl: ttl)
25
+ end
26
+
27
+ # `key` only for `:context_read` and `:context_written`, and only when it has a name.
28
+ def skipped(query, reason, scope: nil, key: nil)
29
+ data = key.nil? ? { reason: reason } : { reason: reason, key: key }
30
+ @telemetry.record(:cache_skipped, context: context_of(query), **data)
31
+ write(query, status: :skipped, reason: reason, scope: scope)
32
+ end
33
+
34
+ def rejected(query, reason)
35
+ @telemetry.record(:cache_entry_rejected, context: query.context, reason: reason)
36
+ end
37
+
38
+ # The error's class only: its message may quote the store's URL and credentials.
39
+ def store_failed(query, operation, error, scope: nil)
40
+ @telemetry.record(:cache_store_failed, context: query.context, operation: operation, error: error.class.name.to_s)
41
+ write(query, status: :skipped, reason: :store_failed, scope: scope)
42
+ end
43
+
44
+ private
45
+
46
+ def context_of(query)
47
+ query.respond_to?(:context) ? query.context : nil
48
+ end
49
+
50
+ # Written without recording it: the record is the gate's, not a value the run's answer depends on. A query
51
+ # the app built itself is passed through untouched: no record goes into its context.
52
+ def write(query, status:, reason: nil, scope: nil, ttl: nil, age: nil)
53
+ return unless Admission.guard_built?(query)
54
+
55
+ context = query.context
56
+
57
+ Caching.neutral(context) do
58
+ RecordKeys.record!(context, { status: status, reason: reason, scope: scope, ttl: ttl, age: age })
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ class Gate
7
+ # What a miss's run must show before its answer is stored (docs/response-caching.md "What is cached and when"). Each check
8
+ # answers nil (it holds) or a reason; the gate stores only when every one holds.
9
+ module StoreCheck
10
+ # The only response extension a stored run may carry: the limiters' own, which is never stored.
11
+ EXTENSIONS = %w[rateLimit].freeze
12
+
13
+ module_function
14
+
15
+ # The response itself: no errors, a Hash of data, nothing but JSON-native values in it (a hit must equal the
16
+ # miss: a Symbol or a Time would come back as text), and no extension but the limiters'.
17
+ def response(values)
18
+ return :errors if values.key?("errors")
19
+
20
+ data = values["data"]
21
+ return :no_data unless data.is_a?(Hash)
22
+ return :non_json_data unless json_native?(data)
23
+
24
+ extensions = values["extensions"]
25
+ return :extensions unless extensions.nil? || (extensions.is_a?(Hash) && (extensions.keys - EXTENSIONS).empty?)
26
+
27
+ nil
28
+ end
29
+
30
+ def json_native?(value)
31
+ case value
32
+ when String, Integer, true, false, nil then true
33
+ when Float then value.finite?
34
+ when Array then value.all? { |inner| json_native?(inner) }
35
+ when Hash then value.all? { |key, inner| key.is_a?(String) && json_native?(inner) }
36
+ else false
37
+ end
38
+ end
39
+
40
+ # The context reads and writes the recorder saw, against the keys the cache key covers. Answers
41
+ # `[reason, key name]`, or nil. Only a Symbol key is named: the app's own key, never one a client chose.
42
+ # `write_guarded` is the covered set a write must not touch (graphql-ruby's own writes left out).
43
+ def recorder(recorder, covered, write_guarded: covered)
44
+ uncovered = recorder.uncovered(covered)
45
+ return [:context_read, nameable(uncovered.first)] unless uncovered.empty?
46
+
47
+ written = recorder.forbidden_writes(write_guarded)
48
+ return [:context_written, nameable(written.first)] unless written.empty?
49
+
50
+ nil
51
+ end
52
+
53
+ def nameable(key)
54
+ key.is_a?(Symbol) && key != Recorder::ALL ? key : nil
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # Decides, per `multiplex` call, which queries are answered from the store, which run and may be stored, and
7
+ # which run uncached:
8
+ #
9
+ # gate.(queries, engine:) -> [Decision] # one per query, in order
10
+ # gate.store(query, decision, result) -> :stored | reason
11
+ class Gate
12
+ # Answers the decisions it is told and records what it saw, for the integration's specs:
13
+ #
14
+ # gate = Gate::Substitute.new
15
+ # gate.decide(Decision.hit(entry), Decision.pass(:mutation)) # consumed in order; then pass(:unconfigured)
16
+ # gate.store_answer(:errors) # what `store` answers (default :stored)
17
+ # gate.seen # => [[queries, engine], ...]
18
+ # gate.stored # => [[query, decision, result], ...]
19
+ class Substitute
20
+ attr_reader :seen, :stored
21
+
22
+ def initialize
23
+ @decisions = []
24
+ @store_answer = :stored
25
+ @seen = []
26
+ @stored = []
27
+ end
28
+
29
+ def decide(*decisions)
30
+ raise ArgumentError, "decide takes Decisions" unless decisions.all?(Decision)
31
+
32
+ @decisions.concat(decisions)
33
+ end
34
+
35
+ def store_answer(answer)
36
+ raise ArgumentError, "store answers :stored or a reason Symbol" unless answer.is_a?(Symbol)
37
+
38
+ @store_answer = answer
39
+ end
40
+
41
+ def call(queries, engine:)
42
+ @seen << [queries, engine]
43
+ queries.map do |query|
44
+ decision = @decisions.shift || Decision.pass(:unconfigured)
45
+ # Like the real gate: every hit's Result is set, so `query.result` answers it without running.
46
+ if decision.hit?
47
+ RecordKeys.hit_result!(query.context, GraphQL::Query::Result.new(query: query, values: { "data" => decision.entry.data }))
48
+ end
49
+ decision
50
+ end
51
+ end
52
+
53
+ def store(query, decision, result)
54
+ @stored << [query, decision, result]
55
+ @store_answer
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,384 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+ require "graphql/armory/caching/gate/admission"
5
+ require "graphql/armory/caching/gate/store_check"
6
+ require "graphql/armory/caching/gate/signals"
7
+
8
+ module GraphQL
9
+ module Armory
10
+ module Caching
11
+ # Decides, per `multiplex` call, which queries are answered from the store, which run and may be stored, and
12
+ # which run uncached (docs/response-caching.md "What is cached and when"):
13
+ #
14
+ # decisions = gate.(queries, engine: :interpreter) # one Decision per query, in order
15
+ # gate.store(query, decision, result) # after a miss ran: :stored, or the reason it was not
16
+ #
17
+ # `Gate.new` is inert: its walk refuses every operation, so every query runs uncached and nothing reaches the
18
+ # store. `Gate.build` wires the real walk, keyer, codec, charge and store from the `use` options.
19
+ class Gate
20
+ ENGINES = %i[interpreter next].freeze
21
+
22
+ # graphql-ruby's own context keys: their values are fixed by the request or are key components (4.4).
23
+ MACHINERY_KEYS = [
24
+ *GraphQL::Query::Context::RUNTIME_METADATA_KEYS,
25
+ :trace, :tracers, :trace_mode, :dataloader, :backtrace, :visibility_profile, :__graphql_execute_next,
26
+ # The APM tracers' transaction name settings (lib/graphql/tracing/*).
27
+ :set_appsignal_action_name, :set_new_relic_transaction_name, :set_scout_transaction_name,
28
+ :set_sentry_transaction_name, :tracing_fallback_transaction_name
29
+ ].freeze
30
+
31
+ # Covered keys graphql-ruby itself writes during a request: `Execution::Next.run_all` sets this marker after
32
+ # building each query. Its value is the engine, which is in the key, so that write never makes an answer stale.
33
+ ENGINE_MARKER = :__graphql_execute_next
34
+ WRITTEN_BY_ENGINE = [ENGINE_MARKER].freeze
35
+
36
+ DEFAULT_ON_STORE_ERROR = ->(error, _query) { warn("graphql-armory cache store failed, query runs uncached: #{error.class}") }
37
+
38
+ # Wires the real dependencies from the checked `use` options (`Integration::Settings#to_h`). `digester:` is the
39
+ # one the installer built: `purge` digests tags with it, so the gate never builds its own. The options only the
40
+ # audit reads (`own_checks:`, `sinks:`, ...) are ignored here.
41
+ def self.build(schema, store:, digester:, telemetry:, release:, encoder: nil, viewer: nil, viewer_id: Viewer::DEFAULT_ID,
42
+ anonymous: :uncacheable, anonymous_reason: nil, vary: {}, max_ttl: 3600, max_viewer_ttl: 300,
43
+ max_entry_bytes: 262_144, neutral_keys: {}, context_methods: {}, extensions: false, on_store_error: nil, **_audit_only)
44
+ check_store_ttl(store, max_ttl)
45
+ keyer = Keyer.build(release: release, digester: digester, viewer: viewer, viewer_id: viewer_id, anonymous: anonymous,
46
+ anonymous_reason: anonymous_reason, vary: vary)
47
+ new(store: store, walk: Walk.build, keyer: keyer, codec: encoder ? Codec.build(encoder: encoder) : Codec.new,
48
+ charge: Charge.build(schema), telemetry: telemetry, digester: digester, max_ttl: max_ttl, max_viewer_ttl: max_viewer_ttl,
49
+ max_entry_bytes: max_entry_bytes, viewer_key: keyer.viewer_key, vary_keys: keyer.vary_context_keys,
50
+ neutral_keys: neutral_keys, context_methods: context_methods, recorded_cost: ->(query) { Charge.recorded_cost(query) },
51
+ extensions: extensions, on_store_error: on_store_error)
52
+ end
53
+
54
+ # A store prunes purge marks older than its own `max_ttl`: an entry living longer than that could outlive the
55
+ # mark that purged it and be served again.
56
+ def self.check_store_ttl(store, max_ttl)
57
+ return unless store.respond_to?(:max_ttl) && store.max_ttl.is_a?(Integer)
58
+ return if store.max_ttl >= max_ttl
59
+
60
+ raise ConfigurationError, "max_ttl: #{max_ttl} exceeds the store's max_ttl: #{store.max_ttl}, after which it prunes purge marks: " \
61
+ "build the store with max_ttl: #{max_ttl} or more"
62
+ end
63
+ private_class_method :check_store_ttl
64
+
65
+ # - `store`, `walk`, `keyer`, `codec`, `charge`, `telemetry`, `digester`: the dependencies (Null by default).
66
+ # `codec` defaults to `Codec.new`, the plain JSON codec, read when the gate is built, never at load time.
67
+ # - `max_ttl`, `max_viewer_ttl` (seconds): a stored TTL never exceeds them, whatever the declarations say.
68
+ # - `max_entry_bytes`: a larger sealed entry is not stored.
69
+ # - `viewer_key`: the `viewer:` context key; it covers reads of that key in `:viewer` runs only.
70
+ # - `vary_keys`: the `vary:` entries given as context keys; their whole value is in the key, so they cover.
71
+ # - `neutral_keys`: the app's answer-neutral keys (`{ request_id: "logging only" }`, or an Array).
72
+ # - `context_methods`: the public methods the app's context class adds, each with a reason. A query whose
73
+ # context class adds a method not named here runs uncached (`:context_method`): it reads unrecorded.
74
+ # - `recorded_cost`: a callable answering the Points the query's run was charged (an Integer), or nil when it
75
+ # recorded none; nil (the default) means no Points limiter. When the charge reports a limiter for the query
76
+ # (`charge.limited?(query)`, or always for a charge without `limited?`), a miss without a cost is not stored
77
+ # and an entry without a cost is never served: a hit would be free.
78
+ # - `extensions`: true adds `"cache" => { "hit" => true, "age" => n }` to a hit's response.
79
+ # - `on_store_error`: called with `(error, query)` when the store raises; the query runs uncached.
80
+ # - `clock`: a callable answering the store clock in Integer milliseconds, for `:run_too_long`. Defaults to
81
+ # `store.now` when the store has one; without it, the store's own refusal of an expired write bounds the run.
82
+ def initialize(store: Store::Null.new, walk: Walk::Null.new, keyer: Keyer::Null.new, codec: Codec.new, charge: Charge::Null.new,
83
+ telemetry: Telemetry.new, digester: Digester.new, max_ttl: 3600, max_viewer_ttl: 300, max_entry_bytes: 262_144,
84
+ viewer_key: nil, vary_keys: [], neutral_keys: {}, context_methods: {}, recorded_cost: nil, extensions: false,
85
+ on_store_error: nil, clock: nil)
86
+ positive!(:max_ttl, max_ttl)
87
+ positive!(:max_viewer_ttl, max_viewer_ttl)
88
+ positive!(:max_entry_bytes, max_entry_bytes)
89
+ raise ConfigurationError, "viewer_key: must be a context key (Symbol or String) or nil" unless viewer_key.nil? || context_key?(viewer_key)
90
+ raise ConfigurationError, "vary_keys: must be an Array of context keys (Symbols or Strings)" unless vary_keys.is_a?(Array) && vary_keys.all? { |key| context_key?(key) }
91
+
92
+ neutral = neutral_keys.is_a?(Hash) ? neutral_keys.keys : neutral_keys
93
+ raise ConfigurationError, "neutral_keys: must be a Hash of context key => reason" unless neutral.is_a?(Array) && neutral.all? { |key| context_key?(key) }
94
+
95
+ declared = context_methods.is_a?(Hash) ? context_methods.keys : context_methods
96
+ raise ConfigurationError, "context_methods: must be a Hash of method name => reason" unless declared.is_a?(Array) && declared.all? { |name| context_key?(name) }
97
+
98
+ callable!(:recorded_cost, recorded_cost)
99
+ callable!(:on_store_error, on_store_error)
100
+ callable!(:clock, clock)
101
+ raise ConfigurationError, "extensions: must be true or false" unless [true, false].include?(extensions)
102
+
103
+ @store = store
104
+ @walk = walk
105
+ @keyer = keyer
106
+ @keyer_takes_engine = takes_engine?(keyer)
107
+ @codec = codec
108
+ @charge = charge
109
+ @digester = digester
110
+ @signals = Signals.new(telemetry)
111
+ @max_ttl = max_ttl
112
+ @max_viewer_ttl = max_viewer_ttl
113
+ @max_entry_bytes = max_entry_bytes
114
+ @recorded_cost = recorded_cost
115
+ @context_methods = declared.map(&:to_sym).freeze
116
+ @undeclared = {}.compare_by_identity
117
+ @undeclared_lock = Mutex.new
118
+ @extensions = extensions
119
+ @on_store_error = on_store_error || DEFAULT_ON_STORE_ERROR
120
+ @clock = clock || (store.respond_to?(:now) ? -> { store.now } : nil)
121
+
122
+ always = [*MACHINERY_KEYS, *Admission::ABSENT_KEYS.keys, *neutral, *vary_keys]
123
+ @covered = {
124
+ public: Set.new(always).freeze,
125
+ viewer: Set.new(always + [viewer_key].compact).freeze
126
+ }.freeze
127
+ @write_guarded = @covered.transform_values { |keys| (keys - WRITTEN_BY_ENGINE).freeze }.freeze
128
+ end
129
+
130
+ # One Decision per query, in order: hit (answered: `RecordKeys.hit_result` holds its Result), miss (run it,
131
+ # then `store`), or pass (run it uncached). `engine` is `:interpreter` or `:next`: it is in the key.
132
+ def call(queries, engine:)
133
+ raise ArgumentError, "engine: must be one of #{ENGINES.inspect}, got #{engine.inspect}" unless ENGINES.include?(engine)
134
+
135
+ mutation = queries.any? { |query| Admission.mutation?(query) }
136
+ queries.map { |query| decide(query, engine, mutation) }
137
+ end
138
+
139
+ # After a miss ran: stores its answer when every store-time check holds. Answers `:stored` or the reason it
140
+ # was not stored; for a hit or a pass, answers without storing anything.
141
+ def store(query, decision, result)
142
+ return decision.pass? ? decision.reason : :hit unless decision.miss?
143
+
144
+ key = decision.key
145
+ lookup = decision.lookup
146
+ scope = key.scope
147
+ reason, context_key = refusal(query, decision, values_of(result))
148
+ return skip(query, reason, scope, context_key) if reason
149
+
150
+ ttl = capped_ttl(decision.policy.ttl, scope)
151
+ costed = costed?(query)
152
+ cost = costed ? @recorded_cost.call(query) : nil
153
+ return skip(query, :cost_unknown, scope) if costed && !(cost.is_a?(Integer) && cost >= 0)
154
+ return skip(query, :run_too_long, scope) if run_too_long?(lookup)
155
+
156
+ tags = (decision.policy.tags.map { |tag| @digester.(tag) } + [key.viewer_tag].compact).uniq.sort
157
+ entry = Entry.new(key: key.digest, data: values_of(result)["data"], stored_at: lookup.now, ttl: ttl, scope: scope,
158
+ seq: lookup.seq, epoch: lookup.epoch, tags: tags, cost: cost, copy: false)
159
+ # Sealed at once: the run's answer is not copied, and the app's later changes to it never reach the store.
160
+ blob = encode(query, entry, key, scope)
161
+ return blob if blob.is_a?(Symbol)
162
+ return skip(query, :too_large, scope) if blob.bytesize > @max_entry_bytes
163
+
164
+ write(query, key, blob, entry, scope)
165
+ end
166
+
167
+ private
168
+
169
+ def decide(query, engine, mutation)
170
+ reason = Admission.refusal(query, mutation_in_call: mutation)
171
+ return pass(query, reason) if reason
172
+ return pass(query, :context_method) unless undeclared_methods(query.context.class).empty?
173
+
174
+ policy = @walk.(query)
175
+ return pass(query, refusal_reason(policy)) unless policy.is_a?(Policy) && policy.cacheable?
176
+
177
+ key = @keyer_takes_engine ? @keyer.(query, policy, engine: engine) : @keyer.(query, policy)
178
+ return pass(query, refusal_reason(key)) unless key.is_a?(Key)
179
+ # The key decides who an answer is served to: it must be scoped like the policy that allows it.
180
+ return pass(query, :key_scope, policy.scope) unless key.scope == policy.scope
181
+
182
+ lookup = look_up(query, key)
183
+ return Decision.pass(:store_failed) unless lookup
184
+ return Decision.miss(key, policy, lookup) unless lookup.found?
185
+
186
+ entry, rejection = open(query, lookup, key)
187
+ if rejection
188
+ @signals.rejected(query, rejection)
189
+ return Decision.miss(key, policy, lookup)
190
+ end
191
+
192
+ hit(query, entry, lookup)
193
+ end
194
+
195
+ def pass(query, reason, scope = nil)
196
+ @signals.skipped(query, reason, scope: scope)
197
+ Decision.pass(reason)
198
+ end
199
+
200
+ def refusal_reason(answer)
201
+ answer.is_a?(Policy) && answer.reason.is_a?(Symbol) ? answer.reason : :unconfigured
202
+ end
203
+
204
+ # One round trip; nil when the store failed (reported).
205
+ def look_up(query, key)
206
+ lookup = @store.lookup(key.digest)
207
+ raise TypeError, "the store's lookup answered a #{lookup.class}, not a Lookup" unless lookup.is_a?(Lookup)
208
+
209
+ lookup
210
+ rescue StandardError => error
211
+ failed(query, :lookup, error, key.scope)
212
+ nil
213
+ end
214
+
215
+ # The entry, or the reason it must not be served. A poisoned blob is a miss, whatever the codec raised.
216
+ def open(query, lookup, key)
217
+ entry = @codec.decode(lookup.blob, key.digest)
218
+ [entry, rejection(query, entry, lookup, key)]
219
+ rescue Entry::Rejected => rejected
220
+ [nil, rejected.reason]
221
+ rescue StandardError
222
+ [nil, :format]
223
+ end
224
+
225
+ def rejection(query, entry, lookup, key)
226
+ return :key unless entry.key == key.digest && entry.scope == key.scope
227
+ # A lost meta record (another epoch), or a replica behind the entry's seq: everything older is purged.
228
+ return :epoch unless entry.epoch == lookup.epoch && entry.seq <= lookup.seq
229
+ return :expired if entry.expired?(lookup.now)
230
+ # The store keeps the tags beside the sealed blob only to read their marks; the sealed list is the truth.
231
+ return :tags unless entry.tags == lookup.tags.uniq.sort
232
+ return :purged if lookup.marks.any? { |_tag, mark| mark > entry.seq }
233
+ return :cost_unknown if entry.cost.nil? && costed?(query)
234
+
235
+ nil
236
+ end
237
+
238
+ def hit(query, entry, lookup)
239
+ refusal = @charge.(query, entry.cost)
240
+ result = refusal.nil? ? cached_result(query, entry, lookup) : refusal_result(query, refusal)
241
+ RecordKeys.hit_result!(query.context, result)
242
+ @signals.hit(query, entry, lookup.now, limited: !refusal.nil?)
243
+ Decision.hit(entry)
244
+ end
245
+
246
+ def cached_result(query, entry, lookup)
247
+ values = { "data" => entry.data }
248
+ extensions = query.context.namespace?(:__query_result_extensions__) ? query.context.response_extensions.dup : {}
249
+ extensions["cache"] = { "hit" => true, "age" => entry.age(lookup.now) } if @extensions
250
+ values["extensions"] = extensions unless extensions.empty?
251
+ GraphQL::Query::Result.new(query: query, values: values)
252
+ end
253
+
254
+ # The limiter's refusal, in the shape the charge answered it: a Result, a response Hash, or the error itself.
255
+ def refusal_result(query, refusal)
256
+ case refusal
257
+ when GraphQL::Query::Result then refusal
258
+ when Hash then GraphQL::Query::Result.new(query: query, values: refusal)
259
+ when GraphQL::ExecutionError
260
+ values = { "errors" => [refusal.to_h] }
261
+ values["extensions"] = query.context.response_extensions.dup if query.context.namespace?(:__query_result_extensions__)
262
+ GraphQL::Query::Result.new(query: query, values: values)
263
+ else
264
+ raise ArgumentError, "the charge answered a #{refusal.class}: expected nil, a Result, a response Hash or a GraphQL::ExecutionError"
265
+ end
266
+ end
267
+
268
+ def values_of(result)
269
+ values = result.respond_to?(:to_h) ? result.to_h : result
270
+ values.is_a?(Hash) ? values : {}
271
+ end
272
+
273
+ # Every store-time check of 4.2 step 8 that reads the run, in order. Answers `[reason, key name]` or nil.
274
+ def refusal(query, decision, values)
275
+ reason = StoreCheck.response(values)
276
+ return [reason] if reason
277
+ return [:rescued] if RecordKeys.rescued?(query.context)
278
+
279
+ recorder = RecordKeys.recorder(query.context) || Recorder::Null.new
280
+ scope = decision.key.scope
281
+ checked = StoreCheck.recorder(recorder, @covered.fetch(scope), write_guarded: @write_guarded.fetch(scope))
282
+ return checked if checked
283
+ return [:context_written, ENGINE_MARKER] unless engine_marker_kept?(query.context)
284
+ return [:policy_consulted] if decision.key.scope == :public && RecordKeys.viewer_dependent?(query.context)
285
+
286
+ nil
287
+ end
288
+
289
+ def capped_ttl(ttl, scope)
290
+ ttl = [ttl, @max_ttl].min
291
+ scope == :viewer ? [ttl, @max_viewer_ttl].min : ttl
292
+ end
293
+
294
+ # Purge marks older than max_ttl may already be pruned: a write that long after its lookup could undo one.
295
+ def run_too_long?(lookup)
296
+ now = @clock&.call
297
+ now.is_a?(Integer) && now - lookup.now > @max_ttl * 1000
298
+ end
299
+
300
+ def write(query, key, blob, entry, scope)
301
+ written = @store.write(key.digest, blob, tags: entry.tags, ttl: entry.ttl, seq: entry.seq, epoch: entry.epoch, stored_at: entry.stored_at)
302
+ return skip(query, :write_refused, scope) unless written == true
303
+
304
+ @signals.stored(query, scope, entry.ttl)
305
+ :stored
306
+ rescue StandardError => error
307
+ failed(query, :write, error, scope)
308
+ :store_failed
309
+ end
310
+
311
+ # The sealed entry, or `:unencodable` when the answer cannot be written as JSON (invalid UTF-8, nesting too
312
+ # deep): the query already ran, and its answer is returned uncached.
313
+ def encode(query, entry, key, scope)
314
+ @codec.encode(entry, key.digest)
315
+ rescue JSON::GeneratorError, JSON::NestingError, EncodingError
316
+ skip(query, :unencodable, scope)
317
+ end
318
+
319
+ def skip(query, reason, scope, key = nil)
320
+ @signals.skipped(query, reason, scope: scope, key: key)
321
+ reason
322
+ end
323
+
324
+ def failed(query, operation, error, scope)
325
+ @signals.store_failed(query, operation, error, scope: scope)
326
+ begin
327
+ @on_store_error.call(error, query)
328
+ rescue StandardError => handler_error
329
+ warn("graphql-armory cache on_store_error raised, query runs uncached: #{handler_error.class}")
330
+ end
331
+ end
332
+
333
+ # The engine marker's write is exempt only while it holds what `Execution::Next` writes (true) or nothing: any
334
+ # other value was written by the app, and could carry an input the key does not hold.
335
+ def engine_marker_kept?(context)
336
+ value = Caching.neutral(context) { context[ENGINE_MARKER] }
337
+ value.nil? || value == true
338
+ end
339
+
340
+ # Whether this query's hits must be charged a recorded cost. Looked up per query: Points may be `use`d after
341
+ # Caching, and a subclass may add its own limiter.
342
+ def costed?(query)
343
+ return false unless @recorded_cost
344
+
345
+ !@charge.respond_to?(:limited?) || @charge.limited?(query)
346
+ end
347
+
348
+ # The added public methods of a context class the app did not declare. Memoized per class with its methods'
349
+ # signature, so a method added after the class's first query is still counted.
350
+ def undeclared_methods(klass)
351
+ return [] unless klass.is_a?(Class) && klass <= GraphQL::Query::Context
352
+
353
+ signature = ContextMethods.signature(klass)
354
+ memo = @undeclared[klass]
355
+ return memo.last if memo && memo.first == signature
356
+
357
+ found = ContextMethods.undeclared(klass, @context_methods).freeze
358
+ @undeclared_lock.synchronize { @undeclared[klass] = [signature, found].freeze }
359
+ found
360
+ end
361
+
362
+ # Whether the keyer's `call` takes the engine: a keyword `engine:`, `**`, or `*arguments` (a Substitute).
363
+ def takes_engine?(keyer)
364
+ callable = keyer.is_a?(Proc) || keyer.is_a?(Method) ? keyer : keyer.method(:call)
365
+ callable.parameters.any? { |type, name| (%i[key keyreq].include?(type) && name == :engine) || %i[keyrest rest].include?(type) }
366
+ rescue NameError
367
+ false
368
+ end
369
+
370
+ def context_key?(key)
371
+ key.is_a?(Symbol) || key.is_a?(String)
372
+ end
373
+
374
+ def positive!(name, value)
375
+ raise ConfigurationError, "#{name}: must be a positive Integer, got #{value.class}" unless value.is_a?(Integer) && value.positive?
376
+ end
377
+
378
+ def callable!(name, value)
379
+ raise ConfigurationError, "#{name}: must be a callable or nil, got #{value.class}" unless value.nil? || value.respond_to?(:call)
380
+ end
381
+ end
382
+ end
383
+ end
384
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ module Integration
7
+ # Prepended on the schema's singleton class by `use`. Every request funnels through `multiplex` or
8
+ # `multiplex_next` (2.1); the class readers keep the recorder and the query hooks in whatever class the schema
9
+ # uses, set before or after `use`; `rescue_from` wraps each handler so a rescued run is flagged.
10
+ module Guard
11
+ UNSET = Object.new.freeze
12
+
13
+ # A Next-default schema's `multiplex` is routed by graphql-ruby to `multiplex_next` (on the same condition,
14
+ # `schema.rb` `multiplex`), where the gate runs once, labelled `:next`: running it here too would decide twice.
15
+ def multiplex(queries, **kwargs)
16
+ return super if @default_execution_next
17
+
18
+ Integration.(self, queries, engine: :interpreter) { |runnable| super(runnable, **kwargs) }
19
+ end
20
+
21
+ # Exists only with `use GraphQL::Execution::Next`, which defines the method this calls.
22
+ def multiplex_next(queries, **kwargs)
23
+ raise NoMethodError, "undefined method 'multiplex_next' for #{self}: it needs `use GraphQL::Execution::Next`" unless defined?(super)
24
+
25
+ Integration.(self, queries, engine: :next) { |runnable| super(runnable, **kwargs) }
26
+ end
27
+
28
+ # Reads and writes always answer a recording class (`Recorder::Context.wrap`, the same wrapper per class).
29
+ def context_class(new_context_class = nil)
30
+ return Recorder::Context.wrap(super()) if new_context_class.nil?
31
+
32
+ super(Recorder::Context.wrap(new_context_class))
33
+ end
34
+
35
+ def query_class(new_query_class = UNSET)
36
+ return super() if UNSET.equal?(new_query_class)
37
+
38
+ super(Query.wrap(new_query_class))
39
+ end
40
+
41
+ def rescue_from(*error_classes, &handler)
42
+ return super unless handler
43
+
44
+ super(*error_classes, &Handlers.wrap(handler))
45
+ end
46
+
47
+ # The installed settings (`Integration::Settings`), from this schema or the parent that used Caching.
48
+ def armory_caching
49
+ @armory_caching || superclass.armory_caching
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end