summaryrefslogtreecommitdiffstats
path: root/pkg/com/com.go
blob: 9e0a69831ad973546a64f55d4eacaa6dd6b50c85 (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com

import (
	"context"
	"github.com/icinga/icingadb/pkg/contracts"
	"golang.org/x/sync/errgroup"
)

// WaitAsync calls Wait() on the passed Waiter in a new goroutine and
// sends the first non-nil error (if any) to the returned channel.
// The returned channel is always closed when the Waiter is done.
func WaitAsync(w contracts.Waiter) <-chan error {
	errs := make(chan error, 1)

	go func() {
		defer close(errs)

		if e := w.Wait(); e != nil {
			errs <- e
		}
	}()

	return errs
}

// ErrgroupReceive adds a goroutine to the specified group that
// returns the first non-nil error (if any) from the specified channel.
// If the channel is closed, it will return nil.
func ErrgroupReceive(g *errgroup.Group, err <-chan error) {
	g.Go(func() error {
		if e := <-err; e != nil {
			return e
		}

		return nil
	})
}

// CopyFirst asynchronously forwards all items from input to forward and synchronously returns the first item.
func CopyFirst(
	ctx context.Context, input <-chan contracts.Entity,
) (first contracts.Entity, forward <-chan contracts.Entity, err error) {
	var ok bool
	select {
	case <-ctx.Done():
		return nil, nil, ctx.Err()
	case first, ok = <-input:
	}

	if !ok {
		return
	}

	// Buffer of one because we receive an entity and send it back immediately.
	fwd := make(chan contracts.Entity, 1)
	fwd <- first

	forward = fwd

	go func() {
		defer close(fwd)

		for {
			select {
			case <-ctx.Done():
				return
			case e, ok := <-input:
				if !ok {
					return
				}

				select {
				case <-ctx.Done():
					return
				case fwd <- e:
				}
			}
		}
	}()

	return
}