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
SERVER_DEDUP_ROUTES =

Routes on which Parse Server runs its request-id deduplication (promiseEnsureIdempotency), by HTTP method. Paths are relative to the mount point. Every other endpoint (notably POST /batch, files, push, login, logout, schemas, config, and hooks) applies a replay again, so a request to one of them is never treated as server-deduplicated.

{
  post: [
    %r{\Aclasses/[^/]+\z},
    %r{\Ausers\z},
    %r{\Ainstallations\z},
    %r{\Afunctions/[^/]+\z},
    %r{\Ajobs/[^/]+\z},
  ].freeze,
  put: [
    %r{\Aclasses/[^/]+/[^/]+\z},
    %r{\Ausers/[^/]+\z},
    %r{\Ainstallations/[^/]+\z},
  ].freeze,
}.freeze

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_email_verification, #request_password_reset, #set_service_auth_data, #signup, #update_user, #verify_password

Methods included from API::Sessions

#fetch_session

Methods included from API::Server

#server_features, #server_health, #server_info!, #server_supports?, #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["PARSE_SERVER_URL"] if available, otherwise fallback to Protocol::SERVER_URL.

  • :app_id (String) —

    The Parse application id. Defaults to ENV['PARSE_SERVER_APPLICATION_ID'].

  • :api_key (String) —

    Your Parse REST API Key. Defaults to ENV['PARSE_SERVER_REST_API_KEY'].

  • :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['PARSE_SERVER_MASTER_KEY'].

  • :session_token (String) —

    An optional session token bound to this client. When set, every request that does not pass an explicit session_token: / use_master_key: true and is not inside a Parse.with_session block sends this token (and suppresses the master key), so the client transparently acts as that user. Precedence is explicit per-call > Parse.with_session ambient > this bound token. Typically paired with master_key: nil to build a user-scoped client (see Webhooks::Payload#user_client).

  • :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. A store that deserializes values with Marshal over a backend outside this process (Moneta's default, e.g. Moneta.new(:Redis, url: ...)) raises ArgumentError. Use Parse::Cache::Redis (or a redis:// URL string), which stores JSON. In-process stores such as Moneta.new(:Memory) are accepted. A plain value_serializer: nil is not a substitute: the response cache stores Hash values, which a file or Redis backend cannot hold without a serializer.

  • :allow_marshal_cache (Boolean) —

    Accept a :cache store that deserializes values with Marshal over an external backend. Logs a security warning. Default false.

  • :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_session_requests (Boolean) —

    Whether this client's response cache stores and serves reads made with a session token. Overrides Middleware::Caching.cache_session_requests in either direction; omit it to use that class default (off). Only true enables it. With it on, a revoked session keeps reading its cached rows until the entry expires.

  • :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["PARSE_LIVE_QUERY_URL"]. LiveQuery enables real-time subscriptions to changes in Parse objects. @example Enable LiveQuery Parse.setup( server_url: "https://your-server.com/parse", 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:



727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
# File 'lib/parse/client.rb', line 727

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"]
  # Distinguish an explicit `master_key: nil` (deliberately a non-master
  # client — what user_client / session_client / user_agent rely on) from
  # an omitted key (fall back to ENV). The previous `opts[:master_key] ||
  # ENV[...]` form silently re-inherited the process master key for the
  # explicit-nil case, putting a "non-master" client back into master mode
  # in any deployment that exports PARSE_SERVER_MASTER_KEY / PARSE_MASTER_KEY.
  @master_key = if opts.key?(:master_key)
      opts[:master_key]
    else
      ENV["PARSE_SERVER_MASTER_KEY"] || ENV["PARSE_MASTER_KEY"]
    end
  # Optional token bound to this client; applied per request as the
  # lowest-priority auth fallback (see #request). Normalize blank/whitespace
  # to nil so it never trips the "token present" branch at request time
  # (where `present?` is false for whitespace) and silently fall back to the
  # master key on a master-configured client.
  bound_token = opts[:session_token]
  bound_token = bound_token.session_token if bound_token.respond_to?(:session_token)
  bound_token = bound_token.to_s.strip
  @session_token = bound_token.empty? ? nil : bound_token

  @require_https = opts.fetch(:require_https) { self.class.env_flag_enabled?(ENV["PARSE_REQUIRE_HTTPS"]) }
  @allow_faraday_proxy = opts.fetch(:allow_faraday_proxy, false)

  # Security check for HTTP usage (except localhost/127.0.0.1 for development)
  # The scheme and host come from URI parsing, so `HTTP://` and leading
  # whitespace are treated as plain http, not as a secure URL.
  # Credentials embedded in the URL (`https://user:pass@host/parse`) are
  # sent as a Basic Authorization header and would otherwise appear in
  # every message below, in #inspect, and in #as_json. Those surfaces
  # print a redacted form; warn once so the operator can move them out.
  if self.class.url_userinfo?(@server_url) && !Parse::Client.instance_variable_get(:@userinfo_warned)
    Parse::Client.instance_variable_set(:@userinfo_warned, true)
    warn "[Parse::Client] SECURITY WARNING: the Parse server URL contains embedded credentials " \
         "(user:password@). They are redacted from logs, but prefer configuring them outside the URL: " \
         "#{self.class.redact_url_userinfo(@server_url)}"
  end
  if self.class.url_scheme(@server_url) == "http" && !self.class.loopback_host?(self.class.url_host(@server_url))
    if @require_https
      raise ArgumentError, "[Parse::Client] HTTPS required but server URL uses HTTP: #{self.class.redact_url_userinfo(@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: #{self.class.redact_url_userinfo(@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.
  opts[:faraday] = 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 Redis store.
        if opts[:cache].is_a?(String) && opts[:cache].starts_with?("redis://")
          begin
            # Eagerly load the redis adapter so a missing `redis` gem
            # fails fast here (at setup) with the friendly hint below,
            # rather than deferring to the first cache access — the
            # Parse::Cache::Redis pool builds its Moneta-Redis backends
            # lazily, so without this the LoadError would surface later.
            require "moneta/adapters/redis"
            # Route through Parse::Cache::Redis rather than a bare
            # `Moneta.new(:Redis, ...)`. SECURITY: the Moneta-Redis store
            # Marshals values by default, so every cache hit would
            # `Marshal.load` whatever bytes come back from Redis — an
            # arbitrary-code-execution primitive if the cache is shared,
            # unauthenticated, or reachable over a plaintext `redis://`
            # MITM. The wrapper forces `value_serializer: nil` and
            # JSON-(de)serializes cached values itself, closing that
            # deserialization vector on this shorthand the same way an
            # explicitly-constructed wrapper does.
            opts[:cache] = Parse::Cache::Redis.new(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

        # SECURITY: a caller-built Moneta store keeps Moneta's default
        # Marshal value serializer unless told otherwise, so every cache
        # hit would `Marshal.load` the bytes stored in the backend. For a
        # shared or network-reachable backend (Redis over `redis://`, a
        # cache another service can write) that is a code-execution
        # primitive. Refuse it unless the caller opts in explicitly.
        # In-process stores (`:Memory`, `:LRUHash`, `:Null`) are exempt:
        # only this process can write the values they hold.
        if self.class.marshal_value_cache?(opts[:cache])
          unless opts[:allow_marshal_cache]
            raise ArgumentError,
                  "[Parse::Client] The :cache store deserializes values with Marshal " \
                  "(Moneta's default value serializer), which allows code execution by anyone " \
                  "able to write to the cache backend. Use Parse::Cache::Redis (or a redis:// URL " \
                  "string), an in-process store such as Moneta.new(:Memory), or pass " \
                  "`allow_marshal_cache: true` " \
                  "to accept the risk."
          end
          warn "[Parse::Client] SECURITY WARNING: allow_marshal_cache: true accepts a cache store " \
               "that deserializes values with Marshal. Anyone able to write to the cache backend " \
               "can execute code in this process."
        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]

        # Build one keyspace from the effective namespace and install it on
        # both the middleware and the store, so key generation and eviction
        # can never disagree. Previously the middleware could hold a
        # `cache_namespace:` the store knew nothing about, and
        # `clear_cache!` scoped using only the store's own namespace, so a
        # namespaced client cleared every SDK key on the database.
        #
        # Opt-in: without `cache_keyspace: true` the legacy key shape is
        # kept, so an upgrade changes nothing until an operator asks for it.
        #
        # `scoped` derives an immutable, per-client view rather than
        # mutating the store in place. This matters when one backend
        # (e.g. a `Parse::Cache::Redis` connection pool) is shared across
        # more than one `Parse::Client`: mutating a shared store's
        # keyspace would rebind it out from under whichever client
        # configured it first, so this client's own `sdk_cache` becomes
        # the view while `cache` stays the store that was configured, and
        # the shared backend itself is never touched.
        cache_keyspace = nil
        if opts[:cache_keyspace]
          cache_keyspace = Parse::Cache::Keyspace.new(
            app_id: @application_id,
            server_url: @server_url,
            namespace: opts[:cache_namespace],
          )
          # Derive an immutable per-client view rather than mutating the
          # backend, so two clients can share a connection pool without
          # sharing ownership of the keyspace. There is deliberately no
          # `keyspace=` fallback here, since reintroducing a mutable
          # binding at the call site would restore the cross-client
          # rebinding this replaces.
          #
          # A store that cannot produce a view is wrapped rather than left
          # alone. Leaving it bare still composed keys correctly, because
          # the middleware below receives the keyspace directly, so the
          # deployment looked keyspaced; but `clear_cache!` then called the
          # store's own unrestricted `clear`, which on a plain
          # `Moneta.new(:Redis)` is FLUSHDB. Opting into keyspacing and
          # getting a database-wide flush is the exact inversion of the
          # option: it deletes other applications' entries and any
          # `parse-stack:foc:v1:*` create-locks sharing the database.
          #
          # The view is assigned to `sdk_cache`, NOT over `cache`. An
          # earlier version replaced `cache` outright, which meant the
          # store an application configured and passed in was no longer
          # reachable through the accessor documented for reaching it,
          # and application reads and writes silently moved inside the
          # SDK's keyspace. A scoped view also cannot honestly stand in
          # for a complete Moneta store: `clear`, `each_key`, and `close`
          # either break scope isolation or quietly change meaning.
          @sdk_cache = if self.cache.respond_to?(:scoped)
              self.cache.scoped(cache_keyspace)
            else
              Parse::Cache::KeyspacedStore.new(store: self.cache, keyspace: cache_keyspace)
            end
        end

        # Register the invalidation triggers once a keyspace exists, so
        # role and identity staleness is bounded by webhook rather than by
        # application discipline. Opt-in with the keyspace, since without
        # planes there is nothing to invalidate.
        if cache_keyspace && sdk_cache.respond_to?(:roles) &&
           opts.fetch(:cache_invalidation_hooks, true)
          begin
            Parse::Cache::Invalidation.install!(sdk_cache)
          rescue StandardError => e
            warn "[Parse::Client] cache invalidation hooks not installed: #{e.class}"
          end
        end

        conn.use Parse::Middleware::Caching, sdk_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],
          keyspace: cache_keyspace,
          # During a rolling deploy, new workers write keyspaced keys while
          # old workers still read the legacy shape, so invalidation has to
          # hit both until every old worker is drained.
          delete_legacy_variants: opts.fetch(:cache_delete_legacy_variants, true),
          # Per-client override of
          # Parse::Middleware::Caching.cache_session_requests; omitted
          # means the class default applies.
          **(opts.key?(:cache_session_requests) ? { cache_session_requests: opts[:cache_session_requests] } : {}),
        }

        # 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

.clients ⇒ Object (readonly)

Returns the value of attribute clients.



526
527
528
# File 'lib/parse/client.rb', line 526

def clients
  @clients
end

Instance Attribute Details

#api_key ⇒ String (readonly)

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

Returns:



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

attr_accessor :cache

#application_id ⇒ String (readonly) Also known as: app_id

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

Returns:



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

attr_accessor :cache

#cache ⇒ Moneta::Transformer, Moneta::Expires

The underlying cache store for caching API requests.

Returns:

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

See Also:



371
372
373
# File 'lib/parse/client.rb', line 371

def cache
  @cache
end

#master_key ⇒ String (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:



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

attr_accessor :cache

#retry_limit ⇒ Integer

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.



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

attr_accessor :cache

#server_url ⇒ String (readonly)

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

Returns:



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

attr_accessor :cache

#session_token ⇒ String? (readonly)

Returns the session token bound to this client, if any (see the :session_token constructor option). Applied as the lowest-priority auth fallback on every request.

Returns:

  • (String, nil) —

    the session token bound to this client, if any (see the :session_token constructor option). Applied as the lowest-priority auth fallback on every request.



377
378
379
# File 'lib/parse/client.rb', line 377

def session_token
  @session_token
end

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:



538
539
540
# File 'lib/parse/client.rb', line 538

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.



530
531
532
# File 'lib/parse/client.rb', line 530

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

.env_flag_enabled?(value) ⇒ Boolean

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.

Whether an environment flag is set to a true value: true, 1, or yes, ignoring case and surrounding whitespace.

Parameters:

Returns:

  • (Boolean)


1223
1224
1225
# File 'lib/parse/client.rb', line 1223

def self.env_flag_enabled?(value)
  %w[true 1 yes].include?(value.to_s.strip.downcase)
end

.loopback_host?(host) ⇒ Boolean

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.

Whether a URL host is this machine: localhost, any 127.0.0.0/8 address, ::1, or 0.0.0.0 (a connect to the unspecified address reaches the local host on Linux and macOS). Used by the http:// server warning and the LiveQuery cleartext guards so they agree. Addresses are parsed with IPAddr, so a malformed one such as 127.999.1.1 (which a resolver would look up by name) is not loopback. localhost. with a trailing dot is not either: some resolvers skip /etc/hosts for the fully qualified form. 0.0.0.0 stays local for client URLs only (it is a bind address everywhere else).

Parameters:

Returns:

  • (Boolean)


1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
# File 'lib/parse/client.rb', line 1158

def self.loopback_host?(host)
  h = host.to_s.strip.downcase.delete_prefix("[").delete_suffix("]")
  return false if h.empty?
  return true if h == "localhost" || h == "0.0.0.0"
  return false unless h.match?(/\A[0-9a-f:.]+\z/)
  require "ipaddr"
  IPAddr.new(h).loopback?
rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError
  false
end

.marshal_value_cache?(store) ⇒ Boolean

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.

Whether a Moneta store applies a Marshal value transformer over a backend outside this process. Walks the proxy chain through adapter (Expires, Logger, Transformer, ...) to the innermost adapter. Moneta names each compiled transformer class after its chains, for example MarshalPrefixKeyMarshalValue, so the value chain is the part after the last Key. Parse::Cache::Redis disables Moneta's value serializer and is never flagged.

Parameters:

Returns:

  • (Boolean)


1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
# File 'lib/parse/client.rb', line 1261

def self.marshal_value_cache?(store)
  return false if defined?(Parse::Cache::Redis) && store.is_a?(Parse::Cache::Redis)
  marshal_value = false
  innermost = store
  node = store
  16.times do
    break if node.nil?
    innermost = node
    name = node.class.name.to_s.split("::").last.to_s
    if node.class.name.to_s.start_with?("Moneta::Transformer::") && name.end_with?("Value")
      marshal_value ||= name.sub(/\A.*Key/, "").include?("Marshal")
    end
    break unless node.respond_to?(:adapter)
    nxt = node.adapter
    break if nxt.equal?(node)
    node = nxt
  end
  marshal_value && !IN_PROCESS_CACHE_ADAPTERS.include?(innermost.class.name.to_s)
rescue StandardError
  false
end

.redact_url_userinfo(url) ⇒ String?

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.

The URL with any userinfo replaced by [FILTERED], for logging and serialization. Other parts of the URL are unchanged.

Parameters:

Returns:



1213
1214
1215
1216
# File 'lib/parse/client.rb', line 1213

def self.redact_url_userinfo(url)
  return url if url.nil?
  url.to_s.sub(URL_USERINFO_PATTERN, '\1[FILTERED]@')
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["PARSE_SERVER_URL"] if available, otherwise fallback to Protocol::SERVER_URL.

  • :app_id (String) —

    The Parse application id. Defaults to ENV['PARSE_SERVER_APPLICATION_ID'].

  • :api_key (String) —

    Your Parse REST API Key. Defaults to ENV['PARSE_SERVER_REST_API_KEY'].

  • :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['PARSE_SERVER_MASTER_KEY'].

  • :session_token (String) —

    An optional session token bound to this client. When set, every request that does not pass an explicit session_token: / use_master_key: true and is not inside a Parse.with_session block sends this token (and suppresses the master key), so the client transparently acts as that user. Precedence is explicit per-call > Parse.with_session ambient > this bound token. Typically paired with master_key: nil to build a user-scoped client (see Webhooks::Payload#user_client).

  • :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. A store that deserializes values with Marshal over a backend outside this process (Moneta's default, e.g. Moneta.new(:Redis, url: ...)) raises ArgumentError. Use Parse::Cache::Redis (or a redis:// URL string), which stores JSON. In-process stores such as Moneta.new(:Memory) are accepted. A plain value_serializer: nil is not a substitute: the response cache stores Hash values, which a file or Redis backend cannot hold without a serializer.

  • :allow_marshal_cache (Boolean) —

    Accept a :cache store that deserializes values with Marshal over an external backend. Logs a security warning. Default false.

  • :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_session_requests (Boolean) —

    Whether this client's response cache stores and serves reads made with a session token. Overrides Middleware::Caching.cache_session_requests in either direction; omit it to use that class default (off). Only true enables it. With it on, a revoked session keeps reading its cached rows until the entry expires.

  • :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["PARSE_LIVE_QUERY_URL"]. LiveQuery enables real-time subscriptions to changes in Parse objects. @example Enable LiveQuery Parse.setup( server_url: "https://your-server.com/parse", 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:



557
558
559
# File 'lib/parse/client.rb', line 557

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

.unsafe_request_path?(uri) ⇒ Boolean

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.

Whether a request path would leave the configured server: it has a URI scheme (https:, HTTP:, any other scheme:) or is protocol-relative (//host, or the \\host, /\host and \/host forms some URL parsers normalize to it). Leading whitespace and control characters are ignored. Relative paths, with or without a query string, are safe.

Parameters:

Returns:

  • (Boolean)


1235
1236
1237
1238
1239
# File 'lib/parse/client.rb', line 1235

def self.unsafe_request_path?(uri)
  return false if uri.nil?
  path = uri.to_s.sub(/\A[[:space:][:cntrl:]]+/, "")
  path.match?(/\A[a-z][a-z0-9+.\-]*:/i) || path.match?(%r{\A[/\\]{2}})
end

.url_host(url) ⇒ String?

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.

The lowercased host of a URL String, or nil when it does not parse.

Parameters:

Returns:



1187
1188
1189
1190
1191
1192
# File 'lib/parse/client.rb', line 1187

def self.url_host(url)
  return nil if url.nil?
  URI.parse(url.to_s.strip).host&.downcase
rescue URI::InvalidURIError
  nil
end

.url_scheme(url) ⇒ String?

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.

The lowercased scheme of a URL String, or nil when it does not parse. Leading and trailing whitespace is ignored. Scheme checks go through this instead of a case-sensitive prefix match, which let HTTP:// and WS:// past the plaintext guards.

Parameters:

Returns:



1176
1177
1178
1179
1180
1181
# File 'lib/parse/client.rb', line 1176

def self.url_scheme(url)
  return nil if url.nil?
  URI.parse(url.to_s.strip).scheme&.downcase
rescue URI::InvalidURIError
  nil
end

.url_userinfo?(url) ⇒ Boolean

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.

Whether a URL String embeds userinfo (user:pass@host).

Parameters:

Returns:

  • (Boolean)


1204
1205
1206
# File 'lib/parse/client.rb', line 1204

def self.url_userinfo?(url)
  !url.nil? && URL_USERINFO_PATTERN.match?(url.to_s)
end

Instance Method Details

#anonymous ⇒ Parse::Client

A NEW anonymous client that mirrors THIS client's connection but carries neither a master key nor a session token — every request it makes is unauthenticated (app-id + REST key only). Use it to drop the bound user identity for a one-off public read without mutating a shared client. Equivalent to #become with no token.

Returns:



485
486
487
# File 'lib/parse/client.rb', line 485

def anonymous
  become(nil)
end

#api_relative_path(uri) ⇒ String?

The request path relative to the Parse mount point, without a query string or surrounding slashes. Accepts relative paths (classes/Post) and absolute ones that include the mount prefix (/parse/classes/Post).

Parameters:

Returns:



1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
# File 'lib/parse/client.rb', line 1991

def api_relative_path(uri)
  return nil if uri.nil?
  path = uri.to_s.split("?", 2).first.to_s
  prefix = url_prefix.path.to_s rescue ""
  prefix = prefix.chomp("/")
  if !prefix.empty? && path.start_with?("#{prefix}/")
    path = path.delete_prefix(prefix)
  end
  # Trim slashes with string operations rather than an end-anchored
  # regex, which backtracks polynomially on long runs of "/".
  path = path.delete_prefix("/") while path.start_with?("/")
  path = path.delete_suffix("/") while path.end_with?("/")
  path
end

#as_json ⇒ Hash

Redacted JSON form. ActiveSupport's default as_json serializes every instance variable, so a client in a JSON log or error-tracker context (or inside an object that serializes it, such as a Agent) would emit the master key, REST key, and bound session token.

Returns:



427
428
429
430
431
432
433
434
# File 'lib/parse/client.rb', line 427

def as_json(*)
  {
    "server_url" => self.class.redact_url_userinfo(@server_url),
    "app_id" => @application_id,
    "master_key" => @master_key ? "[FILTERED]" : nil,
    "session_token" => @session_token ? "[FILTERED]" : nil,
  }
end

#authorization ⇒ Parse::Authorization::Context

This client's authorization context: the identity and role caches, and the session-token resolver that feeds every mongo-direct ACL decision.

One context per client, created lazily and never shared. That is the point of it living here rather than in module-level state: two clients pointed at two Parse applications must not resolve a token against each other's caches, nor validate it against each other's /users/me.



408
409
410
# File 'lib/parse/client.rb', line 408

def authorization
  @authorization ||= Parse::Authorization::Context.new(client: self)
end

#become(session_token) ⇒ Parse::Client

A NEW non-master Parse::Client that mirrors THIS client's connection settings (server_url / application_id / api_key) but carries no master key and binds session_token, so it acts on the server as that user (ACL / CLP / protectedFields enforced, no master-key fallback). This is the general primitive behind Webhooks::Payload#user_client and User#session_client: derive a user-scoped client from a configured (e.g. master) client without re-specifying the connection.

user_client = Parse.client.become(user.session_token) Parse::Query.new("Post", client: user_client).results # as the user

Parameters:

  • session_token (String, #session_token) —

    the token to bind. A blank token yields a tokenless non-master client (anonymous REST).

Returns:



469
470
471
472
473
474
475
476
477
# File 'lib/parse/client.rb', line 469

def become(session_token)
  Parse::Client.new(
    server_url: @server_url,
    app_id: @application_id,
    api_key: @api_key,
    master_key: nil,
    session_token: session_token,
  )
end

#body_carries_atomic_op?(body, depth = 0) ⇒ Boolean

Whether a request body carries a Parse operation: an __op key at any depth, including the top level. That covers field ops (Increment, Add, AddUnique, Remove, AddRelation, RemoveRelation, Delete), nested ops such as a schema update's fields: { name: { __op: "Delete" } }, and whole-body ops such as a hook delete's { __op: "Delete" }. Replaying any of them after the first attempt applied turns a landed write into a reported failure, or applies it twice. A pre-serialized String body is scanned for the literal "__op" key.

Parameters:

  • body (Object) —

    the request body.

Returns:

  • (Boolean)


2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
# File 'lib/parse/client.rb', line 2016

def body_carries_atomic_op?(body, depth = 0)
  return false if depth > 32
  case body
  when Hash
    body.key?("__op") || body.key?(:__op) ||
      body.each_value.any? { |v| body_carries_atomic_op?(v, depth + 1) }
  when Array
    body.any? { |v| body_carries_atomic_op?(v, depth + 1) }
  when String
    depth.zero? && body.include?('"__op"')
  else
    false
  end
end

#clear_cache! ⇒ Object

Clear the SDK's own cached entries.

Operates on #sdk_cache, so with cache_keyspace: true this removes only keys under this client's keyspace and leaves application keys in the same store untouched. Without a keyspace sdk_cache IS cache, and the call has its historical whole-store meaning.

To clear the underlying store outright, call client.cache.clear explicitly. On a Redis-backed store that is FLUSHDB and takes everything on the database with it, including other applications and any parse-stack:foc:v1:* create-locks.



1399
1400
1401
1402
# File 'lib/parse/client.rb', line 1399

def clear_cache!
  target = sdk_cache
  target.clear if target.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://...)



1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
# File 'lib/parse/client.rb', line 1287

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] : {}
  resolved_url = live_query_url || live_query_opts[:url]

  # Refuse explicit `ws://` against a non-loopback host unless
  # `allow_insecure: true` is also passed in `live_query:`. The
  # downstream `derive_websocket_url` path already enforces this for
  # URLs derived from a Parse Server `http://` URL, but an explicit
  # `live_query: { url: "ws://prod-host" }` or
  # `live_query_url: "ws://prod-host"` bypassed it — the master key
  # and any session token would ride the connect frame in cleartext.
  resolved_url = validate_live_query_url!(resolved_url, allow_insecure: live_query_opts[:allow_insecure])

  # Warn (don't raise) on `live_query: { ... }` keys that are not
  # `Parse::LiveQuery::Configuration` setters. The block form would
  # otherwise silently swallow typos like
  # `live_query: { ssl_min_versoin: :TLSv1_3 }` and leave TLS at the
  # default, losing the operator's intent. The pre-fix kwargs form
  # raised `ArgumentError` here; this restores the surface without
  # making it a hard failure for unknown-but-harmless keys.
  warn_about_unknown_live_query_keys!(live_query_opts)

  Parse::LiveQuery.configure do |config|
    config.application_id = @application_id if @application_id
    config.client_key = @api_key if @api_key
    config.master_key = @master_key if @master_key

    # Apply hash-form options first so the resolved URL (which honors
    # top-level `live_query_url:` over `live_query: { url: }`) wins.
    # Without this, the loop would re-write `config.url` from the
    # hash and silently invert the documented precedence.
    live_query_opts.each do |key, value|
      next if key == :url
      setter = "#{key}="
      config.public_send(setter, value) if config.respond_to?(setter)
    end

    config.url = resolved_url if resolved_url
  end
end

#connected?(endpoint = nil) ⇒ Boolean

Connectivity probe. By default hits the Parse Server health endpoint — the same target as #reachable? — so it returns true whenever the server is up, regardless of CLP configuration.

Why not a _User find? A limit-0 find against _User exercises the auth stack, but locking _User finds to the master key via a Class-Level Permission is standard production hardening — on such a server the probe gets a permission error and (wrongly) reports "not connected" for a perfectly healthy, correctly-configured deployment. The default therefore avoids any data class.

To ALSO validate credentials, pass endpoint: a path to a class the configured key is allowed to read (e.g. "classes/_User" on a default server, or one of your own readable classes). The probe runs limit: 0 so it never pulls rows, and routes through the auth middleware, so a wrong application_id / REST key surfaces as an Error::AuthenticationError and is converted to false. Any connection, timeout, or API error returns false rather than raising; genuine programming errors (e.g. NoMethodError) still propagate.

Parameters:

  • endpoint (String, nil) (defaults to: nil) —

    optional path to probe instead of the health endpoint, to validate credentials against a readable class.

Returns:

  • (Boolean) —

    true if the server is reachable (and, when an endpoint is given, the credentials are accepted).



1440
1441
1442
1443
1444
1445
1446
# File 'lib/parse/client.rb', line 1440

def connected?(endpoint = nil)
  path = endpoint || Parse::API::Server::SERVER_HEALTH_PATH
  response = request(:get, path, query: { limit: 0 }, opts: { cache: false })
  response.success?
rescue Parse::Error, Faraday::Error
  false
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:



2063
2064
2065
# File 'lib/parse/client.rb', line 2063

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

#encode_with(coder) ⇒ Object

YAML (Psych) serializes instance variables too; emit the redacted summary instead.



443
444
445
# File 'lib/parse/client.rb', line 443

def encode_with(coder)
  as_json.each { |k, v| coder[k] = v }
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:



2036
2037
2038
# File 'lib/parse/client.rb', line 2036

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

#idempotent_retry?(method, body, headers = nil, uri = nil) ⇒ Boolean

Whether a request whose outcome is UNKNOWN (a 500/503 or a dropped connection) is safe to transparently re-send.

Server-dedup fast path: when the operator has asserted Parse Server idempotency is configured (Request.assume_server_idempotency) AND this request carries a stable X-Parse-Request-Id header, the server deduplicates a replay, so even a POST or an atomic-op write is safe to retry — the write applies at most once. The replay is NOT a transparent success, though: Parse Server rejects the duplicate with error 159, surfaced as a raised Error::DuplicateRequestError the caller must rescue (the original write already landed). The SDK sends the same request id on every retry (the header is set once and preserved across the retry), which is what makes the server-side dedup match.

Otherwise the conservative method/body heuristic applies: GET and DELETE are idempotent; a full-object PUT update is idempotent ONLY when it carries no atomic __op mutation (Increment/Add/AddUnique/Remove/Relation would double-apply on replay); POST (object create / batch) is never auto-retried. 429 throttles are handled at the call site, since the server provably discarded the request and those re-send regardless.

Parameters:

  • method (Symbol) —

    the (downcased) HTTP method of the request.

  • body (Hash, Object, nil) —

    the request body.

  • headers (Hash, nil) (defaults to: nil) —

    the outgoing request headers (consulted for the request-id header on the server-dedup fast path).

  • uri (String, nil) (defaults to: nil) —

    the request path, used to confirm the endpoint is one Parse Server deduplicates. Without it the server-dedup fast path does not apply.

Returns:

  • (Boolean)


1936
1937
1938
1939
1940
1941
1942
1943
# File 'lib/parse/client.rb', line 1936

def idempotent_retry?(method, body, headers = nil, uri = nil)
  return true if server_deduped_request?(headers, method, uri)
  case method
  when :get, :delete then true
  when :put then !body_carries_atomic_op?(body)
  else false
  end
end

#inspect ⇒ Object

Redacted inspection. The default Ruby #inspect would dump every ivar, exposing the master key and any bound session token in cleartext wherever a client is logged or surfaced in an error reporter. Show only the connection identity and a boolean for each credential's presence.



416
417
418
419
420
# File 'lib/parse/client.rb', line 416

def inspect
  "#<#{self.class.name} server_url=#{self.class.redact_url_userinfo(@server_url).inspect} " \
  "app_id=#{@application_id.inspect} master_key=#{@master_key ? "[FILTERED]" : "nil"} " \
  "session_token=#{@session_token ? "[FILTERED]" : "nil"}>"
end

#marshal_dump ⇒ Object

A client holds the master key, REST key, and session tokens, so it is never marshaled (Rails.cache, DRb, or a job payload would store them in the clear). Store the configuration and build a new client instead.

Raises:

  • (TypeError)


451
452
453
# File 'lib/parse/client.rb', line 451

def marshal_dump
  raise TypeError, "Parse::Client cannot be marshaled"
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:



2045
2046
2047
# File 'lib/parse/client.rb', line 2045

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:



2054
2055
2056
# File 'lib/parse/client.rb', line 2054

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

#reachable? ⇒ Boolean

No-credentials liveness probe. Hits the Parse Server health endpoint and returns true when the server responds with status "ok". No application credentials are required, so this passes even when the configured application_id or REST key is wrong. Use #connected? to also validate credentials.

Returns:

  • (Boolean) —

    true if the server is up and returned a healthy status.



1410
1411
1412
1413
1414
1415
# File 'lib/parse/client.rb', line 1410

def reachable?
  response = request(:get, Parse::API::Server::SERVER_HEALTH_PATH, opts: { cache: false })
  response.success?
rescue Parse::Error, Faraday::Error
  false
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, relative to the configured server URL. An absolute (https://...) or protocol-relative (//host/...) path raises ArgumentError.

  • 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.

  • Parse::Error::DuplicateRequestError when the Parse response code is Response::ERROR_DUPLICATE_REQUEST (159) — request-id idempotency rejected a duplicate; the original write already applied.

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

See Also:



1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
# File 'lib/parse/client.rb', line 1500

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
  # A Parse::Request carries its own per-request options (session_token,
  # use_master_key, cache, retry, ...). Merge them in before anything
  # below reads `opts`, or the auth resolution never sees them and a
  # request built for a session with `use_master_key: false` still goes
  # out with the configured master key. Options passed to this call
  # directly win over the request's own.
  if method.is_a?(Request) && method.opts.is_a?(Hash) && !method.opts.empty?
    opts = method.opts.merge(opts.is_a?(Hash) ? opts : {})
  end
  # 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 budget. Initialized ONCE here, ABOVE the `begin` below, so the
  # `retry` keyword in the rescue clauses (which re-runs only the begin
  # block, not the whole method) preserves the countdown across attempts.
  # If this initialization ran inside the begin it would reset on every
  # attempt, turning a transient 500/503/429 into an infinite retry loop.
  _retry_count ||= self.retry_limit

  # `retry: false` and `retry: 0` both disable retries; a positive
  # Integer sets the budget. Anything else keeps the client default.
  if opts[:retry] == false
    _retry_count = 0
  elsif opts[:retry].is_a?(Numeric)
    _retry_count = [opts[:retry].to_i, 0].max
  end

  # The effective starting budget, captured ONCE after the opts override
  # (and, like `_retry_count`, above the `begin` so `retry` doesn't reset
  # it). The backoff multiplier is `(_retry_max - _retry_count)`, which
  # grows 1, 2, 3, … as attempts are consumed. Deriving it from
  # `self.retry_limit` instead would go to zero or negative whenever a
  # caller passes `opts: { retry: N }` with N above the instance default,
  # silently disabling the backoff (every retry firing at zero delay).
  _retry_max ||= _retry_count

  # Work on a copy of the caller's headers. The request id header is
  # written into this hash, and it must survive the `retry` keyword (so
  # it is set above the `begin`) without leaking into a hash the caller
  # reuses for its next request.
  headers = headers ? headers.dup : {}
  # Set once a request is re-sent after an ambiguous failure, so a
  # replayed DELETE that finds the object already gone can be recognized.
  _replayed = false

  begin
    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
      # The metadata-master sentinel stays off the stored request: a
      # caller replaying `response.request` later must not inherit it.
      _request = Parse::Request.new(method, uri, body: body, headers: headers,
                                                 opts: opts.except(:metadata_master))
      # Request copies the headers it is given, so carry its request id
      # back onto the outgoing headers.
      headers.merge!(_request.headers)
    end

    # http method
    method = method.downcase.to_sym
    # Faraday resolves an absolute or protocol-relative path against the
    # configured base URL by replacing its host, so a caller-supplied
    # path such as `https://other.example/x` or `//other.example/x` would
    # carry the master key and session token to that host.
    if self.class.unsafe_request_path?(uri)
      raise ArgumentError, "[Parse::Client] Refusing request path #{uri.to_s.strip[0, 80].inspect}: " \
                           "paths must be relative to the configured server URL."
    end
    # 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)

    # SDK metadata reads (class schemas, the role graph) keep the master
    # key inside `Parse.without_master_key`. Only the internal sentinel
    # turns this on; a `true` or any other value from a caller does not.
    # The marker goes on a per-attempt copy of the headers handed to the
    # connection (below), never on `headers` or the stored request, so a
    # retry, `response.request`, or an error reporter never carries it.
     = opts[:metadata_master].equal?(METADATA_MASTER_REQUEST) && opts[:use_master_key] == true

    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

    raw_token = opts[:session_token]
    # A session token the caller put in the request headers directly
    # (`current_user(token)`, `fetch_session(token)`, `logout(token)`)
    # is as explicit as `session_token:`. Treat it as the per-call token
    # so the ambient `with_session` token or this client's bound token
    # cannot overwrite it: otherwise `User.session(token_a)` inside
    # `with_session(token_b)` resolved user B, and the identity cache
    # then mapped token A (or a garbage token) to user B for its TTL.
    if raw_token.nil?
      # Same lookup a batch uses for each request's own credentials
      # (Parse::Request#explicit_authority).
      header_token = Parse::Request.header_value(headers, Parse::Protocol::SESSION_TOKEN)
      raw_token = header_token if header_token.is_a?(String)
    end
    # SEC-02:an EXPLICITLY-supplied session_token that is a blank /
    # whitespace-only string is an unusable credential — NOT an invitation
    # to fall back to the master key. Treat it as "no credential"
    # (anonymous) and fail closed: suppress the master key and send no
    # session header, so Parse Server applies public ACL/CLP instead of
    # silently executing with master authority. The caller passed a token
    # explicitly, so we also do NOT fall through to the ambient / bound
    # token — that was their stated (empty) scope. `session_token: nil`
    # (value literally nil) is unchanged: it means "not set", and still
    # resolves via the ambient / bound fallback below.
    explicit_blank_token = raw_token.is_a?(String) && raw_token.strip.empty?
    token = explicit_blank_token ? nil : raw_token
    # When no explicit token was passed AND the caller didn't ask to send
    # the master key, fall through to (in order) the fiber-local ambient set
    # by `Parse.with_session`, then this client's own bound `@session_token`.
    # Explicit `use_master_key: true` is treated as a deliberate admin call
    # and skips both — otherwise an `admin.do_thing(use_master_key: true)`
    # nested inside a `with_session(user)` block (or on a token-bound client)
    # would silently downgrade. The ambient wins over the bound token so a
    # `with_session` override inside a user-scoped client still takes effect.
    # Inside `Parse.with_session(nil)` (or a token-less user) the block is
    # anonymous: no ambient, no bound token, and no master key, unless
    # this call passed a token or `use_master_key: true` itself.
    anonymous_block = token.nil? && !explicit_blank_token &&
                      !(explicit_master && opts[:use_master_key] == true) &&
                      Parse.respond_to?(:anonymous_session?) && Parse.anonymous_session?
    if anonymous_block
      headers[Parse::Middleware::Authentication::DISABLE_MASTER_KEY] = "true"
    elsif token.nil? && !explicit_blank_token && !(explicit_master && opts[:use_master_key] == true)
      ambient = Parse.current_session_token
      # A whitespace-only ambient must not count as present: otherwise it
      # blocks the bound-token fallback below and then fails the later
      # `token.present?` check, silently sending the master key instead.
      token = ambient if ambient.is_a?(String) && !ambient.strip.empty?
      token = @session_token if (token.nil? || token.to_s.strip.empty?) && @session_token
    end
    if explicit_blank_token
      # Fail closed: never send the master key for an unusable explicit token.
      headers[Parse::Middleware::Authentication::DISABLE_MASTER_KEY] = "true"
      headers.delete(Parse::Protocol::SESSION_TOKEN)
    elsif 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
    send_headers = headers
    if 
      send_headers = headers.merge(Parse::Middleware::Authentication::METADATA_MASTER =>
                                     Parse::Middleware::Authentication::METADATA_MASTER_TOKEN)
    end
    response_env = @conn.send(method, uri, params, send_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
      # Only Parse's timeout code maps here. Code 143 is Parse Server's
      # WEBHOOK_ERROR (for example "no function named: foo is defined"),
      # not a timeout.
      if response.code == Parse::Response::ERROR_TIMEOUT
        Parse::Client._safe_warn("TimeoutError", response)
        raise Parse::Error::TimeoutError, response
      end
    when 404
      if response.object_not_found? && _replayed && method == :delete
        # An earlier attempt of this DELETE failed ambiguously and was
        # re-sent. "Object not found" on the replay means the first
        # attempt removed it, so report the delete as applied.
        warn "[Parse:Retry] #{_request} : object already deleted by an earlier attempt"
        applied = Parse::Response.new({})
        applied.http_status = 200
        applied.headers = response.headers
        applied.request = _request
        return applied
      end
      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, 502, 503, 504
      # 502 and 504 come from a gateway or load balancer in front of
      # Parse Server. Like 500/503, the request may or may not have been
      # applied, so they are retried only when the request is idempotent.
      Parse::Client._safe_warn("ServiceUnavailableError", response)
      raise Parse::Error::ServiceUnavailableError, response
    end

    if response.error?
      if response.code == -1 && response.error.to_s.start_with?("Missing additional authData mfa")
        # Parse Server's OTHER_CAUSE (-1) for a password login on an
        # account with MFA enabled and no token supplied. It is a 400, not
        # an outage: without this branch the `<= 2` check below mapped it
        # to ServiceUnavailableError and retried the login. Surface the
        # typed error callers are documented to rescue to prompt for a code.
        Parse::Client._safe_warn("MFA::RequiredError", response)
        raise Parse::MFA::RequiredError
      end
      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
      elsif response.code == Parse::Response::ERROR_DUPLICATE_REQUEST # 159
        # Request-id idempotency rejected a duplicate — the original write
        # already applied (NOT a second time). Surface a typed, catchable
        # signal rather than a generic error; this is what a transparently-
        # retried write that landed-but-lost-its-response sees on the replay.
        Parse::Client._safe_warn("DuplicateRequestError", response)
        raise Parse::Error::DuplicateRequestError, response
      end
    end

    response
  rescue Parse::Error::RequestLimitExceededError, Parse::Error::ServiceUnavailableError => e
    # 429 (RequestLimitExceeded): the server threw the request away, so
    # re-sending is safe for any method. 500/503 (ServiceUnavailable) is
    # ambiguous — a write may have applied before the error — so only
    # re-send when the request is idempotent (see #idempotent_retry?).
    retryable = e.is_a?(Parse::Error::RequestLimitExceededError) || idempotent_retry?(method, body, headers, uri)
    if _retry_count > 0 && retryable
      warn "[Parse:Retry] Retries remaining #{_retry_count} : #{response&.request || _request}"
      _retry_count -= 1
      _replayed = true unless e.is_a?(Parse::Error::RequestLimitExceededError)
      # Use Retry-After header if available, otherwise use linear 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
        # Linear backoff (RETRY_DELAY × attempt number) with +/-25% jitter.
        # Never zero —
        # zero-wait retries amplify DoS against upstream and stampede on 429.
        backoff_delay = RETRY_DELAY * (_retry_max - _retry_count)
        _retry_delay = backoff_delay * (0.75 + rand * 0.5)
      end
      sleep _retry_delay if _retry_delay > 0
      retry
    end
    raise
  rescue Faraday::ConnectionFailed => e
    # `Faraday::ConnectionFailed` covers two very different failures under
    # one class, so it is split on the wrapped cause (see
    # #connection_reset_error?):
    #
    #   - RESET mid-flight (`Errno::ECONNRESET` / `Errno::EPIPE` /
    #     `Errno::ECONNABORTED` / `EOFError`): the classic stale
    #     keep-alive failure. A pooled persistent connection idled past
    #     the server's (or an LB's) keep-alive window and was closed
    #     remotely, and the next request on it dies at the socket.
    #     Transient by nature (a fresh connection succeeds immediately),
    #     so it retries under the same idempotency rules as a read
    #     timeout: the outcome is unknown, so only idempotent requests
    #     are re-sent.
    #
    #   - REFUSED (and DNS failure): the server is down or misconfigured.
    #     Retrying only adds backoff latency and `[Parse:Retry]` noise
    #     before the inevitable error, so it propagates raw and fast.
    raise unless connection_reset_error?(e)
    if _retry_count > 0 && idempotent_retry?(method, body, headers, uri)
      _retry_count = consume_retry_with_backoff(_retry_count, _retry_max, _request)
      _replayed = true
      retry
    end
    raise Parse::Error::ConnectionError, "#{_request} : #{e.class} - #{e.message}"
  rescue Faraday::ClientError, Faraday::TimeoutError, Net::OpenTimeout => e
    # Request timed out mid-flight: the outcome is unknown (the server may
    # have received and applied the write but never answered), so only
    # re-send idempotent requests to avoid double-applying.
    #
    # Faraday 2.x raises `Faraday::TimeoutError` for a read timeout
    # (`Timeout::Error` / `Errno::ETIMEDOUT`); it subclasses `Faraday::Error`,
    # not `ClientError`, so it must be listed explicitly to be caught.
    # `Faraday::ConnectionFailed` is handled in its own rescue above,
    # split into retry-reset / fail-fast-refused.
    if _retry_count > 0 && idempotent_retry?(method, body, headers, uri)
      _retry_count = consume_retry_with_backoff(_retry_count, _retry_max, _request)
      _replayed = true
      retry
    end
    raise Parse::Error::ConnectionError, "#{_request} : #{e.class} - #{e.message}"
  end
end

#request_time_budget ⇒ Float

The longest one request through #request can take, in seconds, counting every retry attempt at its full open and read timeout plus the largest retry backoff. A server-supplied Retry-After is not included. Used to size locks that must be held across a request.

Returns:

  • (Float)


1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
# File 'lib/parse/client.rb', line 1372

def request_time_budget
  options = @conn.respond_to?(:options) ? @conn.options : nil
  read = options.respond_to?(:timeout) ? options.timeout.to_f : 0.0
  open = options.respond_to?(:open_timeout) ? options.open_timeout.to_f : 0.0
  read = 30.0 if read <= 0
  open = 5.0 if open <= 0
  retries = [retry_limit.to_i, 0].max
  backoff = (1..retries).sum { |attempt| RETRY_DELAY * attempt * 1.25 }
  (open + read) * (retries + 1) + backoff
end

#sdk_cache ⇒ Object

The store the SDK itself reads and writes: the response cache, the identity and role planes, and #clear_cache!.

With cache_keyspace: true this is a Parse::Cache::ScopedView (or a Parse::Cache::KeyspacedStore for a store that cannot produce one) confined to this client's keyspace. Without it, this IS #cache, so nothing about an existing deployment changes.

Kept separate from #cache because the two answer different questions. cache is the store the application configured and may still use for its own keys, under their original physical names. sdk_cache is the SDK's slice of it, and clearing that slice must not reach application data.

Returns:

  • (Object) —

    the SDK-owned store.



395
396
397
# File 'lib/parse/client.rb', line 395

def sdk_cache
  @sdk_cache || self.cache
end

#send_request(req) ⇒ Parse::Response

Send a Request object.

Parameters:

Returns:

Raises:

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



2071
2072
2073
2074
2075
2076
2077
2078
# File 'lib/parse/client.rb', line 2071

def send_request(req) #Parse::Request object
  raise ArgumentError, "Object not of Parse::Request type." unless req.is_a?(Parse::Request)
  # Forward the request's own options so its session token, master-key
  # opt-out, cache directive and retry budget reach the auth resolution.
  # {#request} also merges them; passing them here keeps the contract
  # explicit at the public entry point.
  request req, opts: (req.opts || {})
end

#server_deduped_request?(headers, method = nil, uri = nil) ⇒ Boolean

Whether this request is covered by Parse Server's server-side request-id deduplication, making a replay a no-op. True only when the operator has opted in via Request.assume_server_idempotency, the request carries a non-blank request-id header, AND it targets a route Parse Server deduplicates (see SERVER_DEDUP_ROUTES).

Parameters:

  • headers (Hash, nil) —

    the outgoing request headers.

  • method (Symbol, nil) (defaults to: nil) —

    the HTTP method.

  • uri (String, nil) (defaults to: nil) —

    the request path.

Returns:

  • (Boolean)


1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
# File 'lib/parse/client.rb', line 1974

def server_deduped_request?(headers, method = nil, uri = nil)
  return false unless Parse::Request.assume_server_idempotency
  return false unless headers.is_a?(Hash)
  rid = headers[Parse::Request.request_id_header]
  return false unless rid.is_a?(String) && !rid.strip.empty?
  routes = SERVER_DEDUP_ROUTES[method.to_s.downcase.to_sym] if method
  return false if routes.nil?
  path = api_relative_path(uri)
  return false if path.nil?
  routes.any? { |route| path.match?(route) }
end

#to_json(*args) ⇒ String

Returns the redacted #as_json summary as JSON.

Returns:



437
438
439
# File 'lib/parse/client.rb', line 437

def to_json(*args)
  as_json.to_json(*args)
end

#url_prefix ⇒ String

Returns the url prefix of the Parse Server url.

Returns:

  • (String) —

    the url prefix of the Parse Server url.



1384
1385
1386
# File 'lib/parse/client.rb', line 1384

def url_prefix
  @conn.url_prefix
end

#validate_live_query_url!(url, allow_insecure:) ⇒ String?

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.

Validate an explicit LiveQuery URL at configure time with the same rules LiveQuery::Client applies, and return the URL to use (http:// and https:// are mapped to ws:// and wss://).

Returns:



1339
1340
1341
1342
# File 'lib/parse/client.rb', line 1339

def validate_live_query_url!(url, allow_insecure:)
  return url unless url.is_a?(String)
  Parse::LiveQuery::Client.normalize_url(url, allow_insecure: allow_insecure)
end

#warn_about_unknown_live_query_keys!(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.



1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
# File 'lib/parse/client.rb', line 1345

def warn_about_unknown_live_query_keys!(live_query_opts)
  return unless live_query_opts.is_a?(Hash) && live_query_opts.any?

  probe = Parse::LiveQuery::Configuration.new
  unknown = live_query_opts.keys.reject { |k| probe.respond_to?("#{k}=") }
  return if unknown.empty?

  warn "[Parse::Client] Ignoring unknown live_query option(s): " \
    "#{unknown.inspect}. Valid keys are Parse::LiveQuery::Configuration " \
    "setters (url, application_id, client_key, master_key, ping_interval, " \
    "pong_timeout, allow_insecure, ssl_min_version, ssl_max_version, " \
    "logging_enabled, log_level, ...). Check for typos."
end

#with_session(&block) ⇒ Object

Run a block with this client's bound #session_token active as the ambient session, so every query / object operation inside it that resolves the default client (e.g. Post.count, Post.all, obj.save) is authorized by Parse Server as that user — ACL and CLP enforced, master key suppressed — without threading session_token: through each call.

This is the client-receiver flavor of Parse.with_session (and mirrors User#with_session); it scopes by binding the token as the AMBIENT session — it does not re-route operations through this client object, so the connection used inside the block is still the resolved default client. If you need operations to run against a different client, pass that client explicitly (e.g. Parse::Query.new("Post", client: #{become}(...))).

total = Parse::User.login(u, p).with_session { Post.count } # readable Posts only

Scopes REST-routed operations (find / get / count / save) and mongo-direct reads (results_direct, count_direct, Atlas Search), which resolve the same ambient token when the query carries no explicit session_token:, acl_user:, or use_master_key: true.

Returns:

  • the value of the block.

Raises:

  • (ArgumentError) —

    if this client has no bound session token (scoping would be a no-op and almost certainly a mistake).



512
513
514
515
516
# File 'lib/parse/client.rb', line 512

def with_session(&block)
  raise ArgumentError, "Parse::Client#with_session requires a block" unless block_given?
  raise ArgumentError, "Parse::Client#with_session requires a client with a bound session_token" if @session_token.nil?
  Parse.with_session(@session_token, &block)
end