Class: Parse::Cursor

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/parse/query/cursor.rb

Overview

A cursor-based pagination iterator for efficiently traversing large datasets.

Unlike skip/offset pagination which becomes increasingly slow for large datasets, cursor-based pagination uses the last seen objectId to efficiently fetch the next page. This approach maintains consistent performance regardless of how deep into the dataset you paginate.

Examples:

Basic usage with each_page

cursor = Song.cursor(limit: 100, order: :created_at.desc)
cursor.each_page do |page|
  process(page)
end

Using each to iterate over individual items

Song.cursor(limit: 50).each do |song|
  puts song.title
end

With constraints

cursor = Song.cursor(artist: "Artist Name", limit: 25)
cursor.each_page { |page| process(page) }

Manual pagination control

cursor = User.cursor(limit: 100)
first_page = cursor.next_page
second_page = cursor.next_page
cursor.reset! # Start over from the beginning

Constant Summary collapse

MAX_PAGE_SIZE =

Maximum page size allowed (Parse Server limit)

1000
DEFAULT_PAGE_SIZE =

Default page size

100
MAX_JSON_NESTING =

Maximum JSON nesting accepted when parsing a serialized cursor.

20
SIGNED_VERSION =

Envelope version for signed cursor tokens.

2
MIN_SECRET_BYTES =

Shortest signing secret accepted, in bytes (the HMAC-SHA256 block recommendation for a random key is at least 32 bytes).

32

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query, limit: DEFAULT_PAGE_SIZE, order: nil) ⇒ Cursor

Create a new cursor-based paginator.

Parameters:

  • query (Parse::Query) —

    the base query to paginate

  • limit (Integer) (defaults to: DEFAULT_PAGE_SIZE) —

    the number of items per page (default: 100, max: 1000)

  • order (Parse::Order, Symbol) (defaults to: nil) —

    the ordering for pagination. Defaults to :created_at.asc for stable ordering. Note: cursor pagination requires a stable sort order.

Raises:

  • (ArgumentError) —

    if limit exceeds MAX_PAGE_SIZE



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/parse/query/cursor.rb', line 71

def initialize(query, limit: DEFAULT_PAGE_SIZE, order: nil)
  @query = query.dup
  @page_size = validate_page_size(limit)
  @position = nil
  @pages_fetched = 0
  @items_fetched = 0
  @exhausted = false

  # Set up ordering - cursor pagination needs a stable order
  setup_ordering(order)
end

Class Attribute Details

.signing_secret ⇒ String?

Secret used to HMAC-sign serialized cursors. When set, #serialize emits a signed token and deserialize refuses any token without a valid signature. A per-call secret: argument overrides it. The secret must be a String of at least MIN_SECRET_BYTES bytes; anything else raises ArgumentError, since a blank or short key is guessable and would make signed tokens forgeable.

The length check cannot tell a random key from a long guessable one. Generate the secret from a cryptographic random source, store it with your other application secrets, and keep it out of source control:

ruby -rsecurerandom -e 'puts SecureRandom.hex(32)' # 32 random bytes, 64 hex characters

Parse::Cursor.signing_secret = ENV.fetch("PARSE_CURSOR_SECRET")

Rotating the secret invalidates every token signed with the old one.

Returns:



224
225
226
# File 'lib/parse/query/cursor.rb', line 224

def signing_secret
  @signing_secret
end

Instance Attribute Details

#items_fetched ⇒ Integer (readonly)

Returns the total number of items fetched so far.

Returns:

  • (Integer) —

    the total number of items fetched so far



55
56
57
# File 'lib/parse/query/cursor.rb', line 55

def items_fetched
  @items_fetched
end

#order_direction ⇒ Symbol (readonly)

Returns the order direction (:asc or :desc).

Returns:

  • (Symbol) —

    the order direction (:asc or :desc)



61
62
63
# File 'lib/parse/query/cursor.rb', line 61

def order_direction
  @order_direction
end

#order_field ⇒ Symbol (readonly)

Returns the field to order by for cursor positioning.

Returns:

  • (Symbol) —

    the field to order by for cursor positioning



58
59
60
# File 'lib/parse/query/cursor.rb', line 58

def order_field
  @order_field
end

#page_size ⇒ Integer (readonly)

Returns the number of items per page.

Returns:

  • (Integer) —

    the number of items per page



46
47
48
# File 'lib/parse/query/cursor.rb', line 46

def page_size
  @page_size
end

#pages_fetched ⇒ Integer (readonly)

Returns the number of pages fetched so far.

Returns:

  • (Integer) —

    the number of pages fetched so far



52
53
54
# File 'lib/parse/query/cursor.rb', line 52

def pages_fetched
  @pages_fetched
end

#position ⇒ String? (readonly)

Returns the current cursor position (objectId of last item).

Returns:

  • (String, nil) —

    the current cursor position (objectId of last item)



49
50
51
# File 'lib/parse/query/cursor.rb', line 49

def position
  @position
end

#query ⇒ Parse::Query (readonly)

Returns the base query for this cursor.

Returns:



43
44
45
# File 'lib/parse/query/cursor.rb', line 43

def query
  @query
end

Class Method Details

.deserialize(json_string, secret: signing_secret, expected_class: nil, trusted: false) ⇒ Parse::Cursor

Deserialize a cursor from a previously serialized state.

The state names the class to query and the constraints to apply, so a token from an untrusted source (a client, a URL parameter) can query any class with any constraints unless it is signed. Configure a secret and pass expected_class: before accepting a token from outside the process.

  • With a secret (from secret: or signing_secret), the token must be a signed envelope whose HMAC matches; the comparison is constant-time. Unsigned or tampered tokens raise ArgumentError.
  • Without a secret, an unsigned token is accepted only as trusted persistence: state the process wrote itself and stored where clients cannot change it (a job queue, a server-side table). Pass trusted: true to say so. Without it, an unsigned token is still accepted in this release with a one-time warning; a future minor release will require trusted: true. Never use this mode on client-supplied tokens.

Examples:

Resume a cursor

cursor = Parse::Cursor.deserialize(saved_state, expected_class: Song)
cursor.each_page { |page| process(page) }

Parameters:

  • json_string (String) —

    the serialized cursor state

  • secret (String, nil) (defaults to: signing_secret) —

    signing secret; defaults to signing_secret

  • expected_class (Class, String, nil) (defaults to: nil) —

    refuse tokens for any other Parse class

  • trusted (Boolean) (defaults to: false) —

    the caller asserts an unsigned token came from trusted persistence; ignored when a secret is in effect

Returns:

Raises:

  • (ArgumentError) —

    if the JSON is invalid, missing required fields, fails signature verification, or names a different class



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/parse/query/cursor.rb', line 320

def self.deserialize(json_string, secret: signing_secret, expected_class: nil, trusted: false)
  require "json"
  require "active_support/security_utils"
  raise ArgumentError, "Invalid cursor state: expected a String" unless json_string.is_a?(String)
  secret = validate_secret!(secret) unless secret.nil?

  state = parse_state(json_string)
  signed = state.is_a?(Hash) && state.key?(:sig) && state.key?(:state)

  if signed
    if secret.nil?
      raise ArgumentError, "Signed cursor state requires a signing secret to verify"
    end
    payload = state[:state]
    sig = state[:sig]
    unless payload.is_a?(String) && sig.is_a?(String) &&
           ActiveSupport::SecurityUtils.secure_compare(sign(payload, secret), sig)
      raise ArgumentError, "Invalid cursor state: signature mismatch"
    end
    state = parse_state(payload)
  elsif secret
    raise ArgumentError, "Invalid cursor state: unsigned cursor refused while a signing secret is configured"
  else
    warn_unsigned_once unless trusted
  end

  raise ArgumentError, "Invalid cursor state: expected a JSON object" unless state.is_a?(Hash)

  # Validate required fields
  required = [:class_name, :page_size, :order_field, :order_direction]
  missing = required.select { |f| state[f].nil? }
  unless missing.empty?
    raise ArgumentError, "Invalid cursor state: missing #{missing.join(", ")}"
  end

  if expected_class
    expected_name = expected_class.respond_to?(:parse_class) ? expected_class.parse_class : expected_class.to_s
    unless state[:class_name].to_s == expected_name
      raise ArgumentError, "Cursor state is for class #{state[:class_name].to_s.inspect}, expected #{expected_name.inspect}"
    end
  end

  # Get the model class
  klass = Parse::Model.find_class(state[:class_name])
  unless klass
    raise ArgumentError, "Unknown Parse class: #{state[:class_name]}"
  end

  # Rebuild the query
  query = klass.query(state[:constraints] || {})

  # Create the cursor with the original order
  order = state[:order_direction].to_sym == :desc ?
    state[:order_field].to_s.to_sym.desc :
    state[:order_field].to_s.to_sym.asc

  cursor = new(query, limit: state[:page_size], order: order)

  # Restore state
  cursor.instance_variable_set(:@position, state[:position])
  cursor.instance_variable_set(:@last_order_value, deserialize_value(state[:last_order_value]))
  cursor.instance_variable_set(:@last_object_id, state[:last_object_id])
  cursor.instance_variable_set(:@pages_fetched, state[:pages_fetched] || 0)
  cursor.instance_variable_set(:@items_fetched, state[:items_fetched] || 0)
  cursor.instance_variable_set(:@exhausted, state[:exhausted] || false)

  cursor
end

.deserialize_value(value) ⇒ Object

Deserialize a value from JSON storage



455
456
457
458
459
460
# File 'lib/parse/query/cursor.rb', line 455

def self.deserialize_value(value)
  return value unless value.is_a?(Hash)
  type = value["__type"] || value[:__type]
  return value unless type == "Date"
  DateTime.parse(value["iso"] || value[:iso])
end

.from_json(json_string, **kwargs) ⇒ Parse::Cursor

Alias for deserialize

Parameters:

  • json_string (String) —

    the serialized cursor state

  • kwargs (Hash) —

    secret:, expected_class:, and trusted:, as for deserialize

Returns:



393
394
395
# File 'lib/parse/query/cursor.rb', line 393

def self.from_json(json_string, **kwargs)
  deserialize(json_string, **kwargs)
end

Instance Method Details

#all ⇒ Array<Parse::Object>

Fetch all results at once. Use with caution on large datasets.

Returns:



180
181
182
183
184
# File 'lib/parse/query/cursor.rb', line 180

def all
  results = []
  each_page { |page| results.concat(page) }
  results
end

#each {|Parse::Object| ... } ⇒ self

Iterate over each individual item. This is provided for Enumerable compatibility.

Yields:

Returns:

  • (self)


167
168
169
170
171
172
173
174
175
# File 'lib/parse/query/cursor.rb', line 167

def each(&block)
  return enum_for(:each) unless block_given?

  each_page do |page|
    page.each(&block)
  end

  self
end

#each_page {|Array<Parse::Object>| ... } ⇒ self

Iterate over each page of results.

Yields:

Returns:

  • (self)


151
152
153
154
155
156
157
158
159
160
161
# File 'lib/parse/query/cursor.rb', line 151

def each_page
  return enum_for(:each_page) unless block_given?

  while more_pages?
    page = next_page
    break if page.empty?
    yield page
  end

  self
end

#exhausted? ⇒ Boolean

Check if the cursor has been exhausted (no more results).

Returns:

  • (Boolean) —

    true if all results have been fetched



108
109
110
# File 'lib/parse/query/cursor.rb', line 108

def exhausted?
  @exhausted
end

#more_pages? ⇒ Boolean

Check if more pages are available.

Returns:

  • (Boolean) —

    true if more pages may be available



102
103
104
# File 'lib/parse/query/cursor.rb', line 102

def more_pages?
  !@exhausted
end

#next_page ⇒ Array<Parse::Object>, Array

Fetch the next page of results.

Returns:



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/parse/query/cursor.rb', line 115

def next_page
  return [] if @exhausted

  # Build the page query
  page_query = build_page_query

  # Execute the query
  results = page_query.results

  # Update state
  if results.empty? || results.size < @page_size
    @exhausted = true
  end

  unless results.empty?
    @pages_fetched += 1
    @items_fetched += results.size
    @position = extract_cursor_position(results.last)
  end

  results
end

#reset! ⇒ self

Reset the cursor to the beginning.

Returns:

  • (self)


140
141
142
143
144
145
146
# File 'lib/parse/query/cursor.rb', line 140

def reset!
  @position = nil
  @pages_fetched = 0
  @items_fetched = 0
  @exhausted = false
  self
end

#serialize(secret: self.class.signing_secret) ⇒ String

Serialize the cursor state to a JSON string for persistence. Useful for background jobs that may be interrupted and resumed.

The token contains the class name and the full query constraints. Without a secret it is plain JSON that anyone holding it can edit. When a secret is configured (via signing_secret or secret:), the state is wrapped in an envelope with an HMAC-SHA256 signature that deserialize verifies before rebuilding the query.

Examples:

Save cursor state for later

Parse::Cursor.signing_secret = ENV["CURSOR_SECRET"]
cursor = Song.cursor(limit: 100)
cursor.next_page
state = cursor.serialize
# Store state in Redis, database, etc.

Resume in a background job

state = redis.get("cursor:#{job_id}")
cursor = Parse::Cursor.deserialize(state, expected_class: Song)
cursor.each_page { |page| process(page) }

Parameters:

  • secret (String, nil) (defaults to: self.class.signing_secret) —

    signing secret; defaults to signing_secret

Returns:

  • (String) —

    JSON string containing cursor state



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/parse/query/cursor.rb', line 259

def serialize(secret: self.class.signing_secret)
  require "json"
  state = {
    class_name: @query.table,
    constraints: @query.constraints(true),
    page_size: @page_size,
    position: @position,
    last_order_value: serialize_value(@last_order_value),
    last_object_id: @last_object_id,
    pages_fetched: @pages_fetched,
    items_fetched: @items_fetched,
    exhausted: @exhausted,
    order_field: @order_field,
    order_direction: @order_direction,
    version: 1,  # For future compatibility
  }
  payload = JSON.generate(state)
  return payload if secret.nil?

  JSON.generate(v: SIGNED_VERSION, state: payload, sig: self.class.sign(payload, secret))
end

#stats ⇒ Hash

Get current cursor statistics.

Returns:

  • (Hash) —

    statistics about the cursor pagination



188
189
190
191
192
193
194
195
196
197
198
# File 'lib/parse/query/cursor.rb', line 188

def stats
  {
    pages_fetched: @pages_fetched,
    items_fetched: @items_fetched,
    page_size: @page_size,
    exhausted: @exhausted,
    position: @position,
    order_field: @order_field,
    order_direction: @order_direction,
  }
end

#to_json(*_args, secret: self.class.signing_secret) ⇒ String

Alias for serialize

Parameters:

  • secret (String, nil) (defaults to: self.class.signing_secret) —

    signing secret; defaults to signing_secret

Returns:

  • (String) —

    JSON string containing cursor state



284
285
286
# File 'lib/parse/query/cursor.rb', line 284

def to_json(*_args, secret: self.class.signing_secret)
  serialize(secret: secret)
end