Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement asynchronous support in ODataJsonLightBatchWriter #2111

Merged

Conversation

gathogojr
Copy link
Contributor

@gathogojr gathogojr commented Jun 21, 2021

Issues

This pull request is in partial fulfilment of issue #2019.

Description

Implement asynchronous support in ODataJsonLightBatchWriter

To prevent a breaking change, I added the following 6 protected virtual asynchronous methods to the public abstract ODataBatchWriter class as asynchronous wrappers over the synchronous methods.

  • WriteStartBatchImplementationAsync
  • WriteEndBatchImplementationAsync
  • WriteStartChangesetImplementationAsync
  • WriteEndChangesetImplementationAsync
  • CreateOperationRequestMessageImplementationAsync
  • CreateOperationResponseMessageImplementationAsync

These virtual asynchronous methods are then invoked from the public asynchronous methods. For example;

public Task WriteStartBatchAsync()
{
    // ...
    return TaskUtils.GetTaskForSynchronousOperation(this.WriteStartBatchImplementation);
}

protected abstract void WriteEndBatchImplementation();

becomes

public Task WriteStartBatchAsync()
{
    // ...
    return this.WriteStartBatchImplementationAsync();
}

protected abstract void WriteEndBatchImplementation();

protected virtual Task WriteStartBatchImplementationAsync()
{
    return TaskUtils.GetTaskForSynchronousOperation(this.WriteStartBatchImplementation);
}

This I believe should guarantee asynchronous methods in the abstract base class will work as before unless overridden in a derived class.
It also allows asynchronous support to be implemented by overriding the protected methods in the derived class(es).

Checklist (Uncheck if it is not completed)

  • Test cases added
  • Build and test with one-click build and test script passed

Additional work necessary

If documentation update is needed, please add "Docs Needed" label to the issue and provide details about the required document change in the issue.

@gathogojr gathogojr force-pushed the feature/odatajsonlightbatchwriter-async branch from c52bf6e to fca52e2 Compare June 24, 2021 08:45
@gathogojr gathogojr added the Ready for review Use this label if a pull request is ready to be reviewed label Jun 24, 2021
@gathogojr gathogojr force-pushed the feature/odatajsonlightbatchwriter-async branch from fca52e2 to c45de75 Compare June 25, 2021 07:26
@gathogojr gathogojr force-pushed the feature/odatajsonlightbatchwriter-async branch from c45de75 to 653a8f7 Compare June 30, 2021 18:57
Copy link
Contributor

@KenitoInc KenitoInc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

// Note that we intentionally go through the public API so that if the Flush fails the writer moves to the Error state.
.FollowOnSuccessWithTask(task => this.FlushAsync());
.FollowOnSuccessWithTask(task => this.FlushAsync())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity, do you know why ContinueWith is not used here instead?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or just using await on the second statement, i.e.

await this.WriteEndBatchImplementationAsync();
await this.FlushAsync();

What else is FollowOnSuccessWithTask doing behind the scenes?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can think of FollowOnSuccessWithTask as a "syntactic" sugar for ContinueWith, although it's a little more than that. We actually use ContinueWith in the method. The method is designed to propagate failures if the antecedent task fails. If WriteEndBatchImplementationAsync throws an ODataException, we propagate that to the caller - not an AggregateException like ContinueWith would do.
The delegate passed to FollowOnSuccessWithTask will not be executed if the antecedent task fails. Specifically in this case, we do not wish to execute FlushAsync if WriteEndBatchImplementationAsync fails.
The method is defined in TaskUtils class just in case you'd like to study the implementation further.

return TaskUtils.GetTaskForSynchronousOperation(() => this.WriteStartChangesetImplementation(changesetId))
.FollowOnSuccessWith(t => this.FinishWriteStartChangeset());
await this.WriteStartChangesetImplementationAsync(changesetId)
.FollowOnSuccessWith(t => this.FinishWriteStartChangeset())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity, what's the difference between FollowOnSuccessWithTask and FollowOnSuccessWith

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there async versions of this.FinishWriteStartChangeSet()?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FollowOnSuccessWithTask supports delegate that return another Task instance while FollowOnSuccessWith doesn't. As an illustration consider the following two usages:

Task.Factory.StartNew(() =>
{
    // Do work
    return new Random().Next(1, 100);
}).FollowOnSuccessWith((antecedentTask) =>
{
    Console.WriteLine("Result: {0}", antecedentTask.Result);
});

// vs.

Task.Factory.StartNew(() =>
{
    // Do work
    // return new Random().Next(1, 100);
}).FollowOnSuccessWithTask((antecedentTask) =>
{
    return Task.Factory.StartNew(() => Console.WriteLine("Result: {0}", antecedentTask.Result));
});

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's no async version of FinishWriteStartChangeSet. The private method currently doesn't do any writing. It's an implementation detail so it'd be easy to introduce an async equivalent if the synchronous version evolved to doing any writing.

{
Debug.Assert(outputStream != null, "outputStream != null");
Debug.Assert(operationListener != null, "operationListener != null");

return new ODataWriteStream(outputStream, operationListener);
return new ODataWriteStream(outputStream, operationListener, synchronous);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you remind me what the synchronous argument does again? I remember it from a previous PR but don't remember what it was used for. I think it was used in the dispose methods, but I'm not quite sure.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reference to #2109, ODataWriteStream previously had no way of telling whether we're writing synchronously or asynchronously. We address that gap by introducing this argument such that when the Dispose method is invoked, either of StreamDisposed or StreamDisposedAsync is called depending on the value passed for the argument.
This approach is necessitated by the fact that we support NET45 and NETSTANDARD1_1 both of which do not support IAsyncDisposable that would make it feasible to use DisposeAsync in asynchronous scenarios.

Comment on lines +393 to +395
await this.FlushAsynchronously()
.FollowOnFaultWith(t => this.SetState(BatchWriterState.Error))
.ConfigureAwait(false);
Copy link
Contributor

@habbes habbes Jul 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does FollowOnFaultWith do? Could this be safely transformed to something like:

try {
    await this.FlushAsynchronously();
} catch {
    this.SetState(BatchWriterState.Error);
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FollowOnFaultWith is designed such that the Action delegate is invoked only when the antecedent task fails (i.e. task is in a Faulted state)

Copy link
Contributor Author

@gathogojr gathogojr Jul 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It could be transformed the way you demonstrated. But instead of littering the code with such try...catch I think it's neater to encapsulate that in a helper method

@gathogojr gathogojr force-pushed the feature/odatajsonlightbatchwriter-async branch from 653a8f7 to 83c24dd Compare July 5, 2021 08:29
@pull-request-quantifier-deprecated

This PR has 935 quantified lines of changes. In general, a change size of upto 200 lines is ideal for the best PR experience!


Quantification details

Label      : Extra Large
Size       : +889 -46
Percentile : 97.83%

Total files changed: 6

Change summary by file extension:
.cs : +889 -46

Change counts above are quantified counts, based on the PullRequestQuantifier customizations.

Why proper sizing of changes matters

Optimal pull request sizes drive a better predictable PR flow as they strike a
balance between between PR complexity and PR review overhead. PRs within the
optimal size (typical small, or medium sized PRs) mean:

  • Fast and predictable releases to production:
    • Optimal size changes are more likely to be reviewed faster with fewer
      iterations.
    • Similarity in low PR complexity drives similar review times.
  • Review quality is likely higher as complexity is lower:
    • Bugs are more likely to be detected.
    • Code inconsistencies are more likely to be detetcted.
  • Knowledge sharing is improved within the participants:
    • Small portions can be assimilated better.
  • Better engineering practices are exercised:
    • Solving big problems by dividing them in well contained, smaller problems.
    • Exercising separation of concerns within the code changes.

What can I do to optimize my changes

  • Use the PullRequestQuantifier to quantify your PR accurately
    • Create a context profile for your repo using the context generator
    • Exclude files that are not necessary to be reviewed or do not increase the review complexity. Example: Autogenerated code, docs, project IDE setting files, binaries, etc. Check out the Excluded section from your prquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in your prquantifier.yaml context profile.
    • Only use the labels that matter to you, see context specification to customize your prquantifier.yaml context profile.
  • Change your engineering behaviors
    • For PRs that fall outside of the desired spectrum, review the details and check if:
      • Your PR could be split in smaller, self-contained PRs instead
      • Your PR only solves one particular issue. (For example, don't refactor and code new features in the same PR).

How to interpret the change counts in git diff output

  • One line was added: +1 -0
  • One line was deleted: +0 -1
  • One line was modified: +1 -1 (git diff doesn't know about modified, it will
    interpret that line like one addition plus one deletion)
  • Change percentiles: Change characteristics (addition, deletion, modification)
    of this PR in relation to all other PRs within the repository.


Was this comment helpful? 👍  :ok_hand:  :thumbsdown: (Email)
Customize PullRequestQuantifier for this repository.

@gathogojr gathogojr merged commit df7b313 into OData:master Jul 5, 2021
@gathogojr gathogojr deleted the feature/odatajsonlightbatchwriter-async branch July 5, 2021 10:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Extra Large Ready for review Use this label if a pull request is ready to be reviewed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants