Something went wrong. Try again.
Metric and Time-Series Engine: A Minimal Archiving Time Series Storage Service
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351package query
import ( "fmt" "io" "math" "sort" "strings" "time")
type svgTheme struct { bg string border string borderWidth int titleColor string latestColor string lineColor string areaColor string areaOpacity float64 gridColor string axisColor string tickColor string labelColor string sublabelColor string fontFamily string monoFontFamily string}
func getSVGTheme(name string) svgTheme { if name == "dark" { return svgTheme{ bg: "#18181b", border: "#27272a", borderWidth: 0, titleColor: "#f4f4f5", latestColor: "#38bdf8", lineColor: "#38bdf8", areaColor: "#38bdf8", areaOpacity: 0.25, gridColor: "#27272a", axisColor: "#3f3f46", tickColor: "#52525b", labelColor: "#a1a1aa", sublabelColor: "#71717a", fontFamily: "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif", monoFontFamily: "monospace", } } // Light high-contrast theme matching default.css return svgTheme{ bg: "#ffffff", border: "#000000", borderWidth: 1, titleColor: "#000000", latestColor: "#000000", lineColor: "#000000", areaColor: "#000000", areaOpacity: 0.08, gridColor: "#e0e0e0", axisColor: "#000000", tickColor: "#000000", labelColor: "#000000", sublabelColor: "#444444", fontFamily: "Arial, sans-serif", monoFontFamily: "Menlo, monospace", }}
// RenderSVG writes a self-contained, responsive SVG line chart directly to the writer.// Does not require any external JavaScript libraries.func RenderSVG(w io.Writer, title string, timestamps []int64, values []float64, width, height int, theme ...string) error { selectedTheme := "light" if len(theme) > 0 && theme[0] != "" { selectedTheme = theme[0] } th := getSVGTheme(selectedTheme)
if width <= 0 { width = 600 } if height <= 0 { height = 200 }
var rectAttr string if th.borderWidth > 0 { rectAttr = fmt.Sprintf(`fill="%s" stroke="%s" stroke-width="%d" rx="4"`, th.bg, th.border, th.borderWidth) } else { rectAttr = fmt.Sprintf(`fill="%s" rx="6"`, th.bg) }
if len(timestamps) == 0 || len(values) == 0 { _, err := fmt.Fprintf(w, `<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 %d %d"> <rect width="100%%" height="100%%" %s/> <text x="50%%" y="50%%" dominant-baseline="middle" text-anchor="middle" fill="%s" font-family="%s" font-size="14">No data</text> </svg>`, width, height, width, height, rectAttr, th.sublabelColor, th.monoFontFamily) return err }
minVal := values[0] maxVal := values[0] for _, v := range values { if v < minVal { minVal = v } if v > maxVal { maxVal = v } } if minVal == maxVal { maxVal += 1.0 minVal -= 1.0 }
paddingLeft := 60.0 paddingRight := 25.0 paddingTop := 35.0 paddingBottom := 42.0
plotW := float64(width) - paddingLeft - paddingRight plotH := float64(height) - paddingTop - paddingBottom if plotW <= 0 { plotW = 100 } if plotH <= 0 { plotH = 50 }
minTS := float64(timestamps[0]) maxTS := float64(timestamps[len(timestamps)-1]) if minTS >= maxTS { maxTS = minTS + 60000.0 // Default 1-minute window }
var pathBuilder strings.Builder firstX := paddingLeft lastX := paddingLeft + plotW
for i := range timestamps { x := paddingLeft + ((float64(timestamps[i])-minTS)/(maxTS-minTS))*plotW y := paddingTop + plotH - ((values[i]-minVal)/(maxVal-minVal))*plotH if i == 0 { firstX = x fmt.Fprintf(&pathBuilder, "M %.2f,%.2f", x, y) } else { fmt.Fprintf(&pathBuilder, " L %.2f,%.2f", x, y) } if i == len(timestamps)-1 { lastX = x } }
// Area gradient fill under the line areaPath := fmt.Sprintf("%s L %.2f,%.2f L %.2f,%.2f Z", pathBuilder.String(), lastX, paddingTop+plotH, firstX, paddingTop+plotH)
// Time axis (X-axis) formatting and ticks span := time.Duration(int64(maxTS-minTS)) * time.Millisecond minTime := time.UnixMilli(int64(minTS)).UTC() maxTime := time.UnixMilli(int64(maxTS)).UTC() multiYear := minTime.Year() != maxTime.Year() || span > 180*24*time.Hour
type tickLabel struct { line1 string line2 string }
getTickLabel := func(t time.Time) tickLabel { switch { case span <= 10*time.Minute: dateFmt := "Jan 02" if multiYear { dateFmt = "Jan 02 '06" } return tickLabel{ line1: t.Format("15:04:05"), line2: t.Format(dateFmt), } case span <= 7*24*time.Hour: dateFmt := "Jan 02" if multiYear { dateFmt = "Jan 02 '06" } return tickLabel{ line1: t.Format("15:04"), line2: t.Format(dateFmt), } default: // > 7 days (e.g. 30 days, 90 days, 1 year) return tickLabel{ line1: t.Format("Jan 02"), line2: t.Format("2006"), } } }
numTicks := 5 if width < 500 { numTicks = 3 }
var xTicks strings.Builder for k := range numTicks { frac := float64(k) / float64(numTicks-1) x := paddingLeft + frac*plotW tMillis := int64(minTS + frac*(maxTS-minTS)) tVal := time.UnixMilli(tMillis).UTC() lbl := getTickLabel(tVal)
var anchor string switch k { case 0: anchor = "start" case numTicks - 1: anchor = "end" default: anchor = "middle" }
// Vertical subtle grid line if k > 0 && k < numTicks-1 { fmt.Fprintf(&xTicks, `<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="%s" stroke-width="1" stroke-dasharray="2 4"/>`+"\n ", x, paddingTop, x, paddingTop+plotH, th.gridColor) } // Bottom tick mark fmt.Fprintf(&xTicks, `<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="%s" stroke-width="1"/>`+"\n ", x, paddingTop+plotH, x, paddingTop+plotH+4, th.tickColor) // X-axis time & date label (two-line) fmt.Fprintf(&xTicks, `<text x="%.1f" y="%.1f" fill="%s" font-family="%s" font-size="10" text-anchor="%s"><tspan x="%.1f" dy="0">%s</tspan><tspan x="%.1f" dy="12" fill="%s" font-size="9">%s</tspan></text>`+"\n ", x, paddingTop+plotH+16, th.labelColor, th.monoFontFamily, anchor, x, lbl.line1, x, th.sublabelColor, lbl.line2) }
latestVal := values[len(values)-1] midVal := (minVal + maxVal) / 2.0
_, err := fmt.Fprintf(w, `<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 %d %d"> <defs> <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1"> <stop offset="0%%" stop-color="%s" stop-opacity="%.2f"/> <stop offset="100%%" stop-color="%s" stop-opacity="0.0"/> </linearGradient> </defs> <rect width="100%%" height="100%%" %s/> <text x="16" y="22" fill="%s" font-family="%s" font-size="13" font-weight="600">%s</text> <text x="%.1f" y="22" fill="%s" font-family="%s" font-size="12" font-weight="600" text-anchor="end">Latest: %.2f</text> <!-- Y Axis Grid & Labels --> <line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="%s" stroke-width="1" stroke-dasharray="3 3"/> <text x="%.1f" y="%.1f" fill="%s" font-family="%s" font-size="10" text-anchor="end">%.2f</text> <line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="%s" stroke-width="1" stroke-dasharray="3 3"/> <text x="%.1f" y="%.1f" fill="%s" font-family="%s" font-size="10" text-anchor="end">%.2f</text> <line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="%s" stroke-width="1"/> <text x="%.1f" y="%.1f" fill="%s" font-family="%s" font-size="10" text-anchor="end">%.2f</text>
<!-- X Axis Time Grid & Labels (UTC) --> %s <text x="%.1f" y="%.1f" fill="%s" font-family="%s" font-size="9" text-anchor="end">UTC</text>
<!-- Data Plot --> <path d="%s" fill="url(#areaGrad)"/> <path d="%s" fill="none" stroke="%s" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`, width, height, width, height, th.areaColor, th.areaOpacity, th.areaColor, rectAttr, th.titleColor, th.fontFamily, title, float64(width)-paddingRight, th.latestColor, th.monoFontFamily, latestVal, paddingLeft, paddingTop, paddingLeft+plotW, paddingTop, th.gridColor, paddingLeft-8, paddingTop+4, th.labelColor, th.monoFontFamily, maxVal, paddingLeft, paddingTop+plotH/2, paddingLeft+plotW, paddingTop+plotH/2, th.gridColor, paddingLeft-8, paddingTop+plotH/2+4, th.sublabelColor, th.monoFontFamily, midVal, paddingLeft, paddingTop+plotH, paddingLeft+plotW, paddingTop+plotH, th.axisColor, paddingLeft-8, paddingTop+plotH+4, th.labelColor, th.monoFontFamily, minVal, xTicks.String(), paddingLeft-8, paddingTop+plotH+16, th.sublabelColor, th.monoFontFamily, areaPath, pathBuilder.String(), th.lineColor, )
return err}
var sparkBlocks = []rune{' ', '▂', '▃', '▄', '▅', '▆', '▇', '█'}
// RenderASCII writes a concise statistical summary and ASCII sparkline// designed for LLMs, automated agents, and CLI output.func RenderASCII(w io.Writer, title string, timestamps []int64, values []float64) error { if len(values) == 0 { _, err := fmt.Fprintf(w, "Series: %s\nNo data in selected time range.\n", title) return err }
minVal := values[0] maxVal := values[0] sum := 0.0
sortedVals := make([]float64, len(values)) copy(sortedVals, values) sort.Float64s(sortedVals)
for _, v := range values { if v < minVal { minVal = v } if v > maxVal { maxVal = v } sum += v }
mean := sum / float64(len(values)) p95Idx := max(int(math.Ceil(0.95*float64(len(sortedVals))))-1, 0) p95 := sortedVals[p95Idx] latest := values[len(values)-1]
// Compute sparkline characters valRange := maxVal - minVal var spark strings.Builder for _, v := range values { var idx int if valRange == 0 { idx = 0 } else { idx = int(((v - minVal) / valRange) * float64(len(sparkBlocks)-1)) } if idx < 0 { idx = 0 } if idx >= len(sparkBlocks) { idx = len(sparkBlocks) - 1 } spark.WriteRune(sparkBlocks[idx]) }
fromTime := time.UnixMilli(timestamps[0]).UTC().Format(time.RFC3339) toTime := time.UnixMilli(timestamps[len(timestamps)-1]).UTC().Format(time.RFC3339)
_, err := fmt.Fprintf(w, "Series: %s\n"+ "Range: %s to %s (%d points)\n"+ "Metrics: Min: %.2f | Max: %.2f | Mean: %.2f | P95: %.2f | Latest: %.2f\n"+ "Trend: [%s]\n", title, fromTime, toTime, len(values), minVal, maxVal, mean, p95, latest, spark.String(), )
return err}