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,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Core < GraphQL::Subscriptions
7
+ # The viewer could not be loaded back for a delivery (its `load` raised, or the context it built does not dump
8
+ # to the stored id): the subscription ends.
9
+ class ViewerGone < StandardError; end
10
+
11
+ # Who the subscriber is, across processes: the `viewer:` option (`Bound`), or `anonymous:` with `cap_key:`
12
+ # (`Anonymous`). `Null` is what an inert backend holds: it refuses every subscription.
13
+ module Viewer
14
+ KEYS = %i[dump load sets].freeze
15
+
16
+ def self.build(viewer:, anonymous:, cap_key:)
17
+ return anonymous(anonymous, cap_key) if viewer.nil?
18
+
19
+ unless anonymous.nil? && cap_key.nil?
20
+ raise ConfigurationError, "anonymous: and cap_key: are for viewer-independent subscriptions only: give viewer: or anonymous:, not both"
21
+ end
22
+ raise ConfigurationError, "viewer: must be a Hash with dump:, load: and optionally sets:, got #{viewer.class}" unless viewer.is_a?(Hash)
23
+
24
+ unknown = viewer.keys - KEYS
25
+ raise ConfigurationError, "viewer: unknown keys #{unknown.inspect}: it takes #{KEYS.inspect}" unless unknown.empty?
26
+
27
+ dump = viewer[:dump]
28
+ load = viewer[:load]
29
+ raise ConfigurationError, "viewer: dump: must be a callable taking the context and answering the viewer's id String" unless dump.respond_to?(:call)
30
+ raise ConfigurationError, "viewer: load: must be a callable taking the id and the delivery's context Hash" unless load.respond_to?(:call)
31
+
32
+ sets = viewer.fetch(:sets, [])
33
+ raise ConfigurationError, "viewer: sets: must be an Array of the context keys load: sets (Symbols)" unless sets.is_a?(Array) && sets.all?(Symbol)
34
+
35
+ Bound.new(dump: dump, load: load, sets: sets)
36
+ end
37
+
38
+ def self.anonymous(reason, cap_key)
39
+ if reason.nil?
40
+ raise ConfigurationError, "viewer: is required (who the subscriber is, so a delivery runs as them and a channel is theirs only), " \
41
+ "or anonymous: \"why every subscription is viewer-independent\" with cap_key:"
42
+ end
43
+ raise ConfigurationError, "anonymous: must be a non-empty String saying why no subscription depends on the viewer" unless reason.is_a?(String) && !reason.strip.empty?
44
+ raise ConfigurationError, "anonymous: needs cap_key: (a callable taking the context, answering what max_per_viewer counts by, such as the client IP)" unless cap_key.respond_to?(:call)
45
+
46
+ Anonymous.new(reason: reason, cap_key: cap_key)
47
+ end
48
+ private_class_method :anonymous
49
+
50
+ # A configured viewer: `dump` answers the subscriber's id String from a context, `load` puts the viewer back
51
+ # into a delivery's context Hash, `sets` names the context keys `load` sets.
52
+ class Bound
53
+ attr_reader :sets
54
+
55
+ def initialize(dump:, load:, sets: [])
56
+ @dump = dump
57
+ @load = load
58
+ @sets = sets.dup.freeze
59
+ freeze
60
+ end
61
+
62
+ def anonymous? = false
63
+ def reason = nil
64
+
65
+ # The viewer's id: a non-empty String, or RefusedError (a dump that raises or answers anything else).
66
+ def id(context)
67
+ dumped = begin
68
+ @dump.call(context)
69
+ rescue StandardError
70
+ raise RefusedError.new("the viewer could not be identified", reason: :viewer)
71
+ end
72
+ raise RefusedError.new("the viewer could not be identified", reason: :viewer) unless dumped.is_a?(String) && !dumped.empty?
73
+
74
+ dumped
75
+ end
76
+
77
+ # What max_per_viewer counts by.
78
+ def cap_subject(context)
79
+ id(context)
80
+ end
81
+
82
+ # Loads `id` into `values`, then checks it dumps back to the same id: a viewer that is gone, or a load that
83
+ # left someone else, raises ViewerGone.
84
+ def load(id, values)
85
+ begin
86
+ @load.call(id, values)
87
+ rescue StandardError
88
+ raise ViewerGone
89
+ end
90
+ loaded = begin
91
+ id(values)
92
+ rescue RefusedError
93
+ raise ViewerGone
94
+ end
95
+ raise ViewerGone unless loaded == id
96
+
97
+ values
98
+ end
99
+
100
+ def inspect = "#<#{self.class.name} sets=#{sets.inspect}>"
101
+ end
102
+
103
+ # No viewer: every subscription is viewer-independent; `cap_key` answers what max_per_viewer counts by.
104
+ class Anonymous
105
+ attr_reader :reason
106
+
107
+ def initialize(reason:, cap_key:)
108
+ @reason = reason.dup.freeze
109
+ @cap_key = cap_key
110
+ freeze
111
+ end
112
+
113
+ def anonymous? = true
114
+ def sets = [].freeze
115
+ def id(_context) = nil
116
+
117
+ def cap_subject(context)
118
+ key = begin
119
+ @cap_key.call(context)
120
+ rescue StandardError
121
+ raise RefusedError.new("the client could not be identified", reason: :cap_key)
122
+ end
123
+ raise RefusedError.new("the client could not be identified", reason: :cap_key) unless key.is_a?(String) && !key.empty?
124
+
125
+ key
126
+ end
127
+
128
+ def load(_id, values) = values
129
+
130
+ def inspect = "#<#{self.class.name}>"
131
+ end
132
+
133
+ # The viewer of an inert backend: identifies no one, so every subscription is refused.
134
+ class Null
135
+ def anonymous? = false
136
+ def reason = nil
137
+ def sets = [].freeze
138
+
139
+ def id(_context)
140
+ raise RefusedError.new("no viewer configured", reason: :viewer)
141
+ end
142
+
143
+ def cap_subject(context) = id(context)
144
+
145
+ def load(_id, _values)
146
+ raise ViewerGone
147
+ end
148
+ end
149
+ end
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,172 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Core < GraphQL::Subscriptions
7
+ # What a refusal tells the client: the code, never a value it sent.
8
+ REFUSALS = {
9
+ viewer_cap: ["Too many subscriptions", "SUBSCRIPTION_LIMIT"],
10
+ topic_cap: ["Too many subscriptions", "SUBSCRIPTION_LIMIT"]
11
+ }.freeze
12
+ REFUSED = ["Subscription refused", "SUBSCRIPTION_REFUSED"].freeze
13
+
14
+ # Called by graphql-ruby when a subscription operation finished (both engines): stores the subscription, or
15
+ # refuses it with a GraphQL error and stores nothing. Nothing from the context is kept but the viewer's id and
16
+ # the `context_keys:` values.
17
+ def write_subscription(query, events)
18
+ context = query.context
19
+ raise RefusedError.new("subscription_id was set before the subscription was written", reason: :client_id) unless context[:subscription_id].nil?
20
+
21
+ now = now_ms
22
+ viewer = @settings.viewer
23
+ viewer_id = viewer.id(context)
24
+ viewer_digest = viewer_id ? hex_mac(viewer_id, VIEWER_PURPOSE) : Record::ANONYMOUS
25
+ cap_digest = viewer_id ? viewer_digest : hex_mac(viewer.cap_subject(context), CAP_PURPOSE)
26
+ id = build_id
27
+ record = Record.new(
28
+ id: id, document: document_of(query), operation_name: query.operation_name, variables: dump_variables(query),
29
+ operation_id: persisted_id(context), raw_query: context[:armory_allow_raw_query] == true, version: version_label(context),
30
+ visibility_profile: visibility_profile(context), engine: context[:__graphql_execute_next] == true ? :next : :interpreter,
31
+ viewer_id: viewer_id, viewer_digest: viewer_digest, context: stored_context(context), events: digested(query, events),
32
+ created_at: now, expires_at: now + @settings.max_lifetime
33
+ )
34
+ store_record(record, cap_digest, now)
35
+
36
+ channel = @transport.channel_for(id, viewer_digest)
37
+ context[:subscription_id] = id
38
+ context.namespace(:armory)[:subscription_channel] = channel
39
+ (context.namespace(:__query_result_extensions__)["subscription"] = { "channel" => channel }) if channel
40
+ record_signal(:subscription_created, context: context, engine: record.engine, events: record.events.size)
41
+ nil
42
+ rescue RefusedError => error
43
+ refuse(query, error.reason)
44
+ rescue ArgumentError
45
+ # A value the record cannot hold (an empty operation name or profile): refused, never stored half-made.
46
+ refuse(query, :invalid)
47
+ end
48
+
49
+ private
50
+
51
+ def store_record(record, cap_digest, now)
52
+ answer = begin
53
+ sealed = @encoder.seal(JSON.generate(record.to_h), aad: record.id, purpose: SEAL_PURPOSE)
54
+ @store.write(record.id, sealed, topics: record.topics, viewer: cap_digest, expires_at: record.expires_at,
55
+ viewer_cap: @settings.max_per_viewer, topic_cap: @settings.max_per_topic, now: now)
56
+ rescue StandardError
57
+ raise RefusedError.new("the store failed", reason: :store)
58
+ end
59
+ return if answer == :ok
60
+
61
+ raise RefusedError.new("the store refused it", reason: Store::ANSWERS.include?(answer) ? answer : :store)
62
+ end
63
+
64
+ def refuse(query, reason)
65
+ message, code = REFUSALS.fetch(reason, REFUSED)
66
+ query.context.errors << GraphQL::ExecutionError.new(message, extensions: { "code" => code })
67
+ record_signal(:subscription_refused, context: query.context, reason: reason)
68
+ nil
69
+ end
70
+
71
+ # The text a delivery runs: the request's, or the persisted operation's document printed (what PersistedQueries
72
+ # compares a re-sent text with).
73
+ def document_of(query)
74
+ text = query.query_string
75
+ return text if text.is_a?(String) && !text.empty?
76
+
77
+ query.document.to_query_string
78
+ end
79
+
80
+ # The client's variables as plain JSON, never through graphql-ruby's Serialize: before graphql 2.6.11 its
81
+ # `dump` leaves a client's `__gid__`/`__sym__` keys unescaped, and its `load` would then locate or convert them
82
+ # at delivery. Variables that do not come back the same from JSON (other than String keys) are refused.
83
+ def dump_variables(query)
84
+ variables = query.provided_variables
85
+ variables = variables.to_unsafe_h if variables.respond_to?(:to_unsafe_h)
86
+ variables ||= {}
87
+ raise RefusedError.new("the variables are not a Hash", reason: :variables) unless variables.is_a?(Hash)
88
+
89
+ text = JSON.generate(variables)
90
+ raise RefusedError.new("the variables do not round-trip through JSON", reason: :variables) unless JSON.parse(text) == string_keys(variables)
91
+
92
+ text
93
+ rescue RefusedError
94
+ raise
95
+ rescue StandardError
96
+ raise RefusedError.new("the variables cannot be stored", reason: :variables)
97
+ end
98
+
99
+ def string_keys(value)
100
+ case value
101
+ when Hash then value.to_h { |key, item| [key.to_s, string_keys(item)] }
102
+ when Array then value.map { |item| string_keys(item) }
103
+ else value
104
+ end
105
+ end
106
+
107
+ # graphql-ruby's own encoding, so its `load` reads it back. graphql before 2.5 passes `quirks_mode:` to
108
+ # `JSON.generate`, which json 3 refuses as an unknown keyword: the same value is then generated
109
+ # without it.
110
+ def serialize(value)
111
+ GraphQL::Subscriptions::Serialize.dump(value)
112
+ rescue ArgumentError
113
+ JSON.generate(GraphQL::Subscriptions::Serialize.send(:dump_value, value))
114
+ end
115
+
116
+ # Only when PersistedQueries ran the stored operation: its mark lives where a client cannot write.
117
+ def persisted_id(context)
118
+ return nil unless Caching::RecordKeys.persisted?(context)
119
+
120
+ operation_id = context[:operation_id]
121
+ operation_id.is_a?(String) && !operation_id.empty? ? operation_id : nil
122
+ end
123
+
124
+ # The label Versioning decided for the request, not the raw `armory_version`.
125
+ def version_label(context)
126
+ return nil unless context.namespace?(:armory)
127
+
128
+ version = context.namespace(:armory)[:version]
129
+ version.respond_to?(:label) && version.label.is_a?(String) ? version.label : nil
130
+ end
131
+
132
+ def visibility_profile(context)
133
+ profile = context[:visibility_profile]
134
+ profile.nil? ? nil : profile.to_s
135
+ end
136
+
137
+ # Each configured key the context holds, dumped, then loaded back and compared: `dump_value` passes unknown
138
+ # objects through, which would come back as something else.
139
+ def stored_context(context)
140
+ @settings.context_keys.each_key.with_object({}) do |key, stored|
141
+ next unless context.key?(key)
142
+
143
+ value = context[key]
144
+ dumped = serialize(value)
145
+ raise RefusedError.new("a context key does not round-trip", reason: :context) unless GraphQL::Subscriptions::Serialize.load(dumped) == value
146
+
147
+ stored[key.to_s] = dumped
148
+ rescue RefusedError
149
+ raise
150
+ rescue StandardError
151
+ raise RefusedError.new("a context key cannot be stored", reason: :context)
152
+ end
153
+ end
154
+
155
+ # graphql-ruby's topic and the core's digest for each event.
156
+ def digested(query, events)
157
+ events.map do |event|
158
+ field = query.types.field(@schema.subscription, event.name) || raise(RefusedError.new("unknown subscription field", reason: :topic))
159
+ scope_key = field.subscription_scope
160
+ scope = scope_key ? query.context[scope_key] : nil
161
+ digest = begin
162
+ Topic.digest(@encoder, field, event.arguments, scope, context: query.context)
163
+ rescue ArgumentError
164
+ raise RefusedError.new("the arguments or scope do not make a topic", reason: :topic)
165
+ end
166
+ { graphql_topic: event.topic, digest: digest }
167
+ end
168
+ end
169
+ end
170
+ end
171
+ end
172
+ end
@@ -0,0 +1,200 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "json"
5
+ require "zlib"
6
+ require "base64"
7
+ require "openssl"
8
+
9
+ module GraphQL
10
+ module Armory
11
+ module Subscriptions
12
+ # The schema plugin: `use GraphQL::Armory::Subscriptions, store:, transport:, encoder:, viewer:, max_lifetime:, ...`
13
+ # installs a `Core` built and checked by `Core.build` (see docs/subscriptions.md).
14
+ def self.use(schema, **options)
15
+ Core.use(schema, **options)
16
+ end
17
+
18
+ # A checked, wired backend for `schema`, without installing it.
19
+ def self.build(schema, **options)
20
+ Core.build(schema, **options)
21
+ end
22
+
23
+ # An inert backend: it stores nothing, delivers nothing and authorizes no channel.
24
+ def self.new(**dependencies)
25
+ Core.new(**dependencies)
26
+ end
27
+
28
+ DELIVERY = :subscription_delivery
29
+
30
+ # What the core puts in a delivery's `namespace(:armory)`: an object only this code makes, under a namespace no
31
+ # request can write (graphql-ruby keeps namespaces apart from the context values the app provides).
32
+ class DeliveryMark
33
+ def initialize
34
+ freeze
35
+ end
36
+
37
+ def inspect = "#<#{self.class.name}>"
38
+ end
39
+ private_constant :DeliveryMark
40
+
41
+ # Marks `context` (a query's, after `Query.new`) as a subscription delivery: server work a trigger caused, which
42
+ # no rate limiter charges to the subscriber. The id is not kept: a mark may end up in a log.
43
+ def self.delivery!(context, _id)
44
+ context.namespace(:armory)[DELIVERY] = DeliveryMark.new
45
+ nil
46
+ end
47
+
48
+ # Whether `context` is a query context the core marked as a delivery. Anything else answers false: a Hash, nil,
49
+ # NullContext, a context whose request put any value of its own anywhere.
50
+ def self.delivery?(context)
51
+ return false unless context.is_a?(GraphQL::Query::Context) && !context.is_a?(GraphQL::Query::NullContext) && context.namespace?(:armory)
52
+
53
+ context.namespace(:armory)[DELIVERY].is_a?(DeliveryMark)
54
+ end
55
+
56
+ # The graphql-ruby subscriptions backend: subscribe (`write_subscription`), `trigger`, delivery, channel and
57
+ # viewer authorization, webhooks and cleanup over a `Store` and a `Transport`. Each delivery runs as the
58
+ # subscriber (stored allow-listed context keys and the reloaded viewer, never the trigger's context) through the
59
+ # schema's own query class, so Authorization, Versioning and PersistedQueries decide it like a request; a
60
+ # refused delivery ends the subscription.
61
+ #
62
+ # `new` is inert: a Null store (refuses every subscription), a Null transport (delivers nothing, authorizes no
63
+ # channel) and the Null encoder (seals and digests nothing). `build` checks every option and wires the real ones;
64
+ # `use` goes through `build`.
65
+ class Core < GraphQL::Subscriptions
66
+ SEAL_PURPOSE = "subscription"
67
+ VIEWER_PURPOSE = "subscription-viewer"
68
+ CAP_PURPOSE = "subscription-cap"
69
+ ID_PURPOSE = "subscription-id"
70
+ ID_BYTES = 32
71
+
72
+ # Installs a built backend on `schema`. Refuses a schema (or a parent) that already has one.
73
+ def self.use(schema, **options)
74
+ if schema.subscriptions(inherited: false)
75
+ raise ConfigurationError, "#{schema} already has subscriptions (#{schema.subscriptions.class}): install GraphQL::Armory::Subscriptions once"
76
+ end
77
+ if schema.subscriptions
78
+ raise ConfigurationError, "#{schema} inherits subscriptions (#{schema.subscriptions.class}) from a parent schema: install GraphQL::Armory::Subscriptions on one schema only"
79
+ end
80
+
81
+ schema.subscriptions = build(schema, **options)
82
+ schema.add_subscription_extension_if_necessary
83
+ nil
84
+ end
85
+
86
+ # Checks every option (unknown ones raise) and the schema's subscription fields, then wires the dependencies.
87
+ def self.build(schema, **options)
88
+ Settings.check_options(options)
89
+ store = Settings.store(options[:store])
90
+ transport = Settings.transport(options[:transport])
91
+ encoder = Settings.encoder(options[:encoder])
92
+ viewer = Viewer.build(viewer: options[:viewer], anonymous: options[:anonymous], cap_key: options[:cap_key])
93
+ settings = Settings.build(viewer: viewer, **options.slice(*Settings::VALUES))
94
+ Settings.check_transport(transport, viewer)
95
+ Settings.check_schema(schema, settings)
96
+ telemetry = Telemetry.build(sinks: options.fetch(:sinks, []), on_sink_error: options[:on_sink_error])
97
+
98
+ new(schema: schema, settings: settings, store: store, transport: transport, encoder: encoder, telemetry: telemetry)
99
+ end
100
+
101
+ attr_reader :schema, :settings, :store, :transport, :encoder
102
+ # A callable answering Integer milliseconds: `Clock.system`, or a `Clock::Substitute` in tests.
103
+ attr_accessor :clock
104
+ # The Telemetry `build` made from `sinks:`, or a `Telemetry::Substitute` in tests.
105
+ attr_accessor :telemetry
106
+
107
+ def initialize(schema: nil, settings: Settings.new, store: Store::Null.new, transport: Transport::Null.new, encoder: Encoder::Null,
108
+ telemetry: Telemetry.new, clock: Clock.system)
109
+ super(schema: schema)
110
+ @settings = settings
111
+ @store = store
112
+ @transport = transport
113
+ @encoder = encoder
114
+ @telemetry = telemetry
115
+ @clock = clock
116
+ end
117
+
118
+ # 32 random bytes, urlsafe base64: never taken from the context, where a client could choose a victim's id.
119
+ def build_id
120
+ SecureRandom.urlsafe_base64(ID_BYTES, false)
121
+ end
122
+
123
+ # Always false: every subscriber is executed with its own context, never grouped with another viewer's.
124
+ def broadcastable?(_query_str, **_query_options)
125
+ false
126
+ end
127
+
128
+ # Always true: a delivery is validated like a request (PersistedQueries and Versioning refuse through it).
129
+ def validate_update?(**_options)
130
+ true
131
+ end
132
+
133
+ # The channel of the subscription `query` created, for the `X-Subscription-ID` header, or nil.
134
+ def channel_for(query)
135
+ context = query.respond_to?(:context) ? query.context : query
136
+ return nil unless context.respond_to?(:namespace?) && context.namespace?(:armory)
137
+
138
+ context.namespace(:armory)[:subscription_channel]
139
+ end
140
+
141
+ def delete_subscription(subscription_id)
142
+ @store.delete(subscription_id)
143
+ end
144
+
145
+ # Removes every record expired at `now` (a Time, or Integer milliseconds; the clock when nil). Answers how many.
146
+ # Call it from a periodic job: an expired record is also dropped when a trigger reaches it.
147
+ def cleanup(now: nil)
148
+ @store.cleanup(now: milliseconds(now))
149
+ end
150
+
151
+ def inspect = "#<#{self.class.name}>"
152
+ alias_method :to_s, :inspect
153
+
154
+ private
155
+
156
+ def now_ms
157
+ value = @clock.call
158
+ raise ConfigurationError, "clock: must answer Integer milliseconds, got #{value.class}" unless value.is_a?(Integer)
159
+
160
+ value
161
+ end
162
+
163
+ def milliseconds(now)
164
+ case now
165
+ when nil then now_ms
166
+ when Integer then now
167
+ when Time then (now.to_r * 1000).to_i
168
+ else raise ArgumentError, "now: must be a Time or Integer milliseconds, got #{now.class}"
169
+ end
170
+ end
171
+
172
+ def hex_mac(text, purpose)
173
+ @encoder.mac(text, purpose: purpose).unpack1("H*")
174
+ end
175
+
176
+ # What telemetry carries instead of an id: a keyed digest, shortened.
177
+ def id_digest(id)
178
+ hex_mac(id, ID_PURPOSE)[0, 16]
179
+ rescue StandardError
180
+ nil
181
+ end
182
+
183
+ def record_signal(signal, context: nil, **data)
184
+ @telemetry.record(signal, context: context, **data)
185
+ rescue StandardError => error
186
+ warn("graphql-armory subscriptions telemetry failed on #{signal}: #{error.class}")
187
+ end
188
+ end
189
+ end
190
+ end
191
+ end
192
+
193
+ require "graphql/armory/subscriptions/core/clock"
194
+ require "graphql/armory/subscriptions/core/viewer"
195
+ require "graphql/armory/subscriptions/core/settings"
196
+ require "graphql/armory/subscriptions/core/write"
197
+ require "graphql/armory/subscriptions/core/trigger"
198
+ require "graphql/armory/subscriptions/core/delivery"
199
+ require "graphql/armory/subscriptions/core/channels"
200
+ require "graphql/armory/subscriptions/core/controls"
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Error < Armory::Error; end
7
+
8
+ # An option of `use`, the schema or a dependency is not set up the way subscriptions need. Raised at boot.
9
+ class ConfigurationError < Error; end
10
+
11
+ # A subscription refused when it is created (a client-chosen id, a viewer that does not dump, a cap reached, an
12
+ # argument or scope that cannot be digested). `reason` is a Symbol for telemetry; the message never quotes a
13
+ # value the client sent.
14
+ class RefusedError < Error
15
+ attr_reader :reason
16
+
17
+ def initialize(message = "subscription refused", reason: :refused)
18
+ raise ArgumentError, "RefusedError reason: must be a Symbol, got #{reason.class}" unless reason.is_a?(Symbol)
19
+
20
+ @reason = reason
21
+ super(message)
22
+ end
23
+ end
24
+
25
+ # The transport or its HTTP client failed (a timeout, a refused connection, an answer it cannot read). The
26
+ # message names the error class, never a URL's query string, a credential or a payload.
27
+ class TransportError < Error; end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Http
7
+ # The HTTP client of a transport nobody wired: every request raises `TransportError`, so a transport built
8
+ # with `new` never reaches a provider.
9
+ class Null
10
+ def post(_url, _body, _headers = {})
11
+ raise TransportError, "no HTTP client wired: build the transport with `build`"
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GraphQL
4
+ module Armory
5
+ module Subscriptions
6
+ class Http
7
+ # An HTTP client that records each request (`requests`: `{ url:, body:, headers: }`), answers the response it is
8
+ # told (200 with `{}` by default) and fails when told: for transport tests, instead of hand-written fakes.
9
+ class Substitute
10
+ attr_reader :requests
11
+
12
+ def initialize
13
+ @requests = []
14
+ @response = Response.new(status: 200, body: "{}", headers: {})
15
+ @failure = nil
16
+ end
17
+
18
+ # Answers this response to every following request.
19
+ def answer(status:, body: "", headers: {})
20
+ @response = Response.new(status: status, body: body, headers: headers)
21
+ end
22
+
23
+ # Raises `error` from the next `times` requests, or every request until `recover`.
24
+ def fail_with(error, times: nil)
25
+ raise ArgumentError, "times: must be nil (every call) or a positive Integer, got #{times.inspect}" unless times.nil? || (times.is_a?(Integer) && times.positive?)
26
+
27
+ @failure = [error, times]
28
+ end
29
+
30
+ def recover
31
+ @failure = nil
32
+ end
33
+
34
+ def post(url, body, headers = {})
35
+ @requests << { url: url, body: body, headers: headers }
36
+ fail!
37
+ @response
38
+ end
39
+
40
+ private
41
+
42
+ def fail!
43
+ return unless @failure
44
+
45
+ error, times = @failure
46
+ if times
47
+ times -= 1
48
+ @failure = times.zero? ? nil : [error, times]
49
+ end
50
+ raise error
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end