Verify cancellation and failure handling
Verify cancellation and failure handling
Cancellation is a signal to stop unnecessary work, not an automatic undo of effects. Pass the request context to the core and repository. Check cancellation before starting and before committing when possible. A commit can race with cancellation: if the store has already accepted the result, the client may lose the response but the stored result remains. The client should retry with the same ID and exact text to discover the outcome. Never promise that a canceled request implies no mutation.
package main
import ( "context" "errors" "fmt" "strings")
func process(ctx context.Context, s string) (int, error) { if err := ctx.Err(); err != nil { return 0, err } return len(strings.Fields(s)), nil}func main() { ctx, cancel := context.WithCancel(context.Background()) cancel() _, err := process(ctx, "Go now") fmt.Println(errors.Is(err, context.Canceled)) n, err := process(context.Background(), "Go now") fmt.Println(n, err == nil)}The pure bounded calculation is small, so a pre-check is sufficient for this illustration. Long computations need periodic cooperative checks. Cancellation cannot forcibly stop arbitrary Go code. A storage driver must honor context according to its own guarantees; blocking on sync.Mutex itself is not context-aware. The companion memory store checks again after locking, then performs a short critical section.
Expected output:
true2 trueUse a gate to test cancellation without timing guesses
package main
import ( "context" "errors" "fmt")
func work(ctx context.Context, entered chan<- struct{}, done chan<- error) { close(entered) <-ctx.Done() done <- ctx.Err()}func main() { ctx, cancel := context.WithCancel(context.Background()) entered := make(chan struct{}) done := make(chan error, 1) go work(ctx, entered, done) <-entered cancel() fmt.Println(errors.Is(<-done, context.Canceled))}The entered channel proves the worker reached the intended point. The done channel proves it returned. In tests use a bounded watchdog for failures so a broken implementation cannot hang the entire suite. Avoid a fixed sleep as proof that a goroutine has started. Test the lost-response scenario by committing once and replaying the same ID. Test capacity release after repository errors as well as successful requests.
Expected output:
trueTry it locally
Implement a context-aware wait for a result channel. Verify a ready result with an active context and a canceled context with no result. Do not require select to prioritize cancellation when both are ready.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Capstone engineering 05: Verify cancellation and failure handling
Check the lesson objective before moving on.
A client disconnects immediately after a commit. What is true?
What proves a test worker reached a blocking point?