ci: expand CI checks and make consumer sync opt-in

- Add Go, npm, Python, and Java validation to CI
- Run Go tests against PostgreSQL
- Record performance fixes in the report
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:14:31 +00:00
1 parent 199a5efaef
commit 22887fef03
100 files changed
+9740 -429

No files matched your search

+300
View File
@@ -0,0 +1,300 @@
package logshipper
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
)
// captureStd runs fn with os.Stdout and os.Stderr redirected, and returns what it wrote to each.
func captureStd(t *testing.T, fn func()) (stdout, stderr string) {
t.Helper()
oldOut, oldErr := os.Stdout, os.Stderr
outR, outW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
errR, errW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stdout, os.Stderr = outW, errW
defer func() { os.Stdout, os.Stderr = oldOut, oldErr }()
fn()
outW.Close()
errW.Close()
os.Stdout, os.Stderr = oldOut, oldErr
outBytes, _ := io.ReadAll(outR)
errBytes, _ := io.ReadAll(errR)
return string(outBytes), string(errBytes)
}
// ingest is a stand-in OmniLogger that records every batch it is sent.
type ingest struct {
mu sync.Mutex
batches [][]wireEntry
auth []string
status int
server *httptest.Server
}
func newIngest(t *testing.T, status int) *ingest {
t.Helper()
in := &ingest{status: status}
in.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var batch []wireEntry
_ = json.NewDecoder(r.Body).Decode(&batch)
in.mu.Lock()
in.batches = append(in.batches, batch)
in.auth = append(in.auth, r.Method+" "+r.URL.Path+" "+r.Header.Get("Authorization"))
in.mu.Unlock()
w.WriteHeader(in.status)
}))
t.Cleanup(in.server.Close)
return in
}
func (in *ingest) entries() []wireEntry {
in.mu.Lock()
defer in.mu.Unlock()
var all []wireEntry
for _, batch := range in.batches {
all = append(all, batch...)
}
return all
}
// newTestShipper keeps the background loop quiet so a test decides when entries are sent, and
// points a shipper that names no sink at a throwaway one so closing it prints nothing.
func newTestShipper(t *testing.T, cfg Config) *Shipper {
t.Helper()
if cfg.FlushInterval == 0 {
cfg.FlushInterval = time.Hour
}
if cfg.BaseURL == "" {
cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL
}
return New(cfg)
}
func TestLevelOfAcceptsTheSharedLogVocabulary(t *testing.T) {
cases := map[string]Level{
"debug": LevelDebug, " DEBUG ": LevelDebug, "info": LevelInfo, "": LevelInfo, "bogus": LevelInfo,
"warn": LevelWarn, "warning": LevelWarn, "error": LevelError, "critical": LevelCritical,
"silent": LevelSilent, "none": LevelSilent, "off": LevelSilent,
}
for input, want := range cases {
if got := levelOf(input); got != want {
t.Errorf("levelOf(%q) = %d, want %d", input, got, want)
}
}
}
func TestSevNameGivesTheLowercaseNameOmniLoggerExpects(t *testing.T) {
for sev, want := range map[Level][2]string{
LevelDebug: {"DEBUG", "debug"}, LevelInfo: {"INFO", "info"}, LevelWarn: {"WARN", "warn"},
LevelError: {"ERROR", "error"}, LevelCritical: {"CRITICAL", "critical"},
} {
if upper, lower := sevName(sev); upper != want[0] || lower != want[1] {
t.Errorf("sevName(%d) = %q, %q; want %q, %q", sev, upper, lower, want[0], want[1])
}
}
}
func TestFormatArgsJoinsErrorsStringsAndValues(t *testing.T) {
got := formatArgs([]any{"failed:", errors.New("boom"), 42, map[string]int{"a": 1}, make(chan int)})
if !strings.HasPrefix(got, `failed: boom 42 {"a":1} `) {
t.Fatalf("formatArgs = %q", got)
}
if formatArgs(nil) != "" {
t.Fatal("formatArgs(nil) is not empty")
}
}
func TestScrubIDsDropsIdentifierFieldsFromTheLocalDump(t *testing.T) {
ctx := map[string]any{
"id": 1, "userId": 2, "user_id": 3, "requestID": "r", "path": "/x", "status": 200, "ok": true,
}
got := scrubIDs(ctx)
if len(got) != 3 || got["path"] != "/x" || got["status"] != 200 || got["ok"] != true {
t.Fatalf("scrubIDs = %v, want only path, status and ok", got)
}
if len(ctx) != 7 {
t.Fatal("scrubIDs modified its input")
}
}
func TestEmitGatesOnTheThresholdAndWritesTheLocalLine(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", Module: "mod", Level: "warn"})
defer shipper.Close()
stdout, stderr := captureStd(t, func() {
shipper.Info("below threshold")
shipper.Warn("warned")
shipper.Error("failed", errors.New("boom"))
})
if stdout != "" {
t.Fatalf("stdout = %q, want nothing", stdout)
}
if strings.Contains(stderr, "below threshold") || !strings.Contains(stderr, "[WARN] [mod] warned") || !strings.Contains(stderr, "[ERROR] [mod] failed boom") {
t.Fatalf("stderr = %q", stderr)
}
if got := len(shipper.buffer); got != 2 {
t.Fatalf("buffered %d entries, want the 2 at or above the threshold", got)
}
}
func TestSilentLevelWritesAndBuffersNothing(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", Level: "silent"})
defer shipper.Close()
stdout, stderr := captureStd(t, func() {
shipper.Critical("never shown")
})
if stdout != "" || stderr != "" || len(shipper.buffer) != 0 {
t.Fatalf("silent shipper wrote %q / %q and buffered %d entries", stdout, stderr, len(shipper.buffer))
}
}
func TestLogAllScrubsIDsLocallyButShipsTheFullContext(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", LogAll: true})
defer shipper.Close()
stdout, _ := captureStd(t, func() {
shipper.InfoCtx(map[string]any{"userId": 7, "path": "/x"}, "request")
})
if !strings.Contains(stdout, `[DETAILS] {"path":"/x"}`) || strings.Contains(stdout, "userId") {
t.Fatalf("local dump = %q, want the ID scrubbed", stdout)
}
shipper.Flush()
entries := in.entries()
if len(entries) != 1 || !strings.Contains(string(entries[0].Context), `"userId":7`) {
t.Fatalf("shipped entries = %+v, want the unscrubbed context", entries)
}
}
func TestAuditShipsAnInfoEntryWithTheDetails(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
defer shipper.Close()
captureStd(t, func() { shipper.Audit("login", map[string]any{"user": "a"}) })
shipper.Flush()
entries := in.entries()
if len(entries) != 1 || entries[0].Level != "info" || !strings.HasPrefix(entries[0].Message, "audit:login") {
t.Fatalf("entries = %+v", entries)
}
}
func TestFlushSendsOneAuthenticatedBatchAndEmptiesTheBuffer(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL + "/", IngestToken: "secret", Service: "svc"})
defer shipper.Close()
captureStd(t, func() {
shipper.Info("one")
shipper.Error("two")
})
shipper.Flush()
shipper.Flush() // nothing left: no second request
in.mu.Lock()
defer in.mu.Unlock()
if len(in.batches) != 1 || len(in.batches[0]) != 2 {
t.Fatalf("batches = %+v, want one batch of two entries", in.batches)
}
if in.auth[0] != "POST /api/logs Bearer secret" {
t.Fatalf("request = %q", in.auth[0])
}
first := in.batches[0][0]
if first.Service != "svc" || first.Level != "info" || first.Message != "one" || first.OccurredAt.IsZero() {
t.Fatalf("first entry = %+v", first)
}
}
func TestBufferDropsNewEntriesOnceFullInsteadOfBlocking(t *testing.T) {
shipper := newTestShipper(t, Config{Service: "svc", BufferCapacity: 3, MaxBatchSize: 1000})
defer shipper.Close()
_, stderr := captureStd(t, func() {
for i := 0; i < 10; i++ {
shipper.enqueue(wireEntry{Message: "m"})
}
})
if len(shipper.buffer) != 3 {
t.Fatalf("buffer holds %d entries, want the capacity of 3", len(shipper.buffer))
}
if strings.Count(stderr, "buffer full") != 1 {
t.Fatalf("stderr = %q, want the full-buffer warning exactly once", stderr)
}
}
func TestReachingTheBatchSizeFlushesWithoutWaitingForTheInterval(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc", MaxBatchSize: 2})
defer shipper.Close()
captureStd(t, func() {
shipper.Info("a")
shipper.Info("b")
})
deadline := time.Now().Add(5 * time.Second)
for len(in.entries()) < 2 {
if time.Now().After(deadline) {
t.Fatal("a full batch was not flushed ahead of the interval")
}
time.Sleep(10 * time.Millisecond)
}
}
func TestCloseFlushesWhatIsLeft(t *testing.T) {
in := newIngest(t, http.StatusAccepted)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
captureStd(t, func() { shipper.Info("last words") })
if err := shipper.Close(); err != nil {
t.Fatal(err)
}
if err := shipper.Close(); err != nil {
t.Fatalf("second Close error = %v", err)
}
if entries := in.entries(); len(entries) != 1 || entries[0].Message != "last words" {
t.Fatalf("entries after Close = %+v", entries)
}
}
func TestAFailingSinkNeverFailsTheCallerAndWarnsOnlyOnce(t *testing.T) {
in := newIngest(t, http.StatusInternalServerError)
shipper := newTestShipper(t, Config{BaseURL: in.server.URL, IngestToken: "secret", Service: "svc"})
defer shipper.Close()
_, stderr := captureStd(t, func() {
shipper.Info("one")
shipper.Flush()
shipper.Info("two")
shipper.Flush()
})
if strings.Count(stderr, "OmniLogger rejected") != 1 {
t.Fatalf("stderr = %q, want one rate-limited warning", stderr)
}
in.server.Close()
_, stderr = captureStd(t, func() {
shipper.Info("three")
shipper.Flush() // the sink is gone: swallowed, and still inside the warning interval
})
if strings.Contains(stderr, "send 1 entries") {
t.Fatalf("stderr = %q, want the second warning suppressed", stderr)
}
}
func TestNewAppliesDefaults(t *testing.T) {
shipper := New(Config{BaseURL: "http://omni:8090///", IngestToken: "t", Service: "svc"})
defer shipper.Close()
if shipper.url != "http://omni:8090/api/logs" || shipper.module != "svc" || shipper.threshold != LevelInfo {
t.Fatalf("url = %q, module = %q, threshold = %d", shipper.url, shipper.module, shipper.threshold)
}
if shipper.maxBatch != defaultMaxBatchSize || shipper.bufCap != defaultBufferCapacity || shipper.client == nil {
t.Fatalf("defaults not applied: %+v", shipper)
}
}