2024-07-30 14:28:39 +02:00
|
|
|
package protocol
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-08-02 12:57:07 +02:00
|
|
|
"log/slog"
|
2024-08-05 18:10:19 +02:00
|
|
|
"net"
|
2024-08-02 12:57:07 +02:00
|
|
|
|
|
|
|
"forge.cadoles.com/cadoles/go-emlid/reach/client/logger"
|
2024-08-05 18:10:19 +02:00
|
|
|
"github.com/pkg/errors"
|
2024-07-30 14:28:39 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type Identifier string
|
|
|
|
|
2024-08-05 18:10:19 +02:00
|
|
|
type DialFunc func(network string, addr string) (net.Conn, error)
|
|
|
|
|
2024-07-30 14:28:39 +02:00
|
|
|
type Protocol interface {
|
|
|
|
Identifier() Identifier
|
|
|
|
Available(ctx context.Context, addr string) (bool, error)
|
|
|
|
Operations(addr string) Operations
|
|
|
|
}
|
2024-08-02 12:57:07 +02:00
|
|
|
|
|
|
|
type ProtocolOptions struct {
|
|
|
|
Logger logger.Logger
|
2024-08-05 18:10:19 +02:00
|
|
|
Dial DialFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
var DefaultDialFunc = func(network, addr string) (net.Conn, error) {
|
|
|
|
conn, err := net.Dial(network, addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return conn, nil
|
2024-08-02 12:57:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type ProtocolFactory func(opts *ProtocolOptions) (Protocol, error)
|
|
|
|
|
|
|
|
type ProtocolOptionFunc func(opts *ProtocolOptions)
|
|
|
|
|
|
|
|
func NewProtocolOptions(funcs ...ProtocolOptionFunc) *ProtocolOptions {
|
|
|
|
opts := &ProtocolOptions{
|
|
|
|
Logger: slog.Default(),
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, fn := range funcs {
|
|
|
|
fn(opts)
|
|
|
|
}
|
|
|
|
|
|
|
|
return opts
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithProtocolLogger(logger logger.Logger) ProtocolOptionFunc {
|
|
|
|
return func(opts *ProtocolOptions) {
|
|
|
|
opts.Logger = logger
|
|
|
|
}
|
|
|
|
}
|
2024-08-05 18:10:19 +02:00
|
|
|
|
|
|
|
func WithProtocolDial(dial DialFunc) ProtocolOptionFunc {
|
|
|
|
return func(opts *ProtocolOptions) {
|
|
|
|
opts.Dial = dial
|
|
|
|
}
|
|
|
|
}
|