open-nomad/nomad/structs/streaming_rpc.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

76 lines
2.0 KiB
Go
Raw Normal View History

// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package structs
import (
"fmt"
"io"
2018-02-01 01:35:21 +00:00
"sync"
)
// StreamingRpcHeader is the first struct serialized after entering the
// streaming RPC mode. The header is used to dispatch to the correct method.
type StreamingRpcHeader struct {
// Method is the name of the method to invoke.
Method string
}
2018-01-21 01:19:55 +00:00
// StreamingRpcAck is used to acknowledge receiving the StreamingRpcHeader and
2018-03-11 18:43:21 +00:00
// routing to the requested handler.
type StreamingRpcAck struct {
2018-02-16 01:08:58 +00:00
// Error is used to return whether an error occurred establishing the
// streaming RPC. This error occurs before entering the RPC handler.
Error string
}
// StreamingRpcHandler defines the handler for a streaming RPC.
2018-01-21 01:19:55 +00:00
type StreamingRpcHandler func(conn io.ReadWriteCloser)
2018-03-11 18:41:13 +00:00
// StreamingRpcRegistry is used to add and retrieve handlers
type StreamingRpcRegistry struct {
registry map[string]StreamingRpcHandler
}
2018-03-11 18:41:13 +00:00
// NewStreamingRpcRegistry creates a new registry. All registrations of
// handlers should be done before retrieving handlers.
2018-03-11 18:41:13 +00:00
func NewStreamingRpcRegistry() *StreamingRpcRegistry {
return &StreamingRpcRegistry{
registry: make(map[string]StreamingRpcHandler),
}
}
// Register registers a new handler for the given method name
2018-03-11 18:41:13 +00:00
func (s *StreamingRpcRegistry) Register(method string, handler StreamingRpcHandler) {
s.registry[method] = handler
}
// GetHandler returns a handler for the given method or an error if it doesn't exist.
2018-03-11 18:41:13 +00:00
func (s *StreamingRpcRegistry) GetHandler(method string) (StreamingRpcHandler, error) {
h, ok := s.registry[method]
if !ok {
return nil, fmt.Errorf("%s: %q", ErrUnknownMethod, method)
}
return h, nil
}
2018-02-01 01:35:21 +00:00
// Bridge is used to just link two connections together and copy traffic
2018-02-13 22:54:27 +00:00
func Bridge(a, b io.ReadWriteCloser) {
2018-02-01 01:35:21 +00:00
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
_, _ = io.Copy(a, b)
2018-02-01 01:35:21 +00:00
a.Close()
b.Close()
}()
go func() {
defer wg.Done()
_, _ = io.Copy(b, a)
2018-02-01 01:35:21 +00:00
a.Close()
b.Close()
}()
wg.Wait()
}