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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +17 -0
- data/README.md +5 -5
- data/docs/authorization.md +4 -0
- data/docs/encrypted-ids.md +24 -2
- data/docs/persisted-queries.md +4 -0
- data/docs/rate-limiting.md +23 -0
- data/docs/response-caching.md +590 -0
- data/docs/subscriptions.md +261 -0
- data/docs/telemetry.md +39 -1
- data/docs/versioning.md +4 -0
- data/lib/graphql/armory/authorization/authorize.rb +3 -0
- data/lib/graphql/armory/authorization/scope.rb +2 -0
- data/lib/graphql/armory/caching/audit/command.rb +51 -0
- data/lib/graphql/armory/caching/audit/context_class.rb +117 -0
- data/lib/graphql/armory/caching/audit/declarations.rb +166 -0
- data/lib/graphql/armory/caching/audit/own_checks.rb +150 -0
- data/lib/graphql/armory/caching/audit/public_rules.rb +158 -0
- data/lib/graphql/armory/caching/audit/report.rb +113 -0
- data/lib/graphql/armory/caching/audit.rb +136 -0
- data/lib/graphql/armory/caching/base.rb +118 -0
- data/lib/graphql/armory/caching/canonical.rb +138 -0
- data/lib/graphql/armory/caching/charge.rb +86 -0
- data/lib/graphql/armory/caching/codec.rb +108 -0
- data/lib/graphql/armory/caching/context_methods.rb +88 -0
- data/lib/graphql/armory/caching/controls/app_schema.rb +70 -0
- data/lib/graphql/armory/caching/controls/context.rb +30 -0
- data/lib/graphql/armory/caching/controls/operations.rb +37 -0
- data/lib/graphql/armory/caching/controls/schema.rb +123 -0
- data/lib/graphql/armory/caching/controls/store.rb +16 -0
- data/lib/graphql/armory/caching/controls/walk_schema.rb +197 -0
- data/lib/graphql/armory/caching/controls.rb +19 -0
- data/lib/graphql/armory/caching/digester.rb +48 -0
- data/lib/graphql/armory/caching/errors.rb +16 -0
- data/lib/graphql/armory/caching/gate/admission.rb +67 -0
- data/lib/graphql/armory/caching/gate/signals.rb +65 -0
- data/lib/graphql/armory/caching/gate/store_check.rb +60 -0
- data/lib/graphql/armory/caching/gate/substitute.rb +61 -0
- data/lib/graphql/armory/caching/gate.rb +384 -0
- data/lib/graphql/armory/caching/integration/guard.rb +55 -0
- data/lib/graphql/armory/caching/integration/install.rb +262 -0
- data/lib/graphql/armory/caching/integration/query.rb +42 -0
- data/lib/graphql/armory/caching/integration.rb +141 -0
- data/lib/graphql/armory/caching/keyer.rb +208 -0
- data/lib/graphql/armory/caching/memory_store.rb +164 -0
- data/lib/graphql/armory/caching/nulls.rb +121 -0
- data/lib/graphql/armory/caching/purge.rb +98 -0
- data/lib/graphql/armory/caching/record_keys.rb +109 -0
- data/lib/graphql/armory/caching/recorder/context.rb +178 -0
- data/lib/graphql/armory/caching/recorder/log.rb +142 -0
- data/lib/graphql/armory/caching/recorder/null.rb +24 -0
- data/lib/graphql/armory/caching/recorder/shared_writes.rb +58 -0
- data/lib/graphql/armory/caching/recorder/substitute.rb +119 -0
- data/lib/graphql/armory/caching/recorder.rb +34 -0
- data/lib/graphql/armory/caching/redis_store/scripts.rb +159 -0
- data/lib/graphql/armory/caching/redis_store.rb +162 -0
- data/lib/graphql/armory/caching/rspec.rb +25 -0
- data/lib/graphql/armory/caching/schema_identity.rb +102 -0
- data/lib/graphql/armory/caching/store/null.rb +31 -0
- data/lib/graphql/armory/caching/store/substitute.rb +144 -0
- data/lib/graphql/armory/caching/store.rb +34 -0
- data/lib/graphql/armory/caching/tags.rb +39 -0
- data/lib/graphql/armory/caching/values/decision.rb +45 -0
- data/lib/graphql/armory/caching/values/declaration.rb +114 -0
- data/lib/graphql/armory/caching/values/entry.rb +108 -0
- data/lib/graphql/armory/caching/values/key.rb +39 -0
- data/lib/graphql/armory/caching/values/lookup.rb +35 -0
- data/lib/graphql/armory/caching/values/policy.rb +44 -0
- data/lib/graphql/armory/caching/viewer.rb +112 -0
- data/lib/graphql/armory/caching/walk/directives.rb +45 -0
- data/lib/graphql/armory/caching/walk/relay.rb +54 -0
- data/lib/graphql/armory/caching/walk/run.rb +130 -0
- data/lib/graphql/armory/caching/walk/tally.rb +38 -0
- data/lib/graphql/armory/caching/walk.rb +46 -0
- data/lib/graphql/armory/caching.rb +69 -0
- data/lib/graphql/armory/encoder/legacy.rb +14 -0
- data/lib/graphql/armory/encoder/null.rb +14 -1
- data/lib/graphql/armory/encoder/substitute.rb +54 -2
- data/lib/graphql/armory/encoder/versioned.rb +36 -0
- data/lib/graphql/armory/encoder.rb +80 -1
- data/lib/graphql/armory/persisted_queries.rb +8 -1
- data/lib/graphql/armory/rate_limits/cached_charge.rb +43 -0
- data/lib/graphql/armory/rate_limits/concurrency.rb +12 -5
- data/lib/graphql/armory/rate_limits/invalid_queries.rb +3 -2
- data/lib/graphql/armory/rate_limits/points.rb +21 -9
- data/lib/graphql/armory/rate_limits/time.rb +15 -8
- data/lib/graphql/armory/rate_limits.rb +9 -0
- data/lib/graphql/armory/subscriptions/ably/key.rb +49 -0
- data/lib/graphql/armory/subscriptions/ably/publisher.rb +132 -0
- data/lib/graphql/armory/subscriptions/ably/token_request.rb +42 -0
- data/lib/graphql/armory/subscriptions/ably/webhook.rb +96 -0
- data/lib/graphql/armory/subscriptions/ably.rb +126 -0
- data/lib/graphql/armory/subscriptions/audit.rb +92 -0
- data/lib/graphql/armory/subscriptions/controls/dependencies.rb +37 -0
- data/lib/graphql/armory/subscriptions/controls/event_log.rb +30 -0
- data/lib/graphql/armory/subscriptions/controls/id.rb +26 -0
- data/lib/graphql/armory/subscriptions/controls/record.rb +34 -0
- data/lib/graphql/armory/subscriptions/controls/schema.rb +187 -0
- data/lib/graphql/armory/subscriptions/controls/viewer.rb +99 -0
- data/lib/graphql/armory/subscriptions/controls.rb +19 -0
- data/lib/graphql/armory/subscriptions/core/channels.rb +93 -0
- data/lib/graphql/armory/subscriptions/core/clock.rb +40 -0
- data/lib/graphql/armory/subscriptions/core/controls.rb +29 -0
- data/lib/graphql/armory/subscriptions/core/delivery.rb +250 -0
- data/lib/graphql/armory/subscriptions/core/settings.rb +182 -0
- data/lib/graphql/armory/subscriptions/core/trigger.rb +63 -0
- data/lib/graphql/armory/subscriptions/core/viewer.rb +153 -0
- data/lib/graphql/armory/subscriptions/core/write.rb +172 -0
- data/lib/graphql/armory/subscriptions/core.rb +200 -0
- data/lib/graphql/armory/subscriptions/errors.rb +30 -0
- data/lib/graphql/armory/subscriptions/http/null.rb +17 -0
- data/lib/graphql/armory/subscriptions/http/substitute.rb +56 -0
- data/lib/graphql/armory/subscriptions/http.rb +93 -0
- data/lib/graphql/armory/subscriptions/memory_store.rb +115 -0
- data/lib/graphql/armory/subscriptions/pusher/signature.rb +45 -0
- data/lib/graphql/armory/subscriptions/pusher.rb +192 -0
- data/lib/graphql/armory/subscriptions/redis_store/scripts.rb +115 -0
- data/lib/graphql/armory/subscriptions/redis_store.rb +157 -0
- data/lib/graphql/armory/subscriptions/store/null.rb +23 -0
- data/lib/graphql/armory/subscriptions/store/substitute.rb +155 -0
- data/lib/graphql/armory/subscriptions/store.rb +38 -0
- data/lib/graphql/armory/subscriptions/topic.rb +253 -0
- data/lib/graphql/armory/subscriptions/transport/null.rb +28 -0
- data/lib/graphql/armory/subscriptions/transport/substitute.rb +150 -0
- data/lib/graphql/armory/subscriptions/transport.rb +41 -0
- data/lib/graphql/armory/subscriptions/values/capabilities.rb +50 -0
- data/lib/graphql/armory/subscriptions/values/message.rb +31 -0
- data/lib/graphql/armory/subscriptions/values/outcome.rb +42 -0
- data/lib/graphql/armory/subscriptions/values/record.rb +176 -0
- data/lib/graphql/armory/subscriptions/webhook_app.rb +31 -0
- data/lib/graphql/armory/subscriptions.rb +33 -0
- data/lib/graphql/armory/telemetry.rb +8 -4
- data/lib/graphql/armory/version.rb +1 -1
- data/lib/graphql/armory/versioning/integration.rb +2 -1
- data/lib/graphql/armory.rb +2 -0
- data/lib/tasks/graphql_armory.rake +9 -0
- metadata +110 -1
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
|
|
6
|
+
module GraphQL
|
|
7
|
+
module Armory
|
|
8
|
+
module Subscriptions
|
|
9
|
+
# The HTTP client transports post through: Net::HTTP with open, read and write timeouts, one connection per
|
|
10
|
+
# request. `Http::Null` refuses every request (a transport nobody wired), `Http::Substitute` records them.
|
|
11
|
+
#
|
|
12
|
+
# http = Http.build(timeout: 5)
|
|
13
|
+
# http.post("https://api-mt1.pusher.com/apps/1/batch_events?...", body, { "Content-Type" => "application/json" })
|
|
14
|
+
# # => #<Http::Response status=200>
|
|
15
|
+
#
|
|
16
|
+
# Any status is a Response; only a failure to get one (a timeout, a refused connection, a TLS error) raises
|
|
17
|
+
# `TransportError`, whose message names the error class and the host, never the path, query or body.
|
|
18
|
+
class Http
|
|
19
|
+
DEFAULT_TIMEOUT = 5
|
|
20
|
+
SCHEMES = %w[http https].freeze
|
|
21
|
+
|
|
22
|
+
# What the provider answered: `status` (Integer), `body` (String) and `headers` (lowercase names to values).
|
|
23
|
+
Response = Struct.new(:status, :body, :headers, keyword_init: true) do
|
|
24
|
+
def initialize(status:, body: "", headers: {})
|
|
25
|
+
raise ArgumentError, "Response status: must be an Integer" unless status.is_a?(Integer)
|
|
26
|
+
raise ArgumentError, "Response body: must be a String" unless body.is_a?(String)
|
|
27
|
+
raise ArgumentError, "Response headers: must be a Hash" unless headers.is_a?(Hash)
|
|
28
|
+
|
|
29
|
+
super(status: status, body: body.dup.freeze, headers: headers.dup.freeze)
|
|
30
|
+
freeze
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def success? = status.between?(200, 299)
|
|
34
|
+
|
|
35
|
+
def inspect = "#<#{self.class.name} status=#{status}>"
|
|
36
|
+
alias_method :to_s, :inspect
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def self.build(timeout: DEFAULT_TIMEOUT)
|
|
40
|
+
unless timeout.is_a?(Numeric) && timeout.positive?
|
|
41
|
+
raise ConfigurationError, "timeout: must be a positive number of seconds, got #{timeout.inspect}"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
new(timeout: timeout)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
attr_reader :timeout
|
|
48
|
+
|
|
49
|
+
def initialize(timeout: DEFAULT_TIMEOUT)
|
|
50
|
+
@timeout = timeout
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def post(url, body, headers = {})
|
|
54
|
+
uri = parse(url)
|
|
55
|
+
raise ArgumentError, "body must be a String" unless body.is_a?(String)
|
|
56
|
+
raise ArgumentError, "headers must be a Hash" unless headers.is_a?(Hash)
|
|
57
|
+
|
|
58
|
+
request = Net::HTTP::Post.new(uri.request_uri, headers)
|
|
59
|
+
request.body = body
|
|
60
|
+
response = connection(uri).start { |http| http.request(request) }
|
|
61
|
+
Response.new(status: Integer(response.code), body: response.body.to_s, headers: response.each_header.to_h)
|
|
62
|
+
rescue ArgumentError
|
|
63
|
+
raise
|
|
64
|
+
rescue StandardError => error
|
|
65
|
+
raise TransportError, "HTTP POST to #{uri&.host} failed: #{error.class}"
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
private
|
|
69
|
+
|
|
70
|
+
def parse(url)
|
|
71
|
+
uri = URI.parse(url.to_s)
|
|
72
|
+
raise ArgumentError, "url must be an http or https URL with a host" unless SCHEMES.include?(uri.scheme) && uri.host && !uri.host.empty?
|
|
73
|
+
|
|
74
|
+
uri
|
|
75
|
+
rescue URI::InvalidURIError
|
|
76
|
+
raise ArgumentError, "url must be an http or https URL with a host"
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def connection(uri)
|
|
80
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
81
|
+
http.use_ssl = uri.scheme == "https"
|
|
82
|
+
http.open_timeout = timeout
|
|
83
|
+
http.read_timeout = timeout
|
|
84
|
+
http.write_timeout = timeout
|
|
85
|
+
http
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
require "graphql/armory/subscriptions/http/null"
|
|
93
|
+
require "graphql/armory/subscriptions/http/substitute"
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module Subscriptions
|
|
6
|
+
# Subscriptions kept in this process's memory: for tests, development and single-process servers. Each process
|
|
7
|
+
# keeps its own, so a trigger reaches only the subscribers written in the process that runs it; share a
|
|
8
|
+
# `RedisStore` between processes in production.
|
|
9
|
+
#
|
|
10
|
+
# store = GraphQL::Armory::Subscriptions::MemoryStore.new
|
|
11
|
+
#
|
|
12
|
+
# Keeps the store contract (`Store`) under one mutex, so every operation is atomic. It has no clock of its own:
|
|
13
|
+
# every time-dependent call takes the caller's `now:` (Integer ms), as in `RedisStore`. `read` has no `now:`, so
|
|
14
|
+
# an expired record stays readable (and counts as taken for `write`'s `:exists`) until `delete` or `cleanup`
|
|
15
|
+
# removes it; the core checks `expires_at` in the record itself. Call `cleanup` periodically to bound memory.
|
|
16
|
+
class MemoryStore
|
|
17
|
+
Stored = Struct.new(:sealed, :topics, :viewer, :expires_at)
|
|
18
|
+
private_constant :Stored
|
|
19
|
+
|
|
20
|
+
def initialize
|
|
21
|
+
@records = {}
|
|
22
|
+
@topics = Hash.new { |hash, key| hash[key] = {} }
|
|
23
|
+
@viewers = Hash.new { |hash, key| hash[key] = {} }
|
|
24
|
+
@mutex = Mutex.new
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def write(id, sealed, topics:, viewer:, expires_at:, viewer_cap:, topic_cap:, now:)
|
|
28
|
+
check_write!(id, sealed, topics, viewer, expires_at, viewer_cap, topic_cap, now)
|
|
29
|
+
topics = topics.uniq.map { |topic| topic.dup.freeze }
|
|
30
|
+
|
|
31
|
+
@mutex.synchronize do
|
|
32
|
+
next :exists if @records.key?(id)
|
|
33
|
+
next :viewer_cap if viewer_cap && live_count(@viewers.fetch(viewer, {}), now) >= viewer_cap
|
|
34
|
+
next :topic_cap if topic_cap && topics.any? { |topic| live_count(@topics.fetch(topic, {}), now) >= topic_cap }
|
|
35
|
+
|
|
36
|
+
id = id.dup.freeze
|
|
37
|
+
viewer = viewer.dup.freeze
|
|
38
|
+
@records[id] = Stored.new(sealed.dup.freeze, topics.freeze, viewer, expires_at)
|
|
39
|
+
@viewers[viewer][id] = true
|
|
40
|
+
topics.each { |topic| @topics[topic][id] = true }
|
|
41
|
+
:ok
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def read(id)
|
|
46
|
+
@mutex.synchronize { @records[id]&.sealed }
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def ids(topic, now:)
|
|
50
|
+
check_now!(now)
|
|
51
|
+
@mutex.synchronize { live_ids(@topics.fetch(topic, {}), now) }
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def delete(id)
|
|
55
|
+
@mutex.synchronize { remove(id) }
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def count(viewer, now:)
|
|
59
|
+
check_now!(now)
|
|
60
|
+
@mutex.synchronize { live_count(@viewers.fetch(viewer, {}), now) }
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def cleanup(now:)
|
|
64
|
+
check_now!(now)
|
|
65
|
+
@mutex.synchronize do
|
|
66
|
+
expired = @records.select { |_id, stored| stored.expires_at <= now }.keys
|
|
67
|
+
expired.each { |id| remove(id) }
|
|
68
|
+
expired.size
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def inspect = "#<#{self.class.name} records=#{@records.size}>"
|
|
73
|
+
alias_method :to_s, :inspect
|
|
74
|
+
|
|
75
|
+
private
|
|
76
|
+
|
|
77
|
+
def live_ids(index, now) = index.keys.select { |id| @records[id].expires_at > now }
|
|
78
|
+
|
|
79
|
+
def live_count(index, now) = index.count { |id, _| @records[id].expires_at > now }
|
|
80
|
+
|
|
81
|
+
# Removes the record and its entries in the indexes, dropping an index nobody is left in.
|
|
82
|
+
def remove(id)
|
|
83
|
+
stored = @records.delete(id) or return false
|
|
84
|
+
|
|
85
|
+
drop(@viewers, stored.viewer, id)
|
|
86
|
+
stored.topics.each { |topic| drop(@topics, topic, id) }
|
|
87
|
+
true
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def drop(indexes, key, id)
|
|
91
|
+
indexes[key].delete(id)
|
|
92
|
+
indexes.delete(key) if indexes[key].empty?
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# A caller's bug, never a store answer: the core must hand every store the same shapes.
|
|
96
|
+
def check_write!(id, sealed, topics, viewer, expires_at, viewer_cap, topic_cap, now)
|
|
97
|
+
check_now!(now)
|
|
98
|
+
raise ArgumentError, "id must be a non-empty String" unless id.is_a?(String) && !id.empty?
|
|
99
|
+
raise ArgumentError, "sealed must be a String" unless sealed.is_a?(String)
|
|
100
|
+
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? }
|
|
101
|
+
raise ArgumentError, "viewer: must be a non-empty String" unless viewer.is_a?(String) && !viewer.empty?
|
|
102
|
+
raise ArgumentError, "expires_at: must be Integer milliseconds after now:" unless expires_at.is_a?(Integer) && expires_at > now
|
|
103
|
+
|
|
104
|
+
[viewer_cap, topic_cap].each do |cap|
|
|
105
|
+
raise ArgumentError, "a cap must be nil or a positive Integer, got #{cap.inspect}" unless cap.nil? || (cap.is_a?(Integer) && cap.positive?)
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def check_now!(now)
|
|
110
|
+
raise ArgumentError, "now: must be Integer milliseconds" unless now.is_a?(Integer)
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "digest"
|
|
5
|
+
|
|
6
|
+
module GraphQL
|
|
7
|
+
module Armory
|
|
8
|
+
module Subscriptions
|
|
9
|
+
class Pusher
|
|
10
|
+
# Pusher's two HMAC-SHA256 signatures, as documented (no SDK):
|
|
11
|
+
#
|
|
12
|
+
# - REST requests: https://pusher.com/docs/channels/library_auth_reference/rest-api/
|
|
13
|
+
# - private channel authorization: https://pusher.com/docs/channels/library_auth_reference/auth-signatures/
|
|
14
|
+
module Signature
|
|
15
|
+
AUTH_VERSION = "1.0"
|
|
16
|
+
|
|
17
|
+
module_function
|
|
18
|
+
|
|
19
|
+
def hmac(secret, text)
|
|
20
|
+
OpenSSL::HMAC.hexdigest("SHA256", secret, text)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# The signed query string of one request: auth_key, auth_timestamp, auth_version, body_md5 (when there is a
|
|
24
|
+
# body) and auth_signature = hex HMAC of "METHOD\nPATH\nsorted query". Every value is URL safe as it is.
|
|
25
|
+
def query(key:, secret:, method:, path:, body:, timestamp:)
|
|
26
|
+
params = { "auth_key" => key, "auth_timestamp" => timestamp.to_s, "auth_version" => AUTH_VERSION }
|
|
27
|
+
params["body_md5"] = Digest::MD5.hexdigest(body) unless body.empty?
|
|
28
|
+
unsigned = params.sort.map { |name, value| "#{name}=#{value}" }.join("&")
|
|
29
|
+
"#{unsigned}&auth_signature=#{hmac(secret, "#{method.upcase}\n#{path}\n#{unsigned}")}"
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# "<key>:<hex HMAC(secret, "socket_id:channel")>", what a client sends as `auth` to subscribe.
|
|
33
|
+
def channel_auth(key:, secret:, socket_id:, channel:)
|
|
34
|
+
"#{key}:#{hmac(secret, "#{socket_id}:#{channel}")}"
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Constant time; false for any length mismatch (the lengths are not secret).
|
|
38
|
+
def same?(left, right)
|
|
39
|
+
left.is_a?(String) && right.is_a?(String) && left.bytesize == right.bytesize && OpenSSL.fixed_length_secure_compare(left, right)
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "graphql/armory/subscriptions/pusher/signature"
|
|
5
|
+
|
|
6
|
+
module GraphQL
|
|
7
|
+
module Armory
|
|
8
|
+
module Subscriptions
|
|
9
|
+
# The Transport for Pusher Channels (and Pusher-compatible servers such as Soketi), over plain HTTP and HMAC with
|
|
10
|
+
# no SDK. Each subscription gets a private channel, `private-<prefix>-<id>`; the client is let onto it by the
|
|
11
|
+
# app's auth endpoint calling `authorize_channel` once the core matched the viewer.
|
|
12
|
+
#
|
|
13
|
+
# Pusher.build(app_id: "3", key: "...", secret: "...", cluster: "eu")
|
|
14
|
+
# Pusher.new # inert: names no channel and refuses everything
|
|
15
|
+
#
|
|
16
|
+
# `publish` never raises for what the provider answers and never retries inline: 2xx is `:ok`, a payload or
|
|
17
|
+
# request Pusher refuses for good is `:refused` (with a reason), a rate limit, a timeout or a 5xx is `:retry`.
|
|
18
|
+
class Pusher
|
|
19
|
+
MAX_PAYLOAD_BYTES = 10_240
|
|
20
|
+
MAX_BATCH = 10
|
|
21
|
+
MAX_WEBHOOK_BYTES = 1024 * 1024
|
|
22
|
+
WEBHOOK_MAX_AGE_MS = 5 * 60 * 1000
|
|
23
|
+
MAX_CHANNEL_LENGTH = 164
|
|
24
|
+
SOCKET_ID = /\A\d+\.\d+\z/
|
|
25
|
+
SEGMENT = /\A[A-Za-z0-9_-]+\z/
|
|
26
|
+
HOST = /\A[A-Za-z0-9.-]+(:\d+)?\z/
|
|
27
|
+
CLUSTER = /\A[a-z0-9-]+\z/
|
|
28
|
+
SCHEMES = %w[https http].freeze
|
|
29
|
+
DEFAULT_CLUSTER = "mt1"
|
|
30
|
+
|
|
31
|
+
# HTTP status to [Outcome status, reason], for what Pusher answers a batch.
|
|
32
|
+
REFUSED = { 400 => :bad_request, 401 => :unauthorized, 403 => :forbidden, 413 => :payload_rejected }.freeze
|
|
33
|
+
RETRY = { 408 => :timeout, 429 => :rate_limited }.freeze
|
|
34
|
+
|
|
35
|
+
def self.build(app_id:, key:, secret:, cluster: nil, host: nil, scheme: "https", prefix: "graphql", compress: false, http: Http.build, clock: Time)
|
|
36
|
+
new(app_id: app_id, key: key, secret: secret, cluster: cluster, host: host, scheme: scheme, prefix: prefix, compress: compress, http: http, clock: clock).tap(&:validate!)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
attr_reader :capabilities, :http
|
|
40
|
+
|
|
41
|
+
def initialize(app_id: nil, key: nil, secret: nil, cluster: nil, host: nil, scheme: "https", prefix: "graphql", compress: false, http: Http::Null.new, clock: Time)
|
|
42
|
+
@app_id = app_id
|
|
43
|
+
@key = key
|
|
44
|
+
@secret = secret
|
|
45
|
+
@cluster = cluster
|
|
46
|
+
@host = host
|
|
47
|
+
@scheme = scheme
|
|
48
|
+
@prefix = prefix
|
|
49
|
+
@compress = compress
|
|
50
|
+
@http = http
|
|
51
|
+
@clock = clock
|
|
52
|
+
@capabilities = Capabilities.new(viewer_bound: true, max_payload_bytes: MAX_PAYLOAD_BYTES, max_batch: MAX_BATCH, webhooks: :existence, compress: compress == true)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def authorization = :channel
|
|
56
|
+
|
|
57
|
+
def configured? = !@secret.nil? && !@key.nil? && !@app_id.nil?
|
|
58
|
+
|
|
59
|
+
def channel_for(id, _viewer_digest)
|
|
60
|
+
return nil unless configured? && id.is_a?(String) && SEGMENT.match?(id)
|
|
61
|
+
|
|
62
|
+
channel = "#{channel_prefix}#{id}"
|
|
63
|
+
channel.length <= MAX_CHANNEL_LENGTH ? channel : nil
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def id_from(channel)
|
|
67
|
+
return nil unless configured? && channel.is_a?(String) && channel.length <= MAX_CHANNEL_LENGTH && channel.start_with?(channel_prefix)
|
|
68
|
+
|
|
69
|
+
id = channel.delete_prefix(channel_prefix)
|
|
70
|
+
SEGMENT.match?(id) ? id : nil
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def publish(messages)
|
|
74
|
+
check(messages)
|
|
75
|
+
return refuse_all(messages, :not_configured) unless configured?
|
|
76
|
+
|
|
77
|
+
body = JSON.generate(batch: messages.map { |message| { name: message.event, channel: message.channel, data: JSON.generate(message.payload) } })
|
|
78
|
+
response = @http.post(url("/batch_events", body), body, { "Content-Type" => "application/json" })
|
|
79
|
+
status, reason = classify(response.status)
|
|
80
|
+
messages.each_index.map { |index| Outcome.new(status: status, index: index, reason: reason) }
|
|
81
|
+
rescue TransportError
|
|
82
|
+
messages.each_index.map { |index| Outcome.new(status: :retry, index: index, reason: :transport_error) }
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def authorize_channel(channel:, socket_id: nil)
|
|
86
|
+
return nil unless configured? && socket_id.is_a?(String) && SOCKET_ID.match?(socket_id) && id_from(channel)
|
|
87
|
+
|
|
88
|
+
{ "auth" => Signature.channel_auth(key: @key, secret: @secret, socket_id: socket_id, channel: channel) }
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def authorize_viewer(_viewer_digest) = nil
|
|
92
|
+
|
|
93
|
+
# Verifies a Pusher webhook (Rack env): size, X-Pusher-Key, X-Pusher-Signature (constant time), age (at most 5
|
|
94
|
+
# minutes old or ahead, else `:stale`). Answers `[:ok, channels]` for the `channel_vacated` events on channels
|
|
95
|
+
# this transport named, `[:refused, reason]` otherwise.
|
|
96
|
+
def webhook(env)
|
|
97
|
+
return [:refused, :not_configured] unless configured?
|
|
98
|
+
|
|
99
|
+
body = read_body(env)
|
|
100
|
+
return [:refused, :too_large] unless body
|
|
101
|
+
return [:refused, :wrong_key] unless Signature.same?(env["HTTP_X_PUSHER_KEY"], @key)
|
|
102
|
+
return [:refused, :bad_signature] unless Signature.same?(env["HTTP_X_PUSHER_SIGNATURE"], Signature.hmac(@secret, body))
|
|
103
|
+
|
|
104
|
+
vacated(body)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def inspect = "#<#{self.class.name} app_id=#{@app_id.inspect} prefix=#{@prefix.inspect}>"
|
|
108
|
+
alias_method :to_s, :inspect
|
|
109
|
+
|
|
110
|
+
def validate!
|
|
111
|
+
text = ->(name, value, pattern) { fail!("#{name}: must match #{pattern.inspect}") unless value.is_a?(String) && pattern.match?(value) }
|
|
112
|
+
text.(:app_id, @app_id, SEGMENT)
|
|
113
|
+
fail!("key: must be a non-empty String without ':' or whitespace") unless @key.is_a?(String) && @key.match?(/\A[^:\s]+\z/)
|
|
114
|
+
fail!("secret: must be a non-empty String") unless @secret.is_a?(String) && !@secret.empty?
|
|
115
|
+
text.(:prefix, @prefix, SEGMENT)
|
|
116
|
+
fail!("scheme: must be one of #{SCHEMES.inspect}") unless SCHEMES.include?(@scheme)
|
|
117
|
+
fail!("cluster: and host: are two ways to say where the API is; give one") if @cluster && @host
|
|
118
|
+
text.(:cluster, @cluster, CLUSTER) if @cluster
|
|
119
|
+
text.(:host, @host, HOST) if @host
|
|
120
|
+
fail!("compress: must be true or false") unless @compress == true || @compress == false
|
|
121
|
+
fail!("http: must answer post(url, body, headers)") unless @http.respond_to?(:post)
|
|
122
|
+
fail!("clock: must answer now") unless @clock.respond_to?(:now) || @clock.respond_to?(:call)
|
|
123
|
+
self
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
private
|
|
127
|
+
|
|
128
|
+
def fail!(message) = raise(ConfigurationError, "Pusher #{message}")
|
|
129
|
+
|
|
130
|
+
def channel_prefix = "private-#{@prefix}-"
|
|
131
|
+
|
|
132
|
+
def check(messages)
|
|
133
|
+
raise ArgumentError, "publish takes a non-empty Array of Messages" unless messages.is_a?(Array) && !messages.empty? && messages.all?(Message)
|
|
134
|
+
raise ArgumentError, "publish got #{messages.size} messages, over max_batch #{MAX_BATCH}" if messages.size > MAX_BATCH
|
|
135
|
+
|
|
136
|
+
messages.each do |message|
|
|
137
|
+
bytes = JSON.generate(message.payload).bytesize
|
|
138
|
+
raise ArgumentError, "a payload of #{bytes} bytes is over max_payload_bytes #{MAX_PAYLOAD_BYTES}" if bytes > MAX_PAYLOAD_BYTES
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def refuse_all(messages, reason)
|
|
143
|
+
messages.each_index.map { |index| Outcome.new(status: :refused, index: index, reason: reason) }
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
def classify(status)
|
|
147
|
+
return [:ok, nil] if status.between?(200, 299)
|
|
148
|
+
return [:refused, REFUSED[status]] if REFUSED.key?(status)
|
|
149
|
+
return [:retry, RETRY[status]] if RETRY.key?(status)
|
|
150
|
+
return [:retry, :provider_error] if status >= 500
|
|
151
|
+
return [:refused, :client_error] if status.between?(400, 499)
|
|
152
|
+
|
|
153
|
+
[:retry, :unexpected_status]
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def url(path, body)
|
|
157
|
+
api_path = "/apps/#{@app_id}#{path}"
|
|
158
|
+
query = Signature.query(key: @key, secret: @secret, method: "POST", path: api_path, body: body, timestamp: now.to_i)
|
|
159
|
+
"#{@scheme}://#{@host || "api-#{@cluster || DEFAULT_CLUSTER}.pusher.com"}#{api_path}?#{query}"
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def now = @clock.respond_to?(:call) ? @clock.call : @clock.now
|
|
163
|
+
|
|
164
|
+
# The body, or nil when it is over the limit. Reads at most one byte past the limit, then rewinds.
|
|
165
|
+
def read_body(env)
|
|
166
|
+
input = env["rack.input"]
|
|
167
|
+
return "" unless input
|
|
168
|
+
|
|
169
|
+
declared = env["CONTENT_LENGTH"].to_s
|
|
170
|
+
return nil if declared.match?(/\A\d+\z/) && declared.to_i > MAX_WEBHOOK_BYTES
|
|
171
|
+
|
|
172
|
+
body = input.read(MAX_WEBHOOK_BYTES + 1).to_s
|
|
173
|
+
input.rewind if input.respond_to?(:rewind)
|
|
174
|
+
body.bytesize > MAX_WEBHOOK_BYTES ? nil : body
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
def vacated(body)
|
|
178
|
+
data = JSON.parse(body)
|
|
179
|
+
time_ms = data.is_a?(Hash) ? data["time_ms"] : nil
|
|
180
|
+
events = data["events"] if data.is_a?(Hash)
|
|
181
|
+
return [:refused, :malformed] unless time_ms.is_a?(Integer) && events.is_a?(Array)
|
|
182
|
+
return [:refused, :stale] if ((now.to_f * 1000) - time_ms).abs > WEBHOOK_MAX_AGE_MS
|
|
183
|
+
|
|
184
|
+
channels = events.select { |event| event.is_a?(Hash) && event["name"] == "channel_vacated" }.map { |event| event["channel"] }
|
|
185
|
+
[:ok, channels.select { |channel| id_from(channel) }.uniq]
|
|
186
|
+
rescue JSON::ParserError
|
|
187
|
+
[:refused, :malformed]
|
|
188
|
+
end
|
|
189
|
+
end
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
end
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module GraphQL
|
|
4
|
+
module Armory
|
|
5
|
+
module Subscriptions
|
|
6
|
+
class RedisStore
|
|
7
|
+
# One Lua script per operation, so each one is atomic and one round trip. Layout (`P` is the prefix):
|
|
8
|
+
#
|
|
9
|
+
# P r:<id> hash with a PX TTL: sealed, viewer, topics (JSON array of digests), expires_at (ms)
|
|
10
|
+
# P t:<topic> sorted set of ids scored by expires_at, trimmed on read, expiring with its longest record
|
|
11
|
+
# P v:<viewer> the same per viewer digest
|
|
12
|
+
# P x sorted set of every id scored by expires_at, no TTL: what `cleanup` walks
|
|
13
|
+
#
|
|
14
|
+
# The clock is the caller's `now` (Integer ms) in every script, never Redis's `TIME`: the core, MemoryStore
|
|
15
|
+
# and every process then agree on what is live, and the examples can move time. Only the TTLs (relative:
|
|
16
|
+
# `expires_at - now`) are Redis's own countdown; they are a memory bound, never what decides liveness.
|
|
17
|
+
module Scripts
|
|
18
|
+
PRELUDE = <<~LUA
|
|
19
|
+
local function ms(value)
|
|
20
|
+
return string.format("%.0f", value)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
-- Drops what is expired at `now` from a sorted set, then answers the number of live members.
|
|
24
|
+
local function live(key, now)
|
|
25
|
+
redis.call("ZREMRANGEBYSCORE", key, "-inf", now)
|
|
26
|
+
return redis.call("ZCARD", key)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
-- Lets an index live as long as its longest record.
|
|
30
|
+
local function extend(key, now)
|
|
31
|
+
local last = redis.call("ZREVRANGE", key, 0, 0, "WITHSCORES")
|
|
32
|
+
if last[2] then redis.call("PEXPIRE", key, ms(math.max(tonumber(last[2]) - now, 1))) end
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
-- Removes the id from the indexes the record names. A record that is gone, or one someone rewrote
|
|
36
|
+
-- into something unreadable, has no names: its index entries then die by score or by TTL.
|
|
37
|
+
local function unindex(prefix, id)
|
|
38
|
+
local fields = redis.call("HMGET", prefix .. "r:" .. id, "viewer", "topics")
|
|
39
|
+
if fields[1] then redis.call("ZREM", prefix .. "v:" .. fields[1], id) end
|
|
40
|
+
if fields[2] then
|
|
41
|
+
local ok, topics = pcall(cjson.decode, fields[2])
|
|
42
|
+
if ok and type(topics) == "table" then
|
|
43
|
+
for _, topic in ipairs(topics) do
|
|
44
|
+
if type(topic) == "string" then redis.call("ZREM", prefix .. "t:" .. topic, id) end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
return redis.call("DEL", prefix .. "r:" .. id)
|
|
49
|
+
end
|
|
50
|
+
LUA
|
|
51
|
+
|
|
52
|
+
# KEYS: record, viewer set, expiry set, topic sets... ARGV: id, sealed, viewer, topics (JSON), expires_at,
|
|
53
|
+
# viewer_cap or "", topic_cap or "", now. Answers "ok", "exists", "viewer_cap" or "topic_cap"; a refused
|
|
54
|
+
# write stores nothing (the sets it trimmed held only expired ids).
|
|
55
|
+
WRITE = <<~LUA
|
|
56
|
+
#{PRELUDE}
|
|
57
|
+
local now, expires_at = tonumber(ARGV[8]), ARGV[5]
|
|
58
|
+
if redis.call("EXISTS", KEYS[1]) == 1 or redis.call("ZSCORE", KEYS[3], ARGV[1]) then return "exists" end
|
|
59
|
+
|
|
60
|
+
if ARGV[6] ~= "" and live(KEYS[2], now) >= tonumber(ARGV[6]) then return "viewer_cap" end
|
|
61
|
+
if ARGV[7] ~= "" then
|
|
62
|
+
for index = 4, #KEYS do
|
|
63
|
+
if live(KEYS[index], now) >= tonumber(ARGV[7]) then return "topic_cap" end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
redis.call("HSET", KEYS[1], "sealed", ARGV[2], "viewer", ARGV[3], "topics", ARGV[4], "expires_at", expires_at)
|
|
68
|
+
redis.call("PEXPIRE", KEYS[1], ms(tonumber(expires_at) - now))
|
|
69
|
+
redis.call("ZADD", KEYS[3], expires_at, ARGV[1])
|
|
70
|
+
redis.call("ZADD", KEYS[2], expires_at, ARGV[1])
|
|
71
|
+
extend(KEYS[2], now)
|
|
72
|
+
for index = 4, #KEYS do
|
|
73
|
+
redis.call("ZADD", KEYS[index], expires_at, ARGV[1])
|
|
74
|
+
extend(KEYS[index], now)
|
|
75
|
+
end
|
|
76
|
+
return "ok"
|
|
77
|
+
LUA
|
|
78
|
+
|
|
79
|
+
# KEYS: topic set. ARGV: now. Answers the live ids, after trimming the expired ones.
|
|
80
|
+
IDS = <<~LUA
|
|
81
|
+
#{PRELUDE}
|
|
82
|
+
redis.call("ZREMRANGEBYSCORE", KEYS[1], "-inf", ARGV[1])
|
|
83
|
+
return redis.call("ZRANGEBYSCORE", KEYS[1], "(" .. ARGV[1], "+inf")
|
|
84
|
+
LUA
|
|
85
|
+
|
|
86
|
+
# KEYS: viewer set. ARGV: now. Answers the number of live records.
|
|
87
|
+
COUNT = <<~LUA
|
|
88
|
+
#{PRELUDE}
|
|
89
|
+
return live(KEYS[1], tonumber(ARGV[1]))
|
|
90
|
+
LUA
|
|
91
|
+
|
|
92
|
+
# KEYS: expiry set. ARGV: id, prefix. Answers 1 when the id was stored (its record, or only its expiry
|
|
93
|
+
# entry once the TTL took the record), else 0.
|
|
94
|
+
DELETE = <<~LUA
|
|
95
|
+
#{PRELUDE}
|
|
96
|
+
local removed = unindex(ARGV[2], ARGV[1])
|
|
97
|
+
return math.max(removed, redis.call("ZREM", KEYS[1], ARGV[1]))
|
|
98
|
+
LUA
|
|
99
|
+
|
|
100
|
+
# KEYS: expiry set. ARGV: now, prefix, batch size. Removes up to `batch` records expired at `now` with their
|
|
101
|
+
# index entries and answers how many.
|
|
102
|
+
CLEANUP = <<~LUA
|
|
103
|
+
#{PRELUDE}
|
|
104
|
+
local expired = redis.call("ZRANGEBYSCORE", KEYS[1], "-inf", ARGV[1], "LIMIT", 0, tonumber(ARGV[3]))
|
|
105
|
+
for _, id in ipairs(expired) do
|
|
106
|
+
unindex(ARGV[2], id)
|
|
107
|
+
redis.call("ZREM", KEYS[1], id)
|
|
108
|
+
end
|
|
109
|
+
return #expired
|
|
110
|
+
LUA
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|