Context | Go
The context package provides functions to derive new Context values from existing ones. These values form a tree: when a Context is canceled, all Contexts derived from it are also canceled.
It's important that you derive your contexts so that cancellations are propagated throughout the call stack for a given request.
What we do is derive a new cancellingCtx from our request which returns us a cancel function. We then schedule that function to be called in 5 milliseconds by using time.AfterFunc. Finally we use this new context in our request by calling request.WithContext.
What have we done here?
context has a method Done() which returns a channel which gets sent a signal when the context is "done" or "cancelled". We want to listen to that signal and call store.Cancel if we get it but we want to ignore it if our Store manages to Fetch before it.
To manage this we run Fetch in a goroutine and it will write the result into a new channel data. We then use select to effectively race to the two asynchronous processes and then we either write a response or Cancel.
propagation#
One of the main points of context is that it is a consistent way of offering cancellation.
Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue. When a Context is canceled, all Contexts derived from it are also canceled.
From the Go Blog: Context again:
At Google, we require that Go programmers pass a Context parameter as the first argument to every function on the call path between incoming and outgoing requests. This allows Go code developed by many different teams to interoperate well. It provides simple control over timeouts and cancelation and ensures that critical values like security credentials transit Go programs properly.
What about context.Value ?#
Michal Å trba and I have a similar opinion.
If you use ctx.Value in my (non-existent) company, you’re fired
Some engineers have advocated passing values through context as it feels convenient.
Convenience is often the cause of bad code.
The problem with context.Values is that it's just an untyped map so you have no type-safety and you have to handle it not actually containing your value. You have to create a coupling of map keys from one module to another and if someone changes something things start breaking.
In short, if a function needs some values, put them as typed parameters rather than trying to fetch them from context.Value. This makes it statically checked and documented for everyone to see.
But...#
On other hand, it can be helpful to include information that is orthogonal to a request in a context, such as a trace id. Potentially this information would not be needed by every function in your call-stack and would make your functional signatures very messy.
Jack Lindamood says Context.Value should inform, not control
The content of context.Value is for maintainers not users. It should never be required input for documented or expected results.
Additional material#
- I really enjoyed reading Context should go away for Go 2 by Michal Å trba. His argument is that having to pass
contexteverywhere is a smell, that it's pointing to a deficiency in the language in respect to cancellation. He says it would better if this was somehow solved at the language level, rather than at a library level. Until that happens, you will needcontextif you want to manage long running processes. - The Go blog further describes the motivation for working with
contextand has some examples