Zero-dependency clients for errors.bitreport.pt following the same patterns as clients/node and clients/php: batch size 25, 5 s flush interval, 8 s HTTP timeout, fire-and-forget, env-var config. Each client ships with unit tests backed by an embedded HTTP server (no mocks), an example file, and a build manifest (pyproject.toml, go.mod, pom.xml). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
327 lines
7.2 KiB
Go
327 lines
7.2 KiB
Go
// Package errorreporter is a lightweight client for errors.bitreport.pt.
|
|
//
|
|
// Drop this file (and go.mod) into any Go 1.21+ project. Zero external dependencies.
|
|
//
|
|
// Usage:
|
|
//
|
|
// import errorreporter "pt.bitreport/errors-go"
|
|
//
|
|
// func main() {
|
|
// errorreporter.Init(errorreporter.Config{Token: os.Getenv("ERROR_REPORTING_TOKEN")})
|
|
// defer errorreporter.Flush()
|
|
// ...
|
|
// if err := doSomething(); err != nil {
|
|
// errorreporter.ReportError(err, nil)
|
|
// }
|
|
// }
|
|
//
|
|
// Environment variables:
|
|
//
|
|
// ERROR_REPORTING_TOKEN — ingest API key (required)
|
|
// ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
|
|
// ERROR_REPORTING_DISABLED — set to "1" to disable
|
|
// ERROR_REPORTING_PROJECT_NAME — display name (optional)
|
|
// ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional)
|
|
// ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional)
|
|
package errorreporter
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
defaultEndpoint = "https://errors.bitreport.pt"
|
|
batchSize = 25
|
|
flushInterval = 5 * time.Second
|
|
httpTimeout = 8 * time.Second
|
|
)
|
|
|
|
// Config holds reporter configuration. All fields are optional; unset fields
|
|
// fall back to the corresponding environment variable.
|
|
type Config struct {
|
|
Token string
|
|
Endpoint string
|
|
Disabled bool
|
|
ProjectName string
|
|
ProjectSlug string
|
|
GiteaRepo string
|
|
}
|
|
|
|
type ingestEvent struct {
|
|
SchemaVersion int `json:"schema_version"`
|
|
OccurredAt string `json:"occurred_at"`
|
|
Level string `json:"level"`
|
|
Message string `json:"message"`
|
|
Stacktrace string `json:"stacktrace,omitempty"`
|
|
Context map[string]interface{} `json:"context,omitempty"`
|
|
}
|
|
|
|
var (
|
|
mu sync.Mutex
|
|
cfg Config
|
|
queue []ingestEvent
|
|
flushTimer *time.Timer
|
|
httpClient = &http.Client{Timeout: httpTimeout}
|
|
)
|
|
|
|
// Init initialises the reporter. Call once at startup before any Report* calls.
|
|
func Init(c Config) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
cfg.Token = coalesce(c.Token, os.Getenv("ERROR_REPORTING_TOKEN"))
|
|
ep := coalesce(c.Endpoint, os.Getenv("ERROR_REPORTING_ENDPOINT"), defaultEndpoint)
|
|
cfg.Endpoint = strings.TrimRight(ep, "/")
|
|
cfg.Disabled = c.Disabled || os.Getenv("ERROR_REPORTING_DISABLED") == "1"
|
|
cfg.ProjectName = coalesce(c.ProjectName, os.Getenv("ERROR_REPORTING_PROJECT_NAME"))
|
|
cfg.ProjectSlug = coalesce(c.ProjectSlug, os.Getenv("ERROR_REPORTING_PROJECT_SLUG"))
|
|
cfg.GiteaRepo = coalesce(c.GiteaRepo, os.Getenv("ERROR_REPORTING_GITEA_REPO"))
|
|
}
|
|
|
|
// ReportError reports an error with an optional context map.
|
|
func ReportError(err error, ctx map[string]interface{}) {
|
|
mu.Lock()
|
|
tok, dis, pn, ps, gr, ep := cfg.Token, cfg.Disabled, cfg.ProjectName, cfg.ProjectSlug, cfg.GiteaRepo, cfg.Endpoint
|
|
mu.Unlock()
|
|
|
|
if dis || tok == "" || err == nil {
|
|
return
|
|
}
|
|
_ = ep // used via snapshot; referenced in send
|
|
|
|
buf := make([]byte, 8192)
|
|
n := runtime.Stack(buf, false)
|
|
stack := string(buf[:n])
|
|
|
|
filePath, lineNum := callerInfo()
|
|
|
|
c := map[string]interface{}{
|
|
"error_type": typeName(err),
|
|
}
|
|
if filePath != "" {
|
|
c["file_path"] = filePath
|
|
}
|
|
if lineNum > 0 {
|
|
c["line_number"] = lineNum
|
|
}
|
|
if pn != "" {
|
|
c["project_name"] = pn
|
|
}
|
|
if ps != "" {
|
|
c["project_slug"] = ps
|
|
}
|
|
if gr != "" {
|
|
c["gitea_repo"] = gr
|
|
}
|
|
for k, v := range ctx {
|
|
c[k] = v
|
|
}
|
|
|
|
enqueue(ingestEvent{
|
|
SchemaVersion: 1,
|
|
OccurredAt: nowISO(),
|
|
Level: "error",
|
|
Message: err.Error(),
|
|
Stacktrace: stack,
|
|
Context: c,
|
|
})
|
|
}
|
|
|
|
// ReportMessage reports a plain string message at the given level.
|
|
// level must be one of: "error", "warning", "info", "critical".
|
|
func ReportMessage(message, level string, ctx map[string]interface{}) {
|
|
mu.Lock()
|
|
tok, dis, pn, ps, gr := cfg.Token, cfg.Disabled, cfg.ProjectName, cfg.ProjectSlug, cfg.GiteaRepo
|
|
mu.Unlock()
|
|
|
|
if dis || tok == "" {
|
|
return
|
|
}
|
|
if level == "" {
|
|
level = "error"
|
|
}
|
|
|
|
c := map[string]interface{}{}
|
|
if pn != "" {
|
|
c["project_name"] = pn
|
|
}
|
|
if ps != "" {
|
|
c["project_slug"] = ps
|
|
}
|
|
if gr != "" {
|
|
c["gitea_repo"] = gr
|
|
}
|
|
for k, v := range ctx {
|
|
c[k] = v
|
|
}
|
|
|
|
ev := ingestEvent{
|
|
SchemaVersion: 1,
|
|
OccurredAt: nowISO(),
|
|
Level: level,
|
|
Message: message,
|
|
}
|
|
if len(c) > 0 {
|
|
ev.Context = c
|
|
}
|
|
enqueue(ev)
|
|
}
|
|
|
|
// Flush sends all queued events synchronously. Call before process exit (e.g. via defer).
|
|
func Flush() {
|
|
mu.Lock()
|
|
if flushTimer != nil {
|
|
flushTimer.Stop()
|
|
flushTimer = nil
|
|
}
|
|
batch := make([]ingestEvent, len(queue))
|
|
copy(batch, queue)
|
|
queue = queue[:0]
|
|
mu.Unlock()
|
|
|
|
send(batch)
|
|
}
|
|
|
|
// RecoverAndReport is a deferred helper that catches a panic, reports it, flushes,
|
|
// then re-panics so the runtime still terminates the goroutine normally.
|
|
//
|
|
// defer errorreporter.RecoverAndReport(nil)
|
|
func RecoverAndReport(ctx map[string]interface{}) {
|
|
if r := recover(); r != nil {
|
|
var err error
|
|
switch v := r.(type) {
|
|
case error:
|
|
err = v
|
|
default:
|
|
err = fmt.Errorf("%v", v)
|
|
}
|
|
ReportError(err, ctx)
|
|
Flush()
|
|
panic(r)
|
|
}
|
|
}
|
|
|
|
// --- internals ---
|
|
|
|
func enqueue(ev ingestEvent) {
|
|
var toSend []ingestEvent
|
|
|
|
mu.Lock()
|
|
queue = append(queue, ev)
|
|
if len(queue) >= batchSize {
|
|
toSend = make([]ingestEvent, len(queue))
|
|
copy(toSend, queue)
|
|
queue = queue[:0]
|
|
} else if flushTimer == nil {
|
|
flushTimer = time.AfterFunc(flushInterval, flushAsync)
|
|
}
|
|
mu.Unlock()
|
|
|
|
if toSend != nil {
|
|
go send(toSend)
|
|
}
|
|
}
|
|
|
|
func flushAsync() {
|
|
mu.Lock()
|
|
flushTimer = nil
|
|
if len(queue) == 0 {
|
|
mu.Unlock()
|
|
return
|
|
}
|
|
batch := make([]ingestEvent, len(queue))
|
|
copy(batch, queue)
|
|
queue = queue[:0]
|
|
mu.Unlock()
|
|
|
|
send(batch)
|
|
}
|
|
|
|
func send(events []ingestEvent) {
|
|
if len(events) == 0 {
|
|
return
|
|
}
|
|
mu.Lock()
|
|
tok := cfg.Token
|
|
ep := cfg.Endpoint
|
|
mu.Unlock()
|
|
|
|
for i := 0; i < len(events); i += batchSize {
|
|
end := i + batchSize
|
|
if end > len(events) {
|
|
end = len(events)
|
|
}
|
|
sendBatch(tok, ep, events[i:end])
|
|
}
|
|
}
|
|
|
|
func sendBatch(token, endpoint string, events []ingestEvent) {
|
|
body, err := json.Marshal(map[string]interface{}{"events": events})
|
|
if err != nil {
|
|
return
|
|
}
|
|
req, err := http.NewRequest(http.MethodPost, endpoint+"/v1/ingest/events", bytes.NewReader(body))
|
|
if err != nil {
|
|
return
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
resp, err := httpClient.Do(req)
|
|
if err != nil {
|
|
return
|
|
}
|
|
resp.Body.Close()
|
|
}
|
|
|
|
func nowISO() string {
|
|
t := time.Now().UTC()
|
|
ms := t.Nanosecond() / 1e6
|
|
return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
|
|
t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), ms)
|
|
}
|
|
|
|
func callerInfo() (string, int) {
|
|
pcs := make([]uintptr, 16)
|
|
// skip: runtime.Callers, callerInfo, ReportError/ReportMessage
|
|
n := runtime.Callers(3, pcs)
|
|
frames := runtime.CallersFrames(pcs[:n])
|
|
for {
|
|
f, more := frames.Next()
|
|
if !strings.HasSuffix(f.File, "error_reporter.go") {
|
|
return f.File, f.Line
|
|
}
|
|
if !more {
|
|
break
|
|
}
|
|
}
|
|
return "", 0
|
|
}
|
|
|
|
func typeName(err error) string {
|
|
if err == nil {
|
|
return ""
|
|
}
|
|
t := fmt.Sprintf("%T", err)
|
|
if idx := strings.LastIndex(t, "."); idx >= 0 {
|
|
return t[idx+1:]
|
|
}
|
|
return t
|
|
}
|
|
|
|
func coalesce(vals ...string) string {
|
|
for _, v := range vals {
|
|
if v != "" {
|
|
return v
|
|
}
|
|
}
|
|
return ""
|
|
}
|