fix: protocol v1
This commit is contained in:
@ -2,27 +2,39 @@ package protocol
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type Registry struct {
|
||||
protocols map[Identifier]Protocol
|
||||
protocols map[Identifier]ProtocolFactory
|
||||
}
|
||||
|
||||
func (r *Registry) Register(protocol Protocol) {
|
||||
r.protocols[protocol.Identifier()] = protocol
|
||||
func (r *Registry) Register(identifier Identifier, factory ProtocolFactory) {
|
||||
r.protocols[identifier] = factory
|
||||
}
|
||||
|
||||
func (r *Registry) Availables(ctx context.Context, addr string) ([]Protocol, error) {
|
||||
func (r *Registry) Availables(ctx context.Context, addr string, timeout time.Duration, funcs ...ProtocolOptionFunc) ([]Protocol, error) {
|
||||
availables := make([]Protocol, 0)
|
||||
protocolOpts := NewProtocolOptions(funcs...)
|
||||
|
||||
for _, proto := range r.protocols {
|
||||
available, err := proto.Available(ctx, addr)
|
||||
for _, factory := range r.protocols {
|
||||
proto, err := factory(protocolOpts)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
|
||||
available, err := proto.Available(timeoutCtx, addr)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
cancel()
|
||||
|
||||
if !available {
|
||||
continue
|
||||
}
|
||||
@ -35,7 +47,7 @@ func (r *Registry) Availables(ctx context.Context, addr string) ([]Protocol, err
|
||||
|
||||
func NewRegistry() *Registry {
|
||||
return &Registry{
|
||||
protocols: make(map[Identifier]Protocol),
|
||||
protocols: make(map[Identifier]ProtocolFactory),
|
||||
}
|
||||
}
|
||||
|
||||
@ -45,10 +57,10 @@ func DefaultRegistry() *Registry {
|
||||
return defaultRegistry
|
||||
}
|
||||
|
||||
func Register(protocol Protocol) {
|
||||
defaultRegistry.Register(protocol)
|
||||
func Register(identifier Identifier, factory ProtocolFactory) {
|
||||
defaultRegistry.Register(identifier, factory)
|
||||
}
|
||||
|
||||
func Availables(ctx context.Context, addr string) ([]Protocol, error) {
|
||||
return defaultRegistry.Availables(ctx, addr)
|
||||
func Availables(ctx context.Context, addr string, timeout time.Duration) ([]Protocol, error) {
|
||||
return defaultRegistry.Availables(ctx, addr, timeout)
|
||||
}
|
||||
|
Reference in New Issue
Block a user