Module: Parse
- Defined in:
- lib/parse/agent.rb,
lib/parse/lock.rb,
lib/parse/query.rb,
lib/parse/query.rb,
lib/parse/stack.rb,
lib/parse/access.rb,
lib/parse/client.rb,
lib/parse/schema.rb,
lib/parse/api/all.rb,
lib/parse/console.rb,
lib/parse/graphql.rb,
lib/parse/mongodb.rb,
lib/parse/api/push.rb,
lib/parse/webhooks.rb,
lib/parse/acl_scope.rb,
lib/parse/api/batch.rb,
lib/parse/api/files.rb,
lib/parse/api/hooks.rb,
lib/parse/api/users.rb,
lib/parse/clp_scope.rb,
lib/parse/model/acl.rb,
lib/parse/model/clp.rb,
lib/parse/api/config.rb,
lib/parse/api/schema.rb,
lib/parse/api/server.rb,
lib/parse/cache/pool.rb,
lib/parse/embeddings.rb,
lib/parse/embeddings.rb,
lib/parse/live_query.rb,
lib/parse/live_query.rb,
lib/parse/model/date.rb,
lib/parse/model/file.rb,
lib/parse/model/push.rb,
lib/parse/agent/tools.rb,
lib/parse/api/objects.rb,
lib/parse/cache/redis.rb,
lib/parse/model/bytes.rb,
lib/parse/model/email.rb,
lib/parse/model/model.rb,
lib/parse/model/phone.rb,
lib/parse/stack/tasks.rb,
lib/parse/agent/errors.rb,
lib/parse/api/sessions.rb,
lib/parse/atlas_search.rb,
lib/parse/client/batch.rb,
lib/parse/client/batch.rb,
lib/parse/lock_backend.rb,
lib/parse/model/object.rb,
lib/parse/model/vector.rb,
lib/parse/query/cursor.rb,
lib/parse/agent/prompts.rb,
lib/parse/api/aggregate.rb,
lib/parse/api/analytics.rb,
lib/parse/authorization.rb,
lib/parse/model/geojson.rb,
lib/parse/model/pointer.rb,
lib/parse/model/polygon.rb,
lib/parse/stack/railtie.rb,
lib/parse/stack/version.rb,
lib/parse/terminal_safe.rb,
lib/parse/vector_search.rb,
lib/parse/agent/describe.rb,
lib/parse/cache/keyspace.rb,
lib/parse/client/caching.rb,
lib/parse/client/logging.rb,
lib/parse/client/request.rb,
lib/parse/model/geopoint.rb,
lib/parse/query/ordering.rb,
lib/parse/query/ordering.rb,
lib/parse/cache/sub_cache.rb,
lib/parse/client/protocol.rb,
lib/parse/client/response.rb,
lib/parse/embeddings/jina.rb,
lib/parse/embeddings/qwen.rb,
lib/parse/graphql/scalars.rb,
lib/parse/lookup_rewriter.rb,
lib/parse/model/time_zone.rb,
lib/parse/query/operation.rb,
lib/parse/retrieval/chunk.rb,
lib/parse/two_factor_auth.rb,
lib/parse/agent/log_levels.rb,
lib/parse/agent/mcp_client.rb,
lib/parse/agent/mcp_server.rb,
lib/parse/api/path_segment.rb,
lib/parse/client/profiling.rb,
lib/parse/embeddings/cache.rb,
lib/parse/live_query/event.rb,
lib/parse/query/constraint.rb,
lib/parse/webhooks/payload.rb,
lib/parse/agent/field_names.rb,
lib/parse/cache/scoped_view.rb,
lib/parse/embeddings/cohere.rb,
lib/parse/embeddings/openai.rb,
lib/parse/embeddings/voyage.rb,
lib/parse/live_query/client.rb,
lib/parse/model/core/errors.rb,
lib/parse/model/core/schema.rb,
lib/parse/model/validations.rb,
lib/parse/pipeline_security.rb,
lib/parse/query/constraints.rb,
lib/parse/retrieval/chunker.rb,
lib/parse/agent/field_policy.rb,
lib/parse/agent/mcp_rack_app.rb,
lib/parse/agent/metadata_dsl.rb,
lib/parse/agent/rate_limiter.rb,
lib/parse/cache/invalidation.rb,
lib/parse/embeddings/fixture.rb,
lib/parse/live_query/logging.rb,
lib/parse/model/classes/role.rb,
lib/parse/model/classes/user.rb,
lib/parse/model/core/actions.rb,
lib/parse/model/core/actions.rb,
lib/parse/model/core/builder.rb,
lib/parse/retrieval/profiles.rb,
lib/parse/retrieval/reranker.rb,
lib/parse/agent/approval_gate.rb,
lib/parse/api/cloud_functions.rb,
lib/parse/atlas_search/result.rb,
lib/parse/client/body_builder.rb,
lib/parse/embeddings/provider.rb,
lib/parse/model/core/describe.rb,
lib/parse/model/core/fetching.rb,
lib/parse/model/core/indexing.rb,
lib/parse/model/core/querying.rb,
lib/parse/retrieval/benchmark.rb,
lib/parse/retrieval/retriever.rb,
lib/parse/stack/rack_advisory.rb,
lib/parse/agent/mcp_dispatcher.rb,
lib/parse/agent/metadata_audit.rb,
lib/parse/agent/relation_graph.rb,
lib/parse/atlas_search/session.rb,
lib/parse/cache/moneta_surface.rb,
lib/parse/cache/upstream_roles.rb,
lib/parse/client/url_redaction.rb,
lib/parse/embeddings/spend_cap.rb,
lib/parse/retrieval/agent_tool.rb,
lib/parse/vector_search/hybrid.rb,
lib/parse/agent/mcp_deployments.rb,
lib/parse/client/authentication.rb,
lib/parse/embeddings/local_http.rb,
lib/parse/embeddings/media_file.rb,
lib/parse/model/classes/product.rb,
lib/parse/model/classes/session.rb,
lib/parse/model/core/properties.rb,
lib/parse/schema/index_migrator.rb,
lib/parse/webhooks/registration.rb,
lib/parse/agent/prompt_hardening.rb,
lib/parse/agent/result_formatter.rb,
lib/parse/embeddings/image_fetch.rb,
lib/parse/graphql/type_generator.rb,
lib/parse/live_query/event_queue.rb,
lib/parse/model/classes/audience.rb,
lib/parse/model/core/create_lock.rb,
lib/parse/webhooks/trigger_audit.rb,
lib/parse/agent/mcp_subscriptions.rb,
lib/parse/agent/metadata_registry.rb,
lib/parse/embeddings/video_source.rb,
lib/parse/live_query/subscription.rb,
lib/parse/model/core/field_guards.rb,
lib/parse/agent/cancellation_token.rb,
lib/parse/agent/pipeline_validator.rb,
lib/parse/embeddings/binding_audit.rb,
lib/parse/live_query/configuration.rb,
lib/parse/model/classes/job_status.rb,
lib/parse/model/core/embed_managed.rb,
lib/parse/embeddings/batch_embedder.rb,
lib/parse/embeddings/streaming_body.rb,
lib/parse/live_query/health_monitor.rb,
lib/parse/model/classes/push_status.rb,
lib/parse/query/n_plus_one_detector.rb,
lib/parse/retrieval/reranker/cohere.rb,
lib/parse/retrieval/reranker/voyage.rb,
lib/parse/atlas_search/index_manager.rb,
lib/parse/live_query/circuit_breaker.rb,
lib/parse/model/associations/has_one.rb,
lib/parse/model/classes/installation.rb,
lib/parse/model/classes/job_schedule.rb,
lib/parse/model/core/parse_reference.rb,
lib/parse/model/core/search_indexing.rb,
lib/parse/webhooks/replay_protection.rb,
lib/parse/agent/constraint_translator.rb,
lib/parse/atlas_search/search_builder.rb,
lib/parse/model/associations/has_many.rb,
lib/parse/atlas_search/protected_paths.rb,
lib/parse/model/core/vector_searchable.rb,
lib/parse/schema/search_index_migrator.rb,
lib/parse/model/associations/belongs_to.rb,
lib/parse/model/core/pluralized_aliases.rb,
lib/parse/stack/active_support_advisory.rb,
lib/parse/two_factor_auth/user_extension.rb,
lib/parse/vector_search/index_definition.rb,
lib/parse/model/associations/collection_proxy.rb,
lib/parse/model/core/enhanced_change_tracking.rb,
lib/parse/model/validations/uniqueness_validator.rb,
lib/parse/model/associations/pointer_collection_proxy.rb,
lib/parse/model/associations/relation_collection_proxy.rb
Overview
Note: Do not require "../object" here - this file is loaded from object.rb and adding that require would create a circular dependency.
Defined Under Namespace
Modules: ACLScope, API, Access, Associations, AtlasSearch, Authorization, CLPScope, Cache, Console, Core, CreateLock, Embeddings, Generated, GeoJSON, GraphQL, LiveQuery, Lock, LockBackend, LookupRewriter, MFA, Middleware, MongoDB, PipelineSecurity, PluralizedAliases, Properties, Protocol, QueryFieldAliasScope, RegexSecurity, Retrieval, Schema, Stack, TerminalSafe, Validations, VectorSearch Classes: ACL, Agent, Aggregation, AggregationResult, Audience, AutofetchTriggeredError, BatchOperation, Bytes, CLP, Client, CollectionProxy, Constraint, CreateLockInvalidKey, CreateLockTimeoutError, CreateLockUnavailableError, Cursor, DataType, Date, Email, Error, File, GeoPoint, GroupBy, GroupByDate, GroupedResult, Installation, JobSchedule, JobStatus, Model, NPlusOneDetector, NPlusOneQueryError, Object, Operation, Order, Phone, Pointer, PointerCollectionProxy, Polygon, Product, Push, PushStatus, Query, RecordNotSaved, RelationAction, RelationCollectionProxy, Request, Response, Role, Session, SortableGroupBy, SortableGroupByDate, TimeZone, UnfetchedFieldAccessError, User, Vector, Webhooks
Constant Summary collapse
- NOT_PROVIDED =
Sentinel used by SDK methods that need to distinguish "the caller omitted this kwarg" from "the caller explicitly passed
nil" — the latter must NOT fall through to a default that would silently re-introduce a value the caller is trying to suppress (e.g. a master-key or session-token override).Use as the default value of a keyword argument, then check with
value.equal?(Parse::NOT_PROVIDED)to detect omission. Comparison by identity is intentional —==on the sentinel is meaningless. Object.new.tap do |o| def o.inspect "Parse::NOT_PROVIDED" end end.freeze
- MASTER_KEY_STATE_KEY =
Fiber-local key consulted by the authentication middleware. A truthy entry suppresses the master-key header for the duration of the block set by without_master_key; a
:enabledentry forces the master-key header back on inside a nested with_master_key block. :__parse_master_key_state__- SESSION_TOKEN_STATE_KEY =
Fiber-local key holding the ambient session token consulted by Client#request when no explicit
session_token:was passed. Set by with_session; nested blocks save and restore the previous value on exit. :__parse_session_token__- CACHE_TENANT_PATTERN =
Set an ambient cache-tenant scope for the duration of the block. When set, the Middleware::Caching middleware composes the tenant into the cache key as
<base-namespace>:T:<tenant>:…so a multi-tenant Parse application can share one Redis (or any Moneta- backed cache) without per-tenant configuration plumbing through everyParse::Client.newsite. Tenants do not see each other's cached responses; a SCAN-delete over<base-namespace>:T:<tenant>:*evicts exactly one tenant cleanly.This is purely a key namespacing mechanism — it does NOT enforce any access-control semantics. Tenant isolation at the data layer is the job of
agent_tenant_scope(per-class scoping) and ACL/CLP. The tenant cache scope's role is to keep tenant A's session-token- keyed cache entry from being served on tenant B's request even when the URL and session token happen to collide.Fiber-local — composes safely with
asyncand concurrent web frameworks. The scope is per-fiber, not per-thread, and is restored on block exit even if the block raises. /\A[A-Za-z0-9_\-]{1,256}\z/.freeze
- CURRENT_USER_STATE_KEY =
Fiber-local key holding the User cached by login for current_user lookup. Kept distinct from the session-token key so block-scoped
Parse.with_session(tok)(which has only a token, not a user object) doesn't mis-populate it. :__parse_current_user__- RAG =
Discoverability alias. "RAG" ages badly as a term;
Retrievalis the canonical name. Retrieval
Class Attribute Summary collapse
-
.autofetch_raise_on_missing_keys ⇒ Object
Returns the value of attribute autofetch_raise_on_missing_keys.
-
.cache_write_on_fetch ⇒ Object
Returns the value of attribute cache_write_on_fetch.
-
.default_query_cache ⇒ Object
Returns the value of attribute default_query_cache.
-
.live_query_enabled ⇒ Object
Returns the value of attribute live_query_enabled.
-
.logging ⇒ Object
readonly
Sets Middleware::BodyBuilder logging.
-
.mcp_remote_api ⇒ Object
Returns the value of attribute mcp_remote_api.
-
.mcp_server_enabled ⇒ Object
Returns the value of attribute mcp_server_enabled.
-
.mcp_server_port ⇒ Object
Returns the value of attribute mcp_server_port.
-
.pluralized_aliases ⇒ Object
Returns the value of attribute pluralized_aliases.
-
.rewrite_lookups ⇒ Object
Returns the value of attribute rewrite_lookups.
-
.serialize_only_fetched_fields ⇒ Object
Returns the value of attribute serialize_only_fetched_fields.
-
.strict_pointer_shapes ⇒ Object
Returns the value of attribute strict_pointer_shapes.
-
.strict_property_redefinition ⇒ Object
Returns the value of attribute strict_property_redefinition.
-
.suppress_server_version_warning ⇒ Object
Returns the value of attribute suppress_server_version_warning.
-
.synchronize_classes ⇒ Object
Returns the value of attribute synchronize_classes.
-
.synchronize_create_default ⇒ Object
Returns the value of attribute synchronize_create_default.
-
.synchronize_create_options ⇒ Object
Returns the value of attribute synchronize_create_options.
-
.synchronize_create_secret ⇒ Object
Returns the value of attribute synchronize_create_secret.
-
.synchronize_create_store ⇒ Object
Returns the value of attribute synchronize_create_store.
-
.validate_query_keys ⇒ Object
Returns the value of attribute validate_query_keys.
-
.warn_on_query_issues ⇒ Object
Returns the value of attribute warn_on_query_issues.
Class Method Summary collapse
-
.anonymous_session? ⇒ Boolean
Whether the current fiber is inside an anonymous
Parse.with_session(nil)block (directly, or nested without a token-bearing block inside it). -
.auto_generate_models! ⇒ Array
Create all Parse::Object subclasses, including their properties and inferred associations by importing the schema for the remote collections in a Parse application.
-
.auto_upgrade! ⇒ Object
Perform a non-destructive upgrade of all your Parse schemas in the backend based on the property definitions of your local Object subclasses.
-
.batch(reqs = nil) ⇒ BatchOperation
Create a new batch operation.
-
.cache ⇒ Moneta::Transformer, Moneta::Expires
The shared cache for the default client connection.
-
.call_function(name, body = {}, **opts) ⇒ Object
Helper method to call cloud functions and get results.
-
.call_function!(name, body = {}, **opts) ⇒ Object
Same as Parse.call_function but raises Error::CloudCodeError when the cloud function returns an error instead of silently returning nil.
-
.call_function_with_session(name, body = {}, session_token, **opts) ⇒ Object
Helper method to call cloud functions with a session token.
-
.call_function_with_session!(name, body = {}, session_token, **opts) ⇒ Object
Same as Parse.call_function_with_session but raises Error::CloudCodeError when the cloud function returns an error instead of silently returning nil.
-
.classify(className) ⇒ Class
Find a corresponding Parse::Object subclass for this string or symbol.
-
.clear_n_plus_one_callbacks! ⇒ Object
Clear N+1 detection callbacks.
-
.clear_profiles! ⇒ Object
Clear all stored profiles.
-
.clear_profiling_callbacks! ⇒ Object
Clear all profiling callbacks.
-
.client(conn = :default) ⇒ Parse::Client
Helper method to get the default Parse client.
- .client_mode ⇒ Object
- .client_mode=(value) ⇒ Object
- .client_mode? ⇒ Boolean
-
.config(conn = :default) ⇒ Hash
Retrieve the App specific Parse configuration parameters.
-
.config!(conn = :default) ⇒ Hash
Force fetch updated Parse configuration.
-
.config_entries(conn = :default, master: false) ⇒ Hash{String=>Hash}
Return every config entry zipped with its masterKeyOnly trait.
-
.configure_logging {|Middleware::Logging| ... } ⇒ Object
Configure Parse logging with a block.
-
.configure_mcp_remote_api(provider:, api_key:, model: nil, base_url: nil) ⇒ Hash
Configure MCP remote API connection.
-
.configure_n_plus_one {|NPlusOneDetector| ... } ⇒ Object
Configure N+1 detection thresholds.
-
.connected?(conn = :default, endpoint = nil) ⇒ Boolean
Check that the Parse Server is reachable and responding.
-
.current_cache_tenant ⇒ String?
The ambient cache-tenant scope set by Parse.with_cache_tenant for the current fiber, or
nilwhen not inside such a block. -
.current_session_token ⇒ String?
The ambient session token set by Parse.with_session for the current fiber, or
nilwhen not inside such a block or inside an anonymouswith_session(nil)block (see Parse.anonymous_session?). -
.current_user ⇒ Parse::User?
The User cached alongside the ambient session set by Parse.login, or
nilwhen no imperative login is active. -
.live_query_enabled? ⇒ Boolean
Check if LiveQuery feature is enabled.
-
.log_level ⇒ Symbol
The current log level.
-
.log_level=(value) ⇒ Object
Set the log level for Parse requests.
-
.log_max_body_length ⇒ Integer
The maximum body length.
-
.log_max_body_length=(value) ⇒ Object
Set the maximum body length to log before truncation.
-
.logger ⇒ Logger
The current logger.
-
.logger=(value) ⇒ Object
Set a custom logger for Parse requests.
-
.logging_enabled ⇒ Boolean
Whether logging is enabled.
-
.logging_enabled=(value) ⇒ Object
Enable or disable request/response logging.
-
.login(username, password, mfa_token: nil) ⇒ Parse::User
Imperative login for REPL / Rake-console use: logs in once, stashes the resulting session token as the ambient for the current fiber, and returns the User.
-
.logout(revoke: true) ⇒ Boolean
Imperative logout: clears the ambient session token and cached current user for the current fiber and, by default, revokes the token server-side via
POST /parse/logout. -
.master_key_disabled? ⇒ Boolean
True if the current fiber is inside a Parse.without_master_key block.
-
.master_key_only(conn = :default) ⇒ Hash{String=>Boolean}
Retrieve the masterKeyOnly flag map for the application configuration.
-
.mcp_remote_api_configured? ⇒ Boolean
Check if MCP remote API is configured.
-
.mcp_server_enabled? ⇒ Boolean
Check if MCP server feature is enabled Requires PARSE_MCP_ENABLED=true in environment AND Parse.mcp_server_enabled = true.
-
.n_plus_one_detection_window ⇒ Float
Get the N+1 detection window.
-
.n_plus_one_detection_window=(value) ⇒ Object
Set the N+1 detection window (time in seconds to track related fetches).
-
.n_plus_one_fetch_threshold ⇒ Integer
Get the N+1 fetch threshold.
-
.n_plus_one_fetch_threshold=(value) ⇒ Object
Set the N+1 fetch threshold (minimum fetches to trigger warning).
-
.n_plus_one_mode ⇒ Symbol
Get the current N+1 detection mode.
-
.n_plus_one_mode=(value) ⇒ Object
Set the N+1 detection mode.
-
.n_plus_one_summary ⇒ Hash
Get N+1 detection summary.
-
.on_n_plus_one {|source_class, association, target_class, count, location| ... } ⇒ Object
Register a callback for N+1 detection events.
-
.on_request_complete {|Hash| ... } ⇒ Object
Register a callback for request completion.
-
.pluralized_aliases? ⇒ Boolean
Whether automatic pluralized class-name aliases are enabled.
-
.profiling_enabled ⇒ Boolean
Whether profiling is enabled.
-
.profiling_enabled=(value) ⇒ Object
Enable or disable request profiling.
-
.profiling_statistics ⇒ Hash
Get profiling statistics.
-
.reachable?(conn = :default) ⇒ Boolean
Check that the Parse Server is reachable via the health endpoint.
-
.recent_profiles ⇒ Array<Hash>
Get recent profile data.
-
.registered_classes ⇒ Array
An array of registered Parse::Object subclasses.
-
.reset_n_plus_one_tracking! ⇒ Object
Reset N+1 detection tracking.
-
.schema(className) ⇒ Hash
Fetch the schema for a specific collection name.
-
.schemas ⇒ Array<Hash>
The list of all schemas for this application.
-
.sdk_cache ⇒ Object
The SDK-owned store for the default client: the response cache, the identity and role planes, and what Client#clear_cache! clears.
-
.server_features ⇒ Hash
The coarse
featuresblock advertised byGET /serverInfo, delegated to the default client. -
.server_supports?(feature) ⇒ Boolean
Capability probe against the connected Parse Server, delegated to the default client.
-
.session_token=(token) ⇒ String?
Imperative ambient-token setter, for cases where you already have a session token (e.g. read from a fixture, a test setup, a saved credential) and want to scope subsequent calls without going through the login endpoint.
-
.set_config(field, value, conn = :default, master_key_only: nil) ⇒ Hash
Set a parameter in the Parse configuration for an application.
-
.setup(opts = {}) { ... } ⇒ Client
Helper method that users should call to setup the client stack.
-
.slow_query_threshold_ms ⇒ Integer?
Current slow-query threshold in milliseconds, or
nilwhen unconfigured. -
.slow_query_threshold_ms=(value) ⇒ Object
Set the slow-query threshold in milliseconds.
-
.strict_pointer_shapes? ⇒ Boolean
Check if strict pointer-shape validation is enabled.
-
.suppress_server_version_warning? ⇒ Boolean
Check whether the Parse Server version deprecation warning is silenced.
-
.track_event(name, dimensions: {}, **opts) ⇒ Parse::Response
Send an analytics event to Parse Server's REST
/events/<name>endpoint. -
.trigger_job(name, body = {}, **opts) ⇒ Object
Helper method to trigger cloud jobs and get results.
-
.trigger_job!(name, body = {}, **opts) ⇒ Object
Same as Parse.trigger_job but raises Error::CloudCodeError when the job returns an error instead of silently returning nil.
-
.trigger_job_with_session(name, body = {}, session_token, **opts) ⇒ Object
Helper method to trigger cloud jobs with a session token.
-
.trigger_job_with_session!(name, body = {}, session_token, **opts) ⇒ Object
Same as Parse.trigger_job_with_session but raises Error::CloudCodeError when the job returns an error instead of silently returning nil.
-
.update_config(params, conn = :default, master_key_only: nil) ⇒ Hash
Set a key value pairs in the Parse configuration for an application.
-
.use_shortnames! ⇒ Object
Alias shorter names of core Parse class names.
-
.validate_associations!(classes: nil) ⇒ true
Verify that every association target across the loaded Object subclasses resolves to a known Parse class.
- .wait_for(klass, **kwargs, &block) ⇒ Object
-
.warn_on_n_plus_one ⇒ Boolean
(also: warn_on_n_plus_one?)
Check if N+1 detection is enabled.
-
.warn_on_n_plus_one=(value) ⇒ Object
Enable or disable N+1 query detection.
- .watch(klass, **kwargs, &block) ⇒ Object
- .with_cache_tenant(scope) ⇒ Object
-
.with_master_key { ... } ⇒ Object
Inverse of Parse.without_master_key: forces the master key back on for the duration of the block, even if a containing Parse.without_master_key had suppressed it.
-
.with_session(token) { ... } ⇒ Object
Run
blockwith an ambient session token set for the current fiber. -
.without_ambient_identity(keep_restrictions: false) { ... } ⇒ Object
Run
blockwith no ambient identity on the current fiber: the Parse.with_session token, the Parse.with_master_key / Parse.without_master_key state, and the innermost-block marker are all cleared, and restored on exit (including on exception). -
.without_master_key { ... } ⇒ Object
Run
blockwith the master key suppressed for every Parse request originating in the current fiber.
Class Attribute Details
.autofetch_raise_on_missing_keys ⇒ Object
Returns the value of attribute autofetch_raise_on_missing_keys.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def autofetch_raise_on_missing_keys @autofetch_raise_on_missing_keys end |
.cache_write_on_fetch ⇒ Object
Returns the value of attribute cache_write_on_fetch.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def cache_write_on_fetch @cache_write_on_fetch end |
.default_query_cache ⇒ Object
Returns the value of attribute default_query_cache.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def default_query_cache @default_query_cache end |
.live_query_enabled ⇒ Object
Returns the value of attribute live_query_enabled.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def live_query_enabled @live_query_enabled end |
.logging ⇒ Object
Sets Parse::Middleware::BodyBuilder logging.
You may specify :debug for additional verbosity.
20 21 22 |
# File 'lib/parse/client/body_builder.rb', line 20 def self.logging Parse::Middleware::BodyBuilder.logging end |
.mcp_remote_api ⇒ Object
Returns the value of attribute mcp_remote_api.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def mcp_remote_api @mcp_remote_api end |
.mcp_server_enabled ⇒ Object
Returns the value of attribute mcp_server_enabled.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def mcp_server_enabled @mcp_server_enabled end |
.mcp_server_port ⇒ Object
Returns the value of attribute mcp_server_port.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def mcp_server_port @mcp_server_port end |
.pluralized_aliases ⇒ Object
Returns the value of attribute pluralized_aliases.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def pluralized_aliases @pluralized_aliases end |
.rewrite_lookups ⇒ Object
Returns the value of attribute rewrite_lookups.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def rewrite_lookups @rewrite_lookups end |
.serialize_only_fetched_fields ⇒ Object
Returns the value of attribute serialize_only_fetched_fields.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def serialize_only_fetched_fields @serialize_only_fetched_fields end |
.strict_pointer_shapes ⇒ Object
Returns the value of attribute strict_pointer_shapes.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def strict_pointer_shapes @strict_pointer_shapes end |
.strict_property_redefinition ⇒ Object
Returns the value of attribute strict_property_redefinition.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def strict_property_redefinition @strict_property_redefinition end |
.suppress_server_version_warning ⇒ Object
Returns the value of attribute suppress_server_version_warning.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def suppress_server_version_warning @suppress_server_version_warning end |
.synchronize_classes ⇒ Object
Returns the value of attribute synchronize_classes.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def synchronize_classes @synchronize_classes end |
.synchronize_create_default ⇒ Object
Returns the value of attribute synchronize_create_default.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def synchronize_create_default @synchronize_create_default end |
.synchronize_create_options ⇒ Object
Returns the value of attribute synchronize_create_options.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def @synchronize_create_options end |
.synchronize_create_secret ⇒ Object
Returns the value of attribute synchronize_create_secret.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def synchronize_create_secret @synchronize_create_secret end |
.synchronize_create_store ⇒ Object
Returns the value of attribute synchronize_create_store.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def synchronize_create_store @synchronize_create_store end |
.validate_query_keys ⇒ Object
Returns the value of attribute validate_query_keys.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def validate_query_keys @validate_query_keys end |
.warn_on_query_issues ⇒ Object
Returns the value of attribute warn_on_query_issues.
821 822 823 |
# File 'lib/parse/stack.rb', line 821 def warn_on_query_issues @warn_on_query_issues end |
Class Method Details
.anonymous_session? ⇒ Boolean
Whether the current fiber is inside an anonymous Parse.with_session(nil)
block (directly, or nested without a token-bearing block inside it).
Requests there carry no session token and no master key unless the call
passes session_token: or use_master_key: true explicitly.
320 321 322 |
# File 'lib/parse/stack.rb', line 320 def self.anonymous_session? Fiber[SESSION_TOKEN_STATE_KEY] == ANONYMOUS_SESSION end |
.auto_generate_models! ⇒ Array
Create all Parse::Object subclasses, including their properties and inferred associations by importing the schema for the remote collections in a Parse application. Uses the default configured client.
16 17 18 19 20 |
# File 'lib/parse/model/core/builder.rb', line 16 def self.auto_generate_models! Parse.schemas.map do |schema| Parse::Model::Builder.build!(schema) end end |
.auto_upgrade! ⇒ Object
Perform a non-destructive upgrade of all your Parse schemas in the backend based on the property definitions of your local Object subclasses.
73 74 75 76 77 78 79 |
# File 'lib/parse/model/object.rb', line 73 def self.auto_upgrade! klassModels = Parse::Object.descendants klassModels.sort_by(&:parse_class).each do |klass| yield(klass) if block_given? klass.auto_upgrade! end end |
.batch(reqs = nil) ⇒ BatchOperation
Create a new batch operation.
17 18 19 |
# File 'lib/parse/client/batch.rb', line 17 def self.batch(reqs = nil) BatchOperation.new(reqs) end |
.cache ⇒ Moneta::Transformer, Moneta::Expires
The shared cache for the default client connection. This is useful if you want to also utilize the same cache store for other purposes in your application. This should normally be a Moneta unified cache interface.
238 239 240 241 242 243 244 |
# File 'lib/parse/client.rb', line 238 def self.cache # Deliberately NOT memoized. `@shared_cache ||=` pinned the first default # client's store for the life of the process, so a later `Parse.setup` # (a re-configuration, or a test suite swapping clients between cases) # kept handing back the previous client's cache with no way to reset it. Parse::Client.client(:default).cache end |
.call_function(name, body = {}, **opts) ⇒ Object
Helper method to call cloud functions and get results.
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 |
# File 'lib/parse/client.rb', line 2275 def self.call_function(name, body = {}, **opts) conn = opts[:session] || opts[:client] || :default # Extract request options for the API call request_opts = {} request_opts[:session_token] = opts[:session_token] if opts[:session_token] request_opts[:master_key] = opts[:master_key] if opts[:master_key] # Build call kwargs; only forward context: when explicitly supplied so # call sites that do not use context produce the same opts hash that # existing mock expectations match against. call_kwargs = { opts: request_opts } call_kwargs[:context] = opts[:context] unless opts[:context].nil? response = Parse::Client.client(conn).call_function(name, body, **call_kwargs) return response if opts[:raw].present? if response.error? Parse::Client._safe_warn("CloudCodeError", response, name: name) return nil end _extract_cloud_result(response) end |
.call_function!(name, body = {}, **opts) ⇒ Object
Same as call_function but raises Parse::Error::CloudCodeError when the cloud function returns an error instead of silently returning nil. HTTP-level errors (auth, timeouts, throttling, etc.) still raise their specific Error subclasses as the underlying client does.
2309 2310 2311 2312 2313 |
# File 'lib/parse/client.rb', line 2309 def self.call_function!(name, body = {}, **opts) response = call_function(name, body, **opts.merge(raw: true)) raise Parse::Error::CloudCodeError.new(name, response) if response.error? _extract_cloud_result(response) end |
.call_function_with_session(name, body = {}, session_token, **opts) ⇒ Object
Helper method to call cloud functions with a session token. This is a convenience method that ensures proper session token handling.
2322 2323 2324 2325 |
# File 'lib/parse/client.rb', line 2322 def self.call_function_with_session(name, body = {}, session_token, **opts) opts[:session_token] = session_token call_function(name, body, **opts) end |
.call_function_with_session!(name, body = {}, session_token, **opts) ⇒ Object
Same as call_function_with_session but raises Parse::Error::CloudCodeError when the cloud function returns an error instead of silently returning nil.
2336 2337 2338 2339 |
# File 'lib/parse/client.rb', line 2336 def self.call_function_with_session!(name, body = {}, session_token, **opts) opts[:session_token] = session_token call_function!(name, body, **opts) end |
.classify(className) ⇒ Class
Find a corresponding Parse::Object subclass for this string or symbol
15 16 17 |
# File 'lib/parse/model/model.rb', line 15 def self.classify(className) Parse::Model.find_class className.to_parse_class end |
.clear_n_plus_one_callbacks! ⇒ Object
Clear N+1 detection callbacks
392 393 394 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 392 def clear_n_plus_one_callbacks! NPlusOneDetector.clear_callbacks! end |
.clear_profiles! ⇒ Object
Clear all stored profiles
163 164 165 |
# File 'lib/parse/client/profiling.rb', line 163 def clear_profiles! Middleware::Profiling.clear_profiles! end |
.clear_profiling_callbacks! ⇒ Object
Clear all profiling callbacks
180 181 182 |
# File 'lib/parse/client/profiling.rb', line 180 def clear_profiling_callbacks! Middleware::Profiling.clear_callbacks! end |
.client(conn = :default) ⇒ Parse::Client
Helper method to get the default Parse client.
194 195 196 |
# File 'lib/parse/client.rb', line 194 def self.client(conn = :default) Parse::Client.client(conn) end |
.client_mode ⇒ Object
527 528 529 |
# File 'lib/parse/stack.rb', line 527 def self.client_mode @client_mode == true end |
.client_mode=(value) ⇒ Object
530 531 532 |
# File 'lib/parse/stack.rb', line 530 def self.client_mode=(value) @client_mode = (value == true) end |
.client_mode? ⇒ Boolean
533 534 535 |
# File 'lib/parse/stack.rb', line 533 def self.client_mode? client_mode end |
.config(conn = :default) ⇒ Hash
Retrieve the App specific Parse configuration parameters. The configuration for a connection is cached after the first request. Use the bang version to force update from the Parse backend.
122 123 124 |
# File 'lib/parse/client.rb', line 122 def self.config(conn = :default) Parse::Client.client(conn).config end |
.config!(conn = :default) ⇒ Hash
Force fetch updated Parse configuration
163 164 165 |
# File 'lib/parse/client.rb', line 163 def self.config!(conn = :default) Parse::Client.client(conn).config! end |
.config_entries(conn = :default, master: false) ⇒ Hash{String=>Hash}
Return every config entry zipped with its masterKeyOnly trait.
177 178 179 |
# File 'lib/parse/client.rb', line 177 def self.config_entries(conn = :default, master: false) Parse::Client.client(conn).config_entries(master: master) end |
.configure_logging {|Middleware::Logging| ... } ⇒ Object
Configure Parse logging with a block
316 317 318 |
# File 'lib/parse/client/logging.rb', line 316 def configure_logging yield Middleware::Logging if block_given? end |
.configure_mcp_remote_api(provider:, api_key:, model: nil, base_url: nil) ⇒ Hash
Configure MCP remote API connection
1090 1091 1092 1093 1094 1095 1096 1097 |
# File 'lib/parse/stack.rb', line 1090 def configure_mcp_remote_api(provider:, api_key:, model: nil, base_url: nil) @mcp_remote_api = { provider: provider.to_sym, api_key: api_key, model: model, base_url: base_url, } end |
.configure_n_plus_one {|NPlusOneDetector| ... } ⇒ Object
Configure N+1 detection thresholds.
417 418 419 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 417 def configure_n_plus_one yield NPlusOneDetector if block_given? end |
.connected?(conn = :default, endpoint = nil) ⇒ Boolean
Check that the Parse Server is reachable and responding.
By default this probes the credential-less health endpoint, so it returns
true whenever the server is up (it does NOT, by itself, validate the
application_id or REST key — see Parse::Client#connected? for why a
data-class probe is unreliable on a hardened server). Pass an endpoint
(e.g. "classes/_User") to additionally exercise the auth stack against a
class you know the configured key can read; a bad key then surfaces as an
Parse::Error::AuthenticationError at the instance level, which the
instance method converts to false. Any other failure is caught by this
module-boundary rescue and converted to false.
226 227 228 229 230 |
# File 'lib/parse/client.rb', line 226 def self.connected?(conn = :default, endpoint = nil) client(conn).connected?(endpoint) rescue StandardError false end |
.current_cache_tenant ⇒ String?
The ambient cache-tenant scope set by with_cache_tenant for the
current fiber, or nil when not inside such a block.
395 396 397 |
# File 'lib/parse/stack.rb', line 395 def self.current_cache_tenant Fiber[CACHE_TENANT_STATE_KEY] end |
.current_session_token ⇒ String?
The ambient session token set by with_session for the current
fiber, or nil when not inside such a block or inside an anonymous
with_session(nil) block (see anonymous_session?).
310 311 312 313 |
# File 'lib/parse/stack.rb', line 310 def self.current_session_token value = Fiber[SESSION_TOKEN_STATE_KEY] value == ANONYMOUS_SESSION ? nil : value end |
.current_user ⇒ Parse::User?
403 404 405 |
# File 'lib/parse/stack.rb', line 403 def self.current_user Fiber[CURRENT_USER_STATE_KEY] end |
.live_query_enabled? ⇒ Boolean
Check if LiveQuery feature is enabled
896 897 898 |
# File 'lib/parse/stack.rb', line 896 def live_query_enabled? @live_query_enabled == true end |
.log_level ⇒ Symbol
Returns the current log level.
281 282 283 |
# File 'lib/parse/client/logging.rb', line 281 def log_level Middleware::Logging.current_log_level end |
.log_level=(value) ⇒ Object
Set the log level for Parse requests
273 274 275 276 277 278 |
# File 'lib/parse/client/logging.rb', line 273 def log_level=(value) unless [:info, :debug, :warn].include?(value) raise ArgumentError, "Invalid log level: #{value}. Use :info, :debug, or :warn" end Middleware::Logging.log_level = value end |
.log_max_body_length ⇒ Integer
Returns the maximum body length.
305 306 307 |
# File 'lib/parse/client/logging.rb', line 305 def log_max_body_length Middleware::Logging.current_max_body_length end |
.log_max_body_length=(value) ⇒ Object
Set the maximum body length to log before truncation
300 301 302 |
# File 'lib/parse/client/logging.rb', line 300 def log_max_body_length=(value) Middleware::Logging.max_body_length = value.to_i end |
.logger ⇒ Logger
Returns the current logger.
294 295 296 |
# File 'lib/parse/client/logging.rb', line 294 def logger Middleware::Logging.current_logger end |
.logger=(value) ⇒ Object
Set a custom logger for Parse requests
289 290 291 |
# File 'lib/parse/client/logging.rb', line 289 def logger=(value) Middleware::Logging.logger = value end |
.logging_enabled ⇒ Boolean
Returns whether logging is enabled.
265 266 267 |
# File 'lib/parse/client/logging.rb', line 265 def logging_enabled Middleware::Logging.enabled end |
.logging_enabled=(value) ⇒ Object
Enable or disable request/response logging
260 261 262 |
# File 'lib/parse/client/logging.rb', line 260 def logging_enabled=(value) Middleware::Logging.enabled = value end |
.login(username, password, mfa_token: nil) ⇒ Parse::User
Imperative login for REPL / Rake-console use: logs in once, stashes
the resulting session token as the ambient for the current fiber,
and returns the User. Every subsequent Parse call in the
session (the IRB main fiber) is then auth-scoped to that user
without the caller threading session_token: or wrapping each
statement in with_session.
Intended for interactive use. For scoped work in production code, prefer with_session — it auto-restores prior state on exit, even if the block raises.
449 450 451 452 453 454 455 456 457 458 459 460 461 462 |
# File 'lib/parse/stack.rb', line 449 def self.login(username, password, mfa_token: nil) user = if mfa_token Parse::User.login_with_mfa(username, password, mfa_token) else Parse::User.login!(username, password) end unless user raise Parse::Error::AuthenticationError, "Parse.login: credentials rejected for #{username.inspect} (server returned no session)." end Fiber[SESSION_TOKEN_STATE_KEY] = user.session_token Fiber[CURRENT_USER_STATE_KEY] = user user end |
.logout(revoke: true) ⇒ Boolean
Imperative logout: clears the ambient session token and cached
current user for the current fiber and, by default, revokes the
token server-side via POST /parse/logout. Pair with login.
If you set the ambient via session_token= (no server-side
session to revoke), pass revoke: false to skip the network call.
477 478 479 480 481 482 483 484 485 486 487 488 489 490 |
# File 'lib/parse/stack.rb', line 477 def self.logout(revoke: true) token = Fiber[SESSION_TOKEN_STATE_KEY] Fiber[SESSION_TOKEN_STATE_KEY] = nil Fiber[CURRENT_USER_STATE_KEY] = nil if revoke && token.is_a?(String) && !token.empty? begin Parse::Client.client.logout(token) rescue StandardError # Best-effort: a failed revoke shouldn't make `logout` raise in # a REPL. The local clear already happened. end end true end |
.master_key_disabled? ⇒ Boolean
Returns true if the current fiber is inside a without_master_key block. Consulted by the authentication middleware in addition to the per-request disable header.
148 149 150 |
# File 'lib/parse/stack.rb', line 148 def self.master_key_disabled? Fiber[MASTER_KEY_STATE_KEY] == :disabled end |
.master_key_only(conn = :default) ⇒ Hash{String=>Boolean}
Retrieve the masterKeyOnly flag map for the application configuration.
187 188 189 |
# File 'lib/parse/client.rb', line 187 def self.master_key_only(conn = :default) Parse::Client.client(conn).master_key_only end |
.mcp_remote_api_configured? ⇒ Boolean
Check if MCP remote API is configured
1101 1102 1103 |
# File 'lib/parse/stack.rb', line 1101 def mcp_remote_api_configured? @mcp_remote_api.is_a?(Hash) && @mcp_remote_api[:api_key].present? end |
.mcp_server_enabled? ⇒ Boolean
Check if MCP server feature is enabled Requires PARSE_MCP_ENABLED=true in environment AND Parse.mcp_server_enabled = true
1079 1080 1081 1082 |
# File 'lib/parse/stack.rb', line 1079 def mcp_server_enabled? return false unless ENV["PARSE_MCP_ENABLED"] == "true" @mcp_server_enabled == true end |
.n_plus_one_detection_window ⇒ Float
Get the N+1 detection window
429 430 431 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 429 def n_plus_one_detection_window NPlusOneDetector.detection_window end |
.n_plus_one_detection_window=(value) ⇒ Object
Set the N+1 detection window (time in seconds to track related fetches)
423 424 425 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 423 def n_plus_one_detection_window=(value) NPlusOneDetector.detection_window = value end |
.n_plus_one_fetch_threshold ⇒ Integer
Get the N+1 fetch threshold
441 442 443 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 441 def n_plus_one_fetch_threshold NPlusOneDetector.fetch_threshold end |
.n_plus_one_fetch_threshold=(value) ⇒ Object
Set the N+1 fetch threshold (minimum fetches to trigger warning)
435 436 437 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 435 def n_plus_one_fetch_threshold=(value) NPlusOneDetector.fetch_threshold = value end |
.n_plus_one_mode ⇒ Symbol
Get the current N+1 detection mode.
352 353 354 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 352 def n_plus_one_mode NPlusOneDetector.mode end |
.n_plus_one_mode=(value) ⇒ Object
Set the N+1 detection mode.
346 347 348 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 346 def n_plus_one_mode=(value) NPlusOneDetector.mode = value end |
.n_plus_one_summary ⇒ Hash
Get N+1 detection summary
403 404 405 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 403 def n_plus_one_summary NPlusOneDetector.summary end |
.on_n_plus_one {|source_class, association, target_class, count, location| ... } ⇒ Object
Register a callback for N+1 detection events. Useful for custom logging or metrics collection. Callbacks are called regardless of mode (even in :ignore mode).
387 388 389 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 387 def on_n_plus_one(&block) NPlusOneDetector.on_n_plus_one(&block) end |
.on_request_complete {|Hash| ... } ⇒ Object
Register a callback for request completion
175 176 177 |
# File 'lib/parse/client/profiling.rb', line 175 def on_request_complete(&block) Middleware::Profiling.on_request_complete(&block) end |
.pluralized_aliases? ⇒ Boolean
Whether automatic pluralized class-name aliases are enabled. Defaults
to true; opt out with Parse.pluralized_aliases = false or
PARSE_PLURALIZED_ALIASES=false. See pluralized_aliases.
914 915 916 |
# File 'lib/parse/stack.rb', line 914 def pluralized_aliases? @pluralized_aliases != false end |
.profiling_enabled ⇒ Boolean
Returns whether profiling is enabled.
152 153 154 |
# File 'lib/parse/client/profiling.rb', line 152 def profiling_enabled Middleware::Profiling.enabled end |
.profiling_enabled=(value) ⇒ Object
Enable or disable request profiling
147 148 149 |
# File 'lib/parse/client/profiling.rb', line 147 def profiling_enabled=(value) Middleware::Profiling.enabled = value end |
.profiling_statistics ⇒ Hash
Get profiling statistics
169 170 171 |
# File 'lib/parse/client/profiling.rb', line 169 def profiling_statistics Middleware::Profiling.statistics end |
.reachable?(conn = :default) ⇒ Boolean
Check that the Parse Server is reachable via the health endpoint.
This is a no-credentials liveness probe — it does NOT validate the
application_id or REST key. A server with a mistyped app_id still returns
true here; use connected? when you also need to validate credentials.
205 206 207 208 209 |
# File 'lib/parse/client.rb', line 205 def self.reachable?(conn = :default) client(conn).reachable? rescue StandardError false end |
.recent_profiles ⇒ Array<Hash>
Get recent profile data
158 159 160 |
# File 'lib/parse/client/profiling.rb', line 158 def recent_profiles Middleware::Profiling.profiles end |
.registered_classes ⇒ Array
Returns an array of registered Parse::Object subclasses.
54 55 56 |
# File 'lib/parse/model/object.rb', line 54 def self.registered_classes Parse::Object.descendants.map(&:parse_class).uniq end |
.reset_n_plus_one_tracking! ⇒ Object
Reset N+1 detection tracking
397 398 399 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 397 def reset_n_plus_one_tracking! NPlusOneDetector.reset! end |
.schema(className) ⇒ Hash
Fetch the schema for a specific collection name.
67 68 69 |
# File 'lib/parse/model/object.rb', line 67 def self.schema(className) client.schema(className).result end |
.schemas ⇒ Array<Hash>
Returns the list of all schemas for this application.
59 60 61 |
# File 'lib/parse/model/object.rb', line 59 def self.schemas client.schemas.results end |
.sdk_cache ⇒ Object
The SDK-owned store for the default client: the response cache, the identity and role planes, and what Parse::Client#clear_cache! clears.
Prefer cache for application keys. This exists so the SDK's own slice is reachable and inspectable, not as a place to put application data.
253 254 255 |
# File 'lib/parse/client.rb', line 253 def self.sdk_cache Parse::Client.client(:default).sdk_cache end |
.server_features ⇒ Hash
The coarse features block advertised by GET /serverInfo, delegated
to the default client. @see Parse::API::Server#server_features
1166 1167 1168 |
# File 'lib/parse/stack.rb', line 1166 def server_features Parse.client.server_features end |
.server_supports?(feature) ⇒ Boolean
Capability probe against the connected Parse Server, delegated to the
default client. Builds on the memoized serverInfo fetch — see
Parse::API::Server#server_supports? for the capability table and the
fail-open-to-modern semantics.
1159 1160 1161 |
# File 'lib/parse/stack.rb', line 1159 def server_supports?(feature) Parse.client.server_supports?(feature) end |
.session_token=(token) ⇒ String?
Imperative ambient-token setter, for cases where you already have a
session token (e.g. read from a fixture, a test setup, a saved
credential) and want to scope subsequent calls without going through
the login endpoint. Set to nil to clear the ambient (does not
revoke server-side; use logout for that).
499 500 501 502 503 504 505 |
# File 'lib/parse/stack.rb', line 499 def self.session_token=(token) resolved = token.respond_to?(:session_token) ? token.session_token : token resolved = resolved.to_s if resolved Fiber[SESSION_TOKEN_STATE_KEY] = (resolved && !resolved.empty?) ? resolved : nil Fiber[CURRENT_USER_STATE_KEY] = nil Fiber[SESSION_TOKEN_STATE_KEY] end |
.set_config(field, value, conn = :default, master_key_only: nil) ⇒ Hash
Set a parameter in the Parse configuration for an application.
138 139 140 141 |
# File 'lib/parse/client.rb', line 138 def self.set_config(field, value, conn = :default, master_key_only: nil) opts = master_key_only.nil? ? {} : { master_key_only: { field.to_s => !!master_key_only } } Parse::Client.client(conn).update_config({ field => value }, **opts) end |
.setup(opts = {}) { ... } ⇒ Client
Helper method that users should call to setup the client stack. A block can be passed in order to do additional client configuration. To connect to a Parse server, you will need a minimum of an application_id, an api_key and a server_url. To connect to the server endpoint, you use the setup method below.
2121 2122 2123 2124 2125 2126 2127 2128 |
# File 'lib/parse/client.rb', line 2121 def self.setup(opts = {}, &block) # Delegate to Parse::Client.setup so repeated Parse.setup calls overwrite # the registered :default client. Going through Parse::Client.new instead # would hit the `@clients[:default] ||= self` guard inside #initialize and # silently keep the first-registered client, while Parse::Client.setup # uses `=` and replaces it. Both entry points must behave identically. Parse::Client.setup(opts, &block) end |
.slow_query_threshold_ms ⇒ Integer?
Current slow-query threshold in milliseconds, or nil when
unconfigured. Resolves the in-process accessor first; falls back
to the PARSE_SLOW_QUERY_THRESHOLD_MS ENV. Non-positive values
are treated as nil (disabled).
842 843 844 845 846 |
# File 'lib/parse/stack.rb', line 842 def slow_query_threshold_ms value = @slow_query_threshold_ms value = ENV["PARSE_SLOW_QUERY_THRESHOLD_MS"].to_i if value.nil? && ENV["PARSE_SLOW_QUERY_THRESHOLD_MS"] value && value > 0 ? value : nil end |
.slow_query_threshold_ms=(value) ⇒ Object
Set the slow-query threshold in milliseconds. When set to a
positive integer, lazily attaches the bundled subscriber to
parse.mongodb.aggregate and parse.mongodb.find so events
exceeding the threshold log a warning to logger. Set
to nil (or any non-positive value) to disable; the subscriber
stays attached but becomes a cheap pass-through.
855 856 857 858 859 |
# File 'lib/parse/stack.rb', line 855 def slow_query_threshold_ms=(value) @slow_query_threshold_ms = value _attach_slow_query_subscriber! value end |
.strict_pointer_shapes? ⇒ Boolean
Check if strict pointer-shape validation is enabled. When true,
impossible shapes (e.g. bare string $in element against a
pointer column whose target class is unknown) raise
Parse::Query::PointerShapeError instead of silently returning
zero rows. See strict_pointer_shapes=.
906 907 908 |
# File 'lib/parse/stack.rb', line 906 def strict_pointer_shapes? @strict_pointer_shapes == true end |
.suppress_server_version_warning? ⇒ Boolean
Check whether the Parse Server version deprecation warning is
silenced. Returns true if either the in-process accessor or the
PARSE_SUPPRESS_SERVER_VERSION_WARNING ENV is set.
833 834 835 |
# File 'lib/parse/stack.rb', line 833 def suppress_server_version_warning? @suppress_server_version_warning == true || ENV["PARSE_SUPPRESS_SERVER_VERSION_WARNING"] == "true" end |
.track_event(name, dimensions: {}, **opts) ⇒ Parse::Response
Send an analytics event to Parse Server's REST /events/<name>
endpoint. Thin shortcut around Parse::API::Analytics#send_analytics so
callers don't have to reach into Parse.client directly.
Dimensions MUST be passed via the dimensions: keyword. Loose
symbol-keyed arguments at the call site would otherwise be
absorbed by **opts under Ruby 3's strict keyword separation,
and the dimensions would never reach Parse Server — the POST
would land with an empty body. Forwarded **opts is reserved
for request-layer kwargs (session_token:, use_master_key:,
etc.).
Parse Server's default analytics adapter is a no-op — events
POSTed to /events are accepted but neither persisted nor
queryable through the SDK. Operators who configure a custom
analyticsAdapter decide what (if anything) to do with the
event and whether to cap dimension count. The legacy parse.com
eight-dimension cap does NOT apply to Parse Server out of the
box. If you need to read events back, persist them to a regular
Parse::Object subclass.
The underlying request is a blocking HTTP POST — wrap in a thread or background job if you don't want it on the request path.
1143 1144 1145 1146 1147 1148 1149 1150 1151 |
# File 'lib/parse/stack.rb', line 1143 def track_event(name, dimensions: {}, **opts) event_name = name.to_s unless event_name.match?(/\A[\w\-\.]+\z/) raise ArgumentError, "Parse.track_event: event name must contain only word characters, " \ "hyphens, or dots (got #{name.inspect})" end Parse.client.send_analytics(event_name, dimensions, **opts) end |
.trigger_job(name, body = {}, **opts) ⇒ Object
Helper method to trigger cloud jobs and get results.
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 |
# File 'lib/parse/client.rb', line 2204 def self.trigger_job(name, body = {}, **opts) conn = opts[:session] || opts[:client] || :default # Extract request options for the API call request_opts = {} request_opts[:session_token] = opts[:session_token] if opts[:session_token] request_opts[:master_key] = opts[:master_key] if opts[:master_key] response = Parse::Client.client(conn).trigger_job(name, body, opts: request_opts) return response if opts[:raw].present? if response.error? Parse::Client._safe_warn("CloudCodeError", response, name: name) return nil end _extract_cloud_result(response) end |
.trigger_job!(name, body = {}, **opts) ⇒ Object
Same as trigger_job but raises Parse::Error::CloudCodeError when the job returns an error instead of silently returning nil. HTTP-level errors (auth, timeouts, throttling, etc.) still raise their specific Error subclasses as the underlying client does.
2230 2231 2232 2233 2234 |
# File 'lib/parse/client.rb', line 2230 def self.trigger_job!(name, body = {}, **opts) response = trigger_job(name, body, **opts.merge(raw: true)) raise Parse::Error::CloudCodeError.new(name, response) if response.error? _extract_cloud_result(response) end |
.trigger_job_with_session(name, body = {}, session_token, **opts) ⇒ Object
Helper method to trigger cloud jobs with a session token. This is a convenience method that ensures proper session token handling.
2243 2244 2245 2246 |
# File 'lib/parse/client.rb', line 2243 def self.trigger_job_with_session(name, body = {}, session_token, **opts) opts[:session_token] = session_token trigger_job(name, body, **opts) end |
.trigger_job_with_session!(name, body = {}, session_token, **opts) ⇒ Object
Same as trigger_job_with_session but raises Parse::Error::CloudCodeError when the job returns an error instead of silently returning nil.
2257 2258 2259 2260 |
# File 'lib/parse/client.rb', line 2257 def self.trigger_job_with_session!(name, body = {}, session_token, **opts) opts[:session_token] = session_token trigger_job!(name, body, **opts) end |
.update_config(params, conn = :default, master_key_only: nil) ⇒ Hash
Set a key value pairs in the Parse configuration for an application.
155 156 157 158 |
# File 'lib/parse/client.rb', line 155 def self.update_config(params, conn = :default, master_key_only: nil) opts = master_key_only.nil? ? {} : { master_key_only: master_key_only } Parse::Client.client(conn).update_config(params, **opts) end |
.use_shortnames! ⇒ Object
Alias shorter names of core Parse class names. Ex, alias Parse::User to User, Parse::Installation to Installation, etc.
83 84 85 |
# File 'lib/parse/model/object.rb', line 83 def self.use_shortnames! require_relative "shortnames" end |
.validate_associations!(classes: nil) ⇒ true
Verify that every association target across the loaded Object
subclasses resolves to a known Parse class. Covers belongs_to and
property … as: pointer targets (via each class's references),
has_many … through: :relation targets (via relations), and the
query- and array-backed has_many targets (via has_many_associations)
— the bucket where an as: typo otherwise stays latent until the
association is first traversed at call time.
This is the deferred companion to the definition-time scalar guard in Parse::Associations::BelongsTo::ClassMethods#belongs_to: at declaration time a forward reference (a target class that is required later) is legal and indistinguishable from a typo, so the cross-class resolution check is run here — after all models are loaded. Intended to run once at boot, in CI, or from a rake task ("during the upgrade").
A target resolves when it is a Parse system class (_User, _Role,
_Installation, _Session, …) or a registered Object subclass
(via Parse::Model.find_class). Note this checks against loaded Ruby
models: if you intentionally point at a server-side class that has no
Ruby model, define a stub model for it or exclude it via classes:.
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 |
# File 'lib/parse/stack.rb', line 1017 def validate_associations!(classes: nil) models = classes || Parse::Object.descendants problems = [] models.each do |klass| next unless klass.respond_to?(:parse_class) if klass.respond_to?(:references) klass.references.each do |field, target| next if _association_target_resolvable?(target) # `references` is keyed by the remote (camelCase) column; report the # declared Ruby accessor so the operator can find the offending line. accessor = (klass.respond_to?(:field_map) && klass.field_map.key(field)) || field problems << "#{klass}##{accessor} -> #{target.inspect} (no such Parse class)" end end if klass.respond_to?(:relations) klass.relations.each do |field, target| next if _association_target_resolvable?(target) problems << "#{klass}##{field} (relation) -> #{target.inspect} (no such Parse class)" end end if klass.respond_to?(:has_many_associations) klass.has_many_associations.each do |accessor, | # `:relation`-storage has_many is mirrored into `relations` and is # already reported above; only the `:query` and `:array` storage # targets (which live nowhere else) need checking here. This is the # branch where a `has_many … as:` typo hides, since a query-backed # has_many resolves its target lazily at call time. next if [:storage] == :relation target = [:target_class] next if target.nil? || _association_target_resolvable?(target) problems << "#{klass}##{accessor} (has_many #{[:storage]}) -> " \ "#{target.inspect} (no such Parse class)" end end end unless problems.empty? raise ArgumentError, "Unresolved Parse association targets:\n " + problems.join("\n ") + "\nRequire/define the target class, or fix the `as:`/`class_name:` name." end true end |
.wait_for(klass, **kwargs, &block) ⇒ Object
188 189 190 |
# File 'lib/parse/console.rb', line 188 def wait_for(klass, **kwargs, &block) Console.wait_for(klass, **kwargs, &block) end |
.warn_on_n_plus_one ⇒ Boolean Also known as: warn_on_n_plus_one?
Check if N+1 detection is enabled.
370 371 372 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 370 def warn_on_n_plus_one NPlusOneDetector.enabled? end |
.warn_on_n_plus_one=(value) ⇒ Object
Enable or disable N+1 query detection. When enabled, warnings are emitted when N+1 patterns are detected. For more control, use #n_plus_one_mode= instead.
364 365 366 |
# File 'lib/parse/query/n_plus_one_detector.rb', line 364 def warn_on_n_plus_one=(value) NPlusOneDetector.enabled = value end |
.watch(klass, **kwargs, &block) ⇒ Object
183 184 185 |
# File 'lib/parse/console.rb', line 183 def watch(klass, **kwargs, &block) Console.watch(klass, **kwargs, &block) end |
.with_cache_tenant(scope) ⇒ Object
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
# File 'lib/parse/stack.rb', line 376 def self.with_cache_tenant(scope) resolved = scope.nil? ? nil : scope.to_s resolved = nil if resolved&.empty? if resolved && !CACHE_TENANT_PATTERN.match?(resolved) raise ArgumentError, "Parse.with_cache_tenant scope must match #{CACHE_TENANT_PATTERN.source} " \ "(got #{scope.inspect}). Colon and other key-segment-delimiter characters " \ "are refused — they would collapse the cache-key namespace boundary." end previous = Fiber[CACHE_TENANT_STATE_KEY] Fiber[CACHE_TENANT_STATE_KEY] = resolved yield ensure Fiber[CACHE_TENANT_STATE_KEY] = previous end |
.with_master_key { ... } ⇒ Object
Inverse of without_master_key: forces the master key back on for the duration of the block, even if a containing without_master_key had suppressed it. Useful for re-entering an admin-only operation inside a session-scoped block. If no master key is configured on the client, this is a no-op — the helper does not synthesise one.
The state is restored on exit and is inherited by Threads and Fibers created inside the block; see "Ambient identity lifetime" on with_session and without_ambient_identity.
127 128 129 130 131 132 133 134 135 136 |
# File 'lib/parse/stack.rb', line 127 def self.with_master_key previous = Fiber[MASTER_KEY_STATE_KEY] previous_innermost = Fiber[INNERMOST_AUTH_BLOCK_KEY] Fiber[MASTER_KEY_STATE_KEY] = :enabled Fiber[INNERMOST_AUTH_BLOCK_KEY] = :master yield ensure Fiber[MASTER_KEY_STATE_KEY] = previous Fiber[INNERMOST_AUTH_BLOCK_KEY] = previous_innermost end |
.with_session(token) { ... } ⇒ Object
Run block with an ambient session token set for the current fiber.
Inside the block, every Parse request that doesn't explicitly pass
session_token: and doesn't explicitly request use_master_key:
true will be sent with this token. Equivalent to threading
session_token: through every call site, but block-scoped.
The token argument may be a String, a User (its
session_token is read), a Session (its session_token is
read), or nil. Passing nil, or a user or session that carries no
token, runs the block ANONYMOUSLY: requests inside it send neither a
session token nor the master key, and a client's bound token is not
used either. This is useful for performing one anonymous call inside an
otherwise session-scoped region. A call inside the block can still opt
out with an explicit session_token: or use_master_key: true.
Fiber-local, not thread-local: concurrent fibers (and threads, since each thread starts with its own root fiber) do not share state. Survives Faraday retries. The token lives for the lifetime of the block, not just the first HTTP attempt.
== Ambient identity lifetime
The ambient identity (this session token, the master-key state set by with_master_key and without_master_key, and the innermost-block marker) follows these rules:
- It lasts for the block on the current fiber. On exit the previous
values are restored, whether the block returns, raises, or is left
with
break/throw. - Threads and Fibers created inside the block inherit it for their whole lifetime. This is Ruby's fiber-storage semantics: a new Thread or Fiber starts with a copy of the creating fiber's storage, and that copy is not cleared when the creating block exits. The inheritance is intended for short-lived work done on behalf of the same user, such as a parallel fetch that is joined before the block returns.
- Long-lived workers and pooled threads (job processors, schedulers,
connection readers, thread pools created lazily on first use) should
not be created inside a session block. When that cannot be arranged,
start the worker body with without_ambient_identity, which runs it
with all three values cleared. Assigning
Fiber[...] = nilon the storage keys is not public API. - A reused request thread (Puma, Sidekiq, a thread pool) does not keep identity between units of work, because each block restores the value it found on entry. A job that runs outside any block sees no ambient token even if the previous job on the same thread ran inside one.
The SDK's LiveQuery background threads (socket reader, reconnect, health ping, event dispatch) start under without_ambient_identity, so LiveQuery callbacks do not run with a session inherited from the code that first opened the connection. LiveQuery authorization comes from the client and subscription configuration.
An explicit session_token: kwarg on any call still wins over the
ambient. An explicit use_master_key: true skips the ambient and
sends the master key (if configured).
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/parse/stack.rb', line 226 def self.with_session(token) resolved = token.respond_to?(:session_token) ? token.session_token : token resolved = resolved.to_s if resolved # Capture BEFORE any raise so the `ensure` always restores the real # previous ambient (never clobbers an enclosing with_session). previous = Fiber[SESSION_TOKEN_STATE_KEY] previous_innermost = Fiber[INNERMOST_AUTH_BLOCK_KEY] # SEC-02: a present-but-blank (empty or whitespace) token is an unusable # credential. The prior behavior stored a whitespace token as the ambient # (only an exactly-empty string was treated as absent), and the request # layer would then drop it and silently send the master key. Reject blank # tokens loudly at the source instead. `nil` still means "no ambient". if resolved.is_a?(String) && resolved.strip.empty? raise ArgumentError, "Parse.with_session was given a blank session token. A present-but-empty " \ "token is refused so the block cannot silently execute with master-key " \ "authority — pass a valid session token, or `nil` for no ambient session." end # `nil` (no token, or a user/session without one) installs the # anonymous sentinel rather than clearing the slot. A cleared slot meant # "no ambient", which the request layer resolves to the master key on a # master-keyed client: the opposite of the documented anonymous block. Fiber[SESSION_TOKEN_STATE_KEY] = resolved.nil? ? ANONYMOUS_SESSION : resolved Fiber[INNERMOST_AUTH_BLOCK_KEY] = :session yield ensure Fiber[SESSION_TOKEN_STATE_KEY] = previous Fiber[INNERMOST_AUTH_BLOCK_KEY] = previous_innermost end |
.without_ambient_identity(keep_restrictions: false) { ... } ⇒ Object
Run block with no ambient identity on the current fiber: the
with_session token, the with_master_key / without_master_key
state, and the innermost-block marker are all cleared, and restored on
exit (including on exception).
Use it at the start of a long-lived worker, so a thread that happens to be created inside a session block does not run every later job as that user (see "Ambient identity lifetime" on with_session).
Cleared means "no ambient", not anonymous: requests inside the block authenticate as the client is configured, which on a client with a master key means the master key. Wrap a unit of work in with_session or without_master_key inside the worker to scope it.
Pass keep_restrictions: true to drop the inherited identity without
gaining authority: when the surrounding code was restricted (inside
with_session, an anonymous session, or without_master_key), the
block runs with no session token and the master key suppressed, as in
without_master_key. Only an unrestricted caller's block runs with no
ambient state. The SDK starts its LiveQuery callback threads this way.
286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
# File 'lib/parse/stack.rb', line 286 def self.without_ambient_identity(keep_restrictions: false) previous_token = Fiber[SESSION_TOKEN_STATE_KEY] previous_master = Fiber[MASTER_KEY_STATE_KEY] previous_innermost = Fiber[INNERMOST_AUTH_BLOCK_KEY] restricted = !previous_token.nil? || previous_master == :disabled Fiber[SESSION_TOKEN_STATE_KEY] = nil Fiber[MASTER_KEY_STATE_KEY] = keep_restrictions && restricted ? :disabled : nil Fiber[INNERMOST_AUTH_BLOCK_KEY] = nil yield ensure Fiber[SESSION_TOKEN_STATE_KEY] = previous_token Fiber[MASTER_KEY_STATE_KEY] = previous_master Fiber[INNERMOST_AUTH_BLOCK_KEY] = previous_innermost end |
.without_master_key { ... } ⇒ Object
Run block with the master key suppressed for every Parse request
originating in the current fiber. Equivalent to setting the
X-Disable-Parse-Master-Key header on each request, but block-scoped
so callers can wrap a unit of work — e.g. running an action "as if
the configured master key were not available" — without threading
the header through every intermediate call.
Survives Faraday retries (the per-request header would be stripped on the first attempt and gone by the retry; the fiber-local state lives for the lifetime of the block).
Mongo-direct reads follow the same rule: an explicit master: true
passed to Parse::MongoDB.aggregate, a Parse::Query direct terminal,
Atlas Search, or vector search runs in the public scope inside the
block (or raises ACLRequired when require_session_token is on), and
the parse.mongodb.aggregate notification payload carries
master_dropped: true. Parse::AtlasSearch.faceted_search refuses to
run inside the block. A LiveQuery admin connection opened inside the
block sends no master key; one that already connected with it stays
elevated, because Parse Server authorizes per connection.
The SDK's own metadata reads keep the master key inside the block: the class schemas and role graph it reads to enforce a scope, index statistics, and the Atlas Search index listing. Those requests are marked individually; the block's state is never lifted while they run.
This is a guard against accidental master-key use, not an isolation
boundary: code inside the block can call with_master_key.
Parse::MongoDB.find, which reads raw documents with no scope, raises
Parse::ACLScope::ACLRequired inside the block, and inside a
with_session block unless a with_master_key block is
nested inside the session block. Parse::MongoDB.indexes
returns index metadata only and stays available. Parse::MongoDB.collection
returns the raw driver collection with no scope and is not refused inside
the block, so code that reads through it directly bypasses the block.
The state is restored on exit and is inherited by Threads and Fibers created inside the block; see "Ambient identity lifetime" on with_session and without_ambient_identity.
107 108 109 110 111 112 113 |
# File 'lib/parse/stack.rb', line 107 def self.without_master_key previous = Fiber[MASTER_KEY_STATE_KEY] Fiber[MASTER_KEY_STATE_KEY] = :disabled yield ensure Fiber[MASTER_KEY_STATE_KEY] = previous end |