package probeagent import ( "bytes" "compress/gzip" "context" "encoding/json" "errors" "fmt" "io" "math/rand/v2" "net/http" "net/url" "strconv" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire" ) var ( // ErrUnauthorized: the hub rejected the token or the probe name. Fatal. ErrUnauthorized = errors.New("hub rejected the probe credentials (401)") // ErrIncompatible: protocol version mismatch (409). Fatal. ErrIncompatible = errors.New("hub speaks an incompatible protocol version (409)") ) // retryError asks the caller to wait and retry the same request. type retryError struct { after time.Duration code int } func (e *retryError) Error() string { return fmt.Sprintf("hub busy (%d), retry in %s", e.code, e.after) } // rejectError: the hub refused this batch for good (400/413); retrying is pointless. type rejectError struct{ code int } func (e *rejectError) Error() string { return fmt.Sprintf("hub rejected the batch (%d)", e.code) } const gzipOver = 8 << 10 type client struct { base string name string token string hc *http.Client gz *gzip.Writer buf bytes.Buffer raw bytes.Buffer } func newClient(base *url.URL, name, token string, hc *http.Client) *client { if hc == nil { hc = &http.Client{} } return &client{base: base.String(), name: name, token: token, hc: hc} } func (c *client) req(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { r, err := http.NewRequestWithContext(ctx, method, c.base+path, body) if err != nil { return nil, err } r.Header.Set("Authorization", "Bearer "+c.token) r.Header.Set(wire.HeaderProbe, c.name) r.Header.Set("User-Agent", "urutau-probe") return r, nil } func retryAfter(h http.Header) time.Duration { d := 5 * time.Second if v, err := strconv.Atoi(h.Get("Retry-After")); err == nil && v >= 0 { d = time.Duration(v) * time.Second } return min(d, 2*time.Minute) } func statusErr(resp *http.Response) error { switch { case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden: return ErrUnauthorized case resp.StatusCode == http.StatusConflict: return ErrIncompatible case resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusTooManyRequests: return &retryError{retryAfter(resp.Header), resp.StatusCode} } return fmt.Errorf("hub answered %d", resp.StatusCode) } func (c *client) do(r *http.Request, out any, limit int64) (*http.Response, error) { resp, err := c.hc.Do(r) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) return resp, statusErr(resp) } if out != nil { if err := json.NewDecoder(io.LimitReader(resp.Body, limit)).Decode(out); err != nil { return resp, fmt.Errorf("bad hub answer: %w", err) } } return resp, nil } func (c *client) hello(ctx context.Context, h wire.Hello) (*wire.HelloResp, error) { data, _ := json.Marshal(&h) r, err := c.req(ctx, http.MethodPost, wire.PathHello, bytes.NewReader(data)) if err != nil { return nil, err } r.Header.Set("Content-Type", "application/json") var out wire.HelloResp if _, err := c.do(r, &out, 1<<20); err != nil { return nil, err } if out.Offsets == nil { out.Offsets = map[string]wire.Pos{} } return &out, nil } func (c *client) push(ctx context.Context, b wire.Batch) (*wire.PushResp, error) { c.raw.Reset() if err := json.NewEncoder(&c.raw).Encode(&b); err != nil { return nil, err } data := c.raw.Bytes() var body io.Reader = bytes.NewReader(data) gzipped := false if len(data) > gzipOver { c.buf.Reset() if c.gz == nil { c.gz = gzip.NewWriter(&c.buf) } else { c.gz.Reset(&c.buf) } if _, err := c.gz.Write(data); err != nil { return nil, err } if err := c.gz.Close(); err != nil { return nil, err } body = bytes.NewReader(c.buf.Bytes()) gzipped = true } r, err := c.req(ctx, http.MethodPost, wire.PathPush, body) if err != nil { return nil, err } r.Header.Set("Content-Type", "application/json") if gzipped { r.Header.Set("Content-Encoding", "gzip") } var out wire.PushResp resp, err := c.do(r, &out, 1<<20) if err != nil { if resp != nil && (resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusRequestEntityTooLarge) { return nil, &rejectError{resp.StatusCode} } return nil, err } return &out, nil } // commands long-polls; the caller's context bounds the wait. func (c *client) commands(ctx context.Context, after uint64, wait int) (*wire.CmdResp, error) { q := fmt.Sprintf("%s?after=%d&wait=%d", wire.PathCommands, after, wait) r, err := c.req(ctx, http.MethodGet, q, nil) if err != nil { return nil, err } var out wire.CmdResp if _, err := c.do(r, &out, 8<<20); err != nil { return nil, err } return &out, nil } // backoff is the reconnect delay after n consecutive failures (n >= 1): // 1 s doubling up to 60 s, with +-20% jitter. rnd returns [0,1). func backoff(n int, rnd func() float64) time.Duration { if n < 1 { n = 1 } d := time.Second for i := 1; i < n && d < 60*time.Second; i++ { d *= 2 } d = min(d, 60*time.Second) return time.Duration(float64(d) * (0.8 + 0.4*rnd())) } func jitterRnd() float64 { return rand.Float64() }