-
Notifications
You must be signed in to change notification settings - Fork 607
feat(chproxy): refactor OTEL telemetry #2959
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,19 +1,15 @@ | ||
| FROM golang:1.23-alpine AS builder | ||
|
|
||
| FROM golang:1.24-alpine AS builder | ||
|
|
||
| WORKDIR /go/src/github.com/unkeyed/unkey/apps/chproxy | ||
| COPY go.mod ./ | ||
| # COPY go.sum ./ | ||
| # RUN go mod download | ||
|
|
||
| COPY . . | ||
| RUN go build -o bin/chproxy ./main.go | ||
|
|
||
| RUN go build -o bin/chproxy | ||
|
|
||
| FROM golang:1.23-alpine | ||
| FROM golang:1.24-alpine | ||
| RUN apk add --update curl | ||
|
|
||
| WORKDIR /usr/local/bin | ||
| COPY --from=builder /go/src/github.com/unkeyed/unkey/apps/chproxy/bin/chproxy . | ||
|
|
||
| CMD [ "/usr/local/bin/chproxy"] | ||
| CMD ["/usr/local/bin/chproxy"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
|
|
||
| "go.opentelemetry.io/otel/attribute" | ||
| "go.opentelemetry.io/otel/codes" | ||
| ) | ||
|
|
||
| type Batch struct { | ||
| Rows []string | ||
| Params url.Values | ||
| } | ||
|
|
||
| func persist(ctx context.Context, batch *Batch, config *Config) error { | ||
| ctx, span := telemetry.Tracer.Start(ctx, "persist_batch") | ||
| defer span.End() | ||
|
|
||
| if len(batch.Rows) == 0 { | ||
| return nil | ||
| } | ||
|
|
||
| telemetry.Metrics.BatchCounter.Add(ctx, 1) | ||
| telemetry.Metrics.RowCounter.Add(ctx, int64(len(batch.Rows))) | ||
|
|
||
| span.SetAttributes( | ||
| attribute.Int("rows", len(batch.Rows)), | ||
| attribute.String("query", batch.Params.Get("query")), | ||
| ) | ||
|
|
||
| u, err := url.Parse(config.ClickhouseURL) | ||
| if err != nil { | ||
| telemetry.Metrics.ErrorCounter.Add(ctx, 1) | ||
| span.RecordError(err) | ||
| span.SetStatus(codes.Error, err.Error()) | ||
| return err | ||
| } | ||
|
|
||
| u.RawQuery = batch.Params.Encode() | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, "POST", u.String(), strings.NewReader(strings.Join(batch.Rows, "\n"))) | ||
| if err != nil { | ||
| telemetry.Metrics.ErrorCounter.Add(ctx, 1) | ||
| span.RecordError(err) | ||
| span.SetStatus(codes.Error, err.Error()) | ||
| return err | ||
| } | ||
|
|
||
| req.Header.Add("Content-Type", "text/plain") | ||
|
|
||
| username := u.User.Username() | ||
|
|
||
| password, ok := u.User.Password() | ||
| if !ok { | ||
| err := fmt.Errorf("password not set") | ||
| telemetry.Metrics.ErrorCounter.Add(ctx, 1) | ||
| span.RecordError(err) | ||
| span.SetStatus(codes.Error, err.Error()) | ||
| return err | ||
| } | ||
|
|
||
| req.SetBasicAuth(username, password) | ||
|
|
||
| res, err := httpClient.Do(req) | ||
| if err != nil { | ||
| telemetry.Metrics.ErrorCounter.Add(ctx, 1) | ||
| span.RecordError(err) | ||
| span.SetStatus(codes.Error, err.Error()) | ||
| return err | ||
| } | ||
| defer res.Body.Close() | ||
|
|
||
| if res.StatusCode != http.StatusOK { | ||
| telemetry.Metrics.ErrorCounter.Add(ctx, 1) | ||
| body, err := io.ReadAll(res.Body) | ||
| if err != nil { | ||
| config.Logger.Error("error reading body", | ||
| "error", err) | ||
|
|
||
| span.RecordError(err) | ||
| span.SetStatus(codes.Error, err.Error()) | ||
| return err | ||
| } | ||
|
|
||
| errorMsg := string(body) | ||
|
|
||
| config.Logger.Error("unable to persist batch", | ||
| "response", errorMsg, | ||
| "status_code", res.StatusCode, | ||
| "query", batch.Params.Get("query")) | ||
|
|
||
| span.SetStatus(codes.Error, errorMsg) | ||
| span.RecordError(fmt.Errorf("HTTP %d: %s", res.StatusCode, errorMsg)) | ||
|
|
||
| return fmt.Errorf("http error: %v", errorMsg) | ||
| } | ||
|
|
||
| config.Logger.Info("rows persisted", | ||
| "count", len(batch.Rows), | ||
| "query", batch.Params.Get("query")) | ||
| span.SetStatus(codes.Ok, "") | ||
| span.SetAttributes( | ||
| attribute.String("result", "successfully sent to Clickhouse"), | ||
| attribute.Int("rows_processed", len(batch.Rows)), | ||
| ) | ||
|
|
||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "time" | ||
|
|
||
| "go.opentelemetry.io/otel/attribute" | ||
| "go.opentelemetry.io/otel/metric" | ||
| ) | ||
|
|
||
| // startBufferProcessor manages processing of data sent to Clickhouse. | ||
| // Returns a channel that signals when all pending batches have been processed during shutdown | ||
| func startBufferProcessor( | ||
| ctx context.Context, | ||
| buffer <-chan *Batch, | ||
| config *Config, | ||
| telemetryConfig *TelemetryConfig, | ||
| ) <-chan bool { | ||
| done := make(chan bool) | ||
|
|
||
| go func() { | ||
| buffered := 0 | ||
| batchesByParams := make(map[string]*Batch) | ||
| ticker := time.NewTicker(config.FlushInterval) | ||
| defer ticker.Stop() | ||
|
|
||
| tickerCount := 0 | ||
|
|
||
| flushAndReset := func(ctx context.Context, reason string) { | ||
| ctx, span := telemetryConfig.Tracer.Start(ctx, "flush_batches") | ||
| defer span.End() | ||
|
|
||
| startTime := time.Now() | ||
|
|
||
| // Record metrics | ||
| telemetryConfig.Metrics.FlushCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("reason", reason))) | ||
|
|
||
| span.SetAttributes( | ||
| attribute.Int("batch_count", len(batchesByParams)), | ||
| attribute.Int("buffered_rows", buffered), | ||
| attribute.String("reason", reason), | ||
| ) | ||
|
|
||
| // We'll sample logs for ticker-based flushes | ||
| shouldLog := true | ||
| if reason == "ticker" { | ||
| tickerCount++ | ||
| // Only log every LOG_TICKER_SAMPLE_RATE times | ||
| shouldLog = (tickerCount%LOG_TICKER_SAMPLE_RATE == 0) | ||
| } | ||
|
|
||
| // Only log if we should based on sampling | ||
| if shouldLog { | ||
| config.Logger.Info("flushing batches", | ||
| "reason", reason, | ||
| "batch_count", len(batchesByParams), | ||
| "buffered_rows", buffered) | ||
| } | ||
|
|
||
| for _, batch := range batchesByParams { | ||
| err := persist(ctx, batch, config) | ||
| if err != nil { | ||
| // Always log errors regardless of sampling | ||
| config.Logger.Error("error flushing batch", | ||
| "error", err.Error(), | ||
| "query", batch.Params.Get("query")) | ||
| } | ||
| } | ||
|
|
||
| duration := time.Since(startTime).Seconds() | ||
| telemetryConfig.Metrics.FlushDuration.Record(ctx, duration, | ||
| metric.WithAttributes(attribute.String("reason", reason))) | ||
|
|
||
| span.SetAttributes(attribute.Float64("duration_seconds", duration)) | ||
|
|
||
| buffered = 0 | ||
| SetBufferSize(0) | ||
| batchesByParams = make(map[string]*Batch) | ||
| } | ||
|
|
||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| config.Logger.Info("context cancelled, flushing remaining batches", | ||
| "buffered_rows", buffered, | ||
| "elapsed_time", config.FlushInterval.String()) | ||
| flushAndReset(ctx, "shutdown") | ||
| done <- true | ||
| return | ||
| case b, ok := <-buffer: | ||
| if !ok { | ||
| config.Logger.Info("buffer channel closed, flushing remaining batches") | ||
| flushAndReset(ctx, "shutdown") | ||
| done <- true | ||
| return | ||
| } | ||
|
|
||
| params := b.Params.Encode() | ||
| batch, ok := batchesByParams[params] | ||
| if !ok { | ||
| batchesByParams[params] = b | ||
| config.Logger.Debug("new batch type received", | ||
| "query", b.Params.Get("query")) | ||
| } else { | ||
| batch.Rows = append(batch.Rows, b.Rows...) | ||
| } | ||
|
|
||
| buffered += len(b.Rows) | ||
| SetBufferSize(int64(buffered)) | ||
|
|
||
| if buffered >= config.MaxBatchSize { | ||
| config.Logger.Info("flushing due to max batch size", | ||
| "buffered_rows", buffered, | ||
| "max_size", config.MaxBatchSize) | ||
| flushAndReset(ctx, "max_size") | ||
| } | ||
| case <-ticker.C: | ||
| config.Logger.Info("flushing on ticker", | ||
| "buffered_rows", buffered, | ||
| "elapsed_time", config.FlushInterval.String()) | ||
| flushAndReset(ctx, "ticker") | ||
| } | ||
| } | ||
| }() | ||
|
|
||
| return done | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.