Class: Parse::BatchOperation

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/parse/client/batch.rb,
lib/parse/client/batch.rb

Overview

This class provides a standard way to submit, manage and process batch operations for Parse::Objects and associations.

Batch requests are supported implicitly and intelligently through an extension of array. When an array of Parse::Object subclasses is saved, Parse-Stack will batch all possible save operations for the objects in the array that have changed. It will also batch save 50 at a time until all items in the array are saved. Note: Parse does not allow batch saving Parse::User objects.

songs = Songs.first 1000 #first 1000 songs songs.each do |song| # ... modify song ... end

# will batch save 50 items at a time until all are saved. songs.save

The objects do not have to be of the same collection in order to be supported in the batch request.

Defined Under Namespace

Classes: MixedAuthorityError

Constant Summary collapse

DEFAULT_PARALLELISM =

Default number of threads used to dispatch batch segments concurrently. Raise via Parse::BatchOperation.parallelism = N (or pass parallelism: to #submit) for higher throughput on bulk writes; 2 is intentionally conservative to avoid overwhelming smaller Parse Server deployments.

2

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(reqs = nil, transaction: false) ⇒ BatchOperation

Returns a new instance of BatchOperation.

Parameters:

  • reqs (Array<Parse::Request>) (defaults to: nil) —

    an array of requests.

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

    whether to execute as a transaction.



147
148
149
150
151
152
153
154
# File 'lib/parse/client/batch.rb', line 147

def initialize(reqs = nil, transaction: false)
  @requests = []
  @responses = []
  @submitted = false
  @transaction = transaction
  reqs = [reqs] unless reqs.is_a?(Enumerable)
  reqs.each { |r| add(r) } if reqs.is_a?(Enumerable)
end

Class Attribute Details

.parallelism ⇒ Object



98
99
100
# File 'lib/parse/client/batch.rb', line 98

def parallelism
  @parallelism || DEFAULT_PARALLELISM
end

Instance Attribute Details

#requests ⇒ Object

Returns the value of attribute requests.



# File 'lib/parse/client/batch.rb', line 103

#responses ⇒ Object

Returns the value of attribute responses.



# File 'lib/parse/client/batch.rb', line 106

#transaction ⇒ Boolean

Returns whether this batch should be executed as a transaction.

Returns:

  • (Boolean) —

    whether this batch should be executed as a transaction.



111
# File 'lib/parse/client/batch.rb', line 111

attr_accessor :requests, :responses, :transaction

Instance Method Details

#add(req) ⇒ Array<Parse::Request> #add(batch) ⇒ Array<Parse::Request>

Add an additional request to this batch.

A request tagged to a Parse object (see Request#tag) is skipped when the batch already holds an identical request for that same object, so adding an object twice does not send its changes twice. Untagged requests are always kept: two identical raw requests (for example two Increment operations) are two writes and are both sent.

Overloads:



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/parse/client/batch.rb', line 169

def add(req)
  incoming = if req.is_a?(BatchOperation)
      req.requests
    elsif req.respond_to?(:change_requests)
      req.change_requests
    elsif req.is_a?(Array)
      req
    else
      [req]
    end
  incoming.each do |r|
    next unless r.is_a?(Parse::Request)
    next if duplicate_object_request?(r)
    @requests.push(r)
  end
  @requests
end

#as_json(*args) ⇒ Hash

Returns a formatted payload for the batch request.

Returns:

  • (Hash) —

    a formatted payload for the batch request.



200
201
202
203
204
# File 'lib/parse/client/batch.rb', line 200

def as_json(*args)
  payload = { requests: requests }
  payload[:transaction] = true if @transaction
  payload.as_json
end

#change_requests ⇒ Object

This method is for interoperability with Parse::Object instances.

See Also:

  • Object#change_requests


189
190
191
# File 'lib/parse/client/batch.rb', line 189

def change_requests
  @requests
end

#clear! ⇒ Array

Remove all requests in this batch.

Returns:



213
214
215
# File 'lib/parse/client/batch.rb', line 213

def clear!
  @requests.clear
end

#client ⇒ Parse::Client

Returns the client used for requests that were not built for a specific client. In a batch with no client set explicitly, requests built from an object (Object#change_requests, Object#destroy_request) carry their class's client and are sent through it.

Returns:

  • (Parse::Client) —

    the client used for requests that were not built for a specific client. In a batch with no client set explicitly, requests built from an object (Object#change_requests, Object#destroy_request) carry their class's client and are sent through it.



118
119
120
# File 'lib/parse/client/batch.rb', line 118

def client
  @client ||= Parse::Client.client
end

#client=(c) ⇒ Object

Set the client every request in this batch is sent through. An explicitly chosen client wins over the class client a request was built for, as Client#request ignores it for a single request; each request's own session_token: / use_master_key: options and headers still apply.

Parameters:



128
129
130
131
# File 'lib/parse/client/batch.rb', line 128

def client=(c)
  @client = c
  @explicit_client = !c.nil?
end

#count ⇒ Integer

Returns the number of requests in the batch.

Returns:

  • (Integer) —

    the number of requests in the batch.



207
208
209
# File 'lib/parse/client/batch.rb', line 207

def count
  @requests.count
end

#each(&block) ⇒ Array

Returns:



194
195
196
197
# File 'lib/parse/client/batch.rb', line 194

def each(&block)
  return enum_for(:each) unless block_given?
  @requests.each(&block)
end

#error? ⇒ Boolean

Returns true if at least one response in the batch failed.

Returns:

  • (Boolean) —

    true if at least one response in the batch failed.



226
227
228
229
# File 'lib/parse/client/batch.rb', line 226

def error?
  return false if @responses.empty?
  !success?
end

#submit(segment = 50, parallelism: self.class.parallelism) {|request, response| ... } ⇒ Array<Parse::Response> Also known as: save

Submit the batch operation in chunks until they are all complete. In general, Parse limits requests in each batch to 50 and it is possible that a Parse::BatchOperation instance contains more than 50 requests. This method will slice up the array of request and send them based on the segment amount until they have all been submitted.

The returned array always has one response per request, in request order. When a chunk fails as a whole (an HTTP error, or a response that cannot be matched to its requests), every request in that chunk gets a failed response, so a failure never shifts results onto other requests.

A transactional batch (transaction: true) is never split. All of its requests go to Parse Server in one POST /batch with transaction: true, which commits or rolls back as a unit, regardless of segment. Parse Server has no fixed sub-request limit; a server configured with requestComplexity.batchRequestLimit rejects an oversized transaction for non-master callers, and nothing is written.

When a chunk raises (for example a 5xx or a dropped connection), the other chunks are still processed and the block still sees every request, with failed responses for the chunk that raised. The first exception is then re-raised.

Parameters:

  • segment (Integer) (defaults to: 50) —

    the number of requests to send in each batch. Default 50.

  • parallelism (Integer) (defaults to: self.class.parallelism) —

    the number of segments dispatched in parallel. Defaults to Parse::BatchOperation.parallelism (2).

Yield Parameters:

Returns:



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/parse/client/batch.rb', line 259

def submit(segment = 50, parallelism: self.class.parallelism, &block)
  @responses = []
  @submitted = true
  failure = nil
  return @responses if @requests.empty?

  # Parse Server runs every sub-request under the credentials of the one
  # `POST /batch` call, so requests built for different credentials are
  # sent as separate calls, each with its own client and options. This
  # is decided before anything is sent.
  groups = authority_groups(client, batch_defaults, force_client: @explicit_client)

  if @transaction
    if groups.size > 1
      raise MixedAuthorityError,
            "A transaction cannot mix requests built for different credentials " \
            "(#{groups.size} distinct clients or session/master-key options). Parse Server " \
            "runs a batch under one credential, so it cannot honor each request's own. " \
            "Save these objects in separate transactions."
    end
    group = groups.first
    # One request, one transaction. Exceptions propagate unchanged so the
    # caller can roll back its local state.
    result = group[:client].batch_request(self, **group[:opts])
    @responses = align_responses(@requests, result)
  else
    segment = 50 if segment.nil? || segment < 1
    parallelism = 1 if parallelism.nil? || parallelism < 1
    # Each slice holds requests of one authority group, with their
    # positions in the batch, so responses go back in request order.
    slices = groups.flat_map do |g|
      g[:entries].each_slice(segment).map { |entries| [g, entries] }
    end
    outcomes = slices.threaded_map(parallelism) do |slice|
      g, entries = slice
      reqs = entries.map(&:last)
      begin
        chunk = BatchOperation.new
        chunk.requests = reqs
        [entries, align_responses(reqs, g[:client].batch_request(chunk, **g[:opts])), nil]
      rescue StandardError => e
        [entries, Array.new(reqs.size) { exception_response(e) }, e]
      end
    end
    @responses = Array.new(@requests.size)
    outcomes.each do |entries, responses, _error|
      entries.each_with_index { |(index, _req), i| @responses[index] = responses[i] }
    end
    failure = outcomes.map(&:last).compact.first
  end

  @requests.zip(@responses).each(&block) if block_given?
  raise failure if failure
  @responses
end

#success? ⇒ Boolean

Returns true if every response in the batch succeeded. A batch that was submitted with no requests is successful; one that has not been submitted is not.

Returns:

  • (Boolean) —

    true if every response in the batch succeeded. A batch that was submitted with no requests is successful; one that has not been submitted is not.



220
221
222
223
# File 'lib/parse/client/batch.rb', line 220

def success?
  return @submitted == true if @responses.empty?
  @responses.all? { |r| r.respond_to?(:success?) && r.success? }
end