<commit_before>package typhon

import (
	"context"
	"strconv"
	"time"

	"github.com/monzo/terrors"
)

func TimeoutFilter(defaultTimeout time.Duration) Filter {
	return func(req Request, svc Service) Response {
		timeout := defaultTimeout
		if t, err := strconv.Atoi(req.Header.Get("Timeout")); err == nil {
			timeout = time.Duration(t) * time.Millisecond
		}

		req.Context, _ = context.WithTimeout(req.Context, timeout)
		rspChan := make(chan Response, 1)
		go func() {
			rspChan <- svc(req)
		}()

		select {
		case rsp := <-rspChan:
			return rsp
		case <-req.Context.Done():
			return Response{
				Error: terrors.Timeout("", "Request timed out", nil)}
		}
	}
}<commit_msg>Fix a potential goroutine leak in TimeoutFilter<commit_after>package typhon

import (
	"context"
	"strconv"
	"time"

	"github.com/monzo/terrors"
)

// TimeoutFilter returns a Filter which will cancel a Request after the given timeout
func TimeoutFilter(defaultTimeout time.Duration) Filter {
	return func(req Request, svc Service) Response {
		timeout := defaultTimeout
		if t, err := strconv.Atoi(req.Header.Get("Timeout")); err == nil {
			timeout = time.Duration(t) * time.Millisecond
		}

		ctx, cancel := context.WithTimeout(req.Context, timeout)
		req.Context = ctx
		defer cancel()
		rspChan := make(chan Response, 1)
		go func() {
			rspChan <- svc(req)
		}()

		select {
		case rsp := <-rspChan:
			return rsp
		case <-req.Context.Done():
			return Response{
				Error: terrors.Timeout("", "Request timed out", nil)}
		}
	}
}
{'fraction_non_alphanumeric': 0.1361533377395902, 'fraction_numerical': 0.0013218770654329147, 'mean_word_length': 3.761006289308176, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7263663', 'n_tokens_mistral': 578, 'n_tokens_neox': 512, 'n_words': 134}