graphql-armory 0.1.0.pre13 → 0.1.0.pre15

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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -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 +5 -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/audit.rb +1 -9
  135. data/lib/graphql/armory/versioning/integration.rb +60 -2
  136. data/lib/graphql/armory.rb +2 -0
  137. data/lib/tasks/graphql_armory.rake +9 -0
  138. metadata +110 -1
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ module Caching
8
+ # Answers kept in this process's memory: for tests, development and single-process servers. Each process keeps
9
+ # its own entries and its own purge marks, so a purge reaches only the process it runs in; share a `RedisStore`
10
+ # between processes in production.
11
+ #
12
+ # store = GraphQL::Armory::Caching::MemoryStore.new(max_bytes: 64 * 1024 * 1024)
13
+ #
14
+ # Keeps the store contract (`Store`). Entries are evicted least recently used first once their bytes (blob, key
15
+ # and tag digests) pass `max_bytes`; the meta record (epoch, seq, purge marks) is never evicted. Purge marks are
16
+ # pruned, up to 100 per purge, once older than `max_ttl` (seconds, the longest TTL it stores). `clock` answers
17
+ # Integer milliseconds; the default is the process's monotonic clock.
18
+ class MemoryStore
19
+ DEFAULT_MAX_BYTES = 32 * 1024 * 1024
20
+ DEFAULT_MAX_TTL = 3600
21
+ PRUNE_PER_PURGE = 100
22
+
23
+ def self.monotonic_clock
24
+ -> { Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) }
25
+ end
26
+
27
+ Stored = Struct.new(:blob, :tags, :expires_at, :bytes)
28
+ private_constant :Stored
29
+
30
+ attr_reader :max_bytes, :max_ttl
31
+
32
+ def initialize(max_bytes: DEFAULT_MAX_BYTES, clock: self.class.monotonic_clock, max_ttl: DEFAULT_MAX_TTL)
33
+ raise ConfigurationError, "max_bytes: must be a positive Integer, got #{max_bytes.inspect}" unless max_bytes.is_a?(Integer) && max_bytes.positive?
34
+ raise ConfigurationError, "max_ttl: must be a positive Integer of seconds, got #{max_ttl.inspect}" unless max_ttl.is_a?(Integer) && max_ttl.positive?
35
+ raise ConfigurationError, "clock: must answer call with Integer milliseconds" unless clock.respond_to?(:call)
36
+
37
+ @max_bytes = max_bytes
38
+ @max_ttl = max_ttl
39
+ @clock = clock
40
+ # Insertion order is recency: the first entry is the least recently used, the first mark the oldest.
41
+ @entries = {}
42
+ @bytes = 0
43
+ @epoch = SecureRandom.hex(16)
44
+ @seq = 0
45
+ @marks = {}
46
+ @mutex = Mutex.new
47
+ end
48
+
49
+ def lookup(key_digest)
50
+ check_digest!(key_digest, "key_digest")
51
+
52
+ @mutex.synchronize do
53
+ now = clock
54
+ entry = live(key_digest, now)
55
+ tags = entry ? entry.tags : []
56
+ marks = tags.each_with_object({}) { |tag, found| found[tag] = @marks[tag].first if @marks.key?(tag) }
57
+ Lookup.new(blob: entry&.blob, tags: tags, marks: marks, seq: @seq, epoch: @epoch, now: now)
58
+ end
59
+ end
60
+
61
+ def write(key_digest, blob, tags:, ttl:, seq:, epoch:, stored_at:)
62
+ check_write!(key_digest, blob, tags, ttl, seq, epoch, stored_at)
63
+
64
+ @mutex.synchronize do
65
+ expires_at = stored_at + (ttl * 1000)
66
+ next false if epoch != @epoch || seq > @seq || tags.any? { |tag| @marks.key?(tag) && @marks[tag].first > seq }
67
+ next false if clock >= expires_at
68
+
69
+ bytes = blob.bytesize + key_digest.bytesize + tags.sum(&:bytesize)
70
+ next false if bytes > @max_bytes
71
+
72
+ remove(key_digest)
73
+ @entries[key_digest.dup.freeze] = Stored.new(blob.dup.freeze, tags.map { |tag| tag.dup.freeze }.freeze, expires_at, bytes)
74
+ @bytes += bytes
75
+ @bytes -= remove(@entries.each_key.first) while @bytes > @max_bytes
76
+ true
77
+ end
78
+ end
79
+
80
+ def purge(tag_digests)
81
+ raise ArgumentError, "tag_digests must be an Array" unless tag_digests.is_a?(Array)
82
+
83
+ tag_digests.each { |tag| check_digest!(tag, "tag digest") }
84
+ @mutex.synchronize do
85
+ now = clock
86
+ @seq += 1
87
+ tag_digests.each do |tag|
88
+ @marks.delete(tag)
89
+ @marks[tag.dup.freeze] = [@seq, now]
90
+ end
91
+ prune(now)
92
+ @seq
93
+ end
94
+ end
95
+
96
+ def purge_all
97
+ @mutex.synchronize do
98
+ @epoch = SecureRandom.hex(16)
99
+ @marks.clear
100
+ @epoch
101
+ end
102
+ end
103
+
104
+ def inspect = "#<#{self.class.name} entries=#{@entries.size} bytes=#{@bytes}/#{@max_bytes}>"
105
+ alias_method :to_s, :inspect
106
+
107
+ private
108
+
109
+ def clock
110
+ now = @clock.call
111
+ raise ConfigurationError, "clock: must answer Integer milliseconds, got #{now.inspect}" unless now.is_a?(Integer) && now >= 0
112
+
113
+ now
114
+ end
115
+
116
+ # The entry under `key`, made the most recently used; an expired one is dropped.
117
+ def live(key, now)
118
+ entry = @entries[key] or return
119
+ if now >= entry.expires_at
120
+ remove(key)
121
+ return
122
+ end
123
+
124
+ @entries[key] = @entries.delete(key)
125
+ end
126
+
127
+ def remove(key)
128
+ entry = @entries.delete(key) or return 0
129
+ @bytes -= entry.bytes
130
+ entry.bytes
131
+ end
132
+
133
+ # Marks are kept oldest first, so pruning stops at the first one still young. An entry a mark rejects was
134
+ # stamped no later than that purge and expires within max_ttl of it, so a mark older than max_ttl rejects
135
+ # nothing that could still be answered or written.
136
+ def prune(now)
137
+ PRUNE_PER_PURGE.times do
138
+ tag, (_seq, at) = @marks.first
139
+ break unless tag && now - at > @max_ttl * 1000
140
+
141
+ @marks.delete(tag)
142
+ end
143
+ end
144
+
145
+ def check_digest!(value, name)
146
+ raise ArgumentError, "#{name} must be 64 hex characters" unless value.is_a?(String) && Key::HEX.match?(value)
147
+ end
148
+
149
+ def check_write!(key_digest, blob, tags, ttl, seq, epoch, stored_at)
150
+ check_digest!(key_digest, "key_digest")
151
+ raise ArgumentError, "blob must be a String" unless blob.is_a?(String)
152
+ raise ArgumentError, "tags: must be an Array" unless tags.is_a?(Array)
153
+
154
+ tags.each { |tag| check_digest!(tag, "tag digest") }
155
+ raise ArgumentError, "ttl: must be a positive Integer of seconds" unless ttl.is_a?(Integer) && ttl.positive?
156
+ raise ArgumentError, "ttl: #{ttl} is above this store's max_ttl (#{@max_ttl}): purge marks are kept only that long" if ttl > @max_ttl
157
+ raise ArgumentError, "seq: must be a non-negative Integer" unless seq.is_a?(Integer) && seq >= 0
158
+ raise ArgumentError, "epoch: must be a non-empty String" unless epoch.is_a?(String) && !epoch.empty?
159
+ raise ArgumentError, "stored_at: must be Integer milliseconds" unless stored_at.is_a?(Integer) && stored_at >= 0
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # Answers what it is told (`answer(value)`) to every call and records the arguments in `calls`.
7
+ module Answering
8
+ attr_reader :calls
9
+
10
+ def initialize(answer)
11
+ @answer = answer
12
+ @calls = []
13
+ end
14
+
15
+ def answer(value)
16
+ @answer = value
17
+ end
18
+
19
+ def call(*arguments)
20
+ @calls << arguments
21
+ @answer
22
+ end
23
+ end
24
+
25
+ # The operation's policy from its declarations: `walk.(query) -> Policy`. `Null` refuses everything.
26
+ class Walk
27
+ class Null
28
+ def call(_query) = Policy.refused(:unconfigured)
29
+ end
30
+
31
+ class Substitute
32
+ include Answering
33
+
34
+ def initialize(policy = Policy.refused(:unconfigured)) = super
35
+ end
36
+ end
37
+
38
+ # The request's Key: `keyer.(query, policy) -> Key | Policy.refused(reason)`. `Null` refuses everything.
39
+ class Keyer
40
+ class Null
41
+ def call(_query, _policy, **) = Policy.refused(:unconfigured)
42
+ end
43
+
44
+ class Substitute
45
+ include Answering
46
+
47
+ def initialize(key = Policy.refused(:unconfigured)) = super
48
+ end
49
+ end
50
+
51
+ # Serializes and seals entries: `codec.encode(entry, key_digest) -> String`,
52
+ # `codec.decode(string, key_digest) -> Entry`, raising `Entry::Rejected` with its reason.
53
+ class Codec
54
+ # Plain JSON with the key check, rejecting with the reason it is told (`reject_with(:decrypt)`); records `calls`.
55
+ class Substitute
56
+ attr_reader :calls
57
+
58
+ def initialize
59
+ @calls = []
60
+ @rejection = nil
61
+ end
62
+
63
+ def reject_with(reason)
64
+ @rejection = reason
65
+ end
66
+
67
+ def recover
68
+ @rejection = nil
69
+ end
70
+
71
+ def encode(entry, key_digest)
72
+ @calls << [:encode, key_digest]
73
+ entry.to_json_string
74
+ end
75
+
76
+ def decode(string, key_digest)
77
+ @calls << [:decode, key_digest]
78
+ raise Entry::Rejected, @rejection if @rejection
79
+
80
+ entry = Entry.parse(string)
81
+ raise Entry::Rejected, :key unless entry.key == key_digest
82
+
83
+ entry
84
+ end
85
+ end
86
+ end
87
+
88
+ # Charges a hit the Points its run cost: `charge.(query, cost)` answers nil (charged) or the
89
+ # limiter's refusal.
90
+ class Charge
91
+ # Charges nothing: for schemas without a Points limiter.
92
+ class Null
93
+ def call(_query, _cost) = nil
94
+ end
95
+
96
+ # Answers what it is told (`refuse_with(refusal)`, `recover`) and records `calls` as `[query, cost]`.
97
+ class Substitute
98
+ attr_reader :calls
99
+
100
+ def initialize
101
+ @calls = []
102
+ @refusal = nil
103
+ end
104
+
105
+ def refuse_with(refusal)
106
+ @refusal = refusal
107
+ end
108
+
109
+ def recover
110
+ @refusal = nil
111
+ end
112
+
113
+ def call(query, cost)
114
+ @calls << [query, cost]
115
+ @refusal
116
+ end
117
+ end
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # Purges answers by the keyed digests of their tags (docs/response-caching.md "Purging"):
7
+ #
8
+ # Purge.(AppSchema, all: true) # everything: the store replaces its epoch
9
+ # Purge.(AppSchema, viewer: user) # a principal's answers, by the [class, id] the key uses
10
+ # Purge.(AppSchema, viewer: :anonymous) # the shared anonymous answers
11
+ # Purge.(AppSchema, tag: "pricing") # a declared custom tag
12
+ # Purge.(AppSchema, type: Types::Invoice) # best effort: answers whose selection can return that type
13
+ #
14
+ # A store error raises `PurgeError`: a purge that silently failed serves stale data until the TTL. The signal
15
+ # `:cache_purged` says which kind, never the tag or the viewer.
16
+ class Purge
17
+ def self.call(schema, all: false, viewer: nil, tag: nil, type: nil)
18
+ build(schema).(all: all, viewer: viewer, tag: tag, type: type)
19
+ end
20
+
21
+ # From the schema's installed settings, so the tags are digested with the digester the gate stored them with.
22
+ def self.build(schema)
23
+ settings = schema.respond_to?(:armory_caching) ? schema.armory_caching : nil
24
+ raise ConfigurationError, "#{schema} does not use GraphQL::Armory::Caching: there is nothing to purge" unless settings
25
+
26
+ new(store: settings.store, digester: settings.digester, viewer_id: settings.viewer_id, telemetry: settings.telemetry)
27
+ end
28
+
29
+ # `new` is inert: it purges the null store, which holds nothing.
30
+ def initialize(store: Store::Null.new, digester: Digester.new, viewer_id: Integration::Settings::DEFAULT_VIEWER_ID, telemetry: Telemetry.new)
31
+ @store = store
32
+ @digester = digester
33
+ @viewer_id = viewer_id
34
+ @telemetry = telemetry
35
+ end
36
+
37
+ def call(all: false, viewer: nil, tag: nil, type: nil)
38
+ raise ArgumentError, "all: must be true or false, got #{all.inspect}" unless [true, false].include?(all)
39
+
40
+ given = { all: all || nil, viewer: viewer, tag: tag, type: type }.compact
41
+ raise ArgumentError, "purge takes exactly one of all: true, viewer:, tag: or type:" unless given.size == 1
42
+
43
+ kind, value = given.first
44
+ if kind == :all
45
+ perform { @store.purge_all }
46
+ else
47
+ digests = [@digester.(tag_for(kind, value))]
48
+ perform { @store.purge(digests) }
49
+ end
50
+ @telemetry.record(:cache_purged, kind: kind, **(kind == :type ? { type: value.graphql_name } : {}))
51
+ nil
52
+ end
53
+
54
+ def inspect = "#<#{self.class.name}>"
55
+
56
+ private
57
+
58
+ def tag_for(kind, value)
59
+ case kind
60
+ when :tag then Tags.custom(value)
61
+ when :type then type_tag(value)
62
+ else viewer_tag(value)
63
+ end
64
+ end
65
+
66
+ def type_tag(type)
67
+ raise ArgumentError, "type: takes a GraphQL type class, like Types::Invoice" unless type.respond_to?(:graphql_name) && !type.is_a?(String)
68
+
69
+ Tags.type(type.graphql_name)
70
+ end
71
+
72
+ # The same [class name, id] the key's viewer component uses, so a principal's answers are reached.
73
+ def viewer_tag(principal)
74
+ return Tags::ANONYMOUS if principal == :anonymous
75
+ raise ArgumentError, "viewer: takes a principal or :anonymous, got #{principal.inspect}" if principal.is_a?(Symbol)
76
+
77
+ class_name = principal.class.name
78
+ raise ConfigurationError, "viewer: a principal of an anonymous class cannot be identified: give its class a name" if class_name.nil? || class_name.empty?
79
+
80
+ id = @viewer_id.call(principal)
81
+ unless id.is_a?(Integer) || (id.is_a?(String) && !id.empty?)
82
+ raise ConfigurationError, "viewer_id: must answer a non-empty String or an Integer for a #{class_name}, got a #{id.class}"
83
+ end
84
+
85
+ Tags.viewer(class_name, id)
86
+ end
87
+
88
+ # The error's class only: a store's message may hold its URL and credentials.
89
+ def perform
90
+ yield
91
+ rescue StandardError => error
92
+ @telemetry.record(:cache_store_failed, operation: :purge, error: error.class.name)
93
+ raise PurgeError, "the cache store failed to purge (#{error.class.name}): the answers may still be served, retry the purge"
94
+ end
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # The context and namespace keys the modules share. Every unit reads and writes them through here, never by
7
+ # spelling the key itself.
8
+ #
9
+ # - `namespace(:armory)[:persisted]`: set by PersistedQueries on the persisted branch only.
10
+ # - `namespace(:armory)[:viewer_dependent]`: set by Authorization where a policy or ability is consulted.
11
+ # - `namespace(:armory_cache)`: the query's recorder, the hit's Result and the rescued flag.
12
+ # - `namespace(:graphql_armory)[:response_cache]` and `context[:response_cache]`: the record for the controller.
13
+ #
14
+ # Namespaces other than nil are read without being recorded: they are the gem's own state, not request input.
15
+ module RecordKeys
16
+ ARMORY = :armory
17
+ PERSISTED = :persisted
18
+ VIEWER_DEPENDENT = :viewer_dependent
19
+
20
+ CACHE = :armory_cache
21
+ RECORDER = :recorder
22
+ RESULT = :result
23
+ RESCUED = :rescued
24
+ GUARD_BUILT = :guard_built
25
+
26
+ RECORD_NAMESPACE = :graphql_armory
27
+ RECORD = :response_cache
28
+ CONTEXT_RECORD = :response_cache
29
+
30
+ module_function
31
+
32
+ def persisted!(context)
33
+ context.namespace(ARMORY)[PERSISTED] = true
34
+ end
35
+
36
+ def persisted?(context)
37
+ read(context, ARMORY, PERSISTED) == true
38
+ end
39
+
40
+ def viewer_dependent!(context)
41
+ context.namespace(ARMORY)[VIEWER_DEPENDENT] = true if namespaced?(context)
42
+ end
43
+
44
+ def viewer_dependent?(context)
45
+ read(context, ARMORY, VIEWER_DEPENDENT) == true
46
+ end
47
+
48
+ # The query's recorder, or nil when the context has none (caching not installed, a plain Hash, nil).
49
+ def recorder(context)
50
+ read(context, CACHE, RECORDER)
51
+ end
52
+
53
+ def recorder!(context, recorder)
54
+ context.namespace(CACHE)[RECORDER] = recorder
55
+ end
56
+
57
+ # The guard built this query from the request's options (through `query_class`). The gate refuses any query
58
+ # without the mark as `:built_query`: one the app built itself, or a `Query::Partial`.
59
+ def guard_built!(context)
60
+ context.namespace(CACHE)[GUARD_BUILT] = true
61
+ end
62
+
63
+ def guard_built?(context)
64
+ read(context, CACHE, GUARD_BUILT) == true
65
+ end
66
+
67
+ def rescued!(context)
68
+ context.namespace(CACHE)[RESCUED] = true
69
+ end
70
+
71
+ def rescued?(context)
72
+ read(context, CACHE, RESCUED) == true
73
+ end
74
+
75
+ # The Result the gate answered a hit with, so `query.result` answers it instead of running. The gate sets it for
76
+ # every `Decision.hit`: the cached answer, or the Points limiter's refusal when the client is over budget.
77
+ def hit_result!(context, result)
78
+ context.namespace(CACHE)[RESULT] = result
79
+ end
80
+
81
+ def hit_result(context)
82
+ read(context, CACHE, RESULT)
83
+ end
84
+
85
+ # Writes the controller's record to the query's own namespace and copies it to the context, like Points.
86
+ def record!(context, record)
87
+ record = record.dup.freeze
88
+ context.namespace(RECORD_NAMESPACE)[RECORD] = record
89
+ context[CONTEXT_RECORD] = record
90
+ end
91
+
92
+ def record(context)
93
+ read(context, RECORD_NAMESPACE, RECORD)
94
+ end
95
+
96
+ # Reads without creating the namespace: graphql-ruby creates one on first `namespace` access.
97
+ def read(context, namespace, key)
98
+ return nil unless namespaced?(context) && context.namespace?(namespace)
99
+
100
+ context.namespace(namespace)[key]
101
+ end
102
+
103
+ def namespaced?(context)
104
+ context.is_a?(GraphQL::Query::Context)
105
+ end
106
+ end
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "graphql/armory/caching/recorder/log"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ module Caching
8
+ module Recorder
9
+ # The context class `use` wraps around the schema's own: it records every read and write from construction on
10
+ # (docs/response-caching.md "Inputs you must declare"), into a `Log` stored with `RecordKeys.recorder!`.
11
+ #
12
+ # `Recorder::Context.wrap(klass) -> Class` answers a subclass of `klass` that records, the same class for the
13
+ # same `klass` every time (thread-safe), and `klass` itself when it is already a wrapper. A subclass of a wrapper
14
+ # is wrapped again, so its own overrides are recorded too; both levels then share one Log.
15
+ #
16
+ # What it records, every override calling `super`:
17
+ #
18
+ # - reads: `[]`, `fetch`, `dig` (its first key), `key?`, present or absent. A read the query's own scoped
19
+ # context answers (a value this query set with `scoped_set!` above the reading field) is not recorded;
20
+ # - the whole context (`Recorder::ALL`): `to_h`, `to_hash`, `namespace(nil)` and `scoped_context` (graphql-ruby's
21
+ # own use of that reader inside `Query::Context` is not the app's and is not recorded);
22
+ # - writes: `[]=`, `delete`, `scoped_merge!`, `scoped_set!`, and `set!`/`merge!` on the object `scoped` answers.
23
+ #
24
+ # `dataloader`: once `query.multiplex` is bound it answers `super` (the multiplex's dataloader). Before that it
25
+ # answers `context[:dataloader]` or a fresh dataloader each time, never memoized, so a pre-run caller (an app
26
+ # `visible?` during the walk) leaves no stray dataloader on the query. Its read of `:dataloader` is not recorded
27
+ # in either case: it is graphql-ruby choosing its executor, a key the gate covers anyway.
28
+ module Context
29
+ WRAPPERS = {}.compare_by_identity # wrapped class => wrapper
30
+ WRAPPED = {}.compare_by_identity # wrapper => wrapped class
31
+ LOCK = Mutex.new
32
+
33
+ BASE = GraphQL::Query::Context
34
+ BASE_NAMESPACE = BASE.instance_method(:namespace)
35
+ BASE_SCOPED_CONTEXT = BASE.instance_method(:scoped_context)
36
+ # Calls of `scoped_context` from these files are graphql-ruby's own (`fetch`) or a wrapper's `super`.
37
+ INTERNAL_FILES = [BASE.instance_method(:fetch).source_location&.first, __FILE__].compact.freeze
38
+
39
+ def self.wrap(klass)
40
+ raise ArgumentError, "expected a GraphQL::Query::Context subclass, got #{klass.inspect}" unless klass.is_a?(Class) && klass <= BASE
41
+ return klass if WRAPPED.key?(klass)
42
+
43
+ WRAPPERS[klass] || LOCK.synchronize do
44
+ WRAPPERS[klass] ||= Class.new(klass) do
45
+ include Wrapped
46
+ class_exec(&RECORDING)
47
+ end.tap { |wrapper| WRAPPED[wrapper] = klass }
48
+ end
49
+ end
50
+
51
+ # A class `wrap` built.
52
+ def self.wrapper?(klass)
53
+ WRAPPED.key?(klass)
54
+ end
55
+
56
+ # Marks a wrapper class (and its subclasses).
57
+ module Wrapped
58
+ end
59
+
60
+ # The writer `context.scoped` answers, recording the keys it sets.
61
+ class ScopedWrites
62
+ def initialize(scoped, log)
63
+ @scoped = scoped
64
+ @log = log
65
+ end
66
+
67
+ def merge!(hash)
68
+ hash.each_key { |key| @log.write_scoped(key) }
69
+ @scoped.merge!(hash)
70
+ end
71
+
72
+ def set!(key, value)
73
+ @log.write_scoped(key)
74
+ @scoped.set!(key, value)
75
+ end
76
+ end
77
+
78
+ # The overrides, defined on each wrapper itself (not included from a module) so that a wrapper of a subclass of
79
+ # a wrapper still sits first in the ancestry: Ruby does not include a module twice in one chain.
80
+ RECORDING = proc do
81
+ def initialize(...)
82
+ armory_log
83
+ super(...)
84
+ @armory_log.share(BASE_NAMESPACE.bind_call(self, nil))
85
+ RecordKeys.recorder!(self, @armory_log)
86
+ end
87
+
88
+ def [](key)
89
+ armory_read(key)
90
+ super
91
+ end
92
+
93
+ def fetch(key, *rest, &block)
94
+ armory_read(key)
95
+ super
96
+ end
97
+
98
+ def dig(key, *rest)
99
+ armory_read(key)
100
+ super
101
+ end
102
+
103
+ def key?(key)
104
+ armory_read(key)
105
+ super
106
+ end
107
+
108
+ def to_h
109
+ armory_log.read_all
110
+ super
111
+ end
112
+
113
+ def to_hash
114
+ armory_log.read_all
115
+ super
116
+ end
117
+
118
+ def namespace(ns)
119
+ armory_log.read_all if ns.nil?
120
+ super
121
+ end
122
+
123
+ def scoped_context
124
+ armory_log.read_all unless INTERNAL_FILES.include?(caller_locations(1, 1).first&.path)
125
+ super
126
+ end
127
+
128
+ def []=(key, value)
129
+ armory_log.write(key)
130
+ super
131
+ end
132
+
133
+ def delete(key)
134
+ armory_scoped_key?(key) ? armory_log.write_scoped(key) : armory_log.write(key)
135
+ super
136
+ end
137
+
138
+ def scoped_merge!(hash)
139
+ hash.each_key { |key| armory_log.write_scoped(key) }
140
+ super
141
+ end
142
+
143
+ def scoped_set!(key, value)
144
+ armory_log.write_scoped(key)
145
+ super
146
+ end
147
+
148
+ def scoped
149
+ ScopedWrites.new(super, armory_log)
150
+ end
151
+
152
+ def dataloader
153
+ return armory_log.neutral { super } if query.multiplex
154
+
155
+ armory_log.neutral { self[:dataloader] } || schema.dataloader_class.new
156
+ end
157
+
158
+ private
159
+
160
+ def armory_log
161
+ @armory_log ||= Log.new
162
+ end
163
+
164
+ # A key whose value comes from this query's own scoped context is not an input.
165
+ def armory_read(key)
166
+ log = armory_log
167
+ log.read(key) unless log.scoped_written?(key) && armory_scoped_key?(key)
168
+ end
169
+
170
+ def armory_scoped_key?(key)
171
+ BASE_SCOPED_CONTEXT.bind_call(self).key?(key)
172
+ end
173
+ end
174
+ end
175
+ end
176
+ end
177
+ end
178
+ end