/
connector.go
93 lines (77 loc) · 1.93 KB
/
connector.go
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
// Copyright (c) 2019 Timo Savola. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package origin
import (
"context"
"io"
"gate.computer/gate/service"
)
const (
serviceName = "origin"
serviceRevision = "0"
)
const (
DefaultMaxConns = 3
DefaultBufSize = 32768
)
type Config struct {
MaxConns int
BufSize int
}
var DefaultConfig = Config{
MaxConns: DefaultMaxConns,
BufSize: DefaultBufSize,
}
type Connector struct {
inst instance
closed chan struct{}
}
// New Connector instance for serving one (and only one) program instance.
func New(config *Config) *Connector {
var c Config
if config != nil {
c = *config
}
if c.MaxConns <= 0 {
c.MaxConns = DefaultMaxConns
}
if c.BufSize <= 0 {
c.BufSize = DefaultBufSize
}
return &Connector{
inst: makeInstance(c),
closed: make(chan struct{}),
}
}
// Connect allocates a new I/O stream. The returned function is to be used to
// transfer data between a connection and the program instance. If it's
// non-nil, a connection was established.
func (cr *Connector) Connect(ctx context.Context) func(context.Context, io.Reader, io.WriteCloser) error {
return cr.inst.connect(ctx, cr.closed)
}
// Close causes currently blocked and future Connect calls to return nil.
// Established connections will not be closed.
func (cr *Connector) Close() error {
close(cr.closed)
return nil
}
func (cr *Connector) Properties() service.Properties {
return service.Properties{
Service: service.Service{
Name: serviceName,
Revision: serviceRevision,
},
Streams: true,
}
}
func (cr *Connector) Discoverable(context.Context) bool {
return true
}
func (cr *Connector) CreateInstance(ctx context.Context, config service.InstanceConfig, state []byte) (service.Instance, error) {
cr.inst.init(config.Service)
if err := cr.inst.restore(state); err != nil {
return nil, err
}
return &cr.inst, nil
}