Skip to content

ClickHouse Batch Insert - #2

Merged
Ret2Hell merged 13 commits into
mainfrom
dev
Mar 22, 2026
Merged

Ret2Hell merged 13 commits into
mainfrom
dev

Conversation

@Ret2Hell

@Ret2Hell Ret2Hell commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • ClickHouse storage, IP anonymization with configurable salt, user‑agent parsing, and a pipeline-based event processor.
    • New environment options for consumer tuning (topic, reset offset, fetch/batching, rebalance, concurrency) and ClickHouse connection/batching.
  • Improvements

    • Health probe now served at /livez; readiness probe removed.
    • Structured timestamped logging via zerolog; OpenTelemetry tracing removed.
    • Docker healthcheck updated to use /livez.
  • Tests

    • Added unit and integration tests covering config parsing, pipeline, anonymizer, UA parsing, consumer, and ClickHouse.

@coderabbitai

coderabbitai Bot commented Mar 22, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Replaces OpenTelemetry with an in-process pipeline: adds anonymizer, user-agent parser, ClickHouse writer, consumer fetch/batching controls, ClickHouse connection/batching settings, migrates logging from slog to zerolog, removes readiness probe and OTLP endpoint, and wires consumer to the new pipeline.

Changes

Cohort / File(s) Summary
Env & Config
\.env.example, internal/config/config.go, internal/config/config_test.go
Added consumer topic/reset-offset/fetch tuning, rebalance and concurrency flags, ClickHouse connection/batching env vars, and ANONYMIZATION_SALT. Removed OTEL_EXPORTER_OTLP_ENDPOINT. Implemented typed env parsers and tests for parsing/validation.
Main & Startup
cmd/processor/main.go, Dockerfile
Removed OTel tracer setup and readiness toggling; construct Anonymizer, UserAgentParser, ClickHouseWriter, and pipeline.NewPipeline. Switched logging to zerolog and updated consumer creation to use ConnectionOptions/Options. HEALTHCHECK changed to /livez.
Consumer & Tests
internal/consumer/consumer.go, internal/consumer/consumer_test.go
Refactored consumer API to accept ConnectionOptions, Options, *pipeline.Pipeline, and *zerolog.Logger. Implemented batching (size/time), commit-after-success semantics, optional block-rebalance-on-poll flow, and expanded unit tests for validation and flush behavior.
Pipeline & Tests
internal/pipeline/pipeline.go, internal/pipeline/pipeline_test.go
Added Pipeline with Process(ctx, events) to anonymize IPs, parse UA, derive/parse UUIDs, clamp fields, and batch-write processed events to ClickHouse. Added tests for UUID derivation, clamping, and event normalization.
Processors & Tests
internal/processors/anonymizer.go, internal/processors/anonymizer_test.go, internal/processors/useragent.go, internal/processors/useragent_test.go
Added Anonymizer (IP truncation + sha256-with-salt) and UserAgentParser (browser/OS/device heuristics) with unit tests for truncation, salted hashes, and UA parsing.
Storage ClickHouse & Tests
internal/storage/clickhouse.go, internal/storage/clickhouse_test.go
Added storage.Options and ClickHouseWriter: conn strategy parsing, connection setup, batch INSERT via WriteBatch, and Close(). Tests validate strategy parsing and constructor validation errors.
Observability
internal/observability/logger.go, internal/observability/tracing.go
Replaced slog logger with zerolog (NewLogger now returns *zerolog.Logger). Removed OpenTelemetry tracer initialization and shutdown plumbing.
Server & Health
internal/server/health.go, internal/server/server.go
Removed readiness state and /readyz endpoint; liveness remains and /livez now maps to the health handler.
Deps & Tooling
go.mod, mise.toml
Added github.com/ClickHouse/clickhouse-go/v2 and github.com/rs/zerolog; removed direct OTel packages from require. Added tasks.lint running golangci-lint in mise.toml.

Sequence Diagram(s)

sequenceDiagram
    participant K as Kafka Consumer
    participant C as Consumer (batch)
    participant P as Pipeline
    participant A as Anonymizer
    participant U as UserAgentParser
    participant CH as ClickHouseWriter

    K->>C: Poll messages
    C->>C: accumulate pending (size/time)
    alt batch ready
        C->>P: Process(ctx, events)
        loop per event
            P->>A: Anonymize(rawIP)
            A-->>P: ipHash, country, region
            P->>U: Parse(userAgent)
            U-->>P: browser, os, deviceType
            P->>P: build ProcessedEvent (UUID, clamp fields)
        end
        P->>CH: WriteBatch(ctx, processedEvents)
        CH-->>P: success / error
        alt success
            P-->>C: signal commit offsets
        else error
            P-->>C: do not commit (retry/err handling)
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐇 I hop through logs with zerolog cheer,
I hash each IP that scurries near,
UA secrets turned bright and clear,
Batched to ClickHouse, tidy and dear —
Pipelines hum, the meadow's near.


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 800575ea0c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/consumer/consumer.go Resolved
Comment thread internal/processors/anonymizer.go Resolved
Comment thread internal/pipeline/pipeline.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 69d5ff58c0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/consumer/consumer.go Resolved
Comment thread internal/storage/clickhouse.go Resolved
@sonarqubecloud

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 52a3deb793

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/consumer/consumer.go Resolved
Comment thread internal/consumer/consumer.go Resolved
Comment thread internal/pipeline/pipeline.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR introduces a pipeline-based event processing flow that anonymizes IPs, parses user agents, batches events, and writes them to ClickHouse, alongside updates to runtime configuration, logging, and health endpoints.

Changes:

  • Added ClickHouse writer with batch insert support and corresponding tests.
  • Introduced processors (IP anonymizer, user-agent parser) and a pipeline that transforms InternalEvent → ProcessedEvent.
  • Refactored the Kafka/Redpanda consumer to support configurable fetch/batching options and integrate with the pipeline; migrated logging to zerolog and updated healthcheck endpoints.

Reviewed changes

Copilot reviewed 20 out of 21 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
mise.toml Adds a lint task for golangci-lint.
internal/storage/clickhouse.go Implements ClickHouse connection + batch insert writer.
internal/storage/clickhouse_test.go Unit tests for ClickHouse writer option parsing/validation.
internal/server/server.go Switches health endpoint wiring to /livez.
internal/server/health.go Removes readiness probe and readiness state.
internal/processors/useragent.go Adds UA parsing (browser/OS/device/bot detection).
internal/processors/useragent_test.go Tests UA parsing behavior.
internal/processors/anonymizer.go Adds IP truncation + salted hashing for anonymization.
internal/processors/anonymizer_test.go Tests IP truncation and hashing determinism/salt usage.
internal/pipeline/pipeline.go Adds processing pipeline and ClickHouse batch write step.
internal/pipeline/pipeline_test.go Tests UUID derivation and screen-width clamping via pipeline processing.
internal/observability/tracing.go Removes OpenTelemetry tracing initialization.
internal/observability/logger.go Replaces slog with zerolog structured logging.
internal/consumer/consumer.go Adds consumer options, batching, and pipeline integration; adjusts polling/commit logic.
internal/consumer/consumer_test.go Updates tests for new consumer API/options and batching helpers.
internal/config/config.go Expands env-config parsing for consumer/ClickHouse/anonymization settings.
go.mod Adds ClickHouse + zerolog deps; removes direct OTel tracer deps.
go.sum Updates dependency checksums.
Dockerfile Updates container healthcheck to /livez.
cmd/processor/main.go Wires config → pipeline → consumer → ClickHouse writer; updates logging/shutdown flow.
.env.example Documents new required env vars for consumer + ClickHouse + anonymization.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread cmd/processor/main.go Resolved
Comment thread internal/consumer/consumer.go Resolved
Comment on lines +242 to +245
if err := c.flushPending(ctx, batch.pending); err != nil {
c.logger.Error().Err(err).Int("batch_size", len(batch.pending)).Msg("pipeline processing failed")
return true
}

Copilot AI Mar 22, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On flushPending error, this path immediately returns true without resetting the batch, and the outer loop will retry again immediately (no backoff), potentially creating a tight CPU/log loop during sustained downstream failures. Consider returning an error to break Run (so supervision can restart), or introduce a bounded backoff/sleep before retrying.

Copilot uses AI. Check for mistakes.
Comment thread internal/pipeline/pipeline.go Resolved
@Ret2Hell
Ret2Hell merged commit 5078e69 into main Mar 22, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants