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,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # What a schema author declared about caching a field or a type's fields: for how long (`ttl`, seconds), for
7
+ # whom (`scope`, `:viewer` or `:public`), what to purge it by (`tags`) and why (`reason`, required by `:public`).
8
+ # `FORBIDDEN` is `cache: false`.
9
+ #
10
+ # A field's own declaration may leave out `ttl` or `scope` (`cache: { ttl: 60 }`): it is partial, and `narrow`
11
+ # completes it from its declaring owner's `cache_fields`. A declaration may only narrow its owner's default.
12
+ class Declaration
13
+ SCOPES = %i[viewer public].freeze
14
+ OPTIONS = %i[ttl scope tags reason].freeze
15
+
16
+ attr_reader :ttl, :scope, :tags, :reason
17
+
18
+ # A complete declaration: `cache_fields ttl:, scope: :viewer, tags: [], reason: nil`.
19
+ def self.build(ttl:, scope: :viewer, tags: [], reason: nil)
20
+ new(ttl: ttl, scope: scope, tags: tags, reason: reason).completed
21
+ end
22
+
23
+ # A field's own declaration from its `cache:` value: nil (none), false (forbidden) or a Hash of OPTIONS.
24
+ def self.from_option(value)
25
+ case value
26
+ when nil then nil
27
+ when false then FORBIDDEN
28
+ when Hash
29
+ unknown = value.keys - OPTIONS
30
+ raise ConfigurationError, "cache: takes #{OPTIONS.join(', ')}; unknown: #{unknown.join(', ')}" unless unknown.empty?
31
+
32
+ new(**value)
33
+ else
34
+ raise ConfigurationError, "cache: must be false or a Hash of #{OPTIONS.join(', ')}, got #{value.class}"
35
+ end
36
+ end
37
+
38
+ # The declaration that applies to a field: its own, completed from `owner_default` (the declaring owner's
39
+ # `cache_fields`, or nil). Raises when `own` would widen the default: a longer TTL or `:public` over `:viewer`.
40
+ # Answers nil when neither declares anything.
41
+ def self.narrow(owner_default, own)
42
+ return own if own&.forbidden?
43
+ return owner_default if own.nil?
44
+
45
+ return own.completed if owner_default.nil?
46
+
47
+ if own.ttl && own.ttl > owner_default.ttl
48
+ raise ConfigurationError, "cache: ttl: #{own.ttl} is longer than its type's cache_fields ttl: #{owner_default.ttl}: a field may only narrow it"
49
+ end
50
+ if own.scope == :public && owner_default.scope == :viewer
51
+ raise ConfigurationError, "cache: scope: :public is wider than its type's cache_fields scope: :viewer: a field may only narrow it"
52
+ end
53
+
54
+ build(ttl: own.ttl || owner_default.ttl, scope: own.scope || owner_default.scope,
55
+ tags: (owner_default.tags + own.tags).uniq, reason: own.reason || owner_default.reason)
56
+ end
57
+
58
+ def initialize(ttl: nil, scope: nil, tags: [], reason: nil, forbidden: false)
59
+ @forbidden = forbidden == true
60
+ unless @forbidden
61
+ raise ConfigurationError, "cache ttl: must be a positive Integer of seconds, got #{ttl.inspect}" unless ttl.nil? || (ttl.is_a?(Integer) && ttl.positive?)
62
+ raise ConfigurationError, "cache scope: must be #{SCOPES.map(&:inspect).join(' or ')}, got #{scope.inspect}" unless scope.nil? || SCOPES.include?(scope)
63
+ unless tags.is_a?(Array) && tags.all? { |tag| tag.is_a?(String) && !tag.strip.empty? }
64
+ raise ConfigurationError, "cache tags: must be an Array of non-empty Strings"
65
+ end
66
+ raise ConfigurationError, "cache reason: must be a non-empty String" unless reason.nil? || (reason.is_a?(String) && !reason.strip.empty?)
67
+ end
68
+
69
+ @ttl = ttl
70
+ @scope = scope
71
+ @tags = tags.map { |tag| tag.dup.freeze }.freeze
72
+ @reason = reason&.dup&.freeze
73
+ freeze
74
+ end
75
+
76
+ def forbidden?
77
+ @forbidden
78
+ end
79
+
80
+ def public?
81
+ @scope == :public
82
+ end
83
+
84
+ def complete?
85
+ forbidden? || !(@ttl.nil? || @scope.nil?)
86
+ end
87
+
88
+ # This declaration standing alone: a scope left out is `:viewer`. Raises without a TTL, or for `:public`
89
+ # without a reason.
90
+ def completed
91
+ return self if forbidden?
92
+
93
+ raise ConfigurationError, "cache needs ttl: (a field declares it, or its type's cache_fields does)" if @ttl.nil?
94
+
95
+ declaration = @scope.nil? ? Declaration.new(ttl: @ttl, scope: :viewer, tags: @tags, reason: @reason) : self
96
+ if declaration.public? && declaration.reason.nil?
97
+ raise ConfigurationError, "cache scope: :public needs reason: (why the answer is the same for every viewer and tenant)"
98
+ end
99
+
100
+ declaration
101
+ end
102
+
103
+ def ==(other)
104
+ other.is_a?(Declaration) && other.forbidden? == forbidden? && other.ttl == ttl && other.scope == scope && other.tags == tags && other.reason == reason
105
+ end
106
+ alias eql? ==
107
+
108
+ def hash = [self.class, forbidden?, ttl, scope, tags, reason].hash
109
+
110
+ FORBIDDEN = new(forbidden: true)
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ module Caching
8
+ # A stored answer. Serialized as JSON, never Marshal:
9
+ #
10
+ # { "v": 2, "k": key_hex, "data": {...}, "at": stored_at_ms, "ttl": seconds, "scope": "public|viewer",
11
+ # "seq": S0, "epoch": "...", "tags": [tag digests], "cost": n | null }
12
+ #
13
+ # `stored_at` is the store clock at the lookup that preceded the run, in Integer milliseconds; the entry
14
+ # expires at `stored_at + ttl * 1000`.
15
+ class Entry
16
+ FORMAT = 2
17
+ SCOPES = { "public" => :public, "viewer" => :viewer }.freeze
18
+
19
+ # An entry that must not be served: `reason` is one of REASONS. The query runs instead.
20
+ class Rejected < Error
21
+ REASONS = %i[format key expired purged epoch tags decrypt].freeze
22
+
23
+ attr_reader :reason
24
+
25
+ def initialize(reason)
26
+ raise ArgumentError, "Entry::Rejected reason must be one of #{REASONS.inspect}, got #{reason.inspect}" unless REASONS.include?(reason)
27
+
28
+ @reason = reason
29
+ super("cache entry rejected: #{reason}")
30
+ end
31
+ end
32
+
33
+ attr_reader :key, :data, :stored_at, :ttl, :scope, :seq, :epoch, :tags, :cost
34
+
35
+ # `data` is copied and deep-frozen, unless `copy: false`: then it is used as given, for a tree nobody else
36
+ # holds or changes while the entry is in use (one `parse` just built, or a run's answer sealed at once). A
37
+ # hit answers the parsed tree itself, unfrozen like a run's, without copying it.
38
+ def initialize(key:, data:, stored_at:, ttl:, scope:, seq:, epoch:, tags:, cost: nil, copy: true)
39
+ raise ArgumentError, "Entry key: must be 64 hex characters" unless key.is_a?(String) && Key::HEX.match?(key)
40
+ raise ArgumentError, "Entry data: must be a Hash with String keys" unless data.is_a?(Hash) && data.keys.all?(String)
41
+ raise ArgumentError, "Entry stored_at: must be Integer milliseconds" unless stored_at.is_a?(Integer) && stored_at >= 0
42
+ raise ArgumentError, "Entry ttl: must be a positive Integer" unless ttl.is_a?(Integer) && ttl.positive?
43
+ raise ArgumentError, "Entry scope: must be :viewer or :public" unless Declaration::SCOPES.include?(scope)
44
+ raise ArgumentError, "Entry seq: must be a non-negative Integer" unless seq.is_a?(Integer) && seq >= 0
45
+ raise ArgumentError, "Entry epoch: must be a non-empty String" unless epoch.is_a?(String) && !epoch.empty?
46
+ raise ArgumentError, "Entry tags: must be an Array of hex digests" unless tags.is_a?(Array) && tags.all? { |tag| tag.is_a?(String) && Key::HEX.match?(tag) }
47
+ raise ArgumentError, "Entry cost: must be a non-negative Integer or nil" unless cost.nil? || (cost.is_a?(Integer) && cost >= 0)
48
+
49
+ @key = key.dup.freeze
50
+ @data = copy ? deep_freeze(data) : data
51
+ @stored_at = stored_at
52
+ @ttl = ttl
53
+ @scope = scope
54
+ @seq = seq
55
+ @epoch = epoch.dup.freeze
56
+ @tags = tags.map { |tag| tag.dup.freeze }.uniq.sort.freeze
57
+ @cost = cost
58
+ freeze
59
+ end
60
+
61
+ # Parses what `to_json_string` wrote. Raises `Rejected` (:format) on anything else. The data is the tree this
62
+ # parse built, owned by the entry, so it is not copied.
63
+ def self.parse(string)
64
+ raise Rejected, :format unless string.is_a?(String)
65
+
66
+ hash = JSON.parse(string)
67
+ raise Rejected, :format unless hash.is_a?(Hash) && hash["v"] == FORMAT && SCOPES.key?(hash["scope"])
68
+
69
+ new(key: hash["k"], data: hash["data"], stored_at: hash["at"], ttl: hash["ttl"], scope: SCOPES.fetch(hash["scope"]),
70
+ seq: hash["seq"], epoch: hash["epoch"], tags: hash["tags"], cost: hash["cost"], copy: false)
71
+ rescue JSON::ParserError, ArgumentError
72
+ raise Rejected, :format
73
+ end
74
+
75
+ def to_json_string
76
+ JSON.generate({ "v" => FORMAT, "k" => key, "data" => data, "at" => stored_at, "ttl" => ttl, "scope" => scope.to_s,
77
+ "seq" => seq, "epoch" => epoch, "tags" => tags, "cost" => cost })
78
+ end
79
+
80
+ def expires_at
81
+ stored_at + (ttl * 1000)
82
+ end
83
+
84
+ def expired?(now)
85
+ now >= expires_at
86
+ end
87
+
88
+ # Whole seconds since it was stored, for `context[:response_cache]`.
89
+ def age(now)
90
+ [(now - stored_at) / 1000, 0].max
91
+ end
92
+
93
+ def inspect = "#<#{self.class.name} scope=#{scope.inspect} ttl=#{ttl}>"
94
+
95
+ private
96
+
97
+ def deep_freeze(value)
98
+ case value
99
+ when Hash then value.to_h { |key, inner| [key.frozen? ? key : key.dup.freeze, deep_freeze(inner)] }.freeze
100
+ when Array then value.map { |inner| deep_freeze(inner) }.freeze
101
+ when String then value.frozen? ? value : value.dup.freeze
102
+ else value
103
+ end
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # A request's cache key: `digest`, the keyed hex digest of every key component (built only by the Keyer, so no
7
+ # component is ever in clear), its `scope`, and `viewer_tag`, the keyed digest of the viewer's purge tag for a
8
+ # `:viewer` key (nil for `:public`).
9
+ class Key
10
+ HEX = /\A\h{64}\z/
11
+
12
+ attr_reader :digest, :scope, :viewer_tag
13
+
14
+ def initialize(digest:, scope:, viewer_tag: nil)
15
+ raise ArgumentError, "Key digest: must be 64 hex characters" unless digest.is_a?(String) && HEX.match?(digest)
16
+ raise ArgumentError, "Key scope: must be :viewer or :public, got #{scope.inspect}" unless Declaration::SCOPES.include?(scope)
17
+ raise ArgumentError, "Key viewer_tag: must be 64 hex characters or nil" unless viewer_tag.nil? || (viewer_tag.is_a?(String) && HEX.match?(viewer_tag))
18
+ raise ArgumentError, "a :public Key has no viewer_tag" if scope == :public && viewer_tag
19
+
20
+ @digest = digest.dup.freeze
21
+ @scope = scope
22
+ @viewer_tag = viewer_tag&.dup&.freeze
23
+ freeze
24
+ end
25
+
26
+ def ==(other)
27
+ other.is_a?(Key) && other.digest == digest && other.scope == scope && other.viewer_tag == viewer_tag
28
+ end
29
+ alias eql? ==
30
+
31
+ def hash = [self.class, digest, scope, viewer_tag].hash
32
+
33
+ # Never the digest: a log line must not let anyone look an entry up.
34
+ def inspect = "#<#{self.class.name} scope=#{scope.inspect}>"
35
+ alias to_s inspect
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # What one store round trip answered: the sealed entry (`blob`, nil on a miss), the keyed tag digests stored
7
+ # beside it, the purge `marks` of those tags (digest => seq), the store's purge sequence `seq` and `epoch`, and
8
+ # the store clock `now` in Integer milliseconds, which becomes the run's `lookup_at`.
9
+ Lookup = Struct.new(:blob, :tags, :marks, :seq, :epoch, :now, keyword_init: true) do
10
+ def self.miss(seq:, epoch:, now:)
11
+ new(blob: nil, tags: [], marks: {}, seq: seq, epoch: epoch, now: now)
12
+ end
13
+
14
+ def initialize(blob:, tags:, marks:, seq:, epoch:, now:)
15
+ raise ArgumentError, "Lookup blob: must be a String or nil" unless blob.nil? || blob.is_a?(String)
16
+ raise ArgumentError, "Lookup tags: must be an Array of Strings" unless tags.is_a?(Array) && tags.all?(String)
17
+ raise ArgumentError, "Lookup marks: must be a Hash of String => Integer" unless marks.is_a?(Hash) && marks.all? { |tag, mark| tag.is_a?(String) && mark.is_a?(Integer) }
18
+ raise ArgumentError, "Lookup seq: must be a non-negative Integer" unless seq.is_a?(Integer) && seq >= 0
19
+ raise ArgumentError, "Lookup epoch: must be a non-empty String" unless epoch.is_a?(String) && !epoch.empty?
20
+ raise ArgumentError, "Lookup now: must be Integer milliseconds" unless now.is_a?(Integer) && now >= 0
21
+
22
+ super(blob: blob&.dup&.freeze, tags: tags.map { |tag| tag.dup.freeze }.freeze, marks: marks.dup.freeze, seq: seq, epoch: epoch.dup.freeze, now: now)
23
+ freeze
24
+ end
25
+
26
+ def found?
27
+ !blob.nil?
28
+ end
29
+
30
+ def inspect = "#<#{self.class.name} found=#{found?} seq=#{seq}>"
31
+ alias_method :to_s, :inspect
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # What the walk concluded about an operation: cacheable for `ttl` seconds under `scope`, purgeable by `tags`
7
+ # (custom tags and `type:<Name>` tags, in clear: they are digested before they reach a store), or refused with
8
+ # a `reason` Symbol (`:undeclared_field`, `:directive`, ...).
9
+ Policy = Struct.new(:cacheable, :ttl, :scope, :tags, :reason, keyword_init: true) do
10
+ def self.cacheable(ttl:, scope:, tags: [])
11
+ new(cacheable: true, ttl: ttl, scope: scope, tags: tags, reason: nil)
12
+ end
13
+
14
+ def self.refused(reason)
15
+ new(cacheable: false, ttl: nil, scope: nil, tags: [], reason: reason)
16
+ end
17
+
18
+ def initialize(cacheable:, ttl:, scope:, tags:, reason:)
19
+ if cacheable == true
20
+ raise ArgumentError, "a cacheable Policy needs a positive Integer ttl, got #{ttl.inspect}" unless ttl.is_a?(Integer) && ttl.positive?
21
+ raise ArgumentError, "a cacheable Policy needs scope :viewer or :public, got #{scope.inspect}" unless Declaration::SCOPES.include?(scope)
22
+ raise ArgumentError, "a cacheable Policy has no reason" unless reason.nil?
23
+ elsif cacheable == false
24
+ raise ArgumentError, "a refused Policy needs a reason Symbol, got #{reason.inspect}" unless reason.is_a?(Symbol)
25
+ else
26
+ raise ArgumentError, "cacheable: must be true or false"
27
+ end
28
+ raise ArgumentError, "Policy tags: must be an Array of Strings" unless tags.is_a?(Array) && tags.all?(String)
29
+
30
+ super(cacheable: cacheable, ttl: ttl, scope: scope, tags: tags.map { |tag| tag.dup.freeze }.uniq.sort.freeze, reason: reason)
31
+ freeze
32
+ end
33
+
34
+ def cacheable?
35
+ cacheable
36
+ end
37
+
38
+ def public?
39
+ scope == :public
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ # Who a `:viewer` answer belongs to: the principal the `viewer:` context key holds, as `[class name, id]`, so
7
+ # `User 7` and `AdminUser 7` never share an entry.
8
+ #
9
+ # viewer = Viewer.build(key: :current_user) # id: principal.id
10
+ # viewer = Viewer.build(key: :current_account, id: ->(account) { account.uuid })
11
+ # viewer = Viewer.build(key: :current_user, anonymous: :shared, anonymous_reason: "the storefront is the same for every guest")
12
+ # viewer.(context) # => Identity(component:, tag:), or Policy.refused(:anonymous | :viewer_unconfigured)
13
+ #
14
+ # A request whose key is absent, nil or false is anonymous. `anonymous: :uncacheable` (the default) refuses it;
15
+ # `:shared` gives every anonymous request of one form one entry per key. The component keeps the three forms apart
16
+ # (a resolver can tell an absent key from a nil one), and all three carry the one anonymous purge tag.
17
+ #
18
+ # `new` is inert: with no key it refuses every request as `:viewer_unconfigured`.
19
+ class Viewer
20
+ ANONYMOUS = %i[uncacheable shared].freeze
21
+
22
+ # The default `viewer_id:`.
23
+ DEFAULT_ID = lambda do |principal|
24
+ raise ConfigurationError, "the viewer (a #{principal.class}) has no id: pass viewer_id: to answer it" unless principal.respond_to?(:id)
25
+
26
+ principal.id
27
+ end
28
+
29
+ # `component` enters the key; `tag` is the purge tag in clear (`Tags.viewer` or `Tags::ANONYMOUS`), which the
30
+ # keyer digests before it leaves.
31
+ Identity = Struct.new(:component, :tag, keyword_init: true)
32
+
33
+ # Validates `use`'s `viewer:`, `viewer_id:`, `anonymous:` and `anonymous_reason:`.
34
+ def self.build(key: nil, id: DEFAULT_ID, anonymous: :uncacheable, anonymous_reason: nil)
35
+ unless key.nil? || ((key.is_a?(Symbol) || key.is_a?(String)) && !key.to_s.empty?)
36
+ raise ConfigurationError, "viewer: must be the context key (a Symbol or String) that holds the principal, or nil"
37
+ end
38
+ unless id.respond_to?(:call) && [1, -1, -2].include?(arity(id))
39
+ raise ConfigurationError, "viewer_id: must be a callable taking the principal and answering its id"
40
+ end
41
+ raise ConfigurationError, "anonymous: must be :uncacheable or :shared, got #{anonymous.inspect}" unless ANONYMOUS.include?(anonymous)
42
+
43
+ reason = anonymous_reason.is_a?(String) && !anonymous_reason.strip.empty?
44
+ if anonymous == :shared && !reason
45
+ raise ConfigurationError, "anonymous: :shared needs anonymous_reason: (why every anonymous request may see one answer)"
46
+ end
47
+ raise ConfigurationError, "anonymous_reason: only goes with anonymous: :shared" if anonymous == :uncacheable && !anonymous_reason.nil?
48
+
49
+ new(key: key, id: id, anonymous: anonymous)
50
+ end
51
+
52
+ def self.arity(callable)
53
+ callable.respond_to?(:arity) ? callable.arity : callable.method(:call).arity
54
+ end
55
+ private_class_method :arity
56
+
57
+ attr_reader :key
58
+
59
+ def initialize(key: nil, id: DEFAULT_ID, anonymous: :uncacheable)
60
+ @key = key
61
+ @id = id
62
+ @anonymous = anonymous
63
+ end
64
+
65
+ def call(context)
66
+ return Policy.refused(:viewer_unconfigured) if @key.nil?
67
+
68
+ principal = context[@key]
69
+ return anonymous(context, principal) if principal.nil? || false.equal?(principal)
70
+
71
+ class_name, id = identify(principal)
72
+ Identity.new(component: [class_name, id], tag: Tags.viewer(class_name, id))
73
+ end
74
+
75
+ # `[class name, id]`; raises `ConfigurationError` for a principal of an anonymous class or an id that is not a
76
+ # non-empty String or an Integer. The message never holds the id.
77
+ def identify(principal)
78
+ class_name = principal.class.name
79
+ raise ConfigurationError, "the viewer is an instance of an anonymous class: name its class, so its answers have an owner" if class_name.nil? || class_name.empty?
80
+
81
+ id = @id.call(principal)
82
+ unless id.is_a?(Integer) || (id.is_a?(String) && !id.empty?)
83
+ raise ConfigurationError, "viewer_id: answered a #{id.class} for a #{class_name}: it must answer a non-empty String or an Integer"
84
+ end
85
+
86
+ [class_name, id]
87
+ end
88
+
89
+ # The purge tag in clear of a principal, or of every anonymous request (`:anonymous`).
90
+ def tag(principal)
91
+ return Tags::ANONYMOUS if :anonymous.equal?(principal)
92
+
93
+ Tags.viewer(*identify(principal))
94
+ end
95
+
96
+ def inspect = "#<#{self.class.name} key=#{@key.inspect} anonymous=#{@anonymous.inspect}>"
97
+
98
+ private
99
+
100
+ def anonymous(context, principal)
101
+ return Policy.refused(:anonymous) unless @anonymous == :shared
102
+
103
+ form = if !context.key?(@key) then "absent"
104
+ elsif principal.nil? then "nil"
105
+ else "false"
106
+ end
107
+ Identity.new(component: "anonymous:#{form}", tag: Tags::ANONYMOUS)
108
+ end
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ class Walk
7
+ # Any directive anywhere in the document (the operations, their variable definitions, fields, fragment
8
+ # definitions, inline fragments and fragment spreads, selected or not) makes the operation uncacheable, unless
9
+ # it is graphql-ruby's own `@skip` or `@include` (the walk counts both branches) or its class declares
10
+ # `cache_safe`. A directive the schema does not define (or hides from this query) is refused too.
11
+ module Directives
12
+ IGNORED = [GraphQL::Schema::Directive::Skip, GraphQL::Schema::Directive::Include].freeze
13
+
14
+ module_function
15
+
16
+ # :directive, or nil when every directive in the document is allowed.
17
+ def refusal(document, types)
18
+ classes = nil
19
+ pending = document.definitions.dup
20
+ until pending.empty?
21
+ node = pending.pop
22
+ directives = node.respond_to?(:directives) ? node.directives : []
23
+ if node.is_a?(GraphQL::Language::Nodes::OperationDefinition)
24
+ node.variables.each { |variable| directives += variable.directives if variable.respond_to?(:directives) }
25
+ end
26
+ unless directives.empty?
27
+ classes ||= types.directives.to_h { |directive| [directive.graphql_name, directive] }
28
+ return :directive unless directives.all? { |directive| allowed?(classes[directive.name]) }
29
+ end
30
+ pending.concat(node.selections) if node.respond_to?(:selections)
31
+ end
32
+ nil
33
+ end
34
+
35
+ def allowed?(directive_class)
36
+ return false if directive_class.nil?
37
+
38
+ IGNORED.any? { |ignored| directive_class.equal?(ignored) } ||
39
+ (directive_class.respond_to?(:armory_cache_safe?) && directive_class.armory_cache_safe? == true)
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Caching
6
+ class Walk
7
+ # The fields graphql-ruby generates on Relay connection, edge and PageInfo types. They only page through the
8
+ # connection object the field above them returned, so they take that field's declaration and need none of
9
+ # their own. A field only counts as generated when graphql-ruby's own code resolves it: a field the app adds
10
+ # (`totalCount`) or resolves itself (its own `def nodes`, `resolver_method:`, `method:`, a resolver class,
11
+ # an extension) needs a declaration like any other.
12
+ module Relay
13
+ GENERATED = {
14
+ GraphQL::Types::Relay::ConnectionBehaviors => %i[edges nodes page_info],
15
+ GraphQL::Types::Relay::EdgeBehaviors => %i[node cursor],
16
+ GraphQL::Types::Relay::PageInfoBehaviors => %i[has_next_page has_previous_page start_cursor end_cursor]
17
+ }.freeze
18
+
19
+ # How graphql-ruby resolves a field with no resolver of its own: a method on the type, else the object's.
20
+ PLAIN_MODES = %i[direct_send resolve_legacy_instance_method].freeze
21
+
22
+ module_function
23
+
24
+ def generated?(field)
25
+ owner = field.owner
26
+ return false unless owner.is_a?(Class)
27
+
28
+ behaviors, names = GENERATED.find { |mod, _| owner < mod }
29
+ return false unless behaviors && names.include?(field.original_name)
30
+
31
+ plain?(field) && graphql_ruby_resolves?(field, owner)
32
+ end
33
+
34
+ def plain?(field)
35
+ name = field.original_name
36
+ return false unless field.resolver.nil? && field.method_sym == name && field.resolver_method == name
37
+ return false if field.respond_to?(:execution_mode) && !PLAIN_MODES.include?(field.execution_mode)
38
+
39
+ field.extensions.empty?
40
+ end
41
+
42
+ # The type's own method of that name, if it has one, must be graphql-ruby's (`ConnectionBehaviors#nodes`,
43
+ # `EdgeBehaviors#node`); otherwise the field resolves on the connection or edge object graphql-ruby built.
44
+ def graphql_ruby_resolves?(field, owner)
45
+ name = field.original_name
46
+ return true unless owner.method_defined?(name) || owner.private_method_defined?(name)
47
+
48
+ GENERATED.key?(owner.instance_method(name).owner)
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end