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

Possible to lost tokens in refill function #11

Open
taras-zak opened this issue Jan 1, 2022 · 0 comments
Open

Possible to lost tokens in refill function #11

taras-zak opened this issue Jan 1, 2022 · 0 comments

Comments

@taras-zak
Copy link

In case when ctx that passed to Effector canceled by timeout before refill ticker fires - possible lost token. Here is example:

func TestRefill(t *testing.T) {
	const max uint = 1
	const refillDuration = time.Second

	callsCounter := 0
	effector := callsCountFunction(&callsCounter)

	// Any context with cancellation (WithTimeout, etc)
	ctx, cancel := context.WithCancel(context.Background())
	throttle := Throttle(effector, max, max, refillDuration)

	_, err := throttle(ctx)
	if err != nil {
		t.Fatal("unexpected error: ", err)
	}
	if callsCounter != 1 {
		t.Fatal("unexpected callsCounter value: ", callsCounter)
	}
	// Request cancelled by timeout before refillDuration. (If comment this line – test will be success)
	cancel()

	// Waiting token refill . x2 for ensure that token refiled
	time.Sleep(refillDuration * 2)

	ctx, cancel = context.WithCancel(context.Background())
	defer cancel()

	_, err = throttle(ctx)
	if err != nil {
		t.Fatal("unexpected error: ", err)
	}
	if callsCounter != 2 {
		t.Fatal("unexpected callsCounter value: ", callsCounter)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant