Class: GraphQL::Schema::TimeoutMiddleware
- Inherits:
-
Object
- Object
- GraphQL::Schema::TimeoutMiddleware
- Defined in:
- lib/graphql/schema/timeout_middleware.rb
Overview
This middleware will stop resolving new fields after max_seconds
have elapsed.
After the time has passed, any remaining fields will be nil
, with errors added
to the errors
key. Any already-resolved fields will be in the data
key, so
you'll get a partial response.
You can provide a block which will be called with any timeout errors that occur.
Note that this will stop a query in between field resolutions, but
it doesn't interrupt long-running resolve
functions. Be sure to use
timeout options for external connections. For more info, see
www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/
Defined Under Namespace
Classes: TimeoutError, TimeoutQueryProxy
Instance Method Summary collapse
- #call(parent_type, parent_object, field_definition, field_args, query_context) ⇒ Object
-
#initialize(max_seconds:, context_key: nil, &block) ⇒ TimeoutMiddleware
constructor
A new instance of TimeoutMiddleware.
-
#on_timeout(parent_type, parent_object, field_definition, field_args, field_context) ⇒ GraphQL::Schema::TimeoutMiddleware::TimeoutError
This is called when a field would be resolved, except that we're over the time limit.
Constructor Details
#initialize(max_seconds:, context_key: nil, &block) ⇒ TimeoutMiddleware
Returns a new instance of TimeoutMiddleware.
30 31 32 33 34 35 36 |
# File 'lib/graphql/schema/timeout_middleware.rb', line 30 def initialize(max_seconds:, context_key: nil, &block) @max_seconds = max_seconds if context_key GraphQL::Deprecation.warn("TimeoutMiddleware's `context_key` is ignored, timeout data is now stored in isolated storage") end @error_handler = block end |
Instance Method Details
#call(parent_type, parent_object, field_definition, field_args, query_context) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/graphql/schema/timeout_middleware.rb', line 38 def call(parent_type, parent_object, field_definition, field_args, query_context) ns = query_context.namespace(self.class) now = Process.clock_gettime(Process::CLOCK_MONOTONIC) timeout_at = ns[:timeout_at] ||= now + @max_seconds if timeout_at < now on_timeout(parent_type, parent_object, field_definition, field_args, query_context) else yield end end |
#on_timeout(parent_type, parent_object, field_definition, field_args, field_context) ⇒ GraphQL::Schema::TimeoutMiddleware::TimeoutError
This is called when a field would be resolved, except that we're over the time limit.
52 53 54 55 56 57 58 59 |
# File 'lib/graphql/schema/timeout_middleware.rb', line 52 def on_timeout(parent_type, parent_object, field_definition, field_args, field_context) err = GraphQL::Schema::TimeoutMiddleware::TimeoutError.new(parent_type, field_definition) if @error_handler query_proxy = TimeoutQueryProxy.new(field_context.query, field_context) @error_handler.call(err, query_proxy) end err end |