/
channel.go
75 lines (66 loc) · 1.84 KB
/
channel.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
/* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) Benedict Schlueter
*/
package channels
import (
"context"
"go.uber.org/zap"
"golang.org/x/crypto/ssh"
)
// Channel is the interface that wraps the Serve and Wait methods.
type Channel interface {
Serve(ctx context.Context)
Wait()
}
// Serve starts the server. It will block until the context is canceled or s.requests is closed.
func (h *Handler) Serve(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
defer func() {
cancel()
h.reqData.wg.Wait()
h.log.Debug("stopped channel serve")
h.serveCloseDone <- struct{}{}
}()
for _, funct := range h.onStartupCallback {
funct(ctx, h.reqData)
}
for {
select {
case <-ctx.Done():
return
case req, ok := <-h.requests:
if !ok {
h.log.Debug("request channel closed")
return
}
// h.log.Debug("received data over request channel", zap.Any("req", req))
if callbackFuncions, ok := h.funcMap[req.Type]; ok {
for _, callbackFuncion := range callbackFuncions {
callbackFuncion(ctx, req, h.reqData)
}
} else {
for _, funct := range h.onDefaultCallback {
funct(ctx, req, h.reqData)
}
}
for _, funct := range h.onEveryReqCallback {
funct(ctx, req, h.reqData)
}
}
}
}
// Wait waits until serve has finished (including all goroutines started by it).
func (h *Handler) Wait() {
<-h.serveCloseDone
}
// Handler handles incoming requests on a Handler.
type Handler struct {
requests <-chan *ssh.Request
log *zap.Logger
serveCloseDone chan struct{}
reqData *callbackData
funcMap map[string][]func(context.Context, *ssh.Request, *callbackData)
onEveryReqCallback []func(context.Context, *ssh.Request, *callbackData)
onDefaultCallback []func(context.Context, *ssh.Request, *callbackData)
onStartupCallback []func(context.Context, *callbackData)
}