aboutsummaryrefslogtreecommitdiff
path: root/pipeln.go
blob: ca130e2794eff4137e2f6f2ac02d4745c33f0ba1 (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
83
84
85
86
87
88
89
90
91
92
93
// SPDX-License-Identifier: CC0-1.0

package pipeln

import (
	"context"
	"net"
	"syscall"
)

// PipeListenerDialer can be used to simulate client-server interaction
// within the same process.
type PipeListenerDialer struct {
	addr  string
	conns chan net.Conn
	done  chan struct{}
	ok    bool
}

var _ net.Listener = &PipeListenerDialer{}

// See net.Listener.Accept for more details.
func (ln *PipeListenerDialer) Accept() (net.Conn, error) {
	select {
	case conn := <-ln.conns:
		return conn, nil
	case <-ln.done:
		return nil, syscall.EINVAL
	}
}

// See net.Listener.Addr for more details.
func (ln *PipeListenerDialer) Addr() net.Addr {
	return addr{ln}
}

// See net.Listener.Close for more details.
func (ln *PipeListenerDialer) Close() error {
	if !ln.ok {
		return syscall.EINVAL
	}
	close(ln.done)
	ln.ok = false
	return nil
}

// See net.Dialer.Dial for more details.
func (ln *PipeListenerDialer) Dial(_, addr string) (net.Conn, error) {
	return ln.DialContext(context.Background(), "", addr)
}

// DialContext is a dummy wrapper around Dial.
func (ln *PipeListenerDialer) DialContext(ctx context.Context, _, addr string) (net.Conn, error) {
	if addr != ln.addr {
		return nil, syscall.EINVAL
	}
	s, c := net.Pipe()
	select {
	case ln.conns <- s:
		return c, nil
	case <-ln.done:
		return nil, syscall.ECONNREFUSED
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}

// DialContextAddr is a dummy wrapper around Dial.
//
// This function can be passed to grpc.WithContextDialer.
func (ln *PipeListenerDialer) DialContextAddr(ctx context.Context, addr string) (net.Conn, error) {
	return ln.DialContext(ctx, "", addr)
}

// New returns a PipeListenerDialer that will only accept connections
// made to the given addr.
func New(addr string) *PipeListenerDialer {
	return &PipeListenerDialer{addr, make(chan net.Conn), make(chan struct{}), true}
}

type addr struct {
	ln *PipeListenerDialer
}

var _ net.Addr = addr{}

func (addr) Network() string {
	return "pipe"
}

func (a addr) String() string {
	return "pipe:" + a.ln.addr
}