Class: Parse::Client

Overview

This class is the core and low level API for the Parse SDK REST interface that is used by the other components. It can manage multiple sessions, which means you can have multiple client instances pointing to different Parse Applications at the same time. It handles sending raw requests as well as providing Request/Response objects for all API handlers. The connection engine is Faraday, which means it is open to add any additional middleware for features you'd like to implement.

Defined Under Namespace

Modules: Connectable Classes: DuplicateValueError, ResponseError

Constant Summary collapse

USER_AGENT_HEADER =

The user agent header key.

"User-Agent".freeze
USER_AGENT_VERSION =

The value for the User-Agent header.

"Parse-Stack v#{Parse::Stack::VERSION}".freeze
DEFAULT_RETRIES =

The default retry count

2
RETRY_DELAY =

The wait time in seconds between retries

1.5

Constants included from API::Server

API::Server::DEPRECATED_SERVER_VERSION_BELOW

Constants included from API::Hooks

API::Hooks::TRIGGER_NAMES

Class Attribute Summary collapse

Instance Attribute Summary collapse

Attributes included from API::Server

#server_info

Attributes included from API::Config

#config, #master_key_only

Class Method Summary collapse

Instance Method Summary collapse

Methods included from API::Users

#create_user, #current_user, #delete_user, #fetch_user, #find_users, #login, #login_with_mfa, #logout, #request_password_reset, #set_service_auth_data, #signup, #update_user

Methods included from API::Sessions

#fetch_session

Methods included from API::Server

#server_health, #server_info!, #server_version

Methods included from API::Schema

#create_schema, #schema, #schemas, #update_schema

Methods included from API::Push

#push

Methods included from API::Objects

#create_object, #delete_object, #fetch_object, #find_objects, #update_object, #uri_path

Methods included from API::Hooks

#create_function, #create_trigger, #delete_function, #delete_trigger, #fetch_function, #fetch_trigger, #functions, #triggers, #update_function, #update_trigger

Methods included from API::Files

#create_file

Methods included from API::Config

#config!, #config_entries, #update_config

Methods included from API::CloudFunctions

#call_function, #call_function_with_session, #trigger_job, #trigger_job_with_session

Methods included from API::Batch

#batch_request

Methods included from API::Aggregate

#aggregate_objects, #aggregate_pipeline, #aggregate_uri_path

Methods included from API::Analytics

#send_analytics

Constructor Details

#initialize(opts = {}) ⇒ Client

Create a new client connected to the Parse Server REST API endpoint.

Parameters:

  • opts (Hash) (defaults to: {})

    a set of connection options to configure the client.

Options Hash (opts):

  • :server_url (String)

    The server url of your Parse Server if you are not using the hosted Parse service. By default it will use ENV if available, otherwise fallback to Protocol::SERVER_URL.

  • :app_id (String)

    The Parse application id. Defaults to ENV.

  • :api_key (String)

    Your Parse REST API Key. Defaults to ENV.

  • :master_key (String)

    The Parse application master key (optional). If this key is set, it will be sent on every request sent by the client and your models. Defaults to ENV.

  • :logging (Boolean, Symbol)

    Controls request/response logging.

    • true - Enable logging at :info level
    • :debug - Enable verbose logging with headers and body content
    • :warn - Only log errors and warnings
    • false or nil - Disable logging (default) This configures both the new Middleware::Logging middleware and the legacy Middleware::BodyBuilder logging.
  • :logger (Logger)

    A custom logger instance for request/response logging. Defaults to Logger.new(STDOUT) if not specified.

  • :adapter (Object)

    The connection adapter. By default it uses :net_http_persistent for connection pooling. Set connection_pooling: false to use the standard Faraday.default_adapter (Net/HTTP) instead.

  • :connection_pooling (Boolean, Hash)

    Controls HTTP connection pooling. Defaults to true, using the :net_http_persistent adapter for improved performance through connection reuse. Set to false to disable pooling and create a new connection for each request. This option is ignored if :adapter is explicitly specified. Pass a Hash to enable pooling with custom configuration:

    • :pool_size [Integer] - Number of connections per thread (default: 1)
    • :idle_timeout [Integer] - Seconds before closing idle connections (default: 5)
    • :keep_alive [Integer] - HTTP Keep-Alive timeout in seconds @example Custom connection pooling Parse.setup( connection_pooling: { pool_size: 5, idle_timeout: 60, keep_alive: 60 } )
  • :cache (Moneta::Transformer, Moneta::Expires, Parse::Cache::Redis, String)

    A caching adapter of type Moneta::Transformer or Moneta::Expires that will be used by the caching middleware Middleware::Caching. You can also pass a redis:// URL string (an internal Moneta-Redis store will be built for you) or a Parse::Cache::Redis wrapper, which adds a connection pool and automatic namespace forwarding. Caching queries and object fetches can help improve the performance of your application, even if it is for a few seconds. Only successful GET object fetches and non-empty result queries will be cached by default. You may set the default expiration time with the expires option. At any point in time you may clear the cache by calling the #clear_cache! method on the client connection. See Moneta.

  • :expires (Integer)

    Sets the default cache expiration time (in seconds) for successful non-empty GET requests when using the caching middleware. The default value is 3 seconds. If :expires is set to 0, caching will be disabled. You can always clear the current state of the cache using the clear_cache! method on your Parse::Client instance.

  • :cache_namespace (String)

    Optional prefix applied to every cache key. Useful when two Parse apps share one Redis instance and would otherwise collide on identical paths (e.g. mk:/classes/Song/abc). Keys become <namespace>:<existing-prefix>:<url>, so a SCAN <namespace>:* evicts a whole app cleanly. Defaults to no namespace for backward compatibility — explicit only, never auto-derived from app_id.

  • :faraday (Hash)

    You may pass a hash of options that will be passed to the Faraday constructor.

  • :live_query_url (String)

    The WebSocket URL for Parse LiveQuery server (e.g., "wss://your-parse-server.com"). If not specified, falls back to ENV. LiveQuery enables real-time subscriptions to changes in Parse objects. @example Enable LiveQuery Parse.setup( server_url: "https://your-server.com/parse&quot;, application_id: "YOUR_APP_ID", api_key: "YOUR_API_KEY", live_query_url: "wss://your-server.com" )

  • :live_query (Hash)

    Advanced LiveQuery configuration options. Pass a hash with custom settings for the LiveQuery client.

    • :url [String] - WebSocket URL (alternative to :live_query_url)
    • :auto_reconnect [Boolean] - Auto-reconnect on disconnect (default: true)

Raises:

  • Parse::Error::ConnectionError if the client was not properly configured with required keys or url.

  • ArgumentError if the cache instance passed to the :cache option is not of Moneta::Transformer or Moneta::Expires

See Also:



446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# File 'lib/parse/client.rb', line 446

def initialize(opts = {})
  @server_url = opts[:server_url] || ENV["PARSE_SERVER_URL"] || Parse::Protocol::SERVER_URL
  @application_id = opts[:application_id] || opts[:app_id] || ENV["PARSE_SERVER_APPLICATION_ID"] || ENV["PARSE_APP_ID"]
  @api_key = opts[:api_key] || opts[:rest_api_key] || ENV["PARSE_SERVER_REST_API_KEY"] || ENV["PARSE_API_KEY"]
  @master_key = opts[:master_key] || ENV["PARSE_SERVER_MASTER_KEY"] || ENV["PARSE_MASTER_KEY"]

  @require_https = opts.fetch(:require_https, ENV["PARSE_REQUIRE_HTTPS"] == "true")
  @allow_faraday_proxy = opts.fetch(:allow_faraday_proxy, false)

  # Security check for HTTP usage (except localhost/127.0.0.1 for development)
  if @server_url&.start_with?("http://") && !@server_url.match?(%r{^http://(localhost|127\.0\.0\.1)(:|/)})
    if @require_https
      raise ArgumentError, "[Parse::Client] HTTPS required but server URL uses HTTP: #{@server_url}. " \
                           "Set require_https: false or use an HTTPS URL."
    else
      warn "[Parse::Client] SECURITY WARNING: Using HTTP instead of HTTPS for Parse server. " \
           "This exposes credentials and data to network interception. " \
           "Use HTTPS in production: #{@server_url}"
    end
  end

  # Determine the HTTP adapter to use
  # Priority: explicit :adapter > :connection_pooling setting > default (pooling enabled)
  # Falls back to default adapter if net_http_persistent is not available
  if opts[:adapter]
    # User explicitly specified an adapter, use it directly
    adapter = opts[:adapter]
    adapter_options = {}
  elsif opts[:connection_pooling] == false
    # User explicitly disabled connection pooling
    adapter = Faraday.default_adapter
    adapter_options = {}
  elsif opts[:connection_pooling].is_a?(Hash)
    # User provided connection pooling with custom options
    if NET_HTTP_PERSISTENT_AVAILABLE
      adapter = :net_http_persistent
      adapter_options = opts[:connection_pooling]
    else
      adapter = Faraday.default_adapter
      adapter_options = {}
    end
  else
    # Default: use persistent connections for better performance (if available)
    if NET_HTTP_PERSISTENT_AVAILABLE
      adapter = :net_http_persistent
      adapter_options = {}
    else
      adapter = Faraday.default_adapter
      adapter_options = {}
    end
  end

  opts[:expires] ||= 3
  if @server_url.nil? || @application_id.nil? || (@api_key.nil? && @master_key.nil?)
    raise Parse::Error::ConnectionError, "Please call Parse.setup(server_url:, application_id:, api_key:) to setup a client"
  end
  @server_url += "/" unless @server_url.ends_with?("/")

  # Resolve timeouts. Defaults guard the calling thread against an
  # unresponsive Parse Server (slowloris, hung dyno) which would
  # otherwise tie up Puma/Sidekiq workers indefinitely.
  open_timeout = opts.fetch(:open_timeout, (ENV["PARSE_OPEN_TIMEOUT"] || 5).to_i)
  read_timeout = opts.fetch(:timeout, (ENV["PARSE_TIMEOUT"] || 30).to_i)

  #Configure Faraday
  opts[:faraday] ||= {}
  # Guard against silent TLS downgrade or attacker-controlled proxy via
  # opts[:faraday]. The require_https check earlier only inspects the URL
  # scheme; without this guard a caller passing
  #   faraday: { ssl: { verify: false }, proxy: "http://attacker" }
  # would neuter TLS verification on an HTTPS connection.
  validate_faraday_opts!(opts[:faraday])
  opts[:faraday].merge!(:url => @server_url)
  @conn = Faraday.new(opts[:faraday]) do |conn|
    # Apply timeouts before any user-supplied middleware sees a request.
    conn.options.timeout = read_timeout if read_timeout > 0
    conn.options.open_timeout = open_timeout if open_timeout > 0
    #conn.request :json

    # Configure logging if enabled
    if opts[:logging].present?
      # Configure the new structured logging middleware
      Parse::Middleware::Logging.enabled = true
      Parse::Middleware::Logging.logger = opts[:logger] if opts[:logger]
      case opts[:logging]
      when :debug
        Parse::Middleware::Logging.log_level = :debug
        Parse::Middleware::BodyBuilder.logging = true
      when :warn
        Parse::Middleware::Logging.log_level = :warn
      else
        Parse::Middleware::Logging.log_level = :info
      end
    end

    # This middleware handles sending the proper authentication headers to Parse
    # on each request.

    # this is the required authentication middleware. Should be the first thing
    # so that other middlewares have access to the env that is being set by
    # this middleware. First added is first to brocess.
    conn.use Parse::Middleware::Authentication,
             application_id: @application_id,
             master_key: @master_key,
             api_key: @api_key
    # Request/response logging middleware (configured via Parse.logging_enabled)
    conn.use Parse::Middleware::Logging

    # Performance profiling middleware (configured via Parse.profiling_enabled)
    conn.use Parse::Middleware::Profiling

    # This middleware turns the result from Parse into a Parse::Response object
    # and making sure request that are going out, follow the proper MIME format.
    # We place it after the Authentication middleware in case we need to use then
    # authentication information when building request and responses.
    conn.use Parse::Middleware::BodyBuilder

    if opts[:cache].present?
      if opts[:expires].to_i <= 0
        warn "[Parse::Client] Cache store provided but :expires is not set or is 0. " \
             "Caching will be disabled. Set :expires to enable caching (e.g., expires: 10)."
      else
        # advanced: provide a REDIS url, we'll configure a Moneta Redis store.
        if opts[:cache].is_a?(String) && opts[:cache].starts_with?("redis://")
          begin
            opts[:cache] = Moneta.new(:Redis, url: opts[:cache])
          rescue LoadError
            puts "[Parse::Middleware::Caching] Did you forget to load the redis gem (Gemfile)?"
            raise
          end
        end

        unless [:key?, :[], :delete, :store].all? { |method| opts[:cache].respond_to?(method) }
          raise ArgumentError, "Parse::Client option :cache needs to be a type of Moneta store"
        end

        # If the caller passed a `Parse::Cache::Redis` wrapper, let its
        # built-in namespace flow through automatically. An explicit
        # `cache_namespace:` still wins so callers can override.
        if defined?(Parse::Cache::Redis) && opts[:cache].is_a?(Parse::Cache::Redis)
          opts[:cache_namespace] ||= opts[:cache].namespace
        end

        self.cache = opts[:cache]
        conn.use Parse::Middleware::Caching, self.cache, {
          expires: opts[:expires].to_i,
          # Optional `cache_namespace:` prefixes every key so two Parse
          # apps sharing one Redis don't collide on `mk:/classes/Song/abc`.
          # Explicit only — we do NOT auto-derive from app_id to keep
          # existing single-app deployments backward-compatible.
          namespace: opts[:cache_namespace],
        }

        # Inform about opt-in cache behavior
        unless Parse.default_query_cache
          warn "[Parse::Client] Caching middleware enabled (expires: #{opts[:expires]}s). " \
               "Queries do NOT use cache by default. Use `cache: true` on queries to opt-in, " \
               "or set `Parse.default_query_cache = true` for opt-out behavior."
        end
      end
    end

    yield(conn) if block_given?

    # Configure the adapter with optional settings
    # For net_http_persistent:
    # - pool_size must be passed as an adapter argument (constructor param, no setter)
    # - idle_timeout and keep_alive have setters and are configured in the block
    if adapter_options.any?
      # Extract constructor arguments for the adapter
      adapter_args = {}
      adapter_args[:pool_size] = adapter_options[:pool_size] if adapter_options[:pool_size]

      conn.adapter adapter, **adapter_args do |http|
        http.idle_timeout = adapter_options[:idle_timeout] if adapter_options[:idle_timeout]
        http.keep_alive = adapter_options[:keep_alive] if adapter_options[:keep_alive]
      end
    else
      conn.adapter adapter
    end
  end
  # Faraday's constructor may still synthesise a ProxyOptions from
  # HTTPS_PROXY/HTTP_PROXY env vars regardless of the `proxy: nil`
  # we pass in opts. Clear the proxy on the connection itself to be
  # sure no env-derived MITM survives.
  @conn.proxy = nil if !@allow_faraday_proxy && @conn.respond_to?(:proxy=)
  Parse::Client.clients[:default] ||= self

  # Configure LiveQuery if URL provided
  configure_live_query(opts)
end

Class Attribute Details

.clientsObject (readonly)

Returns the value of attribute clients.



298
299
300
# File 'lib/parse/client.rb', line 298

def clients
  @clients
end

Instance Attribute Details

#api_keyString (readonly)

The Parse API key to be sent in every API request.

Returns:



286
# File 'lib/parse/client.rb', line 286

attr_accessor :cache

#application_idString (readonly) Also known as: app_id

The Parse application identifier to be sent in every API request.

Returns:



286
# File 'lib/parse/client.rb', line 286

attr_accessor :cache

#cacheMoneta::Transformer, Moneta::Expires

The underlying cache store for caching API requests.

Returns:

  • (Moneta::Transformer, Moneta::Expires)

See Also:



286
287
288
# File 'lib/parse/client.rb', line 286

def cache
  @cache
end

#master_keyString (readonly)

The Parse master key for this application, which when set, will be sent in every API request. (There is a way to prevent this on a per request basis.)

Returns:



286
# File 'lib/parse/client.rb', line 286

attr_accessor :cache

#retry_limitInteger

If set, returns the current retry count for this instance. Otherwise, returns DEFAULT_RETRIES. Set to 0 to disable retry mechanism.

Returns:

  • (Integer)

    the current retry count for this client.



286
# File 'lib/parse/client.rb', line 286

attr_accessor :cache

#server_urlString (readonly)

The Parse server url that will be receiving these API requests. By default this will be Protocol::SERVER_URL.

Returns:



286
# File 'lib/parse/client.rb', line 286

attr_accessor :cache

Class Method Details

.client(conn = :default) ⇒ Parse::Client

Returns or create a new Parse::Client connection for the given connection name.

Parameters:

  • conn (Symbol) (defaults to: :default)

    the name of the connection.

Returns:



310
311
312
# File 'lib/parse/client.rb', line 310

def client(conn = :default)
  @clients[conn] ||= self.new
end

.client?(conn = :default) ⇒ Boolean

Returns true if a Parse::Client has been configured.

Parameters:

  • conn (Symbol) (defaults to: :default)

    the name of the connection.

Returns:

  • (Boolean)

    true if a Parse::Client has been configured.



302
303
304
# File 'lib/parse/client.rb', line 302

def client?(conn = :default)
  @clients[conn].present?
end

.setup(opts = {}) { ... } ⇒ Client

Setup the a new client with the appropriate Parse app keys, middleware and options.

Examples:

Parse.setup app_id: "YOUR_APP_ID",
            api_key: "YOUR_REST_API_KEY",
            master_key: "YOUR_MASTER_KEY", # optional
            server_url: 'https://localhost:1337/parse' #default

Parameters:

  • opts (Hash) (defaults to: {})

    a set of connection options to configure the client.

Options Hash (opts):

  • :server_url (String)

    The server url of your Parse Server if you are not using the hosted Parse service. By default it will use ENV if available, otherwise fallback to Protocol::SERVER_URL.

  • :app_id (String)

    The Parse application id. Defaults to ENV.

  • :api_key (String)

    Your Parse REST API Key. Defaults to ENV.

  • :master_key (String)

    The Parse application master key (optional). If this key is set, it will be sent on every request sent by the client and your models. Defaults to ENV.

  • :logging (Boolean, Symbol)

    Controls request/response logging.

    • true - Enable logging at :info level
    • :debug - Enable verbose logging with headers and body content
    • :warn - Only log errors and warnings
    • false or nil - Disable logging (default) This configures both the new Middleware::Logging middleware and the legacy Middleware::BodyBuilder logging.
  • :logger (Logger)

    A custom logger instance for request/response logging. Defaults to Logger.new(STDOUT) if not specified.

  • :adapter (Object)

    The connection adapter. By default it uses :net_http_persistent for connection pooling. Set connection_pooling: false to use the standard Faraday.default_adapter (Net/HTTP) instead.

  • :connection_pooling (Boolean, Hash)

    Controls HTTP connection pooling. Defaults to true, using the :net_http_persistent adapter for improved performance through connection reuse. Set to false to disable pooling and create a new connection for each request. This option is ignored if :adapter is explicitly specified. Pass a Hash to enable pooling with custom configuration:

    • :pool_size [Integer] - Number of connections per thread (default: 1)
    • :idle_timeout [Integer] - Seconds before closing idle connections (default: 5)
    • :keep_alive [Integer] - HTTP Keep-Alive timeout in seconds @example Custom connection pooling Parse.setup( connection_pooling: { pool_size: 5, idle_timeout: 60, keep_alive: 60 } )
  • :cache (Moneta::Transformer, Moneta::Expires, Parse::Cache::Redis, String)

    A caching adapter of type Moneta::Transformer or Moneta::Expires that will be used by the caching middleware Middleware::Caching. You can also pass a redis:// URL string (an internal Moneta-Redis store will be built for you) or a Parse::Cache::Redis wrapper, which adds a connection pool and automatic namespace forwarding. Caching queries and object fetches can help improve the performance of your application, even if it is for a few seconds. Only successful GET object fetches and non-empty result queries will be cached by default. You may set the default expiration time with the expires option. At any point in time you may clear the cache by calling the #clear_cache! method on the client connection. See Moneta.

  • :expires (Integer)

    Sets the default cache expiration time (in seconds) for successful non-empty GET requests when using the caching middleware. The default value is 3 seconds. If :expires is set to 0, caching will be disabled. You can always clear the current state of the cache using the clear_cache! method on your Parse::Client instance.

  • :cache_namespace (String)

    Optional prefix applied to every cache key. Useful when two Parse apps share one Redis instance and would otherwise collide on identical paths (e.g. mk:/classes/Song/abc). Keys become <namespace>:<existing-prefix>:<url>, so a SCAN <namespace>:* evicts a whole app cleanly. Defaults to no namespace for backward compatibility — explicit only, never auto-derived from app_id.

  • :faraday (Hash)

    You may pass a hash of options that will be passed to the Faraday constructor.

  • :live_query_url (String)

    The WebSocket URL for Parse LiveQuery server (e.g., "wss://your-parse-server.com"). If not specified, falls back to ENV. LiveQuery enables real-time subscriptions to changes in Parse objects. @example Enable LiveQuery Parse.setup( server_url: "https://your-server.com/parse&quot;, application_id: "YOUR_APP_ID", api_key: "YOUR_API_KEY", live_query_url: "wss://your-server.com" )

  • :live_query (Hash)

    Advanced LiveQuery configuration options. Pass a hash with custom settings for the LiveQuery client.

    • :url [String] - WebSocket URL (alternative to :live_query_url)
    • :auto_reconnect [Boolean] - Auto-reconnect on disconnect (default: true)

Yields:

  • the block for additional configuration with Faraday middleware.

Returns:

  • (Client)

    a new instance of Client

See Also:



329
330
331
# File 'lib/parse/client.rb', line 329

def setup(opts = {}, &block)
  @clients[:default] = self.new(opts, &block)
end

Instance Method Details

#clear_cache!Object

Clear the client cache



717
718
719
# File 'lib/parse/client.rb', line 717

def clear_cache!
  self.cache.clear if self.cache.present?
end

#configure_live_query(opts) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Configure LiveQuery with the given options

Parameters:

  • opts (Hash)

    configuration options

Options Hash (opts):

  • :live_query_url (String)

    WebSocket URL for LiveQuery server (wss://...)



685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
# File 'lib/parse/client.rb', line 685

def configure_live_query(opts)
  live_query_url = opts[:live_query_url] || ENV["PARSE_LIVE_QUERY_URL"]

  return unless live_query_url || opts[:live_query]

  require_relative "live_query"

  live_query_opts = opts[:live_query].is_a?(Hash) ? opts[:live_query] : {}

  Parse::LiveQuery.configure(
    url: live_query_url || live_query_opts[:url],
    application_id: @application_id,
    client_key: @api_key,
    master_key: @master_key,
    **live_query_opts,
  )
end

#delete(uri, body = nil, headers = {}) ⇒ Parse::Response

Send a DELETE request.

Parameters:

  • uri (String)

    the uri path for this request.

  • body (Hash) (defaults to: nil)

    a hash that will be JSON encoded for the body of this request.

  • headers (Hash) (defaults to: {})

    additional headers to send in this request.

Returns:



974
975
976
# File 'lib/parse/client.rb', line 974

def delete(uri, body = nil, headers = {})
  request :delete, uri, body: body, headers: headers
end

#get(uri, query = nil, headers = {}) ⇒ Parse::Response

Send a GET request.

Parameters:

  • uri (String)

    the uri path for this request.

  • query (Hash) (defaults to: nil)

    the set of url query parameters.

  • headers (Hash) (defaults to: {})

    additional headers to send in this request.

Returns:



947
948
949
# File 'lib/parse/client.rb', line 947

def get(uri, query = nil, headers = {})
  request :get, uri, query: query, headers: headers
end

#post(uri, body = nil, headers = {}) ⇒ Parse::Response

Send a POST request.

Parameters:

  • body (Hash) (defaults to: nil)

    a hash that will be JSON encoded for the body of this request.

  • uri (String)

    the uri path for this request.

  • headers (Hash) (defaults to: {})

    additional headers to send in this request.

Returns:



956
957
958
# File 'lib/parse/client.rb', line 956

def post(uri, body = nil, headers = {})
  request :post, uri, body: body, headers: headers
end

#put(uri, body = nil, headers = {}) ⇒ Parse::Response

Send a PUT request.

Parameters:

  • uri (String)

    the uri path for this request.

  • body (Hash) (defaults to: nil)

    a hash that will be JSON encoded for the body of this request.

  • headers (Hash) (defaults to: {})

    additional headers to send in this request.

Returns:



965
966
967
# File 'lib/parse/client.rb', line 965

def put(uri, body = nil, headers = {})
  request :put, uri, body: body, headers: headers
end

#request(method, uri = nil, body: nil, query: nil, headers: nil, opts: {}) ⇒ Parse::Response

Send a REST API request to the server. This is the low-level API used for all requests to the Parse server with the provided options. Every request sent to Parse through the client goes through the configured set of middleware that can be modified by applying different headers or specific options. This method supports retrying requests a few times when a ServiceUnavailableError is raised.

Parameters:

  • method (Symbol)

    The method type of the HTTP request (ex. :get, :post).

    • This parameter can also be a Request object.
  • uri (String) (defaults to: nil)

    the url path. It should not be an absolute url.

  • body (Hash) (defaults to: nil)

    the body of the request.

  • query (Hash) (defaults to: nil)

    the set of url query parameters to use in a GET request.

  • headers (Hash) (defaults to: nil)

    additional headers to apply to this request.

  • opts (Hash) (defaults to: {})

    a set of options to pass through the middleware stack.

    • :cache [Integer] the number of seconds to cache this specific request. If set to false, caching will be disabled completely all together, which means even if a cached response exists, it will not be used.
    • :use_master_key [Boolean] whether this request should send the master key, if it was configured with Parse.setup. By default, if a master key was configured, all outgoing requests will contain it in the request header. Default true.
    • :session_token [String] The session token to send in this request. This disables sending the master key in the request, and sends this request with the credentials provided by the session_token.
    • :retry [Integer] The number of retrties to perform if the service is unavailable. Set to false to disable the retry mechanism. When performing request retries, the client will sleep for a number of seconds (RETRY_DELAY) between requests. The default value is DEFAULT_RETRIES.

Returns:

Raises:

  • Parse::Error::AuthenticationError when HTTP response status is 401 or 403

  • Parse::Error::TimeoutError when HTTP response status is 400 or 408, and the Parse code is 143 or Response::ERROR_TIMEOUT.

  • Parse::Error::ConnectionError when HTTP response status is 404 is not an object not found error.

    • This will also be raised if after retrying a request a number of times has finally failed.
  • Parse::Error::ProtocolError when HTTP response status is 405 or 406

  • Parse::Error::ServiceUnavailableError when HTTP response status is 500 or 503.

  • Parse::Error::ServerError when the Parse response code is less than 100

  • Parse::Error::RequestLimitExceededError when the Parse response code is Response::ERROR_EXCEEDED_BURST_LIMIT.

    • This usually means you have exceeded the burst limit on requests, which will mean you will be throttled for the next 60 seconds.
  • Parse::Error::InvalidSessionTokenError when the Parse response code is 209.

    • This means the session token that was sent in the request seems to be invalid.

See Also:



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
# File 'lib/parse/client.rb', line 768

def request(method, uri = nil, body: nil, query: nil, headers: nil, opts: {})
  # Pre-declare locals referenced inside rescue blocks so CodeQL's
  # uninitialized-variable analysis is satisfied even if an exception
  # raises before the natural assignment site.
  response     = nil
  _retry_count = nil
  _retry_delay = nil
  _request     = nil
  # Kwarg-absorption guard. The `**opts` splat in API helper methods
  # (lib/parse/api/*.rb) absorbs a caller-passed `opts: { ... }`
  # keyword as a key named `:opts` rather than as the request options
  # hash itself. The auth context (session_token, use_master_key)
  # buried under :opts then never reaches the request — the call
  # silently goes out anonymous (or master, if one is configured),
  # which is a permission-downgrade footgun. Fail loudly here so the
  # bug surfaces in dev/test instead of in production.
  if opts.is_a?(Hash) && opts[:opts].is_a?(Hash)
    raise ArgumentError, "Parse::Client#request received nested `opts: { opts: { ... } }` — " \
                         "pass session_token: / use_master_key: directly as keywords, " \
                         "not wrapped in an `opts:` hash. " \
                         "Bad: Parse.client.create_object('X', body, opts: { session_token: t }) " \
                         "Good: Parse.client.create_object('X', body, session_token: t, use_master_key: false)"
  end

  _retry_count ||= self.retry_limit

  if opts[:retry] == false
    _retry_count = 0
  elsif opts[:retry].to_i > 0
    _retry_count = opts[:retry]
  end

  headers ||= {}
  # if the first argument is a Parse::Request object, then construct it
  _request = nil
  if method.is_a?(Request)
    _request = method
    method = _request.method
    uri ||= _request.path
    query ||= _request.query
    body ||= _request.body
    headers.merge! _request.headers
  else
    _request = Parse::Request.new(method, uri, body: body, headers: headers, opts: opts)
  end

  # http method
  method = method.downcase.to_sym
  # set the User-Agent
  headers[USER_AGENT_HEADER] = USER_AGENT_VERSION

  if opts[:cache] == false
    headers[Parse::Middleware::Caching::CACHE_CONTROL] = "no-cache"
  elsif opts[:cache] == :write_only
    # Write-only mode: skip reading from cache, but still write to cache
    # Useful for fetch!/reload! which want fresh data but should update cache
    headers[Parse::Middleware::Caching::CACHE_WRITE_ONLY] = "true"
  elsif opts[:cache].is_a?(Numeric)
    # specify the cache duration of this request
    headers[Parse::Middleware::Caching::CACHE_EXPIRES_DURATION] = opts[:cache].to_s
  end

  # Resolve the auth context in three layers:
  #   1. explicit per-call `use_master_key:` and `session_token:`
  #   2. ambient session set by `Parse.with_session { ... }` (fiber-local)
  #   3. process-wide `Parse.client_mode` flag — when true, master key is
  #      never sent unless the caller explicitly passed `use_master_key: true`
  explicit_master = opts.key?(:use_master_key)

  if opts[:use_master_key] == false
    headers[Parse::Middleware::Authentication::DISABLE_MASTER_KEY] = "true"
  elsif Parse.client_mode && opts[:use_master_key] != true
    # client mode defaults master key OFF unless explicitly opted in
    headers[Parse::Middleware::Authentication::DISABLE_MASTER_KEY] = "true"
  end

  token = opts[:session_token]
  # When no explicit token was passed AND the caller didn't ask to send
  # the master key, fall through to the fiber-local ambient set by
  # `Parse.with_session`. Explicit `use_master_key: true` is treated as
  # a deliberate admin call and skips the ambient — otherwise an
  # `admin.do_thing(use_master_key: true)` nested inside a
  # `with_session(user)` block would silently downgrade.
  if token.nil? && !(explicit_master && opts[:use_master_key] == true)
    ambient = Parse.current_session_token
    token = ambient if ambient.is_a?(String) && !ambient.empty?
  end
  if token.present?
    token = token.session_token if token.respond_to?(:session_token)
    headers[Parse::Middleware::Authentication::DISABLE_MASTER_KEY] = "true"
    headers[Parse::Protocol::SESSION_TOKEN] = token
  end

  #if it is a :get request, then use query params, otherwise body.
  params = (method == :get ? query : body) || {}
  # if the path does not start with the '/1/' prefix, then add it to be nice.
  # actually send the request and return the body
  response_env = @conn.send(method, uri, params, headers)
  response = response_env.body
  response.request = _request

  case response.http_status
  when 401, 403
    Parse::Client._safe_warn("AuthenticationError", response)
    raise Parse::Error::AuthenticationError, response
  when 400, 408
    if response.code == Parse::Response::ERROR_TIMEOUT || response.code == 143 #"net/http: timeout awaiting response headers"
      Parse::Client._safe_warn("TimeoutError", response)
      raise Parse::Error::TimeoutError, response
    end
  when 404
    unless response.object_not_found?
      Parse::Client._safe_warn("ConnectionError", response)
      raise Parse::Error::ConnectionError, response
    end
  when 405, 406
    Parse::Client._safe_warn("ProtocolError", response)
    raise Parse::Error::ProtocolError, response
  when 429 # Request over the throttle limit
    Parse::Client._safe_warn("RequestLimitExceededError", response)
    raise Parse::Error::RequestLimitExceededError, response
  when 500, 503
    Parse::Client._safe_warn("ServiceUnavailableError", response)
    raise Parse::Error::ServiceUnavailableError, response
  end

  if response.error?
    if response.code <= Parse::Response::ERROR_SERVICE_UNAVAILABLE
      Parse::Client._safe_warn("ServiceUnavailableError", response)
      raise Parse::Error::ServiceUnavailableError, response
    elsif response.code <= 100
      Parse::Client._safe_warn("ServerError", response)
      raise Parse::Error::ServerError, response
    elsif response.code == Parse::Response::ERROR_EXCEEDED_BURST_LIMIT
      Parse::Client._safe_warn("RequestLimitExceededError", response)
      raise Parse::Error::RequestLimitExceededError, response
    elsif response.code == 209 # Error 209: invalid session token
      Parse::Client._safe_warn("InvalidSessionTokenError", response)
      raise Parse::Error::InvalidSessionTokenError, response
    end
  end

  response
rescue Parse::Error::RequestLimitExceededError, Parse::Error::ServiceUnavailableError => e
  if _retry_count > 0
    warn "[Parse:Retry] Retries remaining #{_retry_count} : #{response.request}"
    _retry_count -= 1
    # Use Retry-After header if available, otherwise use exponential backoff
    retry_after = response.retry_after if response.respond_to?(:retry_after)
    if retry_after && retry_after > 0
      _retry_delay = retry_after
      warn "[Parse:Retry] Using Retry-After header: #{_retry_delay}s"
    else
      # Deterministic exponential backoff with +/-25% jitter. Never zero —
      # zero-wait retries amplify DoS against upstream and stampede on 429.
      backoff_delay = RETRY_DELAY * (self.retry_limit - _retry_count)
      _retry_delay = backoff_delay * (0.75 + rand * 0.5)
    end
    sleep _retry_delay if _retry_delay > 0
    retry
  end
  raise
rescue Faraday::ClientError, Net::OpenTimeout => e
  if _retry_count > 0
    warn "[Parse:Retry] Retries remaining #{_retry_count} : #{_request}"
    _retry_count -= 1
    backoff_delay = RETRY_DELAY * (self.retry_limit - _retry_count)
    _retry_delay = backoff_delay * (0.75 + rand * 0.5)
    sleep _retry_delay if _retry_delay > 0
    retry
  end
  raise Parse::Error::ConnectionError, "#{_request} : #{e.class} - #{e.message}"
end

#send_request(req) ⇒ Parse::Response

Send a Request object.

Parameters:

Returns:

Raises:

  • ArgumentError if req is not of type Parse::Request.



982
983
984
985
# File 'lib/parse/client.rb', line 982

def send_request(req) #Parse::Request object
  raise ArgumentError, "Object not of Parse::Request type." unless req.is_a?(Parse::Request)
  request req.method, req.path, req.body, req.headers
end

#url_prefixString

Returns the url prefix of the Parse Server url.

Returns:

  • (String)

    the url prefix of the Parse Server url.



712
713
714
# File 'lib/parse/client.rb', line 712

def url_prefix
  @conn.url_prefix
end