Skip to content
7 changes: 7 additions & 0 deletions Parse/Parse/Internal/BFTask+Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@
*/
- (BFTask *)thenCallBackOnMainThreadAsync:(void(^)(id result, NSError *error))block;

/**
Identical to thenCallBackOnMainThreadAsync:, except that the block will not be called
if the cancellation token is cancelled before the block runs on the main thread.
*/
- (BFTask *)thenCallBackOnMainThreadAsync:(void(^)(id result, NSError *error))block
cancellationToken:(BFCancellationToken *)cancellationToken;

/**
Identical to thenCallBackOnMainThreadAsync:, except that the result of a successful
task will be converted to a BOOL using the boolValue method, and that will
Expand Down
32 changes: 23 additions & 9 deletions Parse/Parse/Internal/BFTask+Private.m
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,30 @@ - (BFTask *)continueWithSuccessResult:(id)result {

- (BFTask *)continueWithMainThreadResultBlock:(PFIdResultBlock)resultBlock
executeIfCancelled:(BOOL)executeIfCancelled {
return [self continueWithMainThreadResultBlock:resultBlock
executeIfCancelled:executeIfCancelled
cancellationToken:nil];
}

- (BFTask *)continueWithMainThreadResultBlock:(PFIdResultBlock)resultBlock
executeIfCancelled:(BOOL)executeIfCancelled
cancellationToken:(BFCancellationToken *)cancellationToken {
if (!resultBlock) {
return self;
}
return [self continueWithExecutor:[BFExecutor mainThreadExecutor]
withBlock:^id(BFTask *task) {
BFTaskCompletionSource *tcs = [BFTaskCompletionSource taskCompletionSource];
@try {
if (!self.cancelled || executeIfCancelled) {
resultBlock(self.result, self.error);
block:^id(BFTask *task) {
BFTaskCompletionSource *tcs = [BFTaskCompletionSource taskCompletionSource];
@try {
if (!self.cancelled || executeIfCancelled) {
resultBlock(self.result, self.error);
}
} @finally {
tcs.result = nil;
}
} @finally {
tcs.result = nil;
return tcs.task;
}
return tcs.task;
}];
cancellationToken:cancellationToken];
}

- (BFTask *)continueWithMainThreadBooleanResultBlock:(PFBooleanResultBlock)resultBlock
Expand All @@ -92,6 +101,11 @@ - (BFTask *)thenCallBackOnMainThreadAsync:(void(^)(id result, NSError *error))bl
return [self continueWithMainThreadResultBlock:block executeIfCancelled:NO];
}

- (BFTask *)thenCallBackOnMainThreadAsync:(void(^)(id result, NSError *error))block
cancellationToken:(BFCancellationToken *)cancellationToken {
return [self continueWithMainThreadResultBlock:block executeIfCancelled:NO cancellationToken:cancellationToken];
}

- (BFTask *)thenCallBackOnMainThreadWithBoolValueAsync:(void(^)(BOOL result, NSError *error))block {
if (!block) {
return self;
Expand Down
17 changes: 17 additions & 0 deletions Parse/Parse/Internal/CloudCode/PFCloudCodeController.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#import "PFConstants.h"
#import "PFDataProvider.h"

@class BFCancellationToken;
@class BFTask<__covariant BFGenericType>;

@interface PFCloudCodeController : NSObject
Expand Down Expand Up @@ -46,4 +47,20 @@
withParameters:(NSDictionary *)parameters
sessionToken:(NSString *)sessionToken;

/**
Calls a Cloud Code function and returns the result of its execution.

@param functionName Function name to call.
@param parameters Parameters to pass, or `nil`.
@param sessionToken Session token to use.
@param cancellationToken Cancellation token or `nil`.

@return `BFTask` with the result of the Cloud Function, or a cancelled task if the token is cancelled
before decoding the result starts.
*/
- (BFTask *)callCloudCodeFunctionAsync:(NSString *)functionName
withParameters:(NSDictionary *)parameters
sessionToken:(NSString *)sessionToken
cancellationToken:(BFCancellationToken *)cancellationToken;

@end
27 changes: 24 additions & 3 deletions Parse/Parse/Internal/CloudCode/PFCloudCodeController.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@

#import "PFCloudCodeController.h"

#if __has_include(<Bolts/BFCancellationToken.h>)
#import <Bolts/BFCancellationToken.h>
#else
#import "BFCancellationToken.h"
#endif

#import "BFTask+Private.h"
#import "PFAssert.h"
#import "PFCommandResult.h"
Expand Down Expand Up @@ -44,9 +50,22 @@ + (instancetype)controllerWithDataSource:(id<PFCommandRunnerProvider>)dataSource
- (BFTask *)callCloudCodeFunctionAsync:(NSString *)functionName
withParameters:(NSDictionary *)parameters
sessionToken:(NSString *)sessionToken {
return [self callCloudCodeFunctionAsync:functionName
withParameters:parameters
sessionToken:sessionToken
cancellationToken:nil];
}

- (BFTask *)callCloudCodeFunctionAsync:(NSString *)functionName
withParameters:(NSDictionary *)parameters
sessionToken:(NSString *)sessionToken
cancellationToken:(BFCancellationToken *)cancellationToken {
@weakify(self);
return [[[BFTask taskFromExecutor:[BFExecutor defaultPriorityBackgroundExecutor] withBlock:^id{
@strongify(self);
if (cancellationToken.cancellationRequested) {
return [BFTask cancelledTask];
}
NSError *error;
NSDictionary *encodedParameters = [[PFNoObjectEncoder objectEncoder] encodeObject:parameters error:&error];
PFPreconditionReturnFailedTask(encodedParameters, error);
Expand All @@ -55,12 +74,14 @@ - (BFTask *)callCloudCodeFunctionAsync:(NSString *)functionName
sessionToken:sessionToken
error:&error];
PFPreconditionReturnFailedTask(command, error);
return [self.dataSource.commandRunner runCommandAsync:command withOptions:PFCommandRunningOptionRetryIfFailed];
return [self.dataSource.commandRunner runCommandAsync:command
withOptions:PFCommandRunningOptionRetryIfFailed
cancellationToken:cancellationToken];
}] continueWithSuccessBlock:^id(BFTask *task) {
return ((PFCommandResult *)(task.result)).result[@"result"];
}] continueWithSuccessBlock:^id(BFTask *task) {
} cancellationToken:cancellationToken] continueWithSuccessBlock:^id(BFTask *task) {
return [[PFDecoder objectDecoder] decodeObject:task.result];
}];
} cancellationToken:cancellationToken];
}

@end
46 changes: 46 additions & 0 deletions Parse/Parse/Source/PFCloud.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ NS_ASSUME_NONNULL_BEGIN

/**
The `PFCloud` class provides methods for interacting with Parse Cloud Functions.

To be able to cancel calls, create an instance of `PFCloud`, make the calls with its instance methods,
and cancel them with `cancel`.
*/
@interface PFCloud : NSObject

Expand Down Expand Up @@ -48,6 +51,49 @@ NS_ASSUME_NONNULL_BEGIN
withParameters:(nullable NSDictionary *)parameters
block:(nullable PFIdResultBlock)block;

/**
Calls the given cloud function *asynchronously* with the parameters provided, in a call that `cancel` can cancel.

If the call is cancelled before it completes, the task is cancelled shortly afterwards, without waiting for
the request to end; a cancelled task has no result and no error. A call that completes at the same time
as it is cancelled may still have a result or error.

@warning Cancelling only affects the client. If the request has already reached the server,
the cloud function keeps running there and its changes are not rolled back.

@param function The function name to call.
@param parameters The parameters to send to the function.

@return The task, that encapsulates the work being done.
*/
- (BFTask<id> *)callFunctionInBackground:(NSString *)function
withParameters:(nullable NSDictionary *)parameters;

/**
Calls the given cloud function *asynchronously* with the parameters provided, in a call that `cancel` can cancel,
and executes the given block when it is done, unless the call is cancelled.

Cancelling on the main thread, where the block is called, ensures that the block isn't called after `cancel` returns.
Cancelling on another thread doesn't ensure this: if the main thread is already about to call the block,
it calls the block even after `cancel` has returned.

@warning Cancelling only affects the client. If the request has already reached the server,
the cloud function keeps running there and its changes are not rolled back.

@param function The function name to call.
@param parameters The parameters to send to the function.
@param block The block to execute when the function call finished.
It should have the following argument signature: `^(id result, NSError *error)`.
*/
- (void)callFunctionInBackground:(NSString *)function
withParameters:(nullable NSDictionary *)parameters
block:(nullable PFIdResultBlock)block;

/**
Cancels the calls made with this instance that haven't completed yet. Calls made afterwards are not affected.
*/
- (void)cancel;

@end

NS_ASSUME_NONNULL_END
108 changes: 107 additions & 1 deletion Parse/Parse/Source/PFCloud.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,38 @@

#import "PFCloud.h"

#if __has_include(<Bolts/BFCancellationTokenSource.h>)
#import <Bolts/BFCancellationTokenSource.h>
#import <Bolts/BFTaskCompletionSource.h>
#else
#import "BFCancellationTokenSource.h"
#import "BFTaskCompletionSource.h"
#endif

#import "BFTask+Private.h"
#import "PFCloudCodeController.h"
#import "PFCommandResult.h"
#import "PFCoreManager.h"
#import "PFMacros.h"
#import "PFUserPrivate.h"
#import "Parse_Private.h"

@implementation PFCloud
@implementation PFCloud {
NSMutableSet<BFCancellationTokenSource *> *_callCancellationTokenSources;
}

///--------------------------------------
#pragma mark - Init
///--------------------------------------

- (instancetype)init {
self = [super init];
if (!self) return nil;

_callCancellationTokenSources = [NSMutableSet set];

return self;
}

///--------------------------------------
#pragma mark - Public
Expand All @@ -38,6 +62,88 @@ + (void)callFunctionInBackground:(NSString *)function
[[self callFunctionInBackground:function withParameters:parameters] thenCallBackOnMainThreadAsync:block];
}

- (BFTask *)callFunctionInBackground:(NSString *)function withParameters:(NSDictionary *)parameters {
return [self _callFunctionInBackground:function withParameters:parameters block:nil];
}

- (void)callFunctionInBackground:(NSString *)function
withParameters:(NSDictionary *)parameters
block:(PFIdResultBlock)block {
[self _callFunctionInBackground:function withParameters:parameters block:block];
}

- (void)cancel {
@synchronized(self) {
NSArray<BFCancellationTokenSource *> *callCancellationTokenSources = _callCancellationTokenSources.allObjects;
[_callCancellationTokenSources removeAllObjects];
// Cancelled while holding the lock, so that a concurrent cancel only returns once all calls are cancelled
[callCancellationTokenSources makeObjectsPerformSelector:@selector(cancel)];
}
}

///--------------------------------------
#pragma mark - Private
///--------------------------------------

/**
Calls the function with a cancellation token of its own, which `cancel` cancels until the call has completed,
and with a block, until the block has been called.

@return The task of the call, which is cancelled without waiting for the request if the call is cancelled
before it completes.
*/
- (BFTask *)_callFunctionInBackground:(NSString *)function
withParameters:(NSDictionary *)parameters
block:(PFIdResultBlock)block {
BFCancellationTokenSource *cancellationTokenSource = [BFCancellationTokenSource cancellationTokenSource];
BFCancellationToken *cancellationToken = cancellationTokenSource.token;
BFTaskCompletionSource *taskCompletionSource = [BFTaskCompletionSource taskCompletionSource];
__weak BFTaskCompletionSource *weakTaskCompletionSource = taskCompletionSource;
[cancellationToken registerCancellationObserverWithBlock:^{
// Not on the cancelling thread, where continuations of the task could block it or deadlock
BFTaskCompletionSource *strongTaskCompletionSource = weakTaskCompletionSource;
[[BFExecutor defaultPriorityBackgroundExecutor] execute:^{
[strongTaskCompletionSource trySetCancelled];
}];
}];
@synchronized(self) {
[_callCancellationTokenSources addObject:cancellationTokenSource];
}

[[[PFUser _getCurrentUserSessionTokenAsync] continueWithBlock:^id(BFTask *task) {
NSString *sessionToken = task.result;
PFCloudCodeController *controller = [Parse _currentManager].coreManager.cloudCodeController;
return [controller callCloudCodeFunctionAsync:function
withParameters:parameters
sessionToken:sessionToken
cancellationToken:cancellationToken];
} cancellationToken:cancellationToken] continueWithBlock:^id(BFTask *task) {
if (task.cancelled) {
[taskCompletionSource trySetCancelled];
} else if (task.faulted) {
[taskCompletionSource trySetError:task.error];
} else {
[taskCompletionSource trySetResult:task.result];
}
return nil;
}];

// The call stays cancellable until the block is called, so that cancelling also stops a queued block
@weakify(self);
[[taskCompletionSource.task thenCallBackOnMainThreadAsync:block
cancellationToken:cancellationToken] continueWithBlock:^id(BFTask *task) {
@strongify(self);
if (!self) {
return nil;
}
@synchronized(self) {
[self->_callCancellationTokenSources removeObject:cancellationTokenSource];
}
return nil;
}];
return taskCompletionSource.task;
}

@end

///--------------------------------------
Expand Down
Loading
Loading