~evanj/evanjon.es

evanjon.es/errgroupsrace.generated.go -rw-r--r-- 1.1 KiB
fecbd67cEvan J Feat(*): Redesign. 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main

import (
	"context"
)

type RaceContent struct {
	pctx  context.Context
	funcs []func() (Content, error)
}

func NewRaceContent(ctx context.Context) *RaceContent {
	return &RaceContent{ctx, []func() (Content, error){}}
}

func (r *RaceContent) Go(f func() (Content, error)) {
	r.funcs = append(r.funcs, f)
}

func (_ *RaceContent) call(ctx context.Context, f func() (Content, error), tch chan Content, ech chan error) {
	select {
	case <-ctx.Done():
		return
	default:
		it, err := f()
		if err != nil {
			ech <- err
			return
		}
		tch <- it
	}
}

func (r *RaceContent) Wait() (Content, error) {
	var (
		t           Content
		errCount    = 0
		maxErrCount = len(r.funcs)
		tch         = make(chan Content, maxErrCount)
		ech         = make(chan error, maxErrCount)
		ctx, cancel = context.WithCancel(r.pctx)
	)
	defer cancel()

	for _, f := range r.funcs {
		go r.call(ctx, f, tch, ech)
	}
	r.funcs = []func() (Content, error){}

	for {
		select {
		case <-ctx.Done():
			return t, ctx.Err()
		case it := <-tch:
			return it, nil
		case err := <-ech:
			errCount++
			if errCount >= maxErrCount {
				return t, err
			}
		}
	}
}