From 66b568426ce7c6fd965c11f315cf0d2261e4dc8d Mon Sep 17 00:00:00 2001 From: Lewis Date: Mon, 11 May 2026 14:40:29 +0300 Subject: [PATCH] tapc: basic auth on dial, OnConnect handler Lewis: May this revision serve well! --- tapc/simple_indexer.go | 17 ++++++++++++++--- tapc/tap.go | 25 +++++++++++++++++-------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/tapc/simple_indexer.go b/tapc/simple_indexer.go index 27ada71c..977fb23a 100644 --- a/tapc/simple_indexer.go +++ b/tapc/simple_indexer.go @@ -3,11 +3,15 @@ package tapc import "context" type SimpleIndexer struct { - EventHandler func(ctx context.Context, evt Event) error - ErrorHandler func(ctx context.Context, err error) + EventHandler func(ctx context.Context, evt Event) error + ErrorHandler func(ctx context.Context, err error) + ConnectHandler func(ctx context.Context) } -var _ Handler = (*SimpleIndexer)(nil) +var ( + _ Handler = (*SimpleIndexer)(nil) + _ ConnectHandler = (*SimpleIndexer)(nil) +) func (i *SimpleIndexer) OnEvent(ctx context.Context, evt Event) error { if i.EventHandler == nil { @@ -22,3 +26,10 @@ func (i *SimpleIndexer) OnError(ctx context.Context, err error) { } i.ErrorHandler(ctx, err) } + +func (i *SimpleIndexer) OnConnect(ctx context.Context) { + if i.ConnectHandler == nil { + return + } + i.ConnectHandler(ctx) +} diff --git a/tapc/tap.go b/tapc/tap.go index c5be61af..c44ca19b 100644 --- a/tapc/tap.go +++ b/tapc/tap.go @@ -5,6 +5,7 @@ package tapc import ( "bytes" "context" + "encoding/base64" "encoding/json" "fmt" "net/http" @@ -21,6 +22,10 @@ type Handler interface { OnError(ctx context.Context, err error) } +type ConnectHandler interface { + OnConnect(ctx context.Context) +} + type Client struct { Url string AdminPassword string @@ -95,9 +100,8 @@ func (c *Client) Connect(ctx context.Context, handler Handler) error { } u.Path = "/channel" - // TODO: set auth on dial - url := u.String() + basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("admin:"+c.AdminPassword)) var backoff int for { @@ -108,22 +112,27 @@ func (c *Client) Connect(ctx context.Context, handler Handler) error { } header := http.Header{ - "Authorization": []string{""}, + "Authorization": []string{basicAuth}, } conn, res, err := websocket.DefaultDialer.DialContext(ctx, url, header) if err != nil { + if backoff < 12 { + backoff++ + } l.Warn("dialing failed", "url", url, "err", err, "backoff", backoff) - time.Sleep(time.Duration(5+backoff) * time.Second) - backoff++ + time.Sleep(time.Duration(5*backoff) * time.Second) continue } - l.Info("connected to tap service") + backoff = 0 + l.Info("connected to tap service", "subscription_code", res.StatusCode) - l.Info("tap event subscription response", "code", res.StatusCode) + if ch, ok := handler.(ConnectHandler); ok { + ch.OnConnect(ctx) + } if err = c.handleConnection(ctx, conn, handler); err != nil { - l.Warn("tap connection failed", "err", err, "backoff", backoff) + l.Warn("tap connection failed", "err", err) } } } -- 2.51.2