Class: GraphQL::Subscriptions
- Inherits:
-
Object
- Object
- GraphQL::Subscriptions
- Defined in:
- lib/graphql/subscriptions.rb,
lib/graphql/subscriptions/event.rb,
lib/graphql/subscriptions/serialize.rb,
lib/graphql/subscriptions/broadcast_analyzer.rb,
lib/graphql/subscriptions/action_cable_subscriptions.rb,
lib/graphql/subscriptions/default_subscription_resolve_extension.rb
Direct Known Subclasses
Defined Under Namespace
Modules: Serialize Classes: ActionCableSubscriptions, BroadcastAnalyzer, DefaultSubscriptionResolveExtension, Event, Finalizer, InvalidTriggerError, SubscriptionScopeMissingError
Instance Attribute Summary collapse
-
#default_broadcastable ⇒ Object
readonly
Returns.
Class Method Summary collapse
-
.use(defn, options = {}) ⇒ Object
See GraphQL::Subscriptions for the base options; concrete implementations may add options.
Instance Method Summary collapse
-
#broadcastable?(query_str, **query_options) ⇒ Boolean
Returns.
-
#build_id ⇒ Object
Returns.
-
#delete_subscription(subscription_id) ⇒ Object
A subscription was terminated server-side.
-
#deliver(subscription_id, result) ⇒ Object
A subscription query was re-evaluated, returning
result. -
#execute(subscription_id, event, object) ⇒ Object
Run the update query for this subscription and deliver it See execute_update See deliver.
-
#execute_all(event, object) ⇒ Object
Event
eventoccurred onobject, Update all subscribers. -
#execute_update(subscription_id, event, object) ⇒ Object
eventwas triggered onobject, andsubscription_idwas subscribed, so it should be updated. - #finalizer ⇒ Object
-
#finish_subscriptions(query) ⇒ Object
Called during execution when a subscription operation has finished.
-
#initialize(schema:, validate_update: true, broadcast: false, default_broadcastable: false, **rest) ⇒ Subscriptions
constructor
Parameters.
-
#initialize_subscriptions(query) ⇒ Object
Called during execution when a new
subscription ...operation is received. -
#normalize_name(event_or_arg_name) ⇒ Object
Convert a user-provided event name or argument to the equivalent in GraphQL.
-
#read_subscription(subscription_id) ⇒ Object
The system wants to send an update to this subscription.
-
#trigger(event_name, args, object, scope: nil, context: {}) ⇒ Object
Fetch subscriptions matching this field + arguments pair And pass them off to the queue.
-
#validate_update?(query:, context:, root_value:, subscription_topic:, operation_name:, variables:) ⇒ Boolean
Define this method to customize whether to validate this subscription when executing an update.
-
#write_subscription(query, events) ⇒ Object
querywas executed and found subscriptions toevents.
Constructor Details
#initialize(schema:, validate_update: true, broadcast: false, default_broadcastable: false, **rest) ⇒ Subscriptions
Parameters
schema(Class) — the GraphQL schema this manager belongs tovalidate_update(Boolean) — If false, then validation is skipped when executing updates
:call-seq:
initialize(Class schema:, bool validate_update:, broadcast:, default_broadcastable:, **rest)
47 48 49 50 51 52 53 54 |
# File 'lib/graphql/subscriptions.rb', line 47 def initialize(schema:, validate_update: true, broadcast: false, default_broadcastable: false, **rest) if broadcast schema.query_analyzer(Subscriptions::BroadcastAnalyzer) end @default_broadcastable = default_broadcastable @schema = schema @validate_update = validate_update end |
Instance Attribute Details
#default_broadcastable ⇒ Object (readonly)
Returns
Boolean— Used when fields don't havebroadcastable:explicitly set
59 60 61 |
# File 'lib/graphql/subscriptions.rb', line 59 def default_broadcastable @default_broadcastable end |
Class Method Details
.use(defn, options = {}) ⇒ Object
See GraphQL::Subscriptions for the base options; concrete implementations may add options.
27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/graphql/subscriptions.rb', line 27 def self.use(defn, = {}) schema = defn.is_a?(Class) ? defn : defn.target if schema.subscriptions(inherited: false) raise ArgumentError, "Can't reinstall subscriptions. #{schema} is using #{schema.subscriptions}, can't also add #{self}" end [:schema] = schema schema.subscriptions = self.new(**) schema.add_subscription_extension_if_necessary nil end |
Instance Method Details
#broadcastable?(query_str, **query_options) ⇒ Boolean
Returns
Boolean— if true, then a query like this one would be broadcasted
:call-seq:
broadcastable?(query_str, **query_options) -> bool
333 334 335 336 337 338 339 340 |
# File 'lib/graphql/subscriptions.rb', line 333 def broadcastable?(query_str, **) query = @schema.query_class.new(@schema, query_str, **) if !query.valid? raise "Invalid query: #{query.validation_errors.map(&:to_h).inspect}" end GraphQL::Analysis.analyze_query(query, @schema.query_analyzers) query.context.namespace(:subscriptions)[:subscription_broadcastable] end |
#build_id ⇒ Object
Returns
String— A new unique identifier for a subscription
:call-seq:
build_id() -> String
303 304 305 |
# File 'lib/graphql/subscriptions.rb', line 303 def build_id SecureRandom.uuid end |
#delete_subscription(subscription_id) ⇒ Object
A subscription was terminated server-side. Clean up the database.
Parameters
subscription_id(String)
Returns
Object— void.
:call-seq:
delete_subscription(String subscription_id) -> Object
293 294 295 |
# File 'lib/graphql/subscriptions.rb', line 293 def delete_subscription(subscription_id) raise GraphQL::RequiredImplementationMissingError end |
#deliver(subscription_id, result) ⇒ Object
A subscription query was re-evaluated, returning result.
The result should be send to subscription_id.
Parameters
subscription_id(String)result(Hash)
Returns
void
:call-seq:
deliver(String subscription_id, Hash result) -> void
258 259 260 |
# File 'lib/graphql/subscriptions.rb', line 258 def deliver(subscription_id, result) raise GraphQL::RequiredImplementationMissingError end |
#execute(subscription_id, event, object) ⇒ Object
Run the update query for this subscription and deliver it See execute_update See deliver
Returns
void
:call-seq:
execute(subscription_id, event, object) -> void
195 196 197 198 199 200 201 202 203 204 205 206 207 |
# File 'lib/graphql/subscriptions.rb', line 195 def execute(subscription_id, event, object) res = execute_update(subscription_id, event, object) if !res.nil? deliver(subscription_id, res) if res.context.namespace(:subscriptions)[:unsubscribed] # `unsubscribe` was called, clean up on our side # The transport should also send `{more: false}` to client delete_subscription(subscription_id) end end end |
#execute_all(event, object) ⇒ Object
Event event occurred on object,
Update all subscribers.
Parameters
event(Subscriptions::Event)object(Object)
Returns
void
:call-seq:
execute_all(Subscriptions::Event event, Object object) -> void
223 224 225 |
# File 'lib/graphql/subscriptions.rb', line 223 def execute_all(event, object) raise GraphQL::RequiredImplementationMissingError end |
#execute_update(subscription_id, event, object) ⇒ Object
event was triggered on object, and subscription_id was subscribed,
so it should be updated.
Load subscription_id's GraphQL data, re-evaluate the query and return the result.
Parameters
subscription_id(String)event(GraphQL::Subscriptions::Event) — The event which was triggeredobject(Object) — The value for the subscription field
Returns
GraphQL::Query::Result
:call-seq:
execute_update(String subscription_id, GraphQL::Subscriptions::Event event, Object object) -> GraphQL::Query::Result
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
# File 'lib/graphql/subscriptions.rb', line 130 def execute_update(subscription_id, event, object) # Lookup the saved data for this subscription query_data = read_subscription(subscription_id) if query_data.nil? delete_subscription(subscription_id) return nil end # Fetch the required keys from the saved data query_string = query_data.fetch(:query_string) variables = query_data.fetch(:variables) context = query_data.fetch(:context) operation_name = query_data.fetch(:operation_name) = { query: query_string, context: context, subscription_topic: event.topic, operation_name: operation_name, variables: variables, root_value: object, } # merge event's and query's context together context.merge!(event.context) unless event.context.nil? || context.nil? [:validate] = validate_update?(**) result = @schema.execute(**) subscriptions_context = result.context.namespace(:subscriptions) if subscriptions_context[:no_update] result = nil end if subscriptions_context[:unsubscribed] && !subscriptions_context[:final_update] # `unsubscribe` was called, clean up on our side # The transport should also send `{more: false}` to client delete_subscription(subscription_id) result = nil end result end |
#finalizer ⇒ Object
380 381 382 |
# File 'lib/graphql/subscriptions.rb', line 380 def finalizer Finalizer.new(self) end |
#finish_subscriptions(query) ⇒ Object
Called during execution when a subscription operation has finished
Parameters
query(GraphQL::Query)
Returns
void
:call-seq:
finish_subscriptions(GraphQL::Query query) -> void
373 374 375 376 377 378 |
# File 'lib/graphql/subscriptions.rb', line 373 def finish_subscriptions(query) if (events = query.context.namespace(:subscriptions)[:events]) && !events.empty? write_subscription(query, events) end nil end |
#initialize_subscriptions(query) ⇒ Object
Called during execution when a new subscription ... operation is received
Parameters
query(GraphQL::Query)
Returns
void
:call-seq:
initialize_subscriptions(GraphQL::Query query) -> void
354 355 356 357 358 359 |
# File 'lib/graphql/subscriptions.rb', line 354 def initialize_subscriptions(query) subs_namespace = query.context.namespace(:subscriptions) subs_namespace[:events] = [] subs_namespace[:subscriptions] = {} nil end |
#normalize_name(event_or_arg_name) ⇒ Object
Convert a user-provided event name or argument to the equivalent in GraphQL.
By default, it converts the identifier to camelcase. Override this in a subclass to change the transformation.
Parameters
event_or_arg_name(String, Symbol)
Returns
String
:call-seq:
normalize_name(String | Symbol event_or_arg_name) -> String
323 324 325 |
# File 'lib/graphql/subscriptions.rb', line 323 def normalize_name(event_or_arg_name) Schema::Member::BuildType.camelize(event_or_arg_name.to_s) end |
#read_subscription(subscription_id) ⇒ Object
The system wants to send an update to this subscription. Read its data and return it.
Parameters
subscription_id(String)
Returns
Hash— Containing required keys
:call-seq:
read_subscription(String subscription_id) -> Hash
240 241 242 |
# File 'lib/graphql/subscriptions.rb', line 240 def read_subscription(subscription_id) raise GraphQL::RequiredImplementationMissingError end |
#trigger(event_name, args, object, scope: nil, context: {}) ⇒ Object
Fetch subscriptions matching this field + arguments pair And pass them off to the queue.
Parameters
event_name(String)args(Hash<String, Symbol => Object>) — Arguments passed to the subscription resolverobject(Object)scope(Symbol, String)context(Hash)
Returns
void
:call-seq:
trigger(String event_name, Hash[String | Symbol, Object] args, Object object, Symbol | String scope:, Hash context:) -> void
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/graphql/subscriptions.rb', line 78 def trigger(event_name, args, object, scope: nil, context: {}) # Make something as context-like as possible, even though there isn't a current query: dummy_query = @schema.query_class.new(@schema, "{ __typename }", validate: false, context: context) context = dummy_query.context event_name = event_name.to_s # Try with the verbatim input first: field = dummy_query.types.field(@schema.subscription, event_name) # rubocop:disable Development/ContextIsPassedCop if field.nil? # And if it wasn't found, normalize it: normalized_event_name = normalize_name(event_name) field = dummy_query.types.field(@schema.subscription, normalized_event_name) # rubocop:disable Development/ContextIsPassedCop if field.nil? raise InvalidTriggerError, "No subscription matching trigger: #{event_name} (looked for #{@schema.subscription.graphql_name}.#{normalized_event_name})" end else # Since we found a field, the original input was already normalized normalized_event_name = event_name end # Normalize symbol-keyed args to strings, try camelizing them # Should this accept a real context somehow? normalized_args = normalize_arguments(normalized_event_name, field, args, @schema.null_context) event = Subscriptions::Event.new( name: normalized_event_name, arguments: normalized_args, field: field, scope: scope, context: context, ) execute_all(event, object) end |
#validate_update?(query:, context:, root_value:, subscription_topic:, operation_name:, variables:) ⇒ Boolean
Define this method to customize whether to validate this subscription when executing an update.
Returns
Boolean— defaults totrue, or false ifvalidate: falseis provided.
:call-seq:
validate_update?(query:, context:, root_value:, subscription_topic:, operation_name:, variables:) -> bool
181 182 183 |
# File 'lib/graphql/subscriptions.rb', line 181 def validate_update?(query:, context:, root_value:, subscription_topic:, operation_name:, variables:) @validate_update end |
#write_subscription(query, events) ⇒ Object
query was executed and found subscriptions to events.
Update the database to reflect this new state.
Parameters
query(GraphQL::Query)events(Array<GraphQL::Subscriptions::Event>)
Returns
void
:call-seq:
write_subscription(GraphQL::Query query, Array[GraphQL::Subscriptions::Event] events) -> void
276 277 278 |
# File 'lib/graphql/subscriptions.rb', line 276 def write_subscription(query, events) raise GraphQL::RequiredImplementationMissingError end |