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,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+ require "graphql/armory/subscriptions/redis_store/scripts"
6
+
7
+ module GraphQL
8
+ module Armory
9
+ module Subscriptions
10
+ # Subscriptions kept in Redis, shared by every process of the app: the store for production.
11
+ #
12
+ # store = GraphQL::Armory::Subscriptions::RedisStore.build(redis: Redis.new(url: ENV.fetch("SUBSCRIPTIONS_REDIS_URL")))
13
+ #
14
+ # Keeps the store contract (`Store`): `write`, `ids`, `count`, `delete` and `cleanup` are each one Lua script
15
+ # (`Scripts`), atomic and one round trip, and `read` is one `HGET`. Both caps are counted inside `write`'s script,
16
+ # over unexpired records only, so no number of processes can go over them; a refused write stores nothing.
17
+ #
18
+ # The clock is the `now:` the caller passes (Integer ms), not Redis's `TIME`: the core, `MemoryStore` and every
19
+ # process then agree on what is live, and a record is live exactly while `now < expires_at` whatever clock skew
20
+ # lies between app servers and Redis. Redis's own clock only runs the keys' TTLs, which bound memory and never
21
+ # decide liveness. Run NTP on the app servers: skew moves when a subscription ends.
22
+ #
23
+ # Keyspace (see `Scripts`): a hash per record, a sorted set per topic digest and per viewer digest scored by
24
+ # `expires_at` (trimmed on read, with the TTL of their longest record), and one sorted set of every id by expiry
25
+ # that `cleanup` walks. A record holds the sealed blob, the viewer digest and the topic digests, nothing in clear.
26
+ #
27
+ # - `cleanup(now:)` removes the records the app's schedule finds expired, up to `CLEANUP_BATCH` per script call.
28
+ # Call it periodically: the key TTL frees a record's memory, but only `cleanup` frees the id in the expiry set.
29
+ # - Redis Cluster: a script touches several keys, so the prefix needs a hash tag that puts every key in one slot,
30
+ # as in `prefix: "graphql-armory:{subscriptions}:"`.
31
+ #
32
+ # Redis errors reach the caller unchanged. `redis:` is a redis-rb client (>= 4.8), or anything answering `eval`,
33
+ # `evalsha` and `call` the same way, on Redis 5 or later. This gem does not depend on the redis gem: the app adds
34
+ # it. Keep subscriptions in a Redis whose eviction policy is `noeviction` or `volatile-*`.
35
+ class RedisStore
36
+ DEFAULT_PREFIX = "graphql-armory:subscriptions:"
37
+ CLEANUP_BATCH = 500
38
+ ANSWERS = %w[ok viewer_cap topic_cap exists].freeze
39
+
40
+ module Client
41
+ # The Redis of a store nobody wired: it holds nothing and every write is refused.
42
+ class Null; end
43
+ end
44
+
45
+ # Validates the settings and wires the real Redis client.
46
+ def self.build(redis:, prefix: DEFAULT_PREFIX)
47
+ unless redis.respond_to?(:eval) && redis.respond_to?(:evalsha) && redis.respond_to?(:call)
48
+ raise ConfigurationError, "redis: must be a Redis client that runs scripts (eval, evalsha and call), like Redis.new from the redis gem"
49
+ end
50
+ raise ConfigurationError, "prefix: must be a non-empty String, got #{prefix.inspect}" unless prefix.is_a?(String) && !prefix.empty?
51
+
52
+ new(redis: redis, prefix: prefix)
53
+ end
54
+
55
+ attr_reader :prefix
56
+
57
+ # `new` is inert, like `Store::Null`: no Redis is wired, so every write is refused and nothing is held.
58
+ def initialize(redis: Client::Null.new, prefix: DEFAULT_PREFIX)
59
+ @redis = redis
60
+ @prefix = prefix
61
+ end
62
+
63
+ def write(id, sealed, topics:, viewer:, expires_at:, viewer_cap:, topic_cap:, now:)
64
+ check_write!(id, sealed, topics, viewer, expires_at, viewer_cap, topic_cap, now)
65
+ return :refused unless wired?
66
+
67
+ topics = topics.uniq
68
+ keys = [record_key(id), viewer_key(viewer), expiry_key, *topics.map { |topic| topic_key(topic) }]
69
+ answer = script(Scripts::WRITE, keys, id, sealed, viewer, JSON.generate(topics), expires_at, viewer_cap, topic_cap, now)
70
+ raise Error, "unexpected answer from the subscriptions store: #{answer.inspect}" unless ANSWERS.include?(answer)
71
+
72
+ answer.to_sym
73
+ end
74
+
75
+ def read(id)
76
+ return nil unless wired?
77
+
78
+ @redis.call("HGET", record_key(id), "sealed")
79
+ end
80
+
81
+ def ids(topic, now:)
82
+ check_now!(now)
83
+ return [] unless wired?
84
+
85
+ script(Scripts::IDS, [topic_key(topic)], now)
86
+ end
87
+
88
+ def delete(id)
89
+ return false unless wired?
90
+
91
+ script(Scripts::DELETE, [expiry_key], id, @prefix) == 1
92
+ end
93
+
94
+ def count(viewer, now:)
95
+ check_now!(now)
96
+ return 0 unless wired?
97
+
98
+ script(Scripts::COUNT, [viewer_key(viewer)], now)
99
+ end
100
+
101
+ def cleanup(now:)
102
+ check_now!(now)
103
+ return 0 unless wired?
104
+
105
+ total = 0
106
+ loop do
107
+ removed = script(Scripts::CLEANUP, [expiry_key], now, @prefix, CLEANUP_BATCH)
108
+ total += removed
109
+ break if removed < CLEANUP_BATCH
110
+ end
111
+ total
112
+ end
113
+
114
+ def inspect = "#<#{self.class.name} prefix=#{@prefix.inspect}>"
115
+ alias_method :to_s, :inspect
116
+
117
+ private
118
+
119
+ def wired? = !@redis.is_a?(Client::Null)
120
+
121
+ def record_key(id) = "#{@prefix}r:#{id}"
122
+ def topic_key(topic) = "#{@prefix}t:#{topic}"
123
+ def viewer_key(viewer) = "#{@prefix}v:#{viewer}"
124
+ def expiry_key = "#{@prefix}x"
125
+
126
+ # A caller's bug, never a store answer: the core must hand every store the same shapes.
127
+ def check_write!(id, sealed, topics, viewer, expires_at, viewer_cap, topic_cap, now)
128
+ check_now!(now)
129
+ raise ArgumentError, "id must be a non-empty String" unless id.is_a?(String) && !id.empty?
130
+ raise ArgumentError, "sealed must be a String" unless sealed.is_a?(String)
131
+ raise ArgumentError, "topics: must be a non-empty Array of non-empty Strings" unless topics.is_a?(Array) && !topics.empty? && topics.all? { |topic| topic.is_a?(String) && !topic.empty? }
132
+ raise ArgumentError, "viewer: must be a non-empty String" unless viewer.is_a?(String) && !viewer.empty?
133
+ raise ArgumentError, "expires_at: must be Integer milliseconds after now:" unless expires_at.is_a?(Integer) && expires_at > now
134
+
135
+ [viewer_cap, topic_cap].each do |cap|
136
+ raise ArgumentError, "a cap must be nil or a positive Integer, got #{cap.inspect}" unless cap.nil? || (cap.is_a?(Integer) && cap.positive?)
137
+ end
138
+ end
139
+
140
+ def check_now!(now)
141
+ raise ArgumentError, "now: must be Integer milliseconds" unless now.is_a?(Integer)
142
+ end
143
+
144
+ # EVALSHA sends only the script's digest; Redis forgets scripts on restart or SCRIPT FLUSH, and then EVAL
145
+ # sends it whole once more. A nil argument (an absent cap) travels as an empty string.
146
+ def script(source, keys, *argv)
147
+ argv = argv.map(&:to_s)
148
+ @redis.evalsha(Digest::SHA1.hexdigest(source), keys: keys, argv: argv)
149
+ rescue StandardError => error
150
+ raise unless error.message.start_with?("NOSCRIPT")
151
+
152
+ @redis.eval(source, keys: keys, argv: argv)
153
+ end
154
+ end
155
+ end
156
+ end
157
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ module Store
7
+ # The store of subscriptions nobody wired: it refuses every write and holds nothing, so `Subscriptions.new`
8
+ # never keeps a subscription. `build` refuses it: a backend that loses every subscription.
9
+ class Null
10
+ def write(_id, _sealed, topics:, viewer:, expires_at:, viewer_cap:, topic_cap:, now:)
11
+ :refused
12
+ end
13
+
14
+ def read(_id) = nil
15
+ def ids(_topic, now:) = []
16
+ def delete(_id) = false
17
+ def count(_viewer, now:) = 0
18
+ def cleanup(now:) = 0
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ module Store
7
+ # An in-memory store that keeps the store contract (`Store`), records its calls, fails when told, answers what
8
+ # it is told and lets a test write a raw record as someone with store access could: for tests, instead of
9
+ # hand-written fakes. `now` is a test clock (Integer milliseconds) for the test's own use and for `poison`'s
10
+ # default expiry; the store itself only uses the `now:` each call is given.
11
+ #
12
+ # store = Store::Substitute.new
13
+ # store.fail_with(Redis::TimeoutError.new, on: :ids)
14
+ # store.answer(:write, :viewer_cap)
15
+ # store.poison(id, "forged", topics: [digest])
16
+ # store.calls # => [[:write, id, { topics:, viewer:, ... }], [:read, id, {}], ...]
17
+ class Substitute
18
+ OPERATIONS = %i[write read ids delete count cleanup].freeze
19
+
20
+ attr_accessor :now
21
+ attr_reader :calls
22
+
23
+ def initialize(now: 1_000_000)
24
+ raise ArgumentError, "now: must be Integer milliseconds" unless now.is_a?(Integer)
25
+
26
+ @now = now
27
+ @records = {}
28
+ @calls = []
29
+ @failures = {}
30
+ @answers = {}
31
+ end
32
+
33
+ # Raises `error` from `on` (an operation, or :all) for the next `times` calls, or every call until `recover`.
34
+ def fail_with(error, on: :all, times: nil)
35
+ raise ArgumentError, "on: must be one of #{(OPERATIONS + [:all]).inspect}, got #{on.inspect}" unless (OPERATIONS + [:all]).include?(on)
36
+ raise ArgumentError, "times: must be nil (every call) or a positive Integer, got #{times.inspect}" unless times.nil? || (times.is_a?(Integer) && times.positive?)
37
+
38
+ @failures[on] = [error, times]
39
+ end
40
+
41
+ def recover
42
+ @failures.clear
43
+ end
44
+
45
+ # Answers `value` from `operation` instead of the real answer (and does nothing else), for answers no real
46
+ # store gives at that moment.
47
+ def answer(operation, value)
48
+ raise ArgumentError, "operation must be one of #{OPERATIONS.inspect}" unless OPERATIONS.include?(operation)
49
+
50
+ @answers[operation] = value
51
+ end
52
+
53
+ # Writes `sealed` under `id` as someone with write access to the store could: no cap, no check, replacing
54
+ # what was there. Not recorded.
55
+ def poison(id, sealed, topics: [], viewer: Record::ANONYMOUS, expires_at: @now + 60_000)
56
+ @records[id] = { sealed: sealed, topics: topics.dup, viewer: viewer, expires_at: expires_at }
57
+ end
58
+
59
+ # Every stored sealed record by id, expired ones included, for assertions. Not recorded.
60
+ def records
61
+ @records.transform_values { |record| record[:sealed] }
62
+ end
63
+
64
+ def write(id, sealed, topics:, viewer:, expires_at:, viewer_cap:, topic_cap:, now:)
65
+ check_write(id, sealed, topics, viewer, expires_at, viewer_cap, topic_cap, now)
66
+ perform(:write, id, topics: topics, viewer: viewer, expires_at: expires_at, viewer_cap: viewer_cap, topic_cap: topic_cap, now: now) do
67
+ live = @records.values.select { |record| record[:expires_at] > now }
68
+ if @records.key?(id)
69
+ :exists
70
+ elsif viewer_cap && live.count { |record| record[:viewer] == viewer } >= viewer_cap
71
+ :viewer_cap
72
+ elsif topic_cap && topics.any? { |topic| live.count { |record| record[:topics].include?(topic) } >= topic_cap }
73
+ :topic_cap
74
+ else
75
+ @records[id] = { sealed: sealed, topics: topics.uniq, viewer: viewer, expires_at: expires_at }
76
+ :ok
77
+ end
78
+ end
79
+ end
80
+
81
+ def read(id)
82
+ perform(:read, id) { @records[id]&.fetch(:sealed) }
83
+ end
84
+
85
+ def ids(topic, now:)
86
+ check_now(now)
87
+ perform(:ids, topic, now: now) do
88
+ @records.select { |_id, record| record[:topics].include?(topic) && record[:expires_at] > now }.keys
89
+ end
90
+ end
91
+
92
+ def delete(id)
93
+ perform(:delete, id) { !@records.delete(id).nil? }
94
+ end
95
+
96
+ def count(viewer, now:)
97
+ check_now(now)
98
+ perform(:count, viewer, now: now) do
99
+ @records.count { |_id, record| record[:viewer] == viewer && record[:expires_at] > now }
100
+ end
101
+ end
102
+
103
+ def cleanup(now:)
104
+ check_now(now)
105
+ perform(:cleanup, nil, now: now) do
106
+ expired = @records.select { |_id, record| record[:expires_at] <= now }.keys
107
+ expired.each { |id| @records.delete(id) }
108
+ expired.size
109
+ end
110
+ end
111
+
112
+ private
113
+
114
+ # A caller's bug, never a store answer: the core must hand every store the same shapes.
115
+ def check_write(id, sealed, topics, viewer, expires_at, viewer_cap, topic_cap, now)
116
+ check_now(now)
117
+ raise ArgumentError, "id must be a non-empty String" unless id.is_a?(String) && !id.empty?
118
+ raise ArgumentError, "sealed must be a String" unless sealed.is_a?(String)
119
+ raise ArgumentError, "topics: must be a non-empty Array of Strings" unless topics.is_a?(Array) && !topics.empty? && topics.all?(String)
120
+ raise ArgumentError, "viewer: must be a non-empty String" unless viewer.is_a?(String) && !viewer.empty?
121
+ raise ArgumentError, "expires_at: must be Integer milliseconds after now:" unless expires_at.is_a?(Integer) && expires_at > now
122
+
123
+ [viewer_cap, topic_cap].each do |cap|
124
+ raise ArgumentError, "a cap must be nil or a positive Integer, got #{cap.inspect}" unless cap.nil? || (cap.is_a?(Integer) && cap.positive?)
125
+ end
126
+ end
127
+
128
+ def check_now(now)
129
+ raise ArgumentError, "now: must be Integer milliseconds" unless now.is_a?(Integer)
130
+ end
131
+
132
+ def perform(operation, subject, **arguments)
133
+ @calls << [operation, subject, arguments]
134
+ fail!(operation)
135
+ return @answers[operation] if @answers.key?(operation)
136
+
137
+ yield
138
+ end
139
+
140
+ def fail!(operation)
141
+ on = @failures.key?(operation) ? operation : :all
142
+ error, times = @failures[on]
143
+ return unless error
144
+
145
+ if times
146
+ times -= 1
147
+ times.zero? ? @failures.delete(on) : @failures[on] = [error, times]
148
+ end
149
+ raise error
150
+ end
151
+ end
152
+ end
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ # Where subscriptions live: `MemoryStore`, `RedisStore`, or any object answering the same six methods. A store
7
+ # sees sealed records, topic digests, viewer digests and ids, never a document, a variable or a viewer in clear.
8
+ # Times are Integer milliseconds and always come from the caller (`now:`), so every store agrees on what is live.
9
+ #
10
+ # store.write(id, sealed, topics:, viewer:, expires_at:, viewer_cap:, topic_cap:, now:)
11
+ # -> :ok | :viewer_cap | :topic_cap | :exists (Store::Null answers :refused)
12
+ # store.read(id) -> String | nil # the sealed record
13
+ # store.ids(topic, now:) -> [id, ...] # the live ids written under that topic digest
14
+ # store.delete(id) -> true | false # whether it was stored
15
+ # store.count(viewer, now:) -> Integer # the viewer's live records
16
+ # store.cleanup(now:) -> Integer # how many expired records were removed
17
+ #
18
+ # The contract every store keeps (`spec/support/subscription_store_contract.rb`):
19
+ #
20
+ # - A record is live while `now < expires_at`. `ids` and `count` answer live records only.
21
+ # - `write` is one atomic step: it answers `:exists` when `id` is already stored (it never replaces a record),
22
+ # `:viewer_cap` when `viewer` already has `viewer_cap` live records, `:topic_cap` when any of `topics` already has
23
+ # `topic_cap` live records (the viewer cap is checked first; a nil cap is no cap). Any of those writes nothing.
24
+ # Otherwise it stores `sealed` under `id`, adds `id` to each topic's index and to `viewer`'s count, and answers
25
+ # `:ok`. An expired record no longer counts against a cap, cleaned up or not.
26
+ # - `read` answers the sealed record until it is deleted or cleaned up; a store may stop answering it any time
27
+ # after `expires_at` (a server-side TTL), never before. The core checks `expires_at` in the record itself.
28
+ # - `delete` removes the record, its id from every topic it was written under and from its viewer's count.
29
+ # - `cleanup` removes every record expired at `now`, with its index entries, and answers how many it removed.
30
+ module Store
31
+ ANSWERS = %i[ok viewer_cap topic_cap exists].freeze
32
+ end
33
+ end
34
+ end
35
+ end
36
+
37
+ require "graphql/armory/subscriptions/store/null"
38
+ require "graphql/armory/subscriptions/store/substitute"
@@ -0,0 +1,253 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module GraphQL
6
+ module Armory
7
+ module Subscriptions
8
+ # The store's key for "subscribers of this field with these arguments in this scope": a keyed digest of
9
+ #
10
+ # [FORMAT, field.graphql_name, args(field, arguments), tagged(scope)]
11
+ #
12
+ # as JSON. Every part is a JSON value inside a fixed-arity array, so a ":" inside a value is just a character
13
+ # (graphql-ruby's own topic joins the parts with unescaped ":"), and `1` and `"1"` scopes differ.
14
+ #
15
+ # The write side (graphql-ruby's coerced Ruby keyword arguments, InputObject instances, defaults filled) and the
16
+ # trigger side (GraphQL names or keywords, the app's raw values) meet because `args` canonicalises through the
17
+ # field's argument definitions: each key becomes its argument's GraphQL name, missing defaults are filled, each
18
+ # leaf becomes its type's result coercion (an ID its String, an enum its GraphQL name, a custom scalar what its
19
+ # `coerce_result` answers), input objects recurse, lists map, and pairs are sorted by name.
20
+ #
21
+ # topic = Topic.build(encoder: AppEncoder)
22
+ # topic.(field, { "roomId" => 5 }, scope) # => 64 hex characters
23
+ #
24
+ # Limits: an argument whose `prepare:` changes its value, or a `loads:` argument (the write side holds the loaded
25
+ # object), cannot meet its trigger: the leaf is refused or digested apart.
26
+ class Topic
27
+ FORMAT = 1
28
+ PURPOSE = "subscription-topic"
29
+ # How deep a scope or an input value may nest: a cycle is refused, never followed.
30
+ MAX_DEPTH = 32
31
+
32
+ def self.build(encoder:)
33
+ raise ConfigurationError, "encoder: must answer mac(bytes, purpose:) (an Encoder subclass), got #{encoder.class}" unless encoder.respond_to?(:mac)
34
+
35
+ new(encoder: encoder)
36
+ end
37
+
38
+ # Inert: Encoder::Null refuses to digest.
39
+ def initialize(encoder: Encoder::Null)
40
+ @encoder = encoder
41
+ end
42
+
43
+ def call(field, arguments, scope, context: nil)
44
+ self.class.digest(@encoder, field, arguments, scope, context: context)
45
+ end
46
+
47
+ # The keyed digest of `canonical`, as 64 lowercase hex characters.
48
+ def self.digest(encoder, field, arguments, scope, context: nil)
49
+ encoder.mac(canonical(field, arguments, scope, context: context), purpose: PURPOSE).unpack1("H*")
50
+ end
51
+
52
+ # The JSON text the digest is made of.
53
+ def self.canonical(field, arguments, scope, context: nil)
54
+ JSON.generate([FORMAT, field.graphql_name, args(field, arguments, context: context), tagged(scope)])
55
+ rescue JSON::GeneratorError, EncodingError
56
+ raise ArgumentError, "the arguments of #{field.path} do not make a topic: a value is not valid UTF-8"
57
+ end
58
+
59
+ # `arguments` (a Hash, graphql-ruby's interpreter Arguments, or nil) as sorted [GraphQL name, canonical value]
60
+ # pairs. Raises ArgumentError for an unknown key, the same argument twice, a missing required argument or a
61
+ # value its type cannot coerce. Messages name the argument, never its value.
62
+ def self.args(field, arguments, context: nil)
63
+ context ||= GraphQL::Query::NullContext.instance
64
+ given = arguments.nil? ? {} : Canonical.hash_of(arguments, field.path)
65
+ extras = field.respond_to?(:extras) ? field.extras.map(&:to_s) : [] # an input object class has none
66
+ Canonical.new(context).object(field, given.reject { |key, _| extras.include?(key.to_s) }, field.path, 0)
67
+ end
68
+
69
+ # The scope, which has no GraphQL type, tagged with its Ruby type: ["s", string], ["i", integer], ["f", float],
70
+ # ["b", bool], ["n"], ["a", [...]], ["h", sorted pairs], a record ["g", its global id]. Raises ArgumentError for
71
+ # anything else (a Symbol, a non-finite Float, two keys that stringify alike, an object without `to_gid`).
72
+ def self.tagged(scope, depth = 0)
73
+ raise ArgumentError, "a subscription scope nests deeper than #{MAX_DEPTH}" if depth > MAX_DEPTH
74
+
75
+ case scope
76
+ when nil then ["n"]
77
+ when true, false then ["b", scope]
78
+ when String then ["s", utf8(scope)]
79
+ when Integer then ["i", scope]
80
+ when Float
81
+ raise ArgumentError, "a subscription scope Float must be finite" unless scope.finite?
82
+
83
+ ["f", scope]
84
+ when Array then ["a", scope.map { |item| tagged(item, depth + 1) }]
85
+ when Hash then ["h", tagged_pairs(scope, depth)]
86
+ else
87
+ raise ArgumentError, "a subscription scope must be nil, a boolean, a String, a number, an Array, a Hash or a record with to_gid, got a #{scope.class}" unless scope.respond_to?(:to_gid)
88
+
89
+ ["g", utf8(global_id(scope))]
90
+ end
91
+ end
92
+
93
+ def self.utf8(string)
94
+ text = string.encoding == Encoding::UTF_8 ? string : string.encode(Encoding::UTF_8)
95
+ raise ArgumentError, "a subscription topic String must be valid UTF-8" unless text.valid_encoding?
96
+
97
+ text
98
+ rescue EncodingError
99
+ raise ArgumentError, "a subscription topic String must be valid UTF-8"
100
+ end
101
+
102
+ def self.tagged_pairs(hash, depth)
103
+ pairs = hash.map do |key, value|
104
+ raise ArgumentError, "a subscription scope Hash must have String or Symbol keys, got a #{key.class}" unless key.is_a?(String) || key.is_a?(Symbol)
105
+
106
+ [utf8(key.to_s), tagged(value, depth + 1)]
107
+ end
108
+ raise ArgumentError, "a subscription scope Hash has two keys that stringify alike" unless pairs.map(&:first).uniq.size == pairs.size
109
+
110
+ pairs.sort_by(&:first)
111
+ end
112
+
113
+ def self.global_id(record)
114
+ gid = record.to_gid
115
+ text = gid.to_s
116
+ raise ArgumentError, "a subscription scope record must have a global id" if gid.nil? || text.empty?
117
+
118
+ text
119
+ rescue ArgumentError
120
+ raise
121
+ rescue StandardError
122
+ raise ArgumentError, "a subscription scope record must have a global id (#{record.class} has none)"
123
+ end
124
+
125
+ private_class_method :utf8, :tagged_pairs, :global_id
126
+
127
+ # Walks one set of arguments through their definitions. `context` is what argument and enum value
128
+ # definitions are looked up with (a query's, or NullContext).
129
+ class Canonical
130
+ # A Hash of arguments from what either side holds: a Hash, an InputObject, or graphql-ruby's interpreter
131
+ # Arguments.
132
+ def self.hash_of(value, path)
133
+ return value.to_h if value.is_a?(GraphQL::Schema::InputObject)
134
+ return value.to_h if defined?(GraphQL::Execution::Interpreter::Arguments) && value.is_a?(GraphQL::Execution::Interpreter::Arguments)
135
+ return value if value.is_a?(Hash)
136
+
137
+ raise ArgumentError, "the arguments of #{path} must be a Hash, got a #{value.class}"
138
+ end
139
+
140
+ def initialize(context)
141
+ @context = context
142
+ end
143
+
144
+ # The sorted pairs of an argument owner (a field or an input object class).
145
+ def object(owner, given, path, depth)
146
+ raise ArgumentError, "the arguments of #{path} nest deeper than #{MAX_DEPTH}" if depth > MAX_DEPTH
147
+
148
+ definitions = owner.arguments(@context)
149
+ pairs = {}
150
+ given.each do |key, value|
151
+ definition = find(definitions, key)
152
+ raise ArgumentError, "unknown argument #{key.to_s.inspect} for #{path}" unless definition
153
+
154
+ name = definition.graphql_name
155
+ raise ArgumentError, "argument #{name} of #{path} given twice" if pairs.key?(name)
156
+
157
+ pairs[name] = value(definition.type, value, "#{path}.#{name}", depth)
158
+ end
159
+ definitions.each_value do |definition|
160
+ next if pairs.key?(definition.graphql_name)
161
+
162
+ if definition.default_value?
163
+ pairs[definition.graphql_name] = value(definition.type, definition.default_value, "#{path}.#{definition.graphql_name}", depth)
164
+ elsif definition.type.non_null?
165
+ raise ArgumentError, "required argument #{definition.graphql_name} of #{path} is missing"
166
+ end
167
+ end
168
+ pairs.sort_by(&:first)
169
+ end
170
+
171
+ private
172
+
173
+ # By GraphQL name first, then by Ruby keyword: the trigger side names arguments in GraphQL, the write side
174
+ # by keyword (an `as:` keyword included).
175
+ def find(definitions, key)
176
+ return nil unless key.is_a?(String) || key.is_a?(Symbol)
177
+
178
+ name = key.to_s
179
+ definitions[name] || definitions.each_value.find { |definition| definition.keyword.to_s == name }
180
+ end
181
+
182
+ def value(type, value, path, depth)
183
+ if type.non_null?
184
+ raise ArgumentError, "argument #{path} cannot be null" if value.nil?
185
+
186
+ return value(type.of_type, value, path, depth)
187
+ end
188
+ return nil if value.nil?
189
+
190
+ if type.list?
191
+ # GraphQL coerces a single value given for a list into a list of one.
192
+ items = value.is_a?(Array) ? value : [value]
193
+ return items.map { |item| value(type.of_type, item, path, depth + 1) }
194
+ end
195
+
196
+ if type.kind.input_object?
197
+ object(type, Canonical.hash_of(value, path), path, depth + 1)
198
+ else
199
+ leaf(type, value, path)
200
+ end
201
+ rescue ArgumentError
202
+ raise
203
+ rescue StandardError
204
+ raise ArgumentError, "argument #{path} has a value its type cannot coerce"
205
+ end
206
+
207
+ # A scalar or an enum value as its result coercion. The value is either already coerced (the write side:
208
+ # its result coercion coerces back to it), or raw input (the trigger side: coerced as a query argument would
209
+ # be, then result-coerced). Anything else is refused.
210
+ def leaf(type, value, path)
211
+ canonical = coerced(type, value)
212
+ canonical = raw(type, value) if canonical.equal?(NONE)
213
+ raise ArgumentError, "argument #{path} has a value its type cannot coerce" if canonical.equal?(NONE) || !json_value?(canonical)
214
+
215
+ canonical
216
+ end
217
+
218
+ NONE = Object.new.freeze
219
+ private_constant :NONE
220
+
221
+ def coerced(type, value)
222
+ result = type.coerce_result(value, @context)
223
+ type.coerce_input(result, @context) == value ? result : NONE
224
+ rescue StandardError
225
+ NONE
226
+ end
227
+
228
+ def raw(type, value)
229
+ return NONE unless type.valid_input?(value, @context)
230
+
231
+ input = type.coerce_input(value, @context)
232
+ input.nil? ? NONE : type.coerce_result(input, @context)
233
+ rescue StandardError
234
+ NONE
235
+ end
236
+
237
+ def json_value?(value, depth = 0)
238
+ return false if depth > MAX_DEPTH
239
+
240
+ case value
241
+ when nil, true, false, Integer then true
242
+ when Float then value.finite?
243
+ when String then value.encoding == Encoding::UTF_8 ? value.valid_encoding? : value.ascii_only?
244
+ when Array then value.all? { |item| json_value?(item, depth + 1) }
245
+ when Hash then value.all? { |key, item| key.is_a?(String) && json_value?(item, depth + 1) }
246
+ else false
247
+ end
248
+ end
249
+ end
250
+ end
251
+ end
252
+ end
253
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ module Transport
7
+ # The transport of subscriptions nobody wired: not viewer bound, nothing fits, no channel is named, every
8
+ # publish, authorization and webhook is refused. `Subscriptions.new` therefore delivers nothing to anyone.
9
+ class Null
10
+ CAPABILITIES = Capabilities.new(viewer_bound: false, max_payload_bytes: 0, max_batch: 1, webhooks: nil, compress: false)
11
+
12
+ def capabilities = CAPABILITIES
13
+ def authorization = :channel
14
+ def channel_for(_id, _viewer_digest) = nil
15
+ def id_from(_channel) = nil
16
+
17
+ def publish(messages)
18
+ messages.each_index.map { |index| Outcome.new(status: :refused, index: index, reason: :null_transport) }
19
+ end
20
+
21
+ def authorize_channel(channel:, socket_id: nil) = nil
22
+ def authorize_viewer(_viewer_digest) = nil
23
+ def webhook(_env) = [:refused, :null_transport]
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end