summaryrefslogtreecommitdiff
path: root/internal/parser/csv.go
blob: 64d16e5c08e36352f519eca735d15f1232af431d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package parser

import (
	"context"
	"encoding/csv"
	"fmt"
	"io"
	"strconv"
	"strings"
	"time"

	"epimetheus/internal/metrics"
)

// CSVParser parses metrics from CSV format
type CSVParser struct{}

// NewCSVParser creates a new CSV parser
func NewCSVParser() *CSVParser {
	return &CSVParser{}
}

// Parse reads metrics from CSV format
// Format: metric_name,label1=value1;label2=value2,value,timestamp_ms
func (p *CSVParser) Parse(ctx context.Context, reader io.Reader) ([]metrics.Sample, error) {
	var samples []metrics.Sample

	csvReader := csv.NewReader(reader)
	csvReader.Comment = '#'

	lineNum := 0
	for {
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		default:
		}

		record, err := csvReader.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("line %d: %w", lineNum, err)
		}
		lineNum++

		if len(record) < 3 {
			continue // Skip invalid records
		}

		sample, err := p.parseRecord(record, lineNum)
		if err != nil {
			continue // Skip records with errors
		}

		samples = append(samples, sample)
	}

	return samples, nil
}

func (p *CSVParser) parseRecord(record []string, lineNum int) (metrics.Sample, error) {
	metricName := strings.TrimSpace(record[0])
	if metricName == "" {
		return metrics.Sample{}, fmt.Errorf("empty metric name")
	}

	labels := parseLabels(record[1])

	value, err := strconv.ParseFloat(strings.TrimSpace(record[2]), 64)
	if err != nil {
		return metrics.Sample{}, fmt.Errorf("invalid value: %w", err)
	}

	timestamp := time.Now()
	if len(record) > 3 && record[3] != "" {
		timestampMs, err := strconv.ParseInt(strings.TrimSpace(record[3]), 10, 64)
		if err == nil {
			timestamp = time.UnixMilli(timestampMs)
		}
	}

	return metrics.NewSample(metricName, labels, value, timestamp), nil
}

func parseLabels(labelStr string) map[string]string {
	labels := make(map[string]string)
	if labelStr == "" {
		return labels
	}

	labelPairs := strings.Split(labelStr, ";")
	for _, pair := range labelPairs {
		parts := strings.SplitN(pair, "=", 2)
		if len(parts) == 2 {
			labels[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
		}
	}
	return labels
}