mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-22 23:16:48 +00:00
websocket/gateio: Support multi connection management and integrate with GateIO (#1580)
* gateio: Add multi asset websocket support WIP. * meow * Add tests and shenanigans * integrate flushing and for enabling/disabling pairs from rpc shenanigans * some changes * linter: fixes strikes again. * Change name ConnectionAssociation -> ConnectionCandidate for better clarity on purpose. Change connections map to point to candidate to track subscriptions for future dynamic connections holder and drop struct ConnectionDetails. * Add subscription tests (state functional) * glorious:nits + proxy handling * Spelling * linter: fixerino * instead of nil, dont do nil. * clean up nils * cya nils * don't need to set URL or check if its running * stop ping handler routine leak * * Fix bug where reader routine on error that is not a disconnection error but websocket frame error or anything really makes the reader routine return and then connection never cycles and the buffer gets filled. * Handle reconnection via an errors.Is check which is simpler and in that scope allow for quick disconnect reconnect without waiting for connection cycle. * Dial now uses code from DialContext but just calls context.Background() * Don't allow reader to return on parse binary response error. Just output error and return a non nil response * Allow rollback on connect on any error across all connections * fix shadow jutsu * glorious/gk: nitters - adds in ws mock server * linter: fix * fix deadlock on connection as the previous channel had no reader and would hang connection reader for eternity. * gk: nits * Leak issue and edge case * gk: nits * gk: drain brain * glorious: nits * Update exchanges/stream/websocket.go Co-authored-by: Scott <gloriousCode@users.noreply.github.com> * glorious: nits * add tests * linter: fix * After merge * Add error connection info * Fix edge case where it does not reconnect made by an already closed connection * stream coverage * glorious: nits * glorious: nits removed asset error handling in stream package * linter: fix * rm block * Add basic readme * fix asset enabled flush cycle for multi connection * spella: fix * linter: fix * Add glorious suggestions, fix some race thing * reinstate name before any routine gets spawned * stop on error in mock tests * glorious: nits * glorious: nits found in CI build * Add test for drain, bumped wait times as there seems to be something happening on macos CI builds, used context.WithTimeout because its instant. * mutex across shutdown and connect for protection * lint: fix * test time withoffset, reinstate stop * fix whoops * const trafficCheckInterval; rm testmain * y * fix lint * bump time check window * stream: fix intermittant test failures while testing routines and remove code that is not needed. * spells * cant do what I did * protect race due to routine. * update testURL * use mock websocket connection instead of test URL's * linter: fix * remove url because its throwing errors on CI builds * connections drop all the time, don't need to worry about not being able to echo back ws data as it can be easily reviewed _test file side. * remove another superfluous url thats not really set up for this * spawn overwatch routine when there is no errors, inline checker instead of waiting for a time period, add sleep inline with echo handler as this is really quick and wanted to ensure that latency is handing correctly * linter: fixerino uperino * glorious: panix * linter: things * whoops * defer lock and use functions that don't require locking in SetProxyAddress * lint: fix * thrasher: nits --------- Co-authored-by: shazbert <ryan.oharareid@thrasher.io> Co-authored-by: Scott <gloriousCode@users.noreply.github.com>
This commit is contained in:
@@ -24,12 +24,19 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// errConnectionFault is a connection fault error which alerts the system that a connection cycle needs to take place.
|
||||
errConnectionFault = errors.New("connection fault")
|
||||
errWebsocketIsDisconnected = errors.New("websocket connection is disconnected")
|
||||
errRateLimitNotFound = errors.New("rate limit definition not found")
|
||||
)
|
||||
|
||||
// Dial sets proxy urls and then connects to the websocket
|
||||
func (w *WebsocketConnection) Dial(dialer *websocket.Dialer, headers http.Header) error {
|
||||
return w.DialContext(context.Background(), dialer, headers)
|
||||
}
|
||||
|
||||
// DialContext sets proxy urls and then connects to the websocket
|
||||
func (w *WebsocketConnection) DialContext(ctx context.Context, dialer *websocket.Dialer, headers http.Header) error {
|
||||
if w.ProxyURL != "" {
|
||||
proxy, err := url.Parse(w.ProxyURL)
|
||||
if err != nil {
|
||||
@@ -40,15 +47,15 @@ func (w *WebsocketConnection) Dial(dialer *websocket.Dialer, headers http.Header
|
||||
|
||||
var err error
|
||||
var conStatus *http.Response
|
||||
|
||||
w.Connection, conStatus, err = dialer.Dial(w.URL, headers)
|
||||
w.Connection, conStatus, err = dialer.DialContext(ctx, w.URL, headers)
|
||||
if err != nil {
|
||||
if conStatus != nil {
|
||||
_ = conStatus.Body.Close()
|
||||
return fmt.Errorf("%s websocket connection: %v %v %v Error: %w", w.ExchangeName, w.URL, conStatus, conStatus.StatusCode, err)
|
||||
}
|
||||
return fmt.Errorf("%s websocket connection: %v Error: %w", w.ExchangeName, w.URL, err)
|
||||
}
|
||||
defer conStatus.Body.Close()
|
||||
_ = conStatus.Body.Close()
|
||||
|
||||
if w.Verbose {
|
||||
log.Infof(log.WebsocketMgr, "%v Websocket connected to %s\n", w.ExchangeName, w.URL)
|
||||
@@ -131,18 +138,18 @@ func (w *WebsocketConnection) SetupPingHandler(epl request.EndpointLimit, handle
|
||||
return
|
||||
}
|
||||
w.Wg.Add(1)
|
||||
defer w.Wg.Done()
|
||||
go func() {
|
||||
defer w.Wg.Done()
|
||||
ticker := time.NewTicker(handler.Delay)
|
||||
for {
|
||||
select {
|
||||
case <-w.ShutdownC:
|
||||
case <-w.shutdown:
|
||||
ticker.Stop()
|
||||
return
|
||||
case <-ticker.C:
|
||||
err := w.SendRawMessage(context.TODO(), epl, handler.MessageType, handler.Message)
|
||||
if err != nil {
|
||||
log.Errorf(log.WebsocketMgr, "%v websocket connection: ping handler failed to send message [%s]", w.ExchangeName, handler.Message)
|
||||
log.Errorf(log.WebsocketMgr, "%v websocket connection: ping handler failed to send message [%s]: %v", w.ExchangeName, handler.Message, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -168,23 +175,24 @@ func (w *WebsocketConnection) IsConnected() bool {
|
||||
func (w *WebsocketConnection) ReadMessage() Response {
|
||||
mType, resp, err := w.Connection.ReadMessage()
|
||||
if err != nil {
|
||||
if IsDisconnectionError(err) {
|
||||
if w.setConnectedStatus(false) {
|
||||
// NOTE: When w.setConnectedStatus() returns true the underlying
|
||||
// state was changed and this infers that the connection was
|
||||
// externally closed and an error is reported else Shutdown()
|
||||
// method on WebsocketConnection type has been called and can
|
||||
// be skipped.
|
||||
select {
|
||||
case w.readMessageErrors <- err:
|
||||
default:
|
||||
// bypass if there is no receiver, as this stops it returning
|
||||
// when shutdown is called.
|
||||
log.Warnf(log.WebsocketMgr,
|
||||
"%s failed to relay error: %v",
|
||||
w.ExchangeName,
|
||||
err)
|
||||
}
|
||||
// If any error occurs, a Response{Raw: nil, Type: 0} is returned, causing the
|
||||
// reader routine to exit. This leaves the connection without an active reader,
|
||||
// leading to potential buffer issue from the ongoing websocket writes.
|
||||
// Such errors are passed to `w.readMessageErrors` when the connection is active.
|
||||
// The `connectionMonitor` handles these errors by flushing the buffer, reconnecting,
|
||||
// and resubscribing to the websocket to restore the connection.
|
||||
if w.setConnectedStatus(false) {
|
||||
// NOTE: When w.setConnectedStatus() returns true the underlying
|
||||
// state was changed and this infers that the connection was
|
||||
// externally closed and an error is reported else Shutdown()
|
||||
// method on WebsocketConnection type has been called and can
|
||||
// be skipped.
|
||||
select {
|
||||
case w.readMessageErrors <- fmt.Errorf("%w: %w", err, errConnectionFault):
|
||||
default:
|
||||
// bypass if there is no receiver, as this stops it returning
|
||||
// when shutdown is called.
|
||||
log.Warnf(log.WebsocketMgr, "%s failed to relay error: %v", w.ExchangeName, err)
|
||||
}
|
||||
}
|
||||
return Response{}
|
||||
@@ -203,7 +211,7 @@ func (w *WebsocketConnection) ReadMessage() Response {
|
||||
standardMessage, err = w.parseBinaryResponse(resp)
|
||||
if err != nil {
|
||||
log.Errorf(log.WebsocketMgr, "%v %v: Parse binary response error: %v", w.ExchangeName, removeURLQueryString(w.URL), err)
|
||||
return Response{}
|
||||
return Response{Raw: []byte(``)} // Non-nil response to avoid the reader returning on this case.
|
||||
}
|
||||
}
|
||||
if w.Verbose {
|
||||
@@ -264,7 +272,9 @@ func (w *WebsocketConnection) Shutdown() error {
|
||||
return nil
|
||||
}
|
||||
w.setConnectedStatus(false)
|
||||
return w.Connection.UnderlyingConn().Close()
|
||||
w.writeControl.Lock()
|
||||
defer w.writeControl.Unlock()
|
||||
return w.Connection.NetConn().Close()
|
||||
}
|
||||
|
||||
// SetURL sets connection URL
|
||||
|
||||
Reference in New Issue
Block a user