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,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Core < GraphQL::Subscriptions
7
+ # Pusher's socket id shape: what the core accepts before a channel transport signs anything.
8
+ SOCKET_ID = /\A\d+\.\d+\z/
9
+ JSON_HEADERS = { "content-type" => "application/json" }.freeze
10
+
11
+ # For a `:channel` transport (Pusher private channels): the transport's signed answer for `channel`, or nil.
12
+ # Nil unless the channel names a live subscription whose stored viewer digest equals the digest of the viewer
13
+ # `context` holds (compared in constant time) and the channel name is the one the transport makes for that
14
+ # subscription and digest. A deleted or expired subscription answers nil: the client re-subscribes. Build
15
+ # `context` the way the GraphQL endpoint does: the channel is only as safe as that.
16
+ def authorize_channel(channel:, socket_id: nil, context:)
17
+ return nil unless @transport.authorization == :channel
18
+ return nil unless socket_id.nil? || (socket_id.is_a?(String) && SOCKET_ID.match?(socket_id))
19
+
20
+ record = live_record(channel)
21
+ return nil unless record && same_viewer?(record.viewer_digest, requester_digest(context))
22
+
23
+ @transport.authorize_channel(channel: channel, socket_id: socket_id)
24
+ end
25
+
26
+ # For a `:viewer` transport (Ably capability tokens): credentials reaching the channels of the viewer `context`
27
+ # holds, and no one else's, or nil when it names no viewer.
28
+ def authorize_viewer(context:)
29
+ return nil unless @transport.authorization == :viewer
30
+
31
+ digest = requester_digest(context)
32
+ digest ? @transport.authorize_viewer(digest) : nil
33
+ end
34
+
35
+ # The provider's webhook, as a Rack triple: the transport verifies the signature, and each channel it reports
36
+ # gone has its subscription deleted (200). A refused or failing webhook answers 401, deletes nothing and is
37
+ # recorded. A forged "gone" can only end a subscription, never deliver one.
38
+ def webhook(env)
39
+ status, reported = begin
40
+ @transport.webhook(env)
41
+ rescue StandardError
42
+ [:refused, :error]
43
+ end
44
+ unless status == :ok && reported.is_a?(Array)
45
+ record_signal(:subscription_webhook_refused, reason: status == :refused && reported.is_a?(Symbol) ? reported : :invalid)
46
+ return [401, JSON_HEADERS.dup, ["{}"]]
47
+ end
48
+
49
+ reported.each do |channel|
50
+ id = @transport.id_from(channel)
51
+ next unless id && @store.delete(id)
52
+
53
+ record_signal(:subscription_ended, reason: :webhook, subscription: id_digest(id))
54
+ end
55
+ [200, JSON_HEADERS.dup, ["{}"]]
56
+ end
57
+
58
+ private
59
+
60
+ # The live record `channel` names, when the transport would make exactly that channel for it.
61
+ def live_record(channel)
62
+ return nil unless channel.is_a?(String)
63
+
64
+ id = @transport.id_from(channel)
65
+ return nil unless id
66
+
67
+ sealed = @store.read(id)
68
+ record = sealed && open_record(id, sealed)
69
+ return nil unless record && !record.expired?(now_ms)
70
+ return nil unless @transport.channel_for(id, record.viewer_digest) == channel
71
+
72
+ record
73
+ end
74
+
75
+ # The digest of the viewer `context` holds (the anonymous marker in anonymous mode), or nil.
76
+ def requester_digest(context)
77
+ viewer = @settings.viewer
78
+ return Record::ANONYMOUS if viewer.anonymous?
79
+
80
+ hex_mac(viewer.id(context), VIEWER_PURPOSE)
81
+ rescue RefusedError
82
+ nil
83
+ end
84
+
85
+ def same_viewer?(stored, requested)
86
+ return false unless stored.is_a?(String) && requested.is_a?(String) && stored.bytesize == requested.bytesize
87
+
88
+ OpenSSL.fixed_length_secure_compare(stored, requested)
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Core < GraphQL::Subscriptions
7
+ # What the core reads the time from: a callable answering Integer milliseconds since the epoch. Every store call
8
+ # gets its `now:` from here, so every store agrees on what is live.
9
+ module Clock
10
+ SYSTEM = -> { Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond) }
11
+
12
+ def self.system
13
+ SYSTEM
14
+ end
15
+
16
+ # A clock the test sets and moves, in milliseconds: for tests, instead of hand-written fakes.
17
+ class Substitute
18
+ attr_accessor :now
19
+
20
+ def initialize(now: 1_000_000)
21
+ raise ArgumentError, "now: must be Integer milliseconds" unless now.is_a?(Integer)
22
+
23
+ @now = now
24
+ end
25
+
26
+ def call
27
+ @now
28
+ end
29
+
30
+ def advance(milliseconds)
31
+ raise ArgumentError, "advance takes Integer milliseconds" unless milliseconds.is_a?(Integer)
32
+
33
+ @now += milliseconds
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ module Controls
7
+ # An Encoder subclass with a fixed key, for tests only: everyone who reads this file knows its key.
8
+ module AppEncoder
9
+ KEY = "subscriptions-control-key-not-a-secret"
10
+
11
+ def self.example(key = KEY)
12
+ Class.new(Armory::Encoder) { key(key) }
13
+ end
14
+ end
15
+
16
+ # The options of `use GraphQL::Armory::Subscriptions` for the control schema (`Schema.example(subscriptions:)`):
17
+ # a `Store::Substitute`, a viewer-bound `Transport::Substitute`, the control encoder, the control app's viewer
18
+ # over `directory`, `tenant_id` stored (the scope of `messagePosted`), one hour of lifetime. Any option can be
19
+ # overridden or added.
20
+ module Options
21
+ def self.example(directory: Directory.example, store: Store.example, transport: Transport.example, encoder: AppEncoder.example, **overrides)
22
+ { store: store, transport: transport, encoder: encoder, viewer: Viewer.example(directory),
23
+ context_keys: { tenant_id: "scopes every message to the subscriber's tenant" }, max_lifetime: 3_600, **overrides }
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,250 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Core < GraphQL::Subscriptions
7
+ # What replaces a result over the transport's limit: the core never truncates one, the client refetches.
8
+ TOO_LARGE = { "errors" => [{ "message" => "Result too large", "extensions" => { "code" => "RESULT_TOO_LARGE" } }] }.freeze
9
+
10
+ # One message ready for the transport, with what to do once it was sent: `ending` (a reason) deletes the
11
+ # subscription, `delivered` (telemetry data) records a result that reached the provider.
12
+ Delivery = Struct.new(:id, :message, :ending, :context, :delivered, keyword_init: true)
13
+
14
+ # Runs the live subscribers of the event's topic (at most `max_executions_per_trigger`), each as itself, and
15
+ # publishes their messages in batches. An error with one subscriber is recorded and the others go on;
16
+ # `on_delivery_error: :raise` raises the first one after the whole topic was processed.
17
+ def execute_all(event, object)
18
+ raise ArgumentError, "execute_all takes the event trigger built (it carries the core's topic digest)" unless event.is_a?(Event)
19
+
20
+ now = now_ms
21
+ errors = []
22
+ ids = begin
23
+ @store.ids(event.digest, now: now)
24
+ rescue StandardError => error
25
+ record_signal(:subscription_delivery_error, error: error.class.name)
26
+ errors << error
27
+ []
28
+ end
29
+ ids = within_budget(ids)
30
+ deliveries = ids.filter_map do |id|
31
+ run(id, event.digest, object, now)
32
+ rescue StandardError => error
33
+ record_signal(:subscription_delivery_error, error: error.class.name, subscription: id_digest(id))
34
+ errors << error
35
+ nil
36
+ end
37
+ publish(deliveries, errors)
38
+ raise errors.first if !errors.empty? && @settings.on_delivery_error == :raise
39
+
40
+ nil
41
+ end
42
+
43
+ # One subscriber of `event`, through the same path as `execute_all`.
44
+ def execute(subscription_id, event, object)
45
+ raise ArgumentError, "execute takes the event trigger built (it carries the core's topic digest)" unless event.is_a?(Event)
46
+
47
+ errors = []
48
+ delivery = run(subscription_id, event.digest, object, now_ms)
49
+ publish([delivery].compact, errors)
50
+ raise errors.first if !errors.empty? && @settings.on_delivery_error == :raise
51
+
52
+ nil
53
+ end
54
+
55
+ # Never used: graphql-ruby's execute_update merges the trigger's context over the subscriber's. Every delivery
56
+ # goes through `trigger`.
57
+ def execute_update(_subscription_id, _event, _object)
58
+ raise NotImplementedError, "#{self.class.name} runs every delivery through trigger: execute_update is not used"
59
+ end
60
+
61
+ # Never used: a result is sent only by the delivery that computed it as its subscriber.
62
+ def deliver(_subscription_id, _result)
63
+ raise NotImplementedError, "#{self.class.name} runs every delivery through trigger: deliver is not used"
64
+ end
65
+
66
+ private
67
+
68
+ def within_budget(ids)
69
+ budget = @settings.max_executions_per_trigger
70
+ return ids if ids.size <= budget
71
+
72
+ record_signal(:subscription_trigger_budget, skipped: ids.size - budget)
73
+ # From a random start each time, so a topic over the budget never skips the same subscribers on every trigger.
74
+ ids.rotate(rand(ids.size)).first(budget)
75
+ end
76
+
77
+ # The Delivery for one subscriber, or nil when nothing is sent.
78
+ def run(id, digest, object, now)
79
+ sealed = @store.read(id)
80
+ if sealed.nil?
81
+ @store.delete(id)
82
+ return nil
83
+ end
84
+ record = open_record(id, sealed)
85
+ return nil unless record
86
+ return Delivery.new(id: id, message: message_for(record, { more: false }), ending: :expired) if record.expired?(now)
87
+
88
+ unless record.topics.include?(digest)
89
+ # The index and the record drifted: never run it for a topic it was not written under.
90
+ @store.delete(id)
91
+ record_signal(:subscription_ended, reason: :drift, subscription: id_digest(id))
92
+ return nil
93
+ end
94
+
95
+ values = begin
96
+ fresh_context(record)
97
+ rescue ViewerGone
98
+ return Delivery.new(id: id, message: message_for(record, { more: false }), ending: :viewer_gone)
99
+ end
100
+ query = delivery_query(record, digest, values, object)
101
+ result = record.engine == :next ? @schema.multiplex_next([query]).first : @schema.multiplex([query]).first
102
+ conclude(record, query, result)
103
+ end
104
+
105
+ # The record `sealed` holds, or nil after deleting it: a record that does not open (another key, moved under
106
+ # another id, tampered) or does not parse is never loaded.
107
+ def open_record(id, sealed)
108
+ text = @encoder.open(sealed, aad: id, purpose: SEAL_PURPOSE).dup.force_encoding(Encoding::UTF_8)
109
+ record = Record.from_h(JSON.parse(text))
110
+ raise ArgumentError, "the record holds another id" unless record.id == id
111
+
112
+ record
113
+ rescue StandardError
114
+ @store.delete(id)
115
+ record_signal(:subscription_record_unreadable, subscription: id_digest(id))
116
+ nil
117
+ end
118
+
119
+ # A fresh context Hash: the stored `context_keys:` values, the decided version, the persisted operation and the
120
+ # raw-query flag as stored, then the reloaded viewer. Nothing from the trigger.
121
+ def fresh_context(record)
122
+ keys = @settings.context_keys.keys.to_h { |key| [key.to_s, key] }
123
+ values = record.context.each_with_object({}) do |(key, dumped), loaded|
124
+ name = keys[key]
125
+ loaded[name] = GraphQL::Subscriptions::Serialize.load(dumped) if name
126
+ end
127
+ values[:armory_version] = record.version if record.version
128
+ values[:operation_id] = record.operation_id if record.operation_id
129
+ values[:armory_allow_raw_query] = true if record.raw_query
130
+ @settings.viewer.load(record.viewer_id, values) unless record.anonymous?
131
+ values
132
+ end
133
+
134
+ # Built through the schema's query class, so Versioning, PersistedQueries and Authorization decide it like a
135
+ # request; then marked as a delivery (a namespace exists only after `Query.new`, and no request can write it).
136
+ def delivery_query(record, digest, values, object)
137
+ options = { variables: JSON.parse(record.variables), operation_name: record.operation_name, context: values,
138
+ subscription_topic: record.graphql_topic(digest), root_value: object, validate: true }
139
+ options[:visibility_profile] = record.visibility_profile.to_sym if record.visibility_profile
140
+ query = @schema.query_class.new(@schema, record.document, **options)
141
+ Subscriptions.delivery!(query.context, record.id)
142
+ query
143
+ end
144
+
145
+ # graphql-ruby's own flags first (`unsubscribe`, `:no_update`), then the ending rule: no `data`, or a null root
146
+ # field, ends the subscription with a final message. A nested null does not.
147
+ def conclude(record, query, result)
148
+ flags = query.context.namespace(:subscriptions)
149
+ hash = result.to_h
150
+ if flags[:unsubscribed]
151
+ payload = flags[:final_update] ? { result: hash, more: false } : { more: false }
152
+ return delivery_for(record, query, payload, :unsubscribed)
153
+ end
154
+ return nil if flags[:no_update]
155
+
156
+ ending = refused?(hash) ? :refused : nil
157
+ delivery_for(record, query, { result: hash, more: ending.nil? }, ending)
158
+ end
159
+
160
+ def refused?(hash)
161
+ data = hash["data"]
162
+ !data.is_a?(Hash) || data.empty? || data.each_value.any?(&:nil?)
163
+ end
164
+
165
+ def delivery_for(record, query, payload, ending)
166
+ message = message_for(record, payload, context: query.context)
167
+ delivered = nil
168
+ if message&.payload&.key?(:result) || message&.payload&.key?(:compressed_result)
169
+ delivered = { subscription: id_digest(record.id), complexity: complexity_of(query), bytes: JSON.generate(message.payload).bytesize }
170
+ end
171
+ Delivery.new(id: record.id, message: message, ending: ending, context: query.context, delivered: delivered)
172
+ end
173
+
174
+ # The transport's message for `payload`: compressed when the transport says the client inflates, replaced with
175
+ # RESULT_TOO_LARGE over its limit. Nil when even that does not fit (recorded): nothing is sent.
176
+ def message_for(record, payload, context: nil)
177
+ channel = @transport.channel_for(record.id, record.viewer_digest)
178
+ capabilities = @transport.capabilities
179
+ payload = compressed(payload) if payload.key?(:result) && capabilities.compress?
180
+ bytes = JSON.generate(payload).bytesize
181
+ if bytes > capabilities.max_payload_bytes
182
+ record_signal(:subscription_payload_too_large, context: context, subscription: id_digest(record.id), bytes: bytes, limit: capabilities.max_payload_bytes)
183
+ payload = { result: TOO_LARGE, more: payload[:more] }
184
+ return nil if JSON.generate(payload).bytesize > capabilities.max_payload_bytes
185
+ end
186
+ Message.new(channel: channel, payload: payload)
187
+ end
188
+
189
+ def compressed(payload)
190
+ { compressed_result: Base64.strict_encode64(Zlib::Deflate.deflate(JSON.generate(payload[:result]))), more: payload[:more] }
191
+ end
192
+
193
+ # The delivery's complexity for telemetry, when someone listens: graphql-ruby's own QueryComplexity analyzer.
194
+ def complexity_of(query)
195
+ return nil unless @telemetry.listening? && query.valid?
196
+
197
+ complexity = GraphQL::Analysis.analyze_query(query, [GraphQL::Analysis::QueryComplexity]).first
198
+ complexity.is_a?(Integer) ? complexity : nil
199
+ rescue StandardError
200
+ nil
201
+ end
202
+
203
+ # Sends in batches of the transport's max_batch, then deletes what ended (whether or not it was sent) and what
204
+ # the transport reports gone.
205
+ def publish(deliveries, errors)
206
+ deliveries.each_slice(@transport.capabilities.max_batch) do |batch|
207
+ sendable = batch.reject { |delivery| delivery.message.nil? }
208
+ outcomes = send_batch(sendable, errors)
209
+ sendable.each_with_index do |delivery, index|
210
+ settle(delivery, outcomes&.find { |outcome| outcome.is_a?(Outcome) && outcome.index == index })
211
+ end
212
+ batch.each { |delivery| finish(delivery) if delivery.ending }
213
+ end
214
+ end
215
+
216
+ def send_batch(sendable, errors)
217
+ return [] if sendable.empty?
218
+
219
+ outcomes = @transport.publish(sendable.map(&:message))
220
+ raise TransportError, "publish answered #{outcomes.class}, not an Array of Outcomes" unless outcomes.is_a?(Array)
221
+
222
+ outcomes
223
+ rescue StandardError => error
224
+ record_signal(:subscription_transport_error, operation: :publish, error: error.class.name)
225
+ errors << error
226
+ nil
227
+ end
228
+
229
+ def settle(delivery, outcome)
230
+ return unless outcome
231
+
232
+ case outcome.status
233
+ when :ok
234
+ record_signal(:subscription_delivered, context: delivery.context, **delivery.delivered) if delivery.delivered
235
+ when :gone
236
+ delivery.ending = nil
237
+ finish(delivery, :gone)
238
+ when :refused
239
+ record_signal(:subscription_transport_error, context: delivery.context, operation: :publish, outcome: :refused, reason: outcome.reason)
240
+ end
241
+ end
242
+
243
+ def finish(delivery, reason = delivery.ending)
244
+ @store.delete(delivery.id)
245
+ record_signal(:subscription_ended, context: delivery.context, reason: reason, subscription: id_digest(delivery.id))
246
+ end
247
+ end
248
+ end
249
+ end
250
+ end
@@ -0,0 +1,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Core < GraphQL::Subscriptions
7
+ # The values `use` was given, checked: the viewer, the context keys a delivery restores, the lifetime and the
8
+ # caps. `new` is inert (the Null viewer refuses every subscription); `build` checks each option. The class
9
+ # methods check the options, the dependencies and the schema for `Core.build`.
10
+ class Settings
11
+ VALUES = %i[context_keys max_lifetime max_per_viewer max_per_topic max_executions_per_trigger on_delivery_error].freeze
12
+ DEPENDENCIES = %i[store transport encoder].freeze
13
+ OTHERS = %i[viewer anonymous cap_key sinks on_sink_error].freeze
14
+ KNOWN = (VALUES + DEPENDENCIES + OTHERS).freeze
15
+ REQUIRED = %i[store transport encoder max_lifetime].freeze
16
+ ON_DELIVERY_ERROR = %i[record raise].freeze
17
+ DEFAULTS = { context_keys: {}, max_per_viewer: 100, max_per_topic: 10_000, max_executions_per_trigger: 10_000, on_delivery_error: :record }.freeze
18
+
19
+ # graphql-ruby's own options, which this backend never honours.
20
+ REFUSED = {
21
+ broadcast: "broadcast: is refused: one execution would be sent to every viewer of a topic; every subscriber runs with its own context",
22
+ default_broadcastable: "default_broadcastable: is refused: no subscription is broadcast",
23
+ validate_update: "validate_update: is refused: every delivery is validated like a request (PersistedQueries and Versioning refuse through validation)"
24
+ }.freeze
25
+
26
+ STORE_METHODS = %i[write read ids delete count cleanup].freeze
27
+ TRANSPORT_METHODS = %i[capabilities authorization channel_for id_from publish authorize_channel authorize_viewer webhook].freeze
28
+ ENCODER_METHODS = %i[seal open mac].freeze
29
+
30
+ attr_reader :viewer, :context_keys, :max_lifetime, :max_per_viewer, :max_per_topic, :max_executions_per_trigger, :on_delivery_error
31
+
32
+ # Milliseconds for `max_lifetime`: everything else as given.
33
+ def initialize(viewer: Viewer::Null.new, context_keys: {}, max_lifetime: 1_000, max_per_viewer: 1, max_per_topic: 1, max_executions_per_trigger: 1,
34
+ on_delivery_error: :record)
35
+ @viewer = viewer
36
+ @context_keys = context_keys
37
+ @max_lifetime = max_lifetime
38
+ @max_per_viewer = max_per_viewer
39
+ @max_per_topic = max_per_topic
40
+ @max_executions_per_trigger = max_executions_per_trigger
41
+ @on_delivery_error = on_delivery_error
42
+ freeze
43
+ end
44
+
45
+ def self.build(viewer:, max_lifetime:, **options)
46
+ values = DEFAULTS.merge(options)
47
+ new(viewer: viewer, context_keys: context_keys(values[:context_keys]), max_lifetime: lifetime(max_lifetime),
48
+ max_per_viewer: positive(:max_per_viewer, values[:max_per_viewer]), max_per_topic: positive(:max_per_topic, values[:max_per_topic]),
49
+ max_executions_per_trigger: positive(:max_executions_per_trigger, values[:max_executions_per_trigger]),
50
+ on_delivery_error: on_delivery_error(values[:on_delivery_error]))
51
+ end
52
+
53
+ def self.check_options(options)
54
+ options.each_key do |name|
55
+ raise ConfigurationError, REFUSED.fetch(name) if REFUSED.key?(name)
56
+ raise ConfigurationError, "unknown option #{name.inspect}: GraphQL::Armory::Subscriptions takes #{KNOWN.inspect}" unless KNOWN.include?(name)
57
+ end
58
+ missing = REQUIRED.reject { |name| options.key?(name) }
59
+ raise ConfigurationError, "missing #{missing.map { |name| "#{name}:" }.join(", ")} (#{REQUIRED.map { |name| "#{name}:" }.join(", ")} are required)" unless missing.empty?
60
+ end
61
+
62
+ # `{ key: "why every delivery needs it" }`: the only context values stored with a subscription.
63
+ def self.context_keys(keys)
64
+ valid = keys.is_a?(Hash) && keys.all? { |key, reason| key.is_a?(Symbol) && reason.is_a?(String) && !reason.strip.empty? }
65
+ raise ConfigurationError, "context_keys: must map Symbol keys to the reason each one is stored, like { tenant_id: \"scopes every query\" }" unless valid
66
+
67
+ reserved = keys.keys & RESERVED_KEYS
68
+ raise ConfigurationError, "context_keys: #{reserved.inspect} are set by the core on every delivery, from the subscription itself" unless reserved.empty?
69
+
70
+ keys.to_h { |key, reason| [key, reason.dup.freeze] }.freeze
71
+ end
72
+
73
+ # Context keys a delivery takes from the stored record, never from `context_keys:`.
74
+ RESERVED_KEYS = %i[armory_version operation_id armory_allow_raw_query visibility_profile subscription_id].freeze
75
+
76
+ # Seconds in, milliseconds out.
77
+ def self.lifetime(value)
78
+ unless value.is_a?(Numeric) && value.real? && value.finite? && value.positive? && (value * 1000).round >= 1
79
+ raise ConfigurationError, "max_lifetime: must be a positive number of seconds (every subscription expires: no provider reports a gone client reliably), got #{value.inspect}"
80
+ end
81
+
82
+ (value * 1000).round
83
+ end
84
+
85
+ def self.positive(name, value)
86
+ raise ConfigurationError, "#{name}: must be a positive Integer, got #{value.inspect}" unless value.is_a?(Integer) && value.positive?
87
+
88
+ value
89
+ end
90
+
91
+ def self.on_delivery_error(value)
92
+ raise ConfigurationError, "on_delivery_error: must be :record or :raise, got #{value.inspect}" unless ON_DELIVERY_ERROR.include?(value)
93
+
94
+ value
95
+ end
96
+
97
+ def self.store(store)
98
+ raise ConfigurationError, "store: Store::Null keeps no subscription: give a MemoryStore (one process) or a RedisStore" if store.is_a?(Store::Null)
99
+ raise ConfigurationError, "store: must answer #{STORE_METHODS.inspect} (a MemoryStore, a RedisStore), got #{store.class}" unless STORE_METHODS.all? { |name| store.respond_to?(name) }
100
+
101
+ store
102
+ end
103
+
104
+ def self.transport(transport)
105
+ raise ConfigurationError, "transport: Transport::Null delivers nothing: give a transport such as Pusher or Ably" if transport.is_a?(Transport::Null)
106
+ raise ConfigurationError, "transport: must answer #{TRANSPORT_METHODS.inspect}, got #{transport.class}" unless TRANSPORT_METHODS.all? { |name| transport.respond_to?(name) }
107
+ raise ConfigurationError, "transport: #{transport.class} must declare its capabilities (a Capabilities)" unless transport.capabilities.is_a?(Capabilities)
108
+ raise ConfigurationError, "transport: #{transport.class} authorization must be one of #{Transport::AUTHORIZATIONS.inspect}" unless Transport::AUTHORIZATIONS.include?(transport.authorization)
109
+
110
+ transport
111
+ end
112
+
113
+ def self.encoder(encoder)
114
+ if encoder.nil? || encoder.equal?(Encoder::Null)
115
+ raise ConfigurationError, "encoder: is required (an Encoder subclass with a key): it seals stored subscriptions and digests topics and viewers"
116
+ end
117
+ raise ConfigurationError, "encoder: must answer #{ENCODER_METHODS.inspect} (an Encoder subclass), got #{encoder.class}" unless ENCODER_METHODS.all? { |name| encoder.respond_to?(name) }
118
+
119
+ encoder
120
+ end
121
+
122
+ # With a viewer, a client must not be able to read another viewer's channel.
123
+ def self.check_transport(transport, viewer)
124
+ return if viewer.anonymous? || transport.capabilities.viewer_bound?
125
+
126
+ raise ConfigurationError, "transport: #{transport.class} is not viewer_bound (it cannot refuse a client a channel), so with viewer: " \
127
+ "one viewer could read another's subscriptions: use a transport with private channels or capability tokens"
128
+ end
129
+
130
+ # Each subscription field (every definition, so every version of a Versioning schema): no `topic_for`
131
+ # override (its topics would never meet the core's digest), no `loads:`/`prepare:` argument and no input object
132
+ # with its own `prepare` (the write side and the trigger side would hold different values), and a
133
+ # `subscription_scope` key a delivery can restore.
134
+ def self.check_schema(schema, settings)
135
+ root = schema.subscription
136
+ raise ConfigurationError, "#{schema} has no subscription root: declare `subscription(Types::Subscription)` before `use GraphQL::Armory::Subscriptions`" unless root
137
+
138
+ restorable = settings.context_keys.keys + settings.viewer.sets
139
+ root.all_field_definitions.each do |field|
140
+ check_topic_for(field)
141
+ unsafe = unsafe_argument(field, [])
142
+ raise ConfigurationError, "#{field.path}: #{unsafe} cannot meet its trigger (the subscription and the trigger would digest different values): remove it from the subscription field" if unsafe
143
+
144
+ scope = field.subscription_scope
145
+ next if scope.nil? || restorable.include?(scope.to_sym)
146
+
147
+ raise ConfigurationError, "#{field.path} is scoped by context[#{scope.inspect}], which a delivery cannot restore: add it to context_keys: or to viewer: { sets: [...] }"
148
+ end
149
+ end
150
+
151
+ def self.check_topic_for(field)
152
+ resolver = field.resolver
153
+ return unless resolver.respond_to?(:topic_for)
154
+ return if resolver.method(:topic_for).owner == GraphQL::Schema::Subscription.singleton_class
155
+
156
+ raise ConfigurationError, "#{field.path}: #{resolver} overrides topic_for: its topics would never meet the core's topic digest; remove the override"
157
+ end
158
+ private_class_method :check_topic_for
159
+
160
+ # The first argument (by path) with `loads:` or `prepare:`, or an input object with its own `prepare`.
161
+ def self.unsafe_argument(owner, seen)
162
+ owner.all_argument_definitions.each do |argument|
163
+ return "the loads: argument #{argument.path}" if argument.loads
164
+ return "the prepare: argument #{argument.path}" if argument.prepare
165
+
166
+ type = argument.type.unwrap
167
+ next unless type.kind.input_object? && !seen.include?(type)
168
+
169
+ seen << type
170
+ return "the input object #{type.graphql_name} with its own prepare" if type.instance_method(:prepare).owner != GraphQL::Schema::InputObject
171
+
172
+ found = unsafe_argument(type, seen)
173
+ return found if found
174
+ end
175
+ nil
176
+ end
177
+ private_class_method :unsafe_argument
178
+ end
179
+ end
180
+ end
181
+ end
182
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Core < GraphQL::Subscriptions
7
+ # graphql-ruby's Event, with the core's topic digest of the triggered field, arguments and scope: the key of the
8
+ # store's topic index.
9
+ class Event < GraphQL::Subscriptions::Event
10
+ attr_reader :digest
11
+
12
+ def initialize(digest:, **options)
13
+ super(**options)
14
+ @digest = digest
15
+ end
16
+ end
17
+
18
+ # Runs every live subscriber of `event_name` with `args` in `scope` against `object`, each as itself.
19
+ #
20
+ # - `context:` must be empty: a trigger never changes who a subscriber is or which version it runs (graphql-ruby
21
+ # merges it over each subscriber's context). It raises ArgumentError otherwise.
22
+ # - `version:` is the API version used only to look the field and its arguments up (with Versioning's
23
+ # `default: :refuse`, a trigger without it finds nothing); a delivery always runs its subscriber's version.
24
+ #
25
+ # An unknown field or argument raises GraphQL::Subscriptions::InvalidTriggerError; a value its type cannot
26
+ # coerce, or a scope the topic cannot hold, raises ArgumentError.
27
+ def trigger(event_name, args, object, scope: nil, context: {}, version: nil)
28
+ unless context.nil? || (context.respond_to?(:empty?) && context.empty?)
29
+ raise ArgumentError, "trigger context: is refused: a delivery runs as its subscriber only (its stored context keys and reloaded viewer); " \
30
+ "use version: to pick the version the field is looked up in"
31
+ end
32
+ raise ArgumentError, "trigger version: must be a non-empty String or nil" unless version.nil? || (version.is_a?(String) && !version.empty?)
33
+
34
+ lookup = lookup_query(version)
35
+ name, field = trigger_field(lookup, event_name.to_s)
36
+ arguments = normalize_arguments(name, field, args, lookup.context)
37
+ digest = Topic.digest(@encoder, field, arguments, scope, context: lookup.context)
38
+ execute_all(Event.new(digest: digest, name: name, arguments: arguments, field: field, scope: scope, context: lookup.context), object)
39
+ end
40
+
41
+ private
42
+
43
+ # A query built without the schema's query class, so PersistedQueries counts nothing (it is never run) and
44
+ # Versioning decides it from `version:` alone.
45
+ def lookup_query(version)
46
+ GraphQL::Query.new(@schema, "{ __typename }", validate: false, context: version ? { armory_version: version } : {})
47
+ end
48
+
49
+ def trigger_field(lookup, name)
50
+ root = @schema.subscription
51
+ field = lookup.types.field(root, name)
52
+ return [name, field] if field
53
+
54
+ normalized = normalize_name(name)
55
+ field = lookup.types.field(root, normalized)
56
+ raise InvalidTriggerError, "No subscription matching trigger: #{name} (looked for #{root.graphql_name}.#{normalized})" unless field
57
+
58
+ [normalized, field]
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end