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

fn: experimental async API #8234

Closed

Conversation

ProofOfKeags
Copy link
Collaborator

@ProofOfKeags ProofOfKeags commented Nov 28, 2023

Change Description

This is an attempt to give us some better building blocks for controlling threads of execution. It was inspired by this PR review.

This PR is intentionally submitted for review despite being incomplete so that it can seek concept/approach ACKs. If we like it. I'll clean up the docs and go through the itests and change them to use this API.

Steps to Test

Steps for reviewers to follow to test the change.

Pull Request Checklist

Testing

  • Your PR passes all CI checks.
  • Tests covering the positive and negative (error paths) are included.
  • Bug fixes contain tests triggering the bug to prevent regressions.

Code Style and Documentation

📝 Please see our Contribution Guidelines for further guidance.

fn/async.go Outdated
}

func (a *async[A]) Cancel() {
close(a.quit)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This is the main thing I'm concerned about. If we tie the Async action to a larger context then the Cancel function will cancel the whole context. So it's possible that RunAsyncWithCancel is an unsafe API that we don't want to expose.

Copy link
Collaborator

@morehouse morehouse Nov 28, 2023

Choose a reason for hiding this comment

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

With the current API, isn't async.quit always a newly created chan? How exactly would quit get tied to some other chan?

Edit: I see, RunAsyncWithCancel is exposed...

Copy link
Collaborator

Choose a reason for hiding this comment

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

Probably we want two chans -- one to cancel from outside, and one to cancel by calling Cancel.

Copy link
Collaborator Author

@ProofOfKeags ProofOfKeags Nov 28, 2023

Choose a reason for hiding this comment

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

🤔 hmm interesting.

@morehouse
Copy link
Collaborator

Concept ACK. I think this could remove a lot of boilerplate from the codebase.

Copy link
Collaborator

@Crypt-iQ Crypt-iQ left a comment

Choose a reason for hiding this comment

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

Concept ACK. I think replacing call-sites with this will allow us to figure out whether or not this API needs to change. For example, some of the itest code will listen on more than 3 channels, so those call-sites couldn't use this API

fn/async.go Show resolved Hide resolved
fn/async.go Outdated Show resolved Hide resolved
fn/async.go Outdated Show resolved Hide resolved
fn/async.go Outdated
// and make it a cancellable asynchronous call. This can be useful if the
// function in the argument can block indefinitely and the calling context needs
// a way to abandon waiting for it to complete.
func RunAsyncWithCancel[A any](
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think it's worth adding a test for this

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I'll write the test after we come to consensus on the desired API.

Copy link
Collaborator

@ellemouton ellemouton Jan 17, 2024

Choose a reason for hiding this comment

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

I happened to write a test for testing the suggested change in the other comment. maybe it's useful so just gonna paste here

func TestAsync(t *testing.T) {
	// Let test func fail internally.
	tf := newTestFunc()

	async := RunAsync[bool](tf.Run)

	tf.forceError()

	_, err := async.Await()
	require.ErrorContains(t, err, "testFunc error")

	// Let the test func succeed.
	tf = newTestFunc()

	async = RunAsync[bool](tf.Run)

	tf.complete()

	_, err = async.Await()
	require.NoError(t, err)

	// Force the func to exit due to parent context being cancelled.
	tf = newTestFunc()

	ctx := context.Background()
	ctxc, cancel := context.WithCancel(ctx)

	async = RunAsyncWithCancel[bool](ctxc, tf.Run)

	cancel()

	_, err = async.Await()
	require.ErrorContains(t, err, "context canceled")

	// Force the func to exit due to an external Cancel call.
	tf = newTestFunc()

	async = RunAsync[bool](tf.Run)

	async.Cancel()

	_, err = async.Await()
	require.ErrorContains(t, err, "context canceled")
}

func newTestFunc() *testFunc {
	return &testFunc{
		error:   make(chan struct{}),
		succeed: make(chan struct{}),
	}
}

type testFunc struct {
	error   chan struct{}
	succeed chan struct{}
}

func (f *testFunc) Run(ctx context.Context) (bool, error) {
	select {
	// Exit if parent ctx is cancelled.
	case <-ctx.Done():
		return false, ctx.Err()

	case <-f.succeed:
		return true, nil

	case <-f.error:
		return false, fmt.Errorf("testFunc error")
	}
}

func (f *testFunc) complete() {
	close(f.succeed)
}

func (f *testFunc) forceError() {
	close(f.error)
}

fn/async.go Outdated
err: make(chan error),
}
go func() {
res, err := f()
Copy link
Collaborator

Choose a reason for hiding this comment

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

should we allow the function to take in a context.Context so that we can cancel it if Cancel is called?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah I think this is a good consideration. I don't have much experience using context.Context. The trick would be that we would need to make the argument function accept a Option[Context], or maybe add a second API that allows us to thread a function that accepts a context in.

Copy link
Collaborator

@ellemouton ellemouton Jan 17, 2024

Choose a reason for hiding this comment

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

just change the current argument to f func(ctx context.Context) (A, error)?

Copy link
Collaborator

@ellemouton ellemouton Jan 17, 2024

Choose a reason for hiding this comment

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

I think context.Context can do a lot of the work for you here actually. Wdyt of this:

type Async[A any] interface {
	Await() (A, error)
	Cancel()
}

func RunAsyncWithCancel[A any](ctx context.Context,
	f func(ctx context.Context) (A, error)) Async[A] {

	ctxc, cancel := context.WithCancel(ctx)

	a := async[A]{
		ctx:    ctxc,
		res:    make(chan A, 1),
		err:    make(chan error, 1),
		cancel: cancel,
	}

	a.wg.Add(1)
	go func() {
		defer a.wg.Done()

		res, err := f(ctxc)
		if err != nil {
			a.err <- err

			return
		}

		a.res <- res
	}()

	return &a
}

func RunAsync[A any](f func(ctx context.Context) (A, error)) Async[A] {
	return RunAsyncWithCancel(context.Background(), f)
}

func (a *async[A]) Await() (A, error) {
	var aa A
	select {
	case r := <-a.res:
		return r, nil
	case e := <-a.err:
		return aa, e
	case <-a.ctx.Done():
		return aa, a.ctx.Err()
	}
}

func (a *async[A]) Cancel() {
	a.cancel()

	a.wg.Wait()
}

type async[A any] struct {
	ctx    context.Context
	cancel func()
	res    chan A
	err    chan error

	wg sync.WaitGroup
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Seems reasonable to me.

@morehouse
Copy link
Collaborator

Naively, the API looks okay to me. I agree with @Crypt-iQ though, we need to see how this is actually used at call sites to inform our API design.

@ProofOfKeags ProofOfKeags self-assigned this Feb 1, 2024
Copy link
Contributor

coderabbitai bot commented Mar 13, 2024

Important

Review skipped

Auto reviews are limited to specific labels.

Labels to auto review (1)
  • llm-review

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator

@ziggie1984 ziggie1984 left a comment

Choose a reason for hiding this comment

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

Concept Ack would love to see this production. I wonder if we can make fn an external package to use it for other projects like neutrino or btcwallet without introducing circular dependencies etc.

}

go func() {
res, err := f(localCtx)
Copy link
Collaborator

Choose a reason for hiding this comment

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

so the provided function needs to cleanly listen to the Done() channel to actually be abortable ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

If you do not listen on context.Done, then the goroutine will hang on whatever other channel signal it is waiting on to continue. The control flow of the Async itself will remain cancellable via the Cancel function producing an error for the thread that is hanging on Await, but a cancellation of the async action won't necessarily abort the inner thread unless f listens on context.Done

Copy link
Collaborator

Choose a reason for hiding this comment

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

That's the best we can do I guess, and the caller needs to be responsible as well.

if err != nil {
select {
case a.err <- err:
case <-a.ctx.Done():
Copy link
Collaborator

Choose a reason for hiding this comment

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

Not an expert but feels designwise a bit odd to always check for the cancel channel and not summarize the cases.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I'm not sure what you mean here. I made this choice since we don't want to spend effort on sending back over the error channel if we've already been cancelled. I suppose that since the channel is buffered and we only ever send on it once, that this shouldn't ever happen though.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I meant the two select statement could be maybe summarized right. Or even go with the proposal of elle which did not use the Done() channel at all because we know they are buffered and will not hold up the process.

a.wg.Add(1)
	go func() {
		defer a.wg.Done()

		res, err := f(ctxc)
		if err != nil {
			a.err <- err

			return
		}

		a.res <- res
	}()

// function in the argument can block indefinitely and the calling context needs
// a way to abandon waiting for it to complete.
func RunAsyncWithCancel[A any](ctx context.Context,
f func(ctx context.Context) (*A, error)) Async[A] {
Copy link
Collaborator

Choose a reason for hiding this comment

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

why use a pointer as a result ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Great question! I actually would prefer not to! I made this choice because it conforms to many go idioms we already have. We could do just (A, error) and provide the zero value. This of course still allows pointers as you can always let A = *B. I think we can make that change.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Yes I prefer to keep the use of pointer minimal, learnt from you 😅

@ProofOfKeags ProofOfKeags added the incomplete WIP PR, not fully finalized, but light review possible label Aug 15, 2024
@lightninglabs-deploy
Copy link

@Roasbeef: review reminder
@morehouse: review reminder
@ProofOfKeags, remember to re-request review from reviewers when ready

@lightninglabs-deploy
Copy link

Closing due to inactivity

4 similar comments
@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

13 similar comments
@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@lightninglabs-deploy
Copy link

Closing due to inactivity

@ellemouton
Copy link
Collaborator

closing as per bot instructions - feel free to open again once activity continues!

@ellemouton ellemouton closed this Oct 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fn incomplete WIP PR, not fully finalized, but light review possible no-changelog no-itest
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants