Open mk-livepeer opened 4 years ago
Context should flow through your program
A great mental model of using Context is that it should flow through your program. Imagine a river or running water. This generally means that you don’t want to store it somewhere like in a struct. Nor do you want to keep it around any more than strictly needed. Context should be an interface that is passed from function to function down your call stack, augmented as needed.
https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39
There is certainly room for us to improve how we use contexts. For example, perhaps to signal shutdown rather than use ad-hoc channels for certain goroutines.
My general feeling about contexts in golang is that they are a bit slapdash. The "best practice" of not storing the context means anywhere a context is used downstream, it infects function signatures until there are contexts being passed around everywhere. It very much reminds me of the "red vs blue function" analogy - https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/
I suspect we use context.Background
so often because of downstream dependencies that expect a context, but we don't otherwise have a pressing need to cancel anything other than maybe a timer. It might be nice to actually remove their usage where possible (eg, for our code takes a context but otherwise doesn't do anything with it).
If we choose to propagate a single cancellable context everywhere, we would need to take a closer look at how upstream context termination may affect the code in question. I'm concerned that changing all this in one fell swoop is less of a mechanical change than it seems.
There are many calls to
context.Background()
across thego-livepeer
codebase. This is wrong. Instead,ctx := context.Background()
...should be assigned once at the top of the main function, and...should be used to fork the context as necessary.
This covers the
main()
function, but all the others will also need to be modified to take a forked context out of main, rather than creating a newcontext.Background()
A forked context from ctx, or ctx itself should be passed from
main()
to the downstream functions: