RelayConnect() ensures there will be a connection, and handle connection errors better.

This commit is contained in:
fiatjaf
2022-11-15 07:53:50 -03:00
parent 2b8807d699
commit dd0571229b
2 changed files with 18 additions and 8 deletions

View File

@@ -39,15 +39,16 @@ type Relay struct {
Connection *Connection
subscriptions s.MapOf[string, *Subscription]
Notices chan string
Notices chan string
ConnectionError chan error
statusChans s.MapOf[string, chan Status]
}
func NewRelay(url string) *Relay {
return &Relay{
URL: NormalizeURL(url),
subscriptions: s.MapOf[string, *Subscription]{},
}
func RelayConnect(url string) (*Relay, error) {
r := &Relay{URL: NormalizeURL(url)}
err := r.Connect()
return r, err
}
func (r *Relay) Connect() error {
@@ -60,6 +61,9 @@ func (r *Relay) Connect() error {
return fmt.Errorf("error opening websocket to '%s': %w", r.URL, err)
}
r.Notices = make(chan string)
r.ConnectionError = make(chan error)
conn := NewConnection(socket)
r.Connection = conn
@@ -67,8 +71,10 @@ func (r *Relay) Connect() error {
for {
typ, message, err := conn.socket.ReadMessage()
if err != nil {
continue
r.ConnectionError <- err
break
}
if typ == websocket.PingMessage {
conn.WriteMessage(websocket.PongMessage, nil)
continue

View File

@@ -65,7 +65,11 @@ func (r *RelayPool) Add(url string, policy RelayPoolPolicy) error {
policy = SimplePolicy{Read: true, Write: true}
}
relay := NewRelay(url)
relay, err := RelayConnect(url)
if err != nil {
return err
}
r.Policies.Store(relay.URL, policy)
r.Relays.Store(relay.URL, relay)