Skip to content

The only tool you need to know what is happening and how to fix it.

2.5 KB
Raw Blame
//go:build telemetry_duckdb

package duckdb

import (
	"context"
	"encoding/json"
	"fmt"
	"sync"
	"time"

	"github.com/duckdb/duckdb-go/v2"
	"github.com/tracewayapp/traceway/backend/app/db"
	traceway "go.tracewayapp.com"
)

// The DuckDB Appender rejects typed Go pointers for nullable columns
// (cast error: cannot cast *string to string). It accepts an untyped nil
// for SQL NULL or the dereferenced value otherwise.
func nullableString(s *string) any {
	if s == nil {
		return nil
	}
	return *s
}

const dropReportInterval = time.Minute

var (
	dropReportMu       sync.Mutex
	droppedSinceReport = map[string]uint64{}
	lastDropReportAt   = map[string]time.Time{}
)

func captureDroppedRow(table string, err error) {
	db.RecordTelemetryRowDropped(table)

	var report uint64
	dropReportMu.Lock()
	droppedSinceReport[table]++
	if time.Since(lastDropReportAt[table]) >= dropReportInterval {
		report = droppedSinceReport[table]
		droppedSinceReport[table] = 0
		lastDropReportAt[table] = time.Now()
	}
	dropReportMu.Unlock()

	if report > 0 {
		traceway.CaptureException(fmt.Errorf("duckdb %s insert: dropped %d rows since last report, latest: %w", table, report, err))
	}
}

func timeBucketExpr(column string, intervalSeconds int) string {
	return fmt.Sprintf("time_bucket(to_seconds(%d), %s, TIMESTAMP '1970-01-01')", intervalSeconds, column)
}

func boolToInt(b bool) int64 {
	if b {
		return 1
	}
	return 0
}

func attrJSON(m map[string]string) (string, error) {
	if len(m) == 0 {
		return "{}", nil
	}
	b, err := json.Marshal(m)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

// withAppender runs fn with an Appender on a dedicated connection — the
// Appender API is not reachable through database/sql, and Close flushes
// the appended rows.
func withAppender(ctx context.Context, table string, fn func(*duckdb.Appender)) error {
	return withAppenderColumns(ctx, table, nil, fn)
}

func withAppenderColumns(ctx context.Context, table string, columns []string, fn func(*duckdb.Appender)) error {
	conn, err := db.DuckDBConnector.Connect(ctx)
	if err != nil {
		db.RecordTelemetryInsertFailure()
		return err
	}
	defer conn.Close()

	var appender *duckdb.Appender
	if len(columns) == 0 {
		appender, err = duckdb.NewAppenderFromConn(conn, "", table)
	} else {
		appender, err = duckdb.NewAppenderWithColumns(conn, "", "", table, columns)
	}
	if err != nil {
		db.RecordTelemetryInsertFailure()
		return err
	}
	fn(appender)
	if err := appender.Close(); err != nil {
		db.RecordTelemetryInsertFailure()
		return err
	}
	return nil
}