Skip to content

Use the context provide to UsageWithContext public function #1837

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

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

GustavoCaso
Copy link

@GustavoCaso GustavoCaso commented Apr 11, 2025

Currently, at work, we use gopsutil. We wanted to use the disk.UsageWithContext to allow setting some timeout when calling the Usage function.

We realized that the function UsageWithContext does not use the ctx provided.

It think would be a good addition to this great package.

That way, the user can do:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

usage, err := UsageWithContext(ctx, "/")
if err != nil {
	log.Fatal(err)
}

Before adding a test or applying this pattern to other functions *WithContext, I wanted to know if we would be okay with having it in the package. If so, I can add tests and extend the pattern to the rest of the *WithContext functions.

Looking forward for your feedback.

@shirou
Copy link
Owner

shirou commented Apr 20, 2025

Thank you for your suggestion.

gopsutil aims to support a wide range of platforms. Some of these platforms use context internally in their implementation, while others do not. For example, disk/disk_aix_nocgo.go makes use of ctx. Because of these differences, we can't write a universal implementation that cancels the context in all cases.

If we were to implement such logic, I believe the best approach would be to define a separate function that handles context cancellation, and then call that function within each platform-specific UsageWithContext function only when necessary. This way, platforms that don't need it can simply omit the call.

@Lomanic
Copy link
Collaborator

Lomanic commented Apr 24, 2025

To be honest, the WithContext() functions were initially introduced because of wmi disastrous performance on windows #469 (comment), I personally wouldn't mind them to be simply removed instead (that would be a breaking change so for a major version bump), they've been a bit of a maintenance annoyance more than anything, duplicating all the API only for a few functions calling wmi on windows, while the number of these slow wmi calls has been greatly reduced over the years.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants