From 362cee26fd878a8518a6d464d485c0714909412f Mon Sep 17 00:00:00 2001 From: Gabriel Date: Sat, 21 Nov 2026 00:23:35 +0100 Subject: [PATCH] Sync shared snapshot from 8701874 Co-Authored-By: Claude Haiku 5.5 --- shared/.changeset/node-backend-logshipper.md | 5 + shared/backend/coreconfig/coreconfig.go | 46 +- .../coreconfig/omnilogger_fields_test.go | 53 ++ shared/backend/logshipper/logger.go | 50 ++ shared/backend/logshipper/logger_test.go | 86 ++ shared/backend/logshipper/shipper.go | 294 ++++++- shared/backend/logshipper/shipper_test.go | 388 +++++++- shared/packages/java-backend/README.md | 1 + .../gabriel20xx/shared/logs/LogShipper.java | 752 ++++++++++++++++ .../shared/logs/LogShipperTest.java | 833 ++++++++++++++++++ shared/packages/node-backend/README.md | 3 +- shared/packages/node-backend/src/index.js | 1 + .../packages/node-backend/src/logshipper.js | 361 ++++++++ .../node-backend/test/logshipper.test.js | 544 ++++++++++++ shared/packages/python-backend/README.md | 91 +- .../src/shared_backend/__init__.py | 13 +- .../src/shared_backend/coreconfig.py | 155 +++- .../src/shared_backend/logshipper.py | 415 +++++++++ .../python-backend/tests/test_coreconfig.py | 190 ++++ .../python-backend/tests/test_logshipper.py | 688 +++++++++++++++ 20 files changed, 4908 insertions(+), 61 deletions(-) create mode 100644 shared/.changeset/node-backend-logshipper.md create mode 100644 shared/backend/coreconfig/omnilogger_fields_test.go create mode 100644 shared/backend/logshipper/logger.go create mode 100644 shared/backend/logshipper/logger_test.go create mode 100644 shared/packages/java-backend/src/main/java/com/gabriel20xx/shared/logs/LogShipper.java create mode 100644 shared/packages/java-backend/src/test/java/com/gabriel20xx/shared/logs/LogShipperTest.java create mode 100644 shared/packages/node-backend/src/logshipper.js create mode 100644 shared/packages/node-backend/test/logshipper.test.js create mode 100644 shared/packages/python-backend/src/shared_backend/logshipper.py create mode 100644 shared/packages/python-backend/tests/test_logshipper.py diff --git a/shared/.changeset/node-backend-logshipper.md b/shared/.changeset/node-backend-logshipper.md new file mode 100644 index 0000000..fe5d2aa --- /dev/null +++ b/shared/.changeset/node-backend-logshipper.md @@ -0,0 +1,5 @@ +--- +"@gabriel20xx/node-backend": patch +--- + +Adds `LogShipper`, `createLogShipperFromEnv` and `mirrorConsole` (`src/logshipper.js`): batches log entries and sends them to OmniLogger's `/api/logs`. Shipping is enabled only when `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are both set, and otherwise the factory returns `null`. diff --git a/shared/backend/coreconfig/coreconfig.go b/shared/backend/coreconfig/coreconfig.go index 487bb4d..1428753 100644 --- a/shared/backend/coreconfig/coreconfig.go +++ b/shared/backend/coreconfig/coreconfig.go @@ -78,6 +78,16 @@ type Info struct { // ProjectConfigurator includes it so consumers with independent databases can // authenticate storage requests without falling back to their own SECRET. CarrierNodeSecret string `json:"carrierNodeSecret,omitempty"` + + // OmniLoggerURL is the OmniLogger instance that receives this service's log entries. Services + // that ship logs use it with OmniLoggerIngestToken; both are optional, so a service that does not + // ship logs ignores them. + OmniLoggerURL string `json:"omniLoggerUrl,omitempty"` + + // OmniLoggerIngestToken is the ingest token ProjectConfigurator minted for this receiving service. + // OmniLogger binds it to the service's name, so it can only write this service's own entries. + // It is a per-service credential, not a SECRET, and is never echoed back in the response. + OmniLoggerIngestToken string `json:"omniLoggerIngestToken,omitempty"` } // Store holds the most recently pushed Info, defaulting to whatever fallback NewStore was given @@ -85,9 +95,10 @@ type Info struct { // first push arrives - or forever, if this deployment isn't registered with a ProjectConfigurator // instance at all, in which case those env vars keep working exactly as before. type Store struct { - mu sync.RWMutex - info Info - onUpdate func(Info) + mu sync.RWMutex + info Info + onUpdate func(Info) + listeners []func(Info) } // NewStore returns a Store seeded with fallback. @@ -132,6 +143,12 @@ func (s *Store) CarrierNodeURLs() []string { return s.Get().CarrierNodeURLs } // CarrierNodeSecret is a convenience accessor for Get().CarrierNodeSecret. func (s *Store) CarrierNodeSecret() string { return s.Get().CarrierNodeSecret } +// OmniLoggerURL is a convenience accessor for Get().OmniLoggerURL. +func (s *Store) OmniLoggerURL() string { return s.Get().OmniLoggerURL } + +// OmniLoggerIngestToken is a convenience accessor for Get().OmniLoggerIngestToken. +func (s *Store) OmniLoggerIngestToken() string { return s.Get().OmniLoggerIngestToken } + // OnUpdate registers fn to be called (synchronously, so keep it fast) with the new Info after // every Set - e.g. client.SetBaseURL for an authclient.Client that isn't already reading through // Store on every call. Only one callback is kept; a second registration replaces the first, which @@ -142,6 +159,16 @@ func (s *Store) OnUpdate(fn func(Info)) { s.mu.Unlock() } +// Subscribe registers fn to be called (synchronously, so keep it fast) with the new Info after every +// Set, in addition to OnUpdate's single callback, which it does not replace. Use it when a service +// has more than one component that follows the pushed values, such as an authclient.Client and a +// log shipper. Subscribers cannot be removed; they live as long as the Store. +func (s *Store) Subscribe(fn func(Info)) { + s.mu.Lock() + s.listeners = append(s.listeners, fn) + s.mu.Unlock() +} + // Set replaces the current Info, field by field, ignoring a blank/empty field so a partial push // (e.g. only carrierNodeUrl(s) changed) never clobbers the other value. func (s *Store) Set(next Info) { @@ -165,16 +192,26 @@ func (s *Store) Set(next Info) { if secret := strings.TrimSpace(next.CarrierNodeSecret); secret != "" { s.info.CarrierNodeSecret = secret } + if url := strings.TrimRight(strings.TrimSpace(next.OmniLoggerURL), "/"); url != "" { + s.info.OmniLoggerURL = url + } + if token := strings.TrimSpace(next.OmniLoggerIngestToken); token != "" { + s.info.OmniLoggerIngestToken = token + } if len(next.CarrierNodeURLs) > 0 { s.info.CarrierNodeURLs = next.CarrierNodeURLs s.info.CarrierNodeURL = next.CarrierNodeURLs[0] } current := s.info callback := s.onUpdate + listeners := append([]func(Info){}, s.listeners...) s.mu.Unlock() if callback != nil { callback(current) } + for _, fn := range listeners { + fn(current) + } } // normalizeInfo trims/drops blank CarrierNodeURLs entries and fills in CarrierNodeURLs from a @@ -228,6 +265,7 @@ func Handler(secret string, store *Store) http.HandlerFunc { info := store.Get() info.CarrierNodeSecret = "" info.ContentScannerSecret = "" + info.OmniLoggerIngestToken = "" writeJSON(w, http.StatusOK, map[string]any{"ok": true, "info": info}) } } @@ -235,7 +273,7 @@ func Handler(secret string, store *Store) http.HandlerFunc { // validateServiceURLs refuses a pushed URL that is not an http or https URL with a host, so a push // cannot point this service's clients at another scheme or at an empty host. func validateServiceURLs(info Info) error { - urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL}, info.CarrierNodeURLs...) + urls := append([]string{info.AuthGuardURL, info.ComfyUIURL, info.ProjectConfiguratorURL, info.ContentScannerURL, info.CarrierNodeURL, info.OmniLoggerURL}, info.CarrierNodeURLs...) for _, raw := range urls { value := strings.TrimSpace(raw) if value == "" { diff --git a/shared/backend/coreconfig/omnilogger_fields_test.go b/shared/backend/coreconfig/omnilogger_fields_test.go new file mode 100644 index 0000000..c45f8fc --- /dev/null +++ b/shared/backend/coreconfig/omnilogger_fields_test.go @@ -0,0 +1,53 @@ +package coreconfig + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const omniTestSecret = "omnilogger-fields-test-secret-0123456789" + +func TestOmniLoggerFieldsKeepTheirValueAcrossPartialPushes(t *testing.T) { + store := NewStore(Info{}) + store.Set(Info{OmniLoggerURL: "https://logs.example.com/", OmniLoggerIngestToken: "token-one"}) + if store.OmniLoggerURL() != "https://logs.example.com" || store.OmniLoggerIngestToken() != "token-one" { + t.Fatalf("got url=%q token=%q", store.OmniLoggerURL(), store.OmniLoggerIngestToken()) + } + store.Set(Info{AuthGuardURL: "https://auth.example.com"}) + if store.OmniLoggerIngestToken() != "token-one" { + t.Fatal("a push without a token cleared the stored token") + } +} + +func TestHandlerNeverEchoesTheOmniLoggerIngestToken(t *testing.T) { + store := NewStore(Info{}) + handler := Handler(omniTestSecret, store) + request := httptest.NewRequest(http.MethodPut, "/api/core-services/internal", + strings.NewReader(`{"omniLoggerUrl":"https://logs.example.com","omniLoggerIngestToken":"token-two"}`)) + request.Header.Set("X-Internal-Auth", omniTestSecret) + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusOK { + t.Fatalf("status = %d: %s", response.Code, response.Body.String()) + } + if strings.Contains(response.Body.String(), "token-two") { + t.Fatalf("response echoed the ingest token: %s", response.Body.String()) + } + if store.OmniLoggerIngestToken() != "token-two" { + t.Fatal("the pushed token was not stored") + } +} + +func TestOmniLoggerURLMustBeHTTPWithAHost(t *testing.T) { + if err := validateServiceURLs(Info{OmniLoggerURL: "ftp://logs.example.com"}); err == nil { + t.Fatal("accepted a non-http OmniLogger URL") + } + if err := validateServiceURLs(Info{OmniLoggerURL: "https://"}); err == nil { + t.Fatal("accepted an OmniLogger URL without a host") + } + if err := validateServiceURLs(Info{OmniLoggerURL: "http://omnilogger:8080"}); err != nil { + t.Fatalf("rejected a valid OmniLogger URL: %v", err) + } +} diff --git a/shared/backend/logshipper/logger.go b/shared/backend/logshipper/logger.go new file mode 100644 index 0000000..da81fc9 --- /dev/null +++ b/shared/backend/logshipper/logger.go @@ -0,0 +1,50 @@ +package logshipper + +import ( + "fmt" + "io" + "log" + "strings" +) + +// Logger writes each line to the console exactly as the standard log package would, and ships it to +// OmniLogger at the severity the caller names. Use it where the caller knows the severity, instead of +// Writer, which has to guess the severity from the wording of the line. +// +// The console writer must be the writer the service logs to without the shipper, such as os.Stderr, so a +// line is never shipped twice. Create the Logger after the service has set its log flags and prefix, which +// NewLogger copies. A nil shipper makes the Logger console-only. +type Logger struct { + console *log.Logger + shipper *Shipper +} + +// NewLogger returns a Logger that writes to console with the standard log flags and prefix in effect now. +func NewLogger(console io.Writer, shipper *Shipper) *Logger { + return &Logger{console: log.New(console, log.Prefix(), log.Flags()), shipper: shipper} +} + +// output writes one line to the console and ships it. The call depth of 3 makes the console's file and line +// flags name the caller of Debugf, Infof, and the other methods, not this file. +func (l *Logger) output(sev Level, format string, args ...any) { + msg := fmt.Sprintf(format, args...) + _ = l.console.Output(3, msg) + if l.shipper != nil { + l.shipper.Ship(sev, nil, strings.TrimRight(msg, "\n")) + } +} + +// Debugf logs at debug severity. +func (l *Logger) Debugf(format string, args ...any) { l.output(LevelDebug, format, args...) } + +// Infof logs at info severity. +func (l *Logger) Infof(format string, args ...any) { l.output(LevelInfo, format, args...) } + +// Warnf logs at warn severity. +func (l *Logger) Warnf(format string, args ...any) { l.output(LevelWarn, format, args...) } + +// Errorf logs at error severity. +func (l *Logger) Errorf(format string, args ...any) { l.output(LevelError, format, args...) } + +// Criticalf logs at critical severity. +func (l *Logger) Criticalf(format string, args ...any) { l.output(LevelCritical, format, args...) } diff --git a/shared/backend/logshipper/logger_test.go b/shared/backend/logshipper/logger_test.go new file mode 100644 index 0000000..04a642b --- /dev/null +++ b/shared/backend/logshipper/logger_test.go @@ -0,0 +1,86 @@ +package logshipper + +import ( + "bytes" + "log" + "net/http" + "regexp" + "strings" + "testing" + "time" +) + +var timestampPattern = regexp.MustCompile(`\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} `) + +// The console output must match what the standard log package writes with the same flags and prefix. +func TestLoggerConsoleOutputMatchesTheStandardLogger(t *testing.T) { + oldFlags, oldPrefix := log.Flags(), log.Prefix() + log.SetFlags(log.LstdFlags) + log.SetPrefix("svc: ") + defer log.SetFlags(oldFlags) + defer log.SetPrefix(oldPrefix) + + var console, reference bytes.Buffer + logger := NewLogger(&console, nil) + logger.Infof("started on %s", ":8080") + logger.Errorf("push failed: %v", "boom") + std := log.New(&reference, log.Prefix(), log.Flags()) + std.Printf("started on %s", ":8080") + std.Printf("push failed: %v", "boom") + + stripTimes := func(s string) string { + return timestampPattern.ReplaceAllString(s, "") + } + if stripTimes(console.String()) != stripTimes(reference.String()) { + t.Fatalf("console = %q, want the standard logger's %q (apart from timestamps)", console.String(), reference.String()) + } +} + +// Each method ships at its own severity, and nothing reaches the console twice. +func TestLoggerShipsEachLineAtItsSeverityOnce(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "debug"}) + defer shipper.Close() + + var console bytes.Buffer + logger := NewLogger(&console, shipper) + logger.Debugf("d") + logger.Infof("i") + logger.Warnf("w") + logger.Errorf("e") + logger.Criticalf("c") + shipper.Flush() + + if n := strings.Count(console.String(), "\n"); n != 5 { + t.Fatalf("console got %d lines, want 5: %q", n, console.String()) + } + entries := in.entries() + want := map[string]string{"d": "debug", "i": "info", "w": "warn", "e": "error", "c": "critical"} + if len(entries) != len(want) { + t.Fatalf("shipped %d entries, want %d: %+v", len(entries), len(want), entries) + } + for _, e := range entries { + if want[e.Message] != e.Level { + t.Errorf("%q shipped at %q, want %q", e.Message, e.Level, want[e.Message]) + } + } +} + +// A nil shipper keeps the Logger console-only, and the threshold still applies to what is shipped. +func TestLoggerWithoutShipperIsConsoleOnlyAndThresholdApplies(t *testing.T) { + var console bytes.Buffer + NewLogger(&console, nil).Debugf("still printed") + if !strings.Contains(console.String(), "still printed") { + t.Fatalf("console-only logger dropped a line: %q", console.String()) + } + + in := newIngest(t, http.StatusAccepted) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"}) + defer shipper.Close() + NewLogger(&bytes.Buffer{}, shipper).Warnf("below threshold") + shipper.Flush() + time.Sleep(10 * time.Millisecond) + if n := len(in.entries()); n != 0 { + t.Fatalf("shipped %d entries below the threshold", n) + } +} diff --git a/shared/backend/logshipper/shipper.go b/shared/backend/logshipper/shipper.go index d700abd..be2f868 100644 --- a/shared/backend/logshipper/shipper.go +++ b/shared/backend/logshipper/shipper.go @@ -25,11 +25,16 @@ import ( "context" "encoding/json" "fmt" + "io" "net/http" "os" + "regexp" "strings" "sync" "time" + "unicode/utf8" + + "repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig" ) // Level mirrors internal/logging's severity scale in every service's local @@ -95,8 +100,10 @@ type Config struct { // BaseURL is OmniLogger's base URL, e.g. "http://omnilogger:8090". // Required. BaseURL string - // IngestToken is the shared INGEST_TOKEN bearer secret OmniLogger - // requires (see OmniLogger/README.md). Required. + // IngestToken is this service's OmniLogger ingest token: a per-service + // bearer secret an administrator creates in OmniLogger and bound to + // Service (see OmniLogger/README.md). OmniLogger rejects entries whose + // service differs from the token's bound service. Required. IngestToken string // Service is this process's service name as reported to OmniLogger, // e.g. "playhouse" or "outdoorgames-server-go". Required. @@ -152,10 +159,14 @@ type Shipper struct { logAll bool service string - url string - token string client *http.Client + // credMu guards url and token, which SetCredentials can replace while the Shipper runs. An empty + // url means shipping is disabled. + credMu sync.RWMutex + url string + token string + maxBatch int bufCap int @@ -201,8 +212,6 @@ func New(cfg Config) *Shipper { threshold: levelOf(cfg.Level), logAll: cfg.LogAll, service: cfg.Service, - url: strings.TrimRight(cfg.BaseURL, "/") + "/api/logs", - token: cfg.IngestToken, client: client, maxBatch: maxBatch, bufCap: bufCap, @@ -211,10 +220,53 @@ func New(cfg Config) *Shipper { doneCh: make(chan struct{}), } + s.SetCredentials(cfg.BaseURL, cfg.IngestToken) go s.loop(flushInterval) return s } +// SetCredentials sets where, and as which ingest token, the Shipper sends entries. It can be called at +// any time, for example when ProjectConfigurator pushes a new token, and takes effect from the next +// flush. An empty baseURL or token disables shipping: entries are no longer buffered, anything already +// buffered is discarded, and the local console output carries on as before. +func (s *Shipper) SetCredentials(baseURL, token string) { + token = strings.TrimSpace(token) + url := "" + if base := strings.TrimRight(strings.TrimSpace(baseURL), "/"); base != "" && token != "" { + url = base + "/api/logs" + } + s.credMu.Lock() + s.url = url + s.token = token + s.credMu.Unlock() + if url == "" { + s.mu.Lock() + s.buffer = nil + s.mu.Unlock() + } +} + +// Follow keeps the Shipper's endpoint and ingest token in step with ProjectConfigurator's pushes. A +// push that carries both an OmniLogger URL and an ingest token replaces the endpoint and token. Any other +// push, including the first one after a restart, leaves the current settings alone, so a service that was +// configured from its environment keeps shipping until ProjectConfigurator supplies both values. +func (s *Shipper) Follow(store *coreconfig.Store) { + apply := func(info coreconfig.Info) { + if info.OmniLoggerURL != "" && info.OmniLoggerIngestToken != "" { + s.SetCredentials(info.OmniLoggerURL, info.OmniLoggerIngestToken) + } + } + apply(store.Get()) + store.Subscribe(apply) +} + +// credentials returns the current endpoint and token. +func (s *Shipper) credentials() (url, token string) { + s.credMu.RLock() + defer s.credMu.RUnlock() + return s.url, s.token +} + func (s *Shipper) loop(flushInterval time.Duration) { defer close(s.doneCh) ticker := time.NewTicker(flushInterval) @@ -241,11 +293,41 @@ func (s *Shipper) requestFlush() { } } +// OmniLogger rejects a whole POST /api/logs batch when any one entry breaks its limits, so every +// entry is clamped to them before it is buffered. These mirror OmniLogger's MaxMessageBytes and +// MaxContextBytes; a message is cut with a marker, and an oversized or unshippable context is dropped +// and replaced with a marker object, so the entry itself still reaches OmniLogger. +const ( + maxMessageBytes = 8 * 1024 + maxContextBytes = 16 * 1024 + truncatedMarker = " [truncated]" + droppedContext = `{"context_dropped":true}` +) + +func clampEntry(e wireEntry) wireEntry { + if len(e.Message) > maxMessageBytes { + cut := maxMessageBytes - len(truncatedMarker) + for cut > 0 && !utf8.RuneStart(e.Message[cut]) { + cut-- + } + e.Message = e.Message[:cut] + truncatedMarker + } + // OmniLogger refuses a NUL in context, which json.Marshal writes as \u0000. + if len(e.Context) > maxContextBytes || bytes.Contains(e.Context, []byte(`\u0000`)) { + e.Context = json.RawMessage(droppedContext) + } + return e +} + // enqueue appends one entry to the buffer, dropping the incoming entry // (rather than blocking the caller or evicting older entries) once the // buffer is full. This is the sole non-blocking guarantee this package // makes: a caller's Debug/Info/... call never waits on network I/O. func (s *Shipper) enqueue(entry wireEntry) { + if url, _ := s.credentials(); url == "" { + return + } + entry = clampEntry(entry) s.mu.Lock() full := len(s.buffer) >= s.bufCap if !full { @@ -268,6 +350,7 @@ func (s *Shipper) enqueue(entry wireEntry) { // design: a host application must never fail, panic, or slow down because // its log sink is unreachable. func (s *Shipper) flush() { + url, token := s.credentials() s.mu.Lock() if len(s.buffer) == 0 { s.mu.Unlock() @@ -276,34 +359,129 @@ func (s *Shipper) flush() { batch := s.buffer s.buffer = nil s.mu.Unlock() - - body, err := json.Marshal(batch) - if err != nil { - s.warnOnce(fmt.Errorf("logshipper: marshal batch: %w", err)) + if url == "" { return } + // A backlog can hold up to bufCap entries, far more than OmniLogger accepts in one request, so the + // buffer is sent as several requests, each within maxRequestEntries and maxRequestBytes. When a request + // fails for a reason that may pass (no connection, a server error, or too many requests), the failed + // entries and everything after them go back to the buffer and are sent again on the next flush. A request + // OmniLogger rejects outright is dropped, because sending it again would fail the same way. + for _, chunk := range encodeBatches(batch) { + if s.send(url, token, chunk.payload, chunk.entries) { + s.requeue(batch[chunk.start:]) + return + } + } +} + +// Request limits for one POST /api/logs. OmniLogger refuses a request with more than 1000 entries or a +// body over 2 MiB, and it refuses the whole request when one entry is out of bounds, so every request +// stays well inside both. +const ( + maxRequestEntries = 100 + maxRequestBytes = 1 << 20 +) + +type encodedBatch struct { + payload []byte + entries int + // start is the index in the flushed batch of this request's first entry. + start int +} + +// encodeBatches marshals each entry once and packs the results into JSON array bodies, starting a new +// body when the current one reaches maxRequestEntries or would pass maxRequestBytes. An entry that +// cannot be marshaled is dropped, so one bad entry never blocks the rest. +func encodeBatches(batch []wireEntry) []encodedBatch { + var out []encodedBatch + var body bytes.Buffer + count := 0 + start := 0 + closeBody := func() { + if count == 0 { + return + } + body.WriteByte(']') + out = append(out, encodedBatch{payload: append([]byte(nil), body.Bytes()...), entries: count, start: start}) + body.Reset() + count = 0 + } + for i, entry := range batch { + raw, err := json.Marshal(entry) + if err != nil { + continue + } + if count > 0 && (count >= maxRequestEntries || body.Len()+len(raw)+2 > maxRequestBytes) { + closeBody() + } + if count == 0 { + body.WriteByte('[') + start = i + } else { + body.WriteByte(',') + } + body.Write(raw) + count++ + } + closeBody() + return out +} + +// requeue puts entries that failed to send back at the front of the buffer, so the next flush sends them +// before newer entries. The buffer stays within bufCap: when the requeued entries and the buffer do not all +// fit, the newest entries are dropped, as enqueue drops them when the buffer is full. +func (s *Shipper) requeue(entries []wireEntry) { + s.mu.Lock() + combined := make([]wireEntry, 0, len(entries)+len(s.buffer)) + combined = append(combined, entries...) + combined = append(combined, s.buffer...) + dropped := 0 + if len(combined) > s.bufCap { + dropped = len(combined) - s.bufCap + combined = combined[:s.bufCap] + } + s.buffer = combined + s.mu.Unlock() + if dropped > 0 { + s.warnOnce(fmt.Errorf("logshipper: buffer full while retrying, dropping %d log entries for service %q", dropped, s.service)) + } +} + +// send posts one encoded batch and reports whether it failed for a reason that may pass, in which case the +// caller keeps the entries for a later retry. A request OmniLogger rejects is reported and dropped. Failures are +// otherwise swallowed by design: a host application must never fail, panic, or slow down because its log sink +// is unreachable. +func (s *Shipper) send(url, token string, body []byte, entries int) (retry bool) { ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout) defer cancel() - req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.url, bytes.NewReader(body)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { s.warnOnce(fmt.Errorf("logshipper: build request: %w", err)) - return + return false } req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+s.token) + req.Header.Set("Authorization", "Bearer "+token) resp, err := s.client.Do(req) if err != nil { - s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s: %w", len(batch), s.url, err)) - return + s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s, will retry: %w", entries, url, err)) + return true } defer resp.Body.Close() - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - s.warnOnce(fmt.Errorf("logshipper: OmniLogger rejected %d entries: HTTP %d", len(batch), resp.StatusCode)) + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return false } + retry = resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 + if retry { + s.warnOnce(fmt.Errorf("logshipper: OmniLogger answered HTTP %d for %d entries, will retry", resp.StatusCode, entries)) + } else { + s.warnOnce(fmt.Errorf("logshipper: OmniLogger rejected %d entries: HTTP %d", entries, resp.StatusCode)) + } + return retry } // warnOnce prints a local stderr warning at most once per minute, no matter @@ -350,7 +528,7 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) { } now := time.Now() msg := formatArgs(args) - upper, lower := sevName(sev) + upper, _ := sevName(sev) line := fmt.Sprintf("[%s] [%s] [%s] [%s] %s", now.Format("2006-01-02"), now.Format("15:04:05.000"), upper, s.module, msg) @@ -368,10 +546,26 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) { } } - // Unlike the local-only verbose dump above (which scrubs IDs for - // readability), the context shipped to OmniLogger is sent unscrubbed: - // the whole point of centralizing logs is cross-service correlation by - // request/user/entity ID, so stripping IDs here would defeat that. + s.shipEntry(sev, ctx, msg, now) +} + +// Ship queues one entry for OmniLogger at severity sev without printing it locally. Use it where the host +// already prints its own lines, such as a zap or slog core that tees to OmniLogger: the console is not +// doubled, and the entry keeps its real severity, where Writer ships everything as info. The threshold +// applies. Context is sent unscrubbed, as in emit. +func (s *Shipper) Ship(sev Level, ctx map[string]any, args ...any) { + if sev < s.threshold { + return + } + s.shipEntry(sev, ctx, formatArgs(args), time.Now()) +} + +// shipEntry buffers one already-formatted entry for OmniLogger. +func (s *Shipper) shipEntry(sev Level, ctx map[string]any, msg string, now time.Time) { + _, lower := sevName(sev) + // The context shipped to OmniLogger is sent unscrubbed: the whole point of centralizing logs is + // cross-service correlation by request/user/entity ID, so stripping IDs here would defeat that. Only + // the local verbose dump scrubs them. var rawCtx json.RawMessage if ctx != nil { if b, err := json.Marshal(ctx); err == nil { @@ -383,10 +577,64 @@ func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) { Level: lower, Message: msg, Context: rawCtx, - OccurredAt: now, + OccurredAt: now.UTC().Truncate(time.Millisecond), }) } +// Writer returns an io.Writer that ships every non-empty line written to it to OmniLogger for this +// Shipper's service. It prints nothing locally, so it is meant to be paired with the console writer, e.g. +// log.SetOutput(io.MultiWriter(os.Stderr, shipper.Writer())), which keeps the existing stdout/stderr +// output and mirrors the lines to OmniLogger. The standard library log package carries no severity, so +// each line's level comes from InferLevel. Where a host knows the real level, use Ship instead. +func (s *Shipper) Writer() io.Writer { + return lineWriter{s: s} +} + +type lineWriter struct { + s *Shipper +} + +func (w lineWriter) Write(p []byte) (int, error) { + now := time.Now() + for _, line := range strings.Split(string(p), "\n") { + line = strings.TrimRight(line, "\r") + if strings.TrimSpace(line) == "" { + continue + } + sev := InferLevel(line) + if sev < w.s.threshold { + continue + } + w.s.shipEntry(sev, nil, line, now) + } + return len(p), nil +} + +// severityRules are checked in order, and the first rule whose words appear in a line sets its level. +// Each word matches as a whole word, case-insensitively. +var severityRules = []struct { + level Level + pattern *regexp.Regexp +}{ + {LevelCritical, regexp.MustCompile(`(?i)\b(panic|fatal|critical)\b`)}, + {LevelError, regexp.MustCompile(`(?i)\b(error|errors|failed|failure|failures|could not|cannot|unable to)\b`)}, + {LevelWarn, regexp.MustCompile(`(?i)\b(warn|warning|skipped|unavailable|retry|retrying|timed out|timeout)\b`)}, +} + +// InferLevel guesses the severity of a plain text line from its wording, for hosts whose logging carries no +// level, such as the standard library log package. Words such as "panic" or "fatal" give critical; "error", +// "failed", "could not", and "cannot" give error; "warning", "skipped", "unavailable", "retry", and "timeout" +// give warn; any other line is info. A line that mentions an error without failing, such as "no errors +// found", is classified as an error too. Use Ship where the real level is known. +func InferLevel(line string) Level { + for _, rule := range severityRules { + if rule.pattern.MatchString(line) { + return rule.level + } + } + return LevelInfo +} + func formatArgs(args []any) string { parts := make([]string, 0, len(args)) for _, a := range args { diff --git a/shared/backend/logshipper/shipper_test.go b/shared/backend/logshipper/shipper_test.go index 1c4dda8..6f31ee9 100644 --- a/shared/backend/logshipper/shipper_test.go +++ b/shared/backend/logshipper/shipper_test.go @@ -11,6 +11,9 @@ import ( "sync" "testing" "time" + "unicode/utf8" + + "repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig" ) // captureStd runs fn with os.Stdout and os.Stderr redirected, and returns what it wrote to each. @@ -83,6 +86,9 @@ func newTestShipper(t *testing.T, cfg Config) *Shipper { if cfg.BaseURL == "" { cfg.BaseURL = newIngest(t, http.StatusAccepted).server.URL } + if cfg.IngestToken == "" { + cfg.IngestToken = "test-token" + } return New(cfg) } @@ -274,7 +280,7 @@ func TestAFailingSinkNeverFailsTheCallerAndWarnsOnlyOnce(t *testing.T) { shipper.Info("two") shipper.Flush() }) - if strings.Count(stderr, "OmniLogger rejected") != 1 { + if strings.Count(stderr, "answered HTTP 500") != 1 { t.Fatalf("stderr = %q, want one rate-limited warning", stderr) } @@ -298,3 +304,383 @@ func TestNewAppliesDefaults(t *testing.T) { t.Fatalf("defaults not applied: %+v", shipper) } } + +func TestWriterShipsEachNonEmptyLineAsInfoWithoutPrintingLocally(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL}) + defer shipper.Close() + + stdout, stderr := captureStd(t, func() { + n, err := shipper.Writer().Write([]byte("first line\r\n\nsecond line\n")) + if err != nil || n != len("first line\r\n\nsecond line\n") { + t.Fatalf("Write = %d, %v", n, err) + } + shipper.Flush() + }) + if stdout != "" || stderr != "" { + t.Fatalf("Writer printed locally: stdout=%q stderr=%q", stdout, stderr) + } + entries := in.entries() + if len(entries) != 2 { + t.Fatalf("shipped %d entries, want 2: %+v", len(entries), entries) + } + if entries[0].Message != "first line" || entries[1].Message != "second line" { + t.Fatalf("messages = %q, %q", entries[0].Message, entries[1].Message) + } + for _, e := range entries { + if e.Service != "svc" || e.Level != "info" { + t.Fatalf("entry = %+v, want service svc at level info", e) + } + } +} + +func TestWriterRespectsTheThreshold(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"}) + defer shipper.Close() + + _, _ = shipper.Writer().Write([]byte("quiet line\n")) + shipper.Flush() + if n := len(in.entries()); n != 0 { + t.Fatalf("shipped %d entries below the threshold", n) + } +} + +func TestClampEntryKeepsEveryEntryInsideOmniLoggerLimits(t *testing.T) { + long := strings.Repeat("é", maxMessageBytes) // 2 bytes per rune, so the cut must land on a rune boundary + got := clampEntry(wireEntry{Message: long}) + if len(got.Message) > maxMessageBytes || !strings.HasSuffix(got.Message, truncatedMarker) { + t.Fatalf("message length %d, want at most %d and ending in the marker", len(got.Message), maxMessageBytes) + } + if !utf8.ValidString(got.Message) { + t.Fatal("truncation split a UTF-8 rune") + } + + big := json.RawMessage(`{"blob":"` + strings.Repeat("x", maxContextBytes) + `"}`) + if string(clampEntry(wireEntry{Context: big}).Context) != droppedContext { + t.Fatal("oversized context was not replaced by the dropped marker") + } + nul := json.RawMessage(`{"s":"a\u0000b"}`) + if string(clampEntry(wireEntry{Context: nul}).Context) != droppedContext { + t.Fatal("context with a NUL escape was not replaced by the dropped marker") + } + small := json.RawMessage(`{"ok":true}`) + if string(clampEntry(wireEntry{Context: small}).Context) != `{"ok":true}` { + t.Fatal("ordinary context was changed") + } +} + +func TestNoTokenMeansShippingIsDisabled(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + shipper := New(Config{Service: "svc", BaseURL: in.server.URL, FlushInterval: time.Hour}) + defer shipper.Close() + + shipper.Info("not shipped") + shipper.Flush() + if n := len(in.entries()); n != 0 { + t.Fatalf("shipped %d entries without a token", n) + } +} + +func TestSetCredentialsEnablesAndDisablesShippingAtRuntime(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + shipper := New(Config{Service: "svc", FlushInterval: time.Hour}) + defer shipper.Close() + + shipper.Info("before credentials") + shipper.SetCredentials(in.server.URL+"/", "pushed-token") + shipper.Info("after credentials") + shipper.Flush() + entries := in.entries() + if len(entries) != 1 || entries[0].Message != "after credentials" { + t.Fatalf("entries after enabling = %+v, want only the one logged after SetCredentials", entries) + } + in.mu.Lock() + gotAuth := in.auth + in.mu.Unlock() + if len(gotAuth) != 1 || !strings.HasSuffix(gotAuth[0], "Bearer pushed-token") || !strings.HasPrefix(gotAuth[0], "POST /api/logs") { + t.Fatalf("request = %q, want a bearer-authenticated POST /api/logs", gotAuth) + } + + shipper.SetCredentials(in.server.URL, "") + shipper.Info("after disabling") + shipper.Flush() + if n := len(in.entries()); n != 1 { + t.Fatalf("shipped %d entries after shipping was disabled, want still 1", n) + } +} + +func TestFollowAppliesOnlyPushesThatCarryAToken(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + store := coreconfig.NewStore(coreconfig.Info{}) + shipper := New(Config{Service: "svc", FlushInterval: time.Hour, BaseURL: in.server.URL, IngestToken: "env-token"}) + defer shipper.Close() + shipper.Follow(store) + + // A push that only moves other URLs must not disable the env-configured shipper. + store.Set(coreconfig.Info{AuthGuardURL: "https://auth.example.com"}) + shipper.Info("still shipping") + shipper.Flush() + if n := len(in.entries()); n != 1 { + t.Fatalf("a push without a token changed shipping: %d entries", n) + } + + pushed := newIngest(t, http.StatusAccepted) + store.Set(coreconfig.Info{OmniLoggerURL: pushed.server.URL, OmniLoggerIngestToken: "pushed-token"}) + shipper.Info("to the pushed endpoint") + shipper.Flush() + if n := len(pushed.entries()); n != 1 { + t.Fatalf("pushed endpoint received %d entries, want 1", n) + } + if n := len(in.entries()); n != 1 { + t.Fatalf("old endpoint still received entries after the push: %d", n) + } +} + +// A backlog larger than one request allows is split so no request exceeds the entry or byte cap. +func TestFlushSplitsABacklogIntoBoundedRequests(t *testing.T) { + var mu sync.Mutex + var counts []int + var sizes []int + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var batch []wireEntry + body := new(strings.Builder) + _, _ = io.Copy(body, r.Body) + _ = json.Unmarshal([]byte(body.String()), &batch) + mu.Lock() + counts = append(counts, len(batch)) + sizes = append(sizes, body.Len()) + mu.Unlock() + w.WriteHeader(http.StatusAccepted) + })) + t.Cleanup(server.Close) + + shipper := New(Config{Service: "svc", BaseURL: server.URL, IngestToken: "t", FlushInterval: time.Hour, BufferCapacity: 2000, MaxBatchSize: 2000}) + defer shipper.Close() + big := strings.Repeat("y", maxMessageBytes) + for i := 0; i < 300; i++ { + shipper.Info("small") + } + for i := 0; i < 200; i++ { + shipper.Info(big) + } + shipper.Flush() + + mu.Lock() + defer mu.Unlock() + total := 0 + for i, n := range counts { + total += n + if n > maxRequestEntries { + t.Fatalf("request %d carried %d entries, want at most %d", i, n, maxRequestEntries) + } + if sizes[i] > maxRequestBytes { + t.Fatalf("request %d was %d bytes, want at most %d", i, sizes[i], maxRequestBytes) + } + } + if total != 500 { + t.Fatalf("shipped %d entries, want all 500", total) + } +} + +// Ship sends at the given severity and prints nothing locally, so a host that already prints its own lines +// is not doubled. +func TestShipKeepsTheSeverityAndPrintsNothingLocally(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "info"}) + defer shipper.Close() + + stdout, stderr := captureStd(t, func() { + shipper.Ship(LevelError, map[string]any{"request_id": "r1"}, "boom") + shipper.Ship(LevelDebug, nil, "below the threshold") + shipper.Flush() + }) + if stdout != "" || stderr != "" { + t.Fatalf("Ship printed locally: stdout=%q stderr=%q", stdout, stderr) + } + entries := in.entries() + if len(entries) != 1 || entries[0].Level != "error" || entries[0].Message != "boom" { + t.Fatalf("entries = %+v, want one error entry", entries) + } + if !strings.Contains(string(entries[0].Context), `"request_id":"r1"`) { + t.Fatalf("context = %s, want the request id", entries[0].Context) + } +} + +func TestFollowIgnoresAPushWithATokenButNoURL(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + store := coreconfig.NewStore(coreconfig.Info{}) + shipper := New(Config{Service: "svc", FlushInterval: time.Hour, BaseURL: in.server.URL, IngestToken: "env-token"}) + defer shipper.Close() + shipper.Follow(store) + + store.Set(coreconfig.Info{OmniLoggerIngestToken: "orphan-token"}) + shipper.Info("still configured from the environment") + shipper.Flush() + if n := len(in.entries()); n != 1 { + t.Fatalf("a token without a URL disabled the env-configured shipper: %d entries", n) + } +} + +func TestInferLevelReadsTheWordingOfPlainLines(t *testing.T) { + cases := map[string]Level{ + "listening on :8080": LevelInfo, + "minted an OmniLogger ingest token for mediaviewer": LevelInfo, + "push login-required to x failed: status 401": LevelError, + "ERROR: database unreachable": LevelError, + "could not open the fixture": LevelError, + "push core service info to x skipped: unreadable": LevelWarn, + "WARNING: disk nearly full": LevelWarn, + "retrying in 5s after a timeout": LevelWarn, + "panic: runtime error": LevelCritical, + "fatal: cannot start": LevelCritical, + "warning: request failed": LevelError, + } + for line, want := range cases { + if got := InferLevel(line); got != want { + t.Errorf("InferLevel(%q) = %v, want %v", line, got, want) + } + } +} + +// Writer keeps each line's inferred severity, so an error line is not shipped as info. +func TestWriterKeepsTheInferredSeverityOfEachLine(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL}) + defer shipper.Close() + + _, _ = shipper.Writer().Write([]byte("listening on :8080\npush to x failed: boom\nretry skipped\n")) + shipper.Flush() + entries := in.entries() + if len(entries) != 3 { + t.Fatalf("shipped %d entries, want 3", len(entries)) + } + want := []string{"info", "error", "warn"} + for i, e := range entries { + if e.Level != want[i] { + t.Errorf("entry %d (%q) level = %s, want %s", i, e.Message, e.Level, want[i]) + } + } +} + +// Writer respects the threshold per line: warnings are dropped when the threshold is error. +func TestWriterDropsLinesBelowTheThreshold(t *testing.T) { + in := newIngest(t, http.StatusAccepted) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, Level: "error"}) + defer shipper.Close() + + _, _ = shipper.Writer().Write([]byte("hello\nfailed hard\n")) + shipper.Flush() + entries := in.entries() + if len(entries) != 1 || entries[0].Level != "error" { + t.Fatalf("entries = %+v, want only the error line", entries) + } +} + +// flakyIngest fails its first `failures` requests with the given status, then accepts every request, and +// counts the entries it accepted. +type flakyIngest struct { + mu sync.Mutex + failures int + status int + accepted []string + server *httptest.Server +} + +func newFlakyIngest(t *testing.T, failures, status int) *flakyIngest { + t.Helper() + in := &flakyIngest{failures: failures, 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() + defer in.mu.Unlock() + if in.failures > 0 { + in.failures-- + w.WriteHeader(in.status) + return + } + for _, e := range batch { + in.accepted = append(in.accepted, e.Message) + } + w.WriteHeader(http.StatusAccepted) + })) + t.Cleanup(in.server.Close) + return in +} + +func (in *flakyIngest) messages() []string { + in.mu.Lock() + defer in.mu.Unlock() + return append([]string(nil), in.accepted...) +} + +// A server error is retried on a later flush, and each entry is delivered exactly once. +func TestRetriesAServerErrorAndDeliversEachEntryOnce(t *testing.T) { + in := newFlakyIngest(t, 1, http.StatusServiceUnavailable) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, IngestToken: "t"}) + defer shipper.Close() + + captureStd(t, func() { + shipper.Info("a") + shipper.Info("b") + shipper.Flush() // refused with 503: kept for retry + shipper.Flush() // accepted + shipper.Flush() // nothing left to send + }) + got := in.messages() + if len(got) != 2 || got[0] != "a" || got[1] != "b" { + t.Fatalf("delivered %v, want a and b exactly once, in order", got) + } +} + +// A request OmniLogger rejects with 4xx is dropped, not retried, because it would fail the same way again. +func TestDropsARejectedRequestWithoutRetrying(t *testing.T) { + in := newFlakyIngest(t, 1, http.StatusBadRequest) + shipper := newTestShipper(t, Config{Service: "svc", BaseURL: in.server.URL, IngestToken: "t"}) + defer shipper.Close() + + captureStd(t, func() { + shipper.Info("rejected") + shipper.Flush() + shipper.Flush() + }) + if got := in.messages(); len(got) != 0 { + t.Fatalf("accepted %v after a 400, want nothing", got) + } + shipper.mu.Lock() + pending := len(shipper.buffer) + shipper.mu.Unlock() + if pending != 0 { + t.Fatalf("a rejected request stayed in the buffer: %d entries", pending) + } +} + +// Entries that cannot be sent while OmniLogger is unreachable wait in the buffer, and the buffer never grows +// past its capacity. +func TestRetryKeepsTheBufferWithinItsCapacity(t *testing.T) { + in := newFlakyIngest(t, 0, http.StatusAccepted) + url := in.server.URL + in.server.Close() + shipper := New(Config{Service: "svc", BaseURL: url, IngestToken: "t", FlushInterval: time.Hour, BufferCapacity: 3, MaxBatchSize: 100}) + defer shipper.Close() + + captureStd(t, func() { + for _, m := range []string{"a", "b", "c"} { + shipper.Info(m) + } + shipper.Flush() // unreachable: kept + for _, m := range []string{"d", "e"} { + shipper.Info(m) + } + shipper.Flush() // still unreachable; the buffer holds at most three entries + }) + shipper.mu.Lock() + defer shipper.mu.Unlock() + if len(shipper.buffer) > 3 { + t.Fatalf("buffer holds %d entries, capacity is 3", len(shipper.buffer)) + } + if len(shipper.buffer) != 3 || shipper.buffer[0].Message != "a" { + t.Fatalf("buffer = %+v, want the oldest three entries first", shipper.buffer) + } +} diff --git a/shared/packages/java-backend/README.md b/shared/packages/java-backend/README.md index b3cde2c..32f65af 100644 --- a/shared/packages/java-backend/README.md +++ b/shared/packages/java-backend/README.md @@ -6,6 +6,7 @@ Shared account-management, TOTP, admin reset-code, and AuthGuard client primitiv - `Totp` - RFC 6238 TOTP secret generation, provisioning URIs, and verification; - `ResetManager` - a short-lived, one-time admin reset-code primitive printed to the server console; - `AuthClient` - a client for a centralized AuthGuard instance's `GET /api/session/validate`, for services that want one shared identity instead of their own local user table. Mirrors `shared/backend/authclient` (Go) and `shared/packages/node-backend/src/authclient.js` (Node) - keep the three in sync if any of them changes shape. Additive: no project is wired up to use it just because this class exists. `setBaseUrl(url)` retargets an existing client's AuthGuard URL in place - the natural target for a ProjectConfigurator core-services push handler - so a client can be constructed with `new AuthClient("")` (usable right away, failing closed with `IllegalStateException` until a real URL arrives) rather than needing one known up front. Unlike the Go/Python/Node siblings, this package has no `coreconfig` module of its own: MegaBasterd, its only consumer, wires the `PUT /api/core-services/internal` route directly against a plain field holding the current `AuthGuardUrl`. +- `LogShipper` (`com.gabriel20xx.shared.logs`) - the client shipper for OmniLogger, the central log sink. It batches entries and POSTs them to `{OMNILOGGER_URL}/api/logs` from a daemon thread. `LogShipper.fromEnv(service)` returns null unless both `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are set, so shipping stays off by default. Mirrors `shared/backend/logshipper` (Go) - keep the two in sync. Additive: it never prints, so the consumer's own logger remains the console output. JDK only (Java 8, `HttpURLConnection`). ## How this package is actually consumed diff --git a/shared/packages/java-backend/src/main/java/com/gabriel20xx/shared/logs/LogShipper.java b/shared/packages/java-backend/src/main/java/com/gabriel20xx/shared/logs/LogShipper.java new file mode 100644 index 0000000..9872d26 --- /dev/null +++ b/shared/packages/java-backend/src/main/java/com/gabriel20xx/shared/logs/LogShipper.java @@ -0,0 +1,752 @@ +package com.gabriel20xx.shared.logs; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; + +/** + * Client-side shipper for OmniLogger, the workspace's central log sink. + * + *

This is the Java port of {@code shared/backend/logshipper/shipper.go}. Keep the two in sync: the + * limits, the wire format and the level names all come from the shared OmniLogger log-shipping contract. + * The class batches entries in memory and POSTs them to {@code {OMNILOGGER_URL}/api/logs} from a daemon + * thread. It never writes to the console, so a service keeps its existing logger and mirrors each line + * into {@link #log(Level, String)}. Nothing here throws, blocks the caller on the network, or exits the + * process because OmniLogger is unreachable or misconfigured. + * + *

Deliberate differences from the Go reference: + *

+ */ +public final class LogShipper implements AutoCloseable { + + /** Environment variable holding OmniLogger's base URL, for example {@code http://omnilogger:8080}. */ + public static final String ENV_URL = "OMNILOGGER_URL"; + /** Environment variable holding this service's OmniLogger ingest bearer token. */ + public static final String ENV_TOKEN = "OMNILOGGER_INGEST_TOKEN"; + + static final int MAX_MESSAGE_BYTES = 8 * 1024; + static final int MAX_CONTEXT_BYTES = 16 * 1024; + static final int MAX_BATCH_ENTRIES = 1000; + /** A request body must stay under 2 MiB, so the limit is one byte below that. */ + static final int MAX_BODY_BYTES = 2 * 1024 * 1024 - 1; + static final String TRUNCATED_MARKER = " [truncated]"; + static final String DROPPED_CONTEXT = "{\"context_dropped\":true}"; + + private static final long DEFAULT_FLUSH_INTERVAL_MILLIS = 2_000L; + private static final int DEFAULT_MAX_BATCH_SIZE = 100; + private static final int DEFAULT_BUFFER_CAPACITY = 2_000; + private static final int HTTP_TIMEOUT_MILLIS = 5_000; + private static final int HTTP_TOO_MANY_REQUESTS = 429; + private static final long WARN_INTERVAL_MILLIS = 60_000L; + private static final int MAX_CONTEXT_DEPTH = 32; + private static final int MAX_DRAINED_RESPONSE_BYTES = 64 * 1024; + + private static final DateTimeFormatter TIMESTAMP = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT).withZone(ZoneOffset.UTC); + private static final DateTimeFormatter WARN_TIME = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT); + private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); + + /** Severity scale. Names and aliases follow the shared LOG vocabulary; the wire names are OmniLogger's. */ + public enum Level { + DEBUG(10, "debug"), + INFO(20, "info"), + WARN(30, "warn"), + ERROR(40, "error"), + CRITICAL(50, "critical"), + /** Threshold only: suppresses everything. An entry is never logged at this level. */ + SILENT(100, null); + + private final int severity; + private final String wireName; + + Level(int severity, String wireName) { + this.severity = severity; + this.wireName = wireName; + } + + /** The lowercase level name OmniLogger's ingest API expects, or null for {@link #SILENT}. */ + public String wireName() { + return wireName; + } + + /** + * Parses a threshold such as a LOG env value. Matching is trimmed and case-insensitive. Unknown or + * empty input means {@link #INFO}. + */ + public static Level parse(String value) { + String normalized = value == null ? "" : value.trim().toLowerCase(Locale.ROOT); + switch (normalized) { + case "debug": + return DEBUG; + case "warn": + case "warning": + return WARN; + case "error": + return ERROR; + case "critical": + return CRITICAL; + case "silent": + case "none": + case "off": + return SILENT; + default: + return INFO; + } + } + + /** + * Maps a java.util.logging level: SEVERE becomes error, WARNING becomes warn, INFO becomes info, and + * anything finer becomes debug. JUL has no critical level, so nothing maps to critical. + */ + public static Level fromJavaUtilLogging(java.util.logging.Level level) { + if (level == null) { + return INFO; + } + int value = level.intValue(); + if (value >= java.util.logging.Level.SEVERE.intValue()) { + return ERROR; + } + if (value >= java.util.logging.Level.WARNING.intValue()) { + return WARN; + } + if (value >= java.util.logging.Level.INFO.intValue()) { + return INFO; + } + return DEBUG; + } + } + + /** + * Builds a shipper from {@code OMNILOGGER_URL} and {@code OMNILOGGER_INGEST_TOKEN}, with threshold INFO. + * + * @return the shipper, or null when either variable is unset or blank. A null result means shipping is + * disabled, and the service must behave exactly as it did without it. + */ + public static LogShipper fromEnv(String service) { + return fromEnv(service, Level.INFO); + } + + /** Like {@link #fromEnv(String)}, with an explicit threshold. */ + public static LogShipper fromEnv(String service, Level threshold) { + return fromEnv(service, threshold, name -> System.getenv(name)); + } + + /** + * Like {@link #fromEnv(String, Level)}, but reads the variables through {@code environment}. Pass a + * lookup such as {@code name -> map.get(name)} to make the disabled path testable. + */ + public static LogShipper fromEnv(String service, Level threshold, Function environment) { + String url = trimOrEmpty(environment.apply(ENV_URL)); + String token = trimOrEmpty(environment.apply(ENV_TOKEN)); + if (url.isEmpty() || token.isEmpty()) { + return null; + } + return new LogShipper(url, token, service, threshold); + } + + /** Creates a shipper that sends entries at INFO and above, flushing every 2 seconds. */ + public LogShipper(String baseUrl, String ingestToken, String service) { + this(baseUrl, ingestToken, service, Level.INFO); + } + + /** Creates a shipper with the given threshold. It starts its background flush thread immediately. */ + public LogShipper(String baseUrl, String ingestToken, String service, Level threshold) { + this(baseUrl, ingestToken, service, threshold, DEFAULT_FLUSH_INTERVAL_MILLIS, + DEFAULT_MAX_BATCH_SIZE, DEFAULT_BUFFER_CAPACITY); + } + + LogShipper(String baseUrl, String ingestToken, String service, Level threshold, + long flushIntervalMillis, int maxBatchSize, int bufferCapacity) { + this.credentials = credentialsFor(baseUrl, ingestToken); + this.service = service == null ? "" : service; + this.threshold = threshold == null ? Level.INFO : threshold; + this.maxBatchSize = maxBatchSize > 0 ? maxBatchSize : DEFAULT_MAX_BATCH_SIZE; + this.bufferCapacity = bufferCapacity > 0 ? bufferCapacity : DEFAULT_BUFFER_CAPACITY; + this.executor = Executors.newSingleThreadScheduledExecutor(daemonThreads("logshipper-" + this.service)); + long interval = flushIntervalMillis > 0 ? flushIntervalMillis : DEFAULT_FLUSH_INTERVAL_MILLIS; + this.executor.scheduleWithFixedDelay(this::runScheduledFlush, interval, interval, TimeUnit.MILLISECONDS); + } + + /** The endpoint and bearer token in use, or null while shipping is disabled. See {@link #setCredentials}. */ + private volatile Credentials credentials; + private final Object credentialsLock = new Object(); + private final String service; + private final Level threshold; + private final int maxBatchSize; + private final int bufferCapacity; + /** Encoded entries waiting to be sent, oldest first. Guarded by bufferLock, which is never held across I/O. */ + private final ArrayDeque buffer = new ArrayDeque<>(); + private final Object bufferLock = new Object(); + private final ScheduledExecutorService executor; + private final AtomicBoolean flushQueued = new AtomicBoolean(false); + private final AtomicBoolean closed = new AtomicBoolean(false); + private final Object warnLock = new Object(); + private boolean warned; + private long lastWarnAtMillis; + + /** Logs {@code message} at {@code level}. Never blocks on the network. */ + public void log(Level level, String message) { + log(level, message, null); + } + + /** + * Logs {@code message} with an optional structured {@code context}. The context must be a map of + * strings to plain values (strings, numbers, booleans, null, maps, iterables and arrays). Other values + * are sent as their {@code toString()}. The context is not scrubbed. + */ + public void log(Level level, String message, Map context) { + if (level == null || level == Level.SILENT || level.severity < threshold.severity || closed.get() + || credentials == null) { + return; + } + try { + String clampedMessage = clampMessage(String.valueOf(message)); + String entry = encodeEntry(service, level.wireName(), clampedMessage, clampContext(context), + TIMESTAMP.format(Instant.now())); + byte[] bytes = entry.getBytes(StandardCharsets.UTF_8); + boolean full; + int size; + synchronized (bufferLock) { + full = buffer.size() >= bufferCapacity; + if (!full) { + buffer.addLast(bytes); + } + size = buffer.size(); + } + if (full) { + warnOnce("buffer full (cap=" + bufferCapacity + "), dropping log entries for service \"" + + service + "\""); + return; + } + if (size >= maxBatchSize) { + requestFlush(); + } + } catch (RuntimeException ex) { + // Logging must never fail the caller. + warnOnce("could not queue an entry: " + ex); + } + } + + public void debug(String message) { + log(Level.DEBUG, message, null); + } + + public void info(String message) { + log(Level.INFO, message, null); + } + + public void warn(String message) { + log(Level.WARN, message, null); + } + + public void error(String message) { + log(Level.ERROR, message, null); + } + + public void critical(String message) { + log(Level.CRITICAL, message, null); + } + + /** + * Synchronously sends everything buffered when the call starts, in requests of at most 1000 entries and 2 MiB. + * When a request fails for a reason that may pass, its entries and every later entry of this flush go back to + * the front of the buffer, and the rest of the flush waits for the next one. A request OmniLogger rejects is + * dropped. Failures never reach the caller, only a rate-limited warning on stderr. Calls are serialized with the + * background flush. + */ + public synchronized void flush() { + Credentials target = credentials; + List batch = takeBuffered(); + if (target == null || batch.isEmpty()) { + return; + } + int start = 0; + while (start < batch.size()) { + int end = batchEnd(batch, start); + if (post(target, batch.subList(start, end))) { + requeue(batch.subList(start, batch.size())); + return; + } + start = end; + } + } + + /** + * Replaces the OmniLogger base URL and ingest token, as ProjectConfigurator pushes them. The next flush uses the new + * values. A blank base URL or token disables shipping: nothing more is buffered, and anything already buffered is + * dropped. The background flusher keeps running in every case, so this never restarts it. Safe to call from any + * thread, and it never waits for a flush in progress. + */ + public void setCredentials(String baseUrl, String ingestToken) { + synchronized (credentialsLock) { + Credentials next = credentialsFor(baseUrl, ingestToken); + credentials = next; + if (next == null) { + synchronized (bufferLock) { + buffer.clear(); + } + } + } + } + + /** + * Stops the background thread after a final flush of whatever is buffered. Call it during graceful + * shutdown. Closing again is a no-op, and entries logged after close are discarded. + */ + @Override + public void close() { + if (!closed.compareAndSet(false, true)) { + return; + } + executor.shutdown(); + flush(); + } + + private void runScheduledFlush() { + try { + flush(); + } catch (RuntimeException ex) { + // Never let one failed flush cancel the periodic task. + warnOnce("flush failed: " + ex); + } + } + + /** Asks the background thread to flush soon. The request is dropped if one is already pending. */ + private void requestFlush() { + if (!flushQueued.compareAndSet(false, true)) { + return; + } + try { + executor.execute(() -> { + flushQueued.set(false); + runScheduledFlush(); + }); + } catch (RejectedExecutionException ex) { + flushQueued.set(false); + } + } + + /** Removes and returns every buffered entry, oldest first. */ + private List takeBuffered() { + synchronized (bufferLock) { + List taken = new ArrayList<>(buffer); + buffer.clear(); + return taken; + } + } + + /** + * Returns the index just past the last entry of the request that starts at {@code start}. A request holds at + * most MAX_BATCH_ENTRIES entries and a body of at most MAX_BODY_BYTES, and always at least one entry. + */ + private static int batchEnd(List entries, int start) { + int bodyBytes = 2; + int end = start; + while (end < entries.size() && end - start < MAX_BATCH_ENTRIES) { + int added = entries.get(end).length + (end == start ? 0 : 1); + if (end > start && bodyBytes + added > MAX_BODY_BYTES) { + break; + } + bodyBytes += added; + end++; + } + return end; + } + + /** + * Puts entries that failed to send back at the front of the buffer, so the next flush sends them before newer + * entries. The buffer stays within its capacity: when the entries and the buffer do not all fit, the newest are + * dropped, as {@link #log(Level, String, Map)} drops them when the buffer is full. + */ + private void requeue(List entries) { + int dropped = 0; + synchronized (bufferLock) { + for (int i = entries.size() - 1; i >= 0; i--) { + buffer.addFirst(entries.get(i)); + } + while (buffer.size() > bufferCapacity) { + buffer.removeLast(); + dropped++; + } + } + if (dropped > 0) { + warnOnce("buffer full while retrying, dropping " + dropped + " log entries for service \"" + + service + "\""); + } + } + + /** + * Sends one request and reports whether it failed for a reason that may pass, in which case the caller keeps + * the entries for a later flush. An IO error, HTTP 429 or any 5xx is retried. Any other non-2xx status is a + * rejection, which is warned about and dropped without a retry. + */ + private boolean post(Credentials target, List entries) { + byte[] body = joinJsonArray(entries); + try { + HttpURLConnection connection = (HttpURLConnection) new URL(target.endpoint).openConnection(); + connection.setRequestMethod("POST"); + connection.setInstanceFollowRedirects(false); + connection.setUseCaches(false); + connection.setConnectTimeout(HTTP_TIMEOUT_MILLIS); + connection.setReadTimeout(HTTP_TIMEOUT_MILLIS); + connection.setDoOutput(true); + connection.setFixedLengthStreamingMode(body.length); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Bearer " + target.token); + try (OutputStream out = connection.getOutputStream()) { + out.write(body); + } + int status = connection.getResponseCode(); + drain(connection, status); + if (status >= 200 && status < 300) { + return false; + } + if (status == HTTP_TOO_MANY_REQUESTS || status >= 500) { + warnOnce("OmniLogger answered HTTP " + status + " for " + entries.size() + " entries, will retry"); + return true; + } + warnOnce("OmniLogger rejected " + entries.size() + " entries: HTTP " + status); + return false; + } catch (MalformedURLException ex) { + // The request cannot be built, and sending it again would fail the same way. + warnOnce("could not build the request for " + entries.size() + " entries: " + ex); + return false; + } catch (IOException ex) { + warnOnce("send " + entries.size() + " entries to " + target.endpoint + ", will retry: " + ex); + return true; + } catch (RuntimeException ex) { + warnOnce("send " + entries.size() + " entries to " + target.endpoint + ": " + ex); + return false; + } + } + + /** + * Reads a bounded part of the response so the connection can be reused, then closes it. This is best effort: + * the status is already known, so a failed read must not turn an accepted request into a retry. + */ + private static void drain(HttpURLConnection connection, int status) { + try { + InputStream in = status >= 200 && status < 300 ? connection.getInputStream() : connection.getErrorStream(); + if (in == null) { + return; + } + try (InputStream stream = in) { + byte[] buffer = new byte[1024]; + int remaining = MAX_DRAINED_RESPONSE_BYTES; + while (remaining > 0 && stream.read(buffer) != -1) { + remaining -= buffer.length; + } + } + } catch (IOException ignored) { + // Nothing more to do: the status has already been read. + } + } + + /** Prints a local stderr warning at most once a minute, so an unreachable OmniLogger cannot spam logs. */ + private void warnOnce(String message) { + synchronized (warnLock) { + long now = System.currentTimeMillis(); + if (warned && now - lastWarnAtMillis < WARN_INTERVAL_MILLIS) { + return; + } + warned = true; + lastWarnAtMillis = now; + } + System.err.println("[" + WARN_TIME.format(LocalDateTime.now()) + "] [logshipper] " + message); + } + + // ---- Limits and encoding. Package-private so the tests can check them directly. ---- + + /** + * Cuts a message longer than 8192 UTF-8 bytes on a code point boundary and appends the truncation marker. + * The result is at most 8192 bytes. + */ + static String clampMessage(String message) { + if (utf8Length(message) <= MAX_MESSAGE_BYTES) { + return message; + } + int budget = MAX_MESSAGE_BYTES - TRUNCATED_MARKER.length(); + int used = 0; + int end = 0; + while (end < message.length()) { + int codePoint = message.codePointAt(end); + int bytes = utf8Bytes(codePoint); + if (used + bytes > budget) { + break; + } + used += bytes; + end += Character.charCount(codePoint); + } + return message.substring(0, end) + TRUNCATED_MARKER; + } + + /** + * Serializes the context to JSON. It is replaced by {@link #DROPPED_CONTEXT} when it is over 16384 bytes + * or contains an escaped NUL. It is omitted (null) when it cannot be encoded at all, for example because it + * holds NaN or is nested too deeply. + */ + static String clampContext(Map context) { + if (context == null) { + return null; + } + String json; + try { + StringBuilder builder = new StringBuilder(); + writeValue(builder, context, 0); + json = builder.toString(); + } catch (RuntimeException ex) { + return null; + } + if (utf8Length(json) > MAX_CONTEXT_BYTES || json.contains("\\u0000")) { + return DROPPED_CONTEXT; + } + return json; + } + + /** Encodes one OmniLogger entry. The field order matches the Go reference's wire struct. */ + static String encodeEntry(String service, String level, String message, String contextJson, String occurredAt) { + StringBuilder builder = new StringBuilder(message.length() + 128); + builder.append("{\"service\":"); + writeString(builder, service); + builder.append(",\"level\":"); + writeString(builder, level); + builder.append(",\"message\":"); + writeString(builder, message); + if (contextJson != null) { + builder.append(",\"context\":").append(contextJson); + } + builder.append(",\"occurred_at\":"); + writeString(builder, occurredAt); + return builder.append('}').toString(); + } + + static byte[] joinJsonArray(List entries) { + int size = 2 + Math.max(0, entries.size() - 1); + for (byte[] entry : entries) { + size += entry.length; + } + byte[] body = new byte[size]; + int position = 0; + body[position++] = '['; + for (int i = 0; i < entries.size(); i++) { + if (i > 0) { + body[position++] = ','; + } + byte[] entry = entries.get(i); + System.arraycopy(entry, 0, body, position, entry.length); + position += entry.length; + } + body[position] = ']'; + return body; + } + + /** + * Counts UTF-8 bytes the way the encoder writes them. A lone surrogate is written as U+FFFD, which is three + * bytes. + */ + static int utf8Length(String value) { + int length = 0; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c < 0x80) { + length += 1; + } else if (c < 0x800) { + length += 2; + } else if (Character.isHighSurrogate(c) && i + 1 < value.length() + && Character.isLowSurrogate(value.charAt(i + 1))) { + length += 4; + i++; + } else { + length += 3; + } + } + return length; + } + + private static int utf8Bytes(int codePoint) { + if (codePoint < 0x80) { + return 1; + } + if (codePoint < 0x800) { + return 2; + } + return codePoint < 0x10000 ? 3 : 4; + } + + /** + * Writes a JSON string literal. Quotes, backslashes and control characters are escaped, and so are lone + * surrogates (written as U+FFFD). Everything else is written as-is, so the output is valid UTF-8 JSON. + */ + private static void writeString(StringBuilder out, String value) { + out.append('"'); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + switch (c) { + case '"': + out.append("\\\""); + break; + case '\\': + out.append("\\\\"); + break; + case '\n': + out.append("\\n"); + break; + case '\r': + out.append("\\r"); + break; + case '\t': + out.append("\\t"); + break; + case '\b': + out.append("\\b"); + break; + case '\f': + out.append("\\f"); + break; + default: + if (c < 0x20) { + out.append("\\u00").append(HEX_DIGITS[c >> 4]).append(HEX_DIGITS[c & 0xF]); + } else if (Character.isHighSurrogate(c)) { + if (i + 1 < value.length() && Character.isLowSurrogate(value.charAt(i + 1))) { + out.append(c).append(value.charAt(++i)); + } else { + out.append("\\ufffd"); + } + } else if (Character.isLowSurrogate(c)) { + out.append("\\ufffd"); + } else { + out.append(c); + } + } + } + out.append('"'); + } + + private static void writeValue(StringBuilder out, Object value, int depth) { + if (depth > MAX_CONTEXT_DEPTH) { + throw new IllegalArgumentException("context is nested too deeply"); + } + if (value == null) { + out.append("null"); + } else if (value instanceof String) { + writeString(out, (String) value); + } else if (value instanceof Boolean || value instanceof Integer || value instanceof Long + || value instanceof Short || value instanceof Byte + || value instanceof BigInteger || value instanceof BigDecimal) { + out.append(value.toString()); + } else if (value instanceof Double || value instanceof Float) { + double number = ((Number) value).doubleValue(); + if (Double.isNaN(number) || Double.isInfinite(number)) { + throw new IllegalArgumentException("non-finite number in context"); + } + out.append(value.toString()); + } else if (value instanceof Map) { + out.append('{'); + boolean first = true; + for (Map.Entry entry : ((Map) value).entrySet()) { + if (!first) { + out.append(','); + } + first = false; + writeString(out, String.valueOf(entry.getKey())); + out.append(':'); + writeValue(out, entry.getValue(), depth + 1); + } + out.append('}'); + } else if (value instanceof Iterable) { + writeArray(out, ((Iterable) value).iterator(), depth); + } else if (value instanceof Object[]) { + writeArray(out, Arrays.asList((Object[]) value).iterator(), depth); + } else { + writeString(out, value.toString()); + } + } + + private static void writeArray(StringBuilder out, Iterator items, int depth) { + out.append('['); + boolean first = true; + while (items.hasNext()) { + if (!first) { + out.append(','); + } + first = false; + writeValue(out, items.next(), depth + 1); + } + out.append(']'); + } + + private static ThreadFactory daemonThreads(String name) { + return runnable -> { + Thread thread = new Thread(runnable, name); + thread.setDaemon(true); + return thread; + }; + } + + private static String trimOrEmpty(String value) { + return value == null ? "" : value.trim(); + } + + private static String trimTrailingSlashes(String value) { + int end = value.length(); + while (end > 0 && value.charAt(end - 1) == '/') { + end--; + } + return value.substring(0, end); + } + + /** The credentials for a base URL and token, or null when either is blank, which disables shipping. */ + private static Credentials credentialsFor(String baseUrl, String ingestToken) { + String base = trimTrailingSlashes(trimOrEmpty(baseUrl)); + String token = trimOrEmpty(ingestToken); + if (base.isEmpty() || token.isEmpty()) { + return null; + } + return new Credentials(base + "/api/logs", token); + } + + /** An endpoint and bearer token, read together so one flush never pairs an old URL with a new token. */ + private static final class Credentials { + final String endpoint; + final String token; + + Credentials(String endpoint, String token) { + this.endpoint = endpoint; + this.token = token; + } + } +} diff --git a/shared/packages/java-backend/src/test/java/com/gabriel20xx/shared/logs/LogShipperTest.java b/shared/packages/java-backend/src/test/java/com/gabriel20xx/shared/logs/LogShipperTest.java new file mode 100644 index 0000000..0008bb7 --- /dev/null +++ b/shared/packages/java-backend/src/test/java/com/gabriel20xx/shared/logs/LogShipperTest.java @@ -0,0 +1,833 @@ +package com.gabriel20xx.shared.logs; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.gabriel20xx.shared.logs.LogShipper.Level; +import com.sun.net.httpserver.HttpServer; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Covers LogShipper against a local com.sun.net.httpserver.HttpServer standing in for OmniLogger. Nothing here + * talks to a real OmniLogger. Mirrors the behaviour the Go reference's shipper_test.go checks. + */ +class LogShipperTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String OCCURRED_AT_PATTERN = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"; + /** Large enough that the 1-hour interval and the batch trigger never fire on their own in a test. */ + private static final long NEVER_MILLIS = 3_600_000L; + private static final int NO_AUTO_BATCH = 5_000; + private static final int DEFAULT_CAPACITY = 2_000; + + private final List shippers = new ArrayList<>(); + private FakeOmniLogger fake; + + @AfterEach + void tearDown() { + for (LogShipper shipper : shippers) { + shipper.close(); + } + shippers.clear(); + if (fake != null) { + fake.stop(); + fake = null; + } + } + + @Test + void levelParseAcceptsTheSharedLogVocabulary() { + assertEquals(Level.DEBUG, Level.parse("debug")); + assertEquals(Level.DEBUG, Level.parse(" DEBUG ")); + assertEquals(Level.INFO, Level.parse("info")); + assertEquals(Level.INFO, Level.parse("")); + assertEquals(Level.INFO, Level.parse(null)); + assertEquals(Level.INFO, Level.parse("bogus")); + assertEquals(Level.WARN, Level.parse("warn")); + assertEquals(Level.WARN, Level.parse("warning")); + assertEquals(Level.ERROR, Level.parse("error")); + assertEquals(Level.CRITICAL, Level.parse("critical")); + assertEquals(Level.SILENT, Level.parse("silent")); + assertEquals(Level.SILENT, Level.parse("none")); + assertEquals(Level.SILENT, Level.parse("off")); + } + + @Test + void wireNamesAreTheLowercaseNamesOmniLoggerExpects() { + assertEquals("debug", Level.DEBUG.wireName()); + assertEquals("info", Level.INFO.wireName()); + assertEquals("warn", Level.WARN.wireName()); + assertEquals("error", Level.ERROR.wireName()); + assertEquals("critical", Level.CRITICAL.wireName()); + assertNull(Level.SILENT.wireName()); + } + + @Test + void javaUtilLoggingLevelsMapOntoTheWireScale() { + assertEquals(Level.ERROR, Level.fromJavaUtilLogging(java.util.logging.Level.SEVERE)); + assertEquals(Level.WARN, Level.fromJavaUtilLogging(java.util.logging.Level.WARNING)); + assertEquals(Level.INFO, Level.fromJavaUtilLogging(java.util.logging.Level.INFO)); + assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.CONFIG)); + assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.FINE)); + assertEquals(Level.DEBUG, Level.fromJavaUtilLogging(java.util.logging.Level.FINEST)); + assertEquals(Level.INFO, Level.fromJavaUtilLogging(null)); + } + + @Test + void fromEnvIsDisabledUnlessBothVariablesAreNonBlank() { + assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(null, null)::get)); + assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080", null)::get)); + assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(null, "token")::get)); + assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env(" ", "token")::get)); + assertNull(LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080", " ")::get)); + + LogShipper shipper = LogShipper.fromEnv("megabasterd", Level.INFO, env("http://omni:8080/", "token")::get); + assertNotNull(shipper); + shipper.close(); + } + + @Test + void disabledModeWritesNothingToTheConsole() { + // With shipping disabled there is no shipper at all, so there is nothing that could print. A shipper + // created but pointed at a dead sink must still leave the console alone on every call. + String stderr = captureStderr(() -> { + LogShipper shipper = shipper("http://127.0.0.1:1", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + shipper.info("quiet"); + }); + assertEquals("", stderr); + } + + @Test + void entriesAreBatchedAndSentWithBearerAuthToTheIngestPath() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl() + "/", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + + captureStdout(() -> captureStderr(() -> { + shipper.info("one"); + shipper.warn("two"); + shipper.error("three"); + shipper.critical("four"); + })); + shipper.flush(); + + assertEquals(1, fake.requests().size(), "one flush of four entries is one request"); + Request request = fake.requests().get(0); + assertEquals("POST", request.method); + assertEquals("/api/logs", request.path); + assertEquals("Bearer secret", request.authorization); + assertEquals("application/json", request.contentType); + + List entries = fake.entries(); + assertEquals(4, entries.size()); + assertEquals("one", entries.get(0).get("message").asText()); + assertEquals("info", entries.get(0).get("level").asText()); + assertEquals("warn", entries.get(1).get("level").asText()); + assertEquals("error", entries.get(2).get("level").asText()); + assertEquals("critical", entries.get(3).get("level").asText()); + for (JsonNode entry : entries) { + assertEquals("megabasterd", entry.get("service").asText()); + assertTrue(entry.get("occurred_at").asText().matches(OCCURRED_AT_PATTERN), + "occurred_at must be RFC 3339 UTC with milliseconds: " + entry.get("occurred_at").asText()); + } + } + + @Test + void flushWithNothingBufferedSendsNoSecondRequest() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + shipper.info("only"); + + shipper.flush(); + shipper.flush(); + + assertEquals(1, fake.requests().size()); + } + + @Test + void theBackgroundThreadFlushesOnItsOwnInterval() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, 50L, NO_AUTO_BATCH, DEFAULT_CAPACITY); + + shipper.info("without an explicit flush"); + + waitUntil(() -> fake.entries().size() == 1); + } + + @Test + void reachingTheBatchSizeFlushesWithoutWaitingForTheInterval() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, 2, DEFAULT_CAPACITY); + + shipper.info("a"); + shipper.info("b"); + + waitUntil(() -> fake.entries().size() == 2); + } + + @Test + void closeDrainsTheBufferAndIsIdempotent() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + shipper.info("last words"); + + shipper.close(); + shipper.close(); + shipper.info("after close is discarded"); + shipper.flush(); + + List entries = fake.entries(); + assertEquals(1, entries.size()); + assertEquals("last words", entries.get(0).get("message").asText()); + } + + @Test + void thresholdFiltersEntriesBelowIt() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.WARN, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + + shipper.info("below"); + shipper.warn("at"); + shipper.flush(); + + List entries = fake.entries(); + assertEquals(1, entries.size()); + assertEquals("at", entries.get(0).get("message").asText()); + } + + @Test + void silentThresholdShipsNothing() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.SILENT, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + + shipper.critical("never shipped"); + shipper.flush(); + + assertTrue(fake.requests().isEmpty()); + } + + @Test + void loggingNeverWritesToTheLocalConsole() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.DEBUG, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + + String stdout = captureStdout(() -> captureStderr(() -> { + shipper.debug("d"); + shipper.info("i"); + shipper.warn("w"); + shipper.error("e"); + shipper.critical("c"); + })); + shipper.flush(); + + assertEquals("", stdout); + assertEquals(5, fake.entries().size()); + } + + @Test + void messagesWithSpecialCharactersStayValidJson() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + String message = "quote \" backslash \\ newline \n cr \r tab \t bell \u0007 nul \u0000 " + + "unit \u0001 unicode é emoji 😀 end"; + + shipper.info(message); + shipper.flush(); + + assertEquals(message, fake.entries().get(0).get("message").asText()); + } + + @Test + void structuredContextRoundTrips() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + Map context = new LinkedHashMap<>(); + context.put("userId", 7); + context.put("path", "/x\"y"); + context.put("ok", true); + context.put("ratio", 1.5); + context.put("none", null); + context.put("tags", java.util.Arrays.asList("a", "b")); + Map nested = new LinkedHashMap<>(); + nested.put("k", "v"); + context.put("nested", nested); + + shipper.log(Level.INFO, "with context", context); + shipper.flush(); + + JsonNode entryContext = fake.entries().get(0).get("context"); + assertEquals(7, entryContext.get("userId").asInt()); + assertEquals("/x\"y", entryContext.get("path").asText()); + assertTrue(entryContext.get("ok").asBoolean()); + assertEquals(1.5, entryContext.get("ratio").asDouble()); + assertTrue(entryContext.get("none").isNull()); + assertEquals("b", entryContext.get("tags").get(1).asText()); + assertEquals("v", entryContext.get("nested").get("k").asText()); + } + + @Test + void anUnencodableContextIsOmittedAndTheEntryStillShips() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + Map context = new HashMap<>(); + context.put("bad", Double.NaN); + + shipper.log(Level.INFO, "still here", context); + shipper.flush(); + + JsonNode entry = fake.entries().get(0); + assertEquals("still here", entry.get("message").asText()); + assertFalse(entry.has("context")); + } + + @Test + void anOversizedMessageIsClampedWithTheMarker() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + + shipper.info(repeat("a", 10_000)); + shipper.flush(); + + String message = fake.entries().get(0).get("message").asText(); + assertTrue(message.getBytes(StandardCharsets.UTF_8).length <= 8192); + assertTrue(message.endsWith(" [truncated]")); + } + + @Test + void aMultiByteMessageIsCutOnACharacterBoundary() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + // Two bytes per character, so the 8180-byte cut lands exactly on a character boundary here. + shipper.info(repeat("é", 8192)); + shipper.flush(); + + String message = fake.entries().get(0).get("message").asText(); + assertTrue(message.getBytes(StandardCharsets.UTF_8).length <= 8192); + assertTrue(message.endsWith(" [truncated]")); + assertFalse(message.contains("�"), "truncation must not split a UTF-8 character"); + } + + @Test + void clampMessageLeavesAShortMessageUntouched() { + assertEquals("short", LogShipper.clampMessage("short")); + String exactlyLimit = repeat("b", 8192); + assertEquals(exactlyLimit, LogShipper.clampMessage(exactlyLimit)); + } + + @Test + void anOversizedContextIsReplacedWithTheDroppedMarker() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + Map context = new HashMap<>(); + context.put("blob", repeat("x", 17_000)); + + shipper.log(Level.INFO, "big", context); + shipper.flush(); + + JsonNode entry = fake.entries().get(0); + assertEquals("big", entry.get("message").asText()); + assertTrue(entry.get("context").get("context_dropped").asBoolean()); + assertEquals(1, entry.get("context").size()); + } + + @Test + void aContextWithAnEscapedNulIsReplacedWithTheDroppedMarker() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + Map context = new HashMap<>(); + context.put("s", "a\u0000b"); + + shipper.log(Level.INFO, "nul", context); + shipper.flush(); + + assertTrue(fake.entries().get(0).get("context").get("context_dropped").asBoolean()); + } + + @Test + void clampContextKeepsAnOrdinaryContextAsItIs() { + Map context = new LinkedHashMap<>(); + context.put("ok", true); + assertEquals("{\"ok\":true}", LogShipper.clampContext(context)); + assertNull(LogShipper.clampContext(null)); + } + + @Test + void batchesNeverExceedOneThousandEntries() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3_000); + for (int i = 0; i < 1_500; i++) { + shipper.info("entry " + i); + } + + shipper.flush(); + + assertEquals(1_500, fake.entries().size()); + for (Request request : fake.requests()) { + assertTrue(JSON.readTree(request.body).size() <= 1_000); + } + } + + @Test + void batchesStayUnderTheRequestBodyLimit() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + // Control characters are escaped to six bytes each, so every entry is about 48 KiB on the wire. + String largeMessage = repeat("\u0001", 8192); + for (int i = 0; i < 60; i++) { + shipper.info(largeMessage); + } + + shipper.flush(); + + assertEquals(60, fake.entries().size()); + assertTrue(fake.requests().size() > 1, "60 entries of this size cannot fit one body under 2 MiB"); + for (Request request : fake.requests()) { + assertTrue(request.body.length < 2 * 1024 * 1024, "body is " + request.body.length + " bytes"); + } + assertEquals(8192, fake.entries().get(0).get("message").asText().length()); + } + + @Test + void anUnreachableOmniLoggerNeverThrowsAndWarnsOnce() throws Exception { + LogShipper shipper = shipper("http://127.0.0.1:1", Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + shipper.info("one"); + + String stderr = captureStderr(() -> { + shipper.flush(); + shipper.info("two"); + shipper.flush(); + }); + + assertEquals(1, countOccurrences(stderr, "[logshipper]")); + } + + @Test + void aRejectedBatchIsDroppedAndWarnedAboutOnce() throws Exception { + fake = new FakeOmniLogger(); + fake.setStatus(400); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + + String stderr = captureStderr(() -> { + shipper.info("one"); + shipper.flush(); + shipper.info("two"); + shipper.flush(); + }); + + assertEquals(1, countOccurrences(stderr, "OmniLogger rejected")); + assertEquals(2, fake.requests().size(), "rejected batches are not retried"); + } + + @Test + void aServerErrorIsRetriedAndEachEntryArrivesOnceInOrder() throws Exception { + fake = new FakeOmniLogger(); + fake.respondNext(503); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, DEFAULT_CAPACITY); + + String stderr = captureStderr(() -> { + shipper.info("a"); + shipper.info("b"); + shipper.flush(); // refused with 503: kept for the next flush + shipper.flush(); // accepted + shipper.flush(); // nothing left to send + }); + + assertEquals(1, countOccurrences(stderr, "will retry")); + assertEquals(2, fake.requests().size(), "the refused request is sent again, and nothing else is"); + List entries = fake.entries(); + assertEquals(2, entries.size()); + assertEquals("a", entries.get(0).get("message").asText()); + assertEquals("b", entries.get(1).get("message").asText()); + } + + @Test + void aFailedRequestEndsTheFlushAndTheRestWaitsForTheNextFlush() throws Exception { + fake = new FakeOmniLogger(); + fake.respondNext(202, 503); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3_000); + for (int i = 0; i < 1_500; i++) { + shipper.info("entry " + i); + } + + captureStderr(shipper::flush); // 1000 accepted, then 500 refused: the flush stops there + assertEquals(2, fake.requests().size()); + assertEquals(1_000, fake.entries().size()); + + shipper.flush(); + assertEquals(3, fake.requests().size()); + List entries = fake.entries(); + assertEquals(1_500, entries.size()); + for (int i = 0; i < entries.size(); i++) { + assertEquals("entry " + i, entries.get(i).get("message").asText()); + } + } + + @Test + void duringAnOutageTheBufferKeepsTheOldestEntriesUpToItsCapacity() throws Exception { + fake = new FakeOmniLogger(); + fake.setStatus(503); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3); + + captureStderr(() -> { + for (String message : new String[] {"a", "b", "c"}) { + shipper.info(message); + } + shipper.flush(); // refused with 503: kept for retry + shipper.info("d"); // the buffer is full, so d is dropped + shipper.info("e"); // and e is dropped + shipper.flush(); // still refused + }); + + fake.setStatus(202); + shipper.flush(); + + List entries = fake.entries(); + assertEquals(3, entries.size(), "the buffer held only its capacity"); + assertEquals("a", entries.get(0).get("message").asText()); + assertEquals("b", entries.get(1).get("message").asText()); + assertEquals("c", entries.get(2).get("message").asText()); + } + + @Test + void aFullBufferDropsTheNewestEntryAndWarnsOnce() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = shipper(fake.baseUrl(), Level.INFO, NEVER_MILLIS, NO_AUTO_BATCH, 3); + + String stderr = captureStderr(() -> { + for (int i = 0; i < 10; i++) { + shipper.info("m" + i); + } + }); + shipper.flush(); + + List entries = fake.entries(); + assertEquals(3, entries.size()); + assertEquals("m0", entries.get(0).get("message").asText()); + assertEquals("m2", entries.get(2).get("message").asText()); + assertEquals(1, countOccurrences(stderr, "buffer full")); + } + + @Test + void fromEnvShipsToTheConfiguredServiceAndToken() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = LogShipper.fromEnv("gamestream", Level.INFO, + env(fake.baseUrl(), "env-token")::get); + assertNotNull(shipper); + shippers.add(shipper); + + shipper.error("boom"); + shipper.flush(); + + assertEquals("Bearer env-token", fake.requests().get(0).authorization); + assertEquals("gamestream", fake.entries().get(0).get("service").asText()); + } + + @Test + void setCredentialsSendsTheNextFlushToTheNewEndpointAndToken() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = neverFlushing("http://127.0.0.1:1", "old-token"); + + shipper.setCredentials(fake.baseUrl() + "/", "new-token"); + shipper.info("after the push"); + shipper.flush(); + + assertEquals(1, fake.requests().size()); + assertEquals("/api/logs", fake.requests().get(0).path); + assertEquals("Bearer new-token", fake.requests().get(0).authorization); + assertEquals("after the push", fake.entries().get(0).get("message").asText()); + } + + @Test + void aBlankCredentialDisablesShippingAndDropsTheBuffer() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = neverFlushing(fake.baseUrl(), "token"); + shipper.info("buffered before the disable"); + + shipper.setCredentials("", "token"); + shipper.info("logged while disabled"); + shipper.flush(); + assertTrue(fake.requests().isEmpty()); + + shipper.setCredentials(fake.baseUrl(), " "); + shipper.info("logged with a blank token"); + shipper.flush(); + assertTrue(fake.requests().isEmpty()); + + shipper.setCredentials(fake.baseUrl(), "token"); + shipper.info("after re-enabling"); + shipper.flush(); + assertEquals(1, fake.requests().size()); + assertEquals("after re-enabling", fake.entries().get(0).get("message").asText()); + } + + @Test + void aShipperBuiltWithoutCredentialsStartsDisabled() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = neverFlushing(null, "token"); + + shipper.info("dropped"); + shipper.flush(); + + assertTrue(fake.requests().isEmpty()); + } + + @Test + void theBackgroundFlusherKeepsRunningAcrossCredentialChanges() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = new LogShipper("http://127.0.0.1:1", "token", "megabasterd", Level.INFO, + 50L, NO_AUTO_BATCH, DEFAULT_CAPACITY); + shippers.add(shipper); + shipper.setCredentials("", ""); + shipper.setCredentials(fake.baseUrl(), "token"); + + shipper.info("sent by the interval, with no explicit flush"); + + waitUntil(() -> !fake.requests().isEmpty()); + assertEquals("sent by the interval, with no explicit flush", + fake.entries().get(0).get("message").asText()); + } + + @Test + void concurrentCredentialChangesAreSafeAndTheLastValuesWin() throws Exception { + fake = new FakeOmniLogger(); + LogShipper shipper = neverFlushing(fake.baseUrl(), "token"); + ExecutorService pool = Executors.newFixedThreadPool(4); + try { + List> writers = new ArrayList<>(); + for (int t = 0; t < 4; t++) { + writers.add(pool.submit(() -> { + for (int i = 0; i < 200; i++) { + shipper.setCredentials(i % 2 == 0 ? "" : fake.baseUrl(), "token"); + shipper.info("noise"); + } + })); + } + for (Future writer : writers) { + writer.get(10, TimeUnit.SECONDS); + } + } finally { + pool.shutdownNow(); + } + + shipper.setCredentials(fake.baseUrl(), "final-token"); + shipper.info("final"); + shipper.flush(); + + List requests = fake.requests(); + assertFalse(requests.isEmpty()); + assertEquals("Bearer final-token", requests.get(requests.size() - 1).authorization); + List entries = fake.entries(); + assertEquals("final", entries.get(entries.size() - 1).get("message").asText()); + } + + private LogShipper neverFlushing(String baseUrl, String token) { + LogShipper shipper = new LogShipper(baseUrl, token, "megabasterd", Level.INFO, NEVER_MILLIS, + NO_AUTO_BATCH, DEFAULT_CAPACITY); + shippers.add(shipper); + return shipper; + } + + private static Map env(String url, String token) { + Map values = new HashMap<>(); + if (url != null) { + values.put(LogShipper.ENV_URL, url); + } + if (token != null) { + values.put(LogShipper.ENV_TOKEN, token); + } + return values; + } + + private LogShipper shipper(String baseUrl, Level threshold, long intervalMillis, int maxBatch, int capacity) { + LogShipper shipper = new LogShipper(baseUrl, "secret", "megabasterd", threshold, intervalMillis, maxBatch, capacity); + shippers.add(shipper); + return shipper; + } + + private static String repeat(String unit, int times) { + StringBuilder builder = new StringBuilder(unit.length() * times); + for (int i = 0; i < times; i++) { + builder.append(unit); + } + return builder.toString(); + } + + private static int countOccurrences(String haystack, String needle) { + int count = 0; + int index = haystack.indexOf(needle); + while (index >= 0) { + count++; + index = haystack.indexOf(needle, index + needle.length()); + } + return count; + } + + private static void waitUntil(BooleanSupplier condition) throws InterruptedException { + long deadline = System.currentTimeMillis() + 5_000L; + while (!condition.getAsBoolean()) { + if (System.currentTimeMillis() > deadline) { + fail("condition not met within 5 seconds"); + } + Thread.sleep(10L); + } + } + + private static String captureStderr(Runnable action) { + return capture(action, true); + } + + private static String captureStdout(Runnable action) { + return capture(action, false); + } + + private static String capture(Runnable action, boolean stderr) { + PrintStream original = stderr ? System.err : System.out; + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + PrintStream replacement = new PrintStream(buffer, true); + if (stderr) { + System.setErr(replacement); + } else { + System.setOut(replacement); + } + try { + action.run(); + } finally { + if (stderr) { + System.setErr(original); + } else { + System.setOut(original); + } + } + return new String(buffer.toByteArray(), StandardCharsets.UTF_8); + } + + /** One request received by the fake OmniLogger, and the status it answered with. */ + private static final class Request { + final String method; + final String path; + final String authorization; + final String contentType; + final byte[] body; + final int status; + + Request(String method, String path, String authorization, String contentType, byte[] body, int status) { + this.method = method; + this.path = path; + this.authorization = authorization; + this.contentType = contentType; + this.body = body; + this.status = status; + } + } + + /** A stand-in OmniLogger that records every POST to it. */ + private static final class FakeOmniLogger { + private final HttpServer server; + private final List requests = Collections.synchronizedList(new ArrayList()); + private final Deque nextStatuses = new ArrayDeque<>(); + private volatile int status = 202; + + FakeOmniLogger() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + byte[] body = readAll(exchange.getRequestBody()); + int answer = nextStatus(); + requests.add(new Request(exchange.getRequestMethod(), exchange.getRequestURI().getPath(), + exchange.getRequestHeaders().getFirst("Authorization"), + exchange.getRequestHeaders().getFirst("Content-Type"), body, answer)); + exchange.sendResponseHeaders(answer, -1); + exchange.close(); + }); + server.start(); + } + + String baseUrl() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + /** The status answered to every request that respondNext does not script. */ + void setStatus(int status) { + this.status = status; + } + + /** Answers the next requests with these statuses, in order, before the status from setStatus applies. */ + void respondNext(int... statuses) { + synchronized (nextStatuses) { + for (int answer : statuses) { + nextStatuses.addLast(answer); + } + } + } + + private int nextStatus() { + synchronized (nextStatuses) { + Integer scripted = nextStatuses.pollFirst(); + return scripted != null ? scripted : status; + } + } + + void stop() { + server.stop(0); + } + + List requests() { + synchronized (requests) { + return new ArrayList<>(requests); + } + } + + /** Every entry from every batch OmniLogger accepted so far, in arrival order. */ + List entries() { + List all = new ArrayList<>(); + for (Request request : requests()) { + if (request.status < 200 || request.status >= 300) { + continue; + } + try { + for (JsonNode entry : JSON.readTree(request.body)) { + all.add(entry); + } + } catch (IOException ex) { + throw new IllegalStateException("request body is not JSON: " + ex.getMessage(), ex); + } + } + return all; + } + + private static byte[] readAll(InputStream in) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return out.toByteArray(); + } + } +} diff --git a/shared/packages/node-backend/README.md b/shared/packages/node-backend/README.md index 7953308..c61d66f 100644 --- a/shared/packages/node-backend/README.md +++ b/shared/packages/node-backend/README.md @@ -7,7 +7,8 @@ Shared Node.js backend infrastructure for services that use PostgreSQL: - PBKDF2 password hashing (`verifyAndUpgradePasswordAsync` returns a current-scheme hash for a login to store) and secure session-token helpers; - short-lived, one-time admin reset codes printed to the server console; - common account/session persistence; -- transaction-locked ordered migrations. +- transaction-locked ordered migrations; +- OmniLogger log shipping: `createLogShipperFromEnv` (off unless `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` are both set), `LogShipper`, and `mirrorConsole`. The package does not depend on Express. Each service keeps its own routes, cookies, roles, validation policy, and domain repositories. Existing diff --git a/shared/packages/node-backend/src/index.js b/shared/packages/node-backend/src/index.js index 30f1691..ef1fd30 100644 --- a/shared/packages/node-backend/src/index.js +++ b/shared/packages/node-backend/src/index.js @@ -36,6 +36,7 @@ export { verifyTotpStep, } from './totp.js'; export { runMigrations } from './migrate.js'; +export { LOG_LEVELS, LogShipper, createLogShipperFromEnv, mirrorConsole } from './logshipper.js'; export { APIError, AuthClient, InvalidSessionError, createAuthClient } from './authclient.js'; export { EXAMPLE_INTERNAL_SECRETS, diff --git a/shared/packages/node-backend/src/logshipper.js b/shared/packages/node-backend/src/logshipper.js new file mode 100644 index 0000000..43229d8 --- /dev/null +++ b/shared/packages/node-backend/src/logshipper.js @@ -0,0 +1,361 @@ +// logshipper.js is the Node equivalent of shared/backend/logshipper (Go) and follows the same +// OmniLogger contract: it batches log entries and POSTs them to OmniLogger's /api/logs with the +// service's ingest token, so a service's existing logs also reach the central sink. +// +// It is a sink, not a logger. It never writes to the console itself: callers keep their +// console.* lines exactly as they are, and mirrorConsole() forwards each of those lines here as +// well. Shipping is off unless both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are set; +// createLogShipperFromEnv returns null otherwise, and nothing here ever throws into the caller. + +import { format } from 'node:util'; + +export const LOG_LEVELS = Object.freeze(['debug', 'info', 'warn', 'error', 'critical']); + +// Thresholds use the same numeric scale as internal/logging in the Go services. +const LEVEL_RANK = new Map([ + ['debug', 10], + ['info', 20], + ['warn', 30], + ['error', 40], + ['critical', 50], + ['silent', 100], +]); +const LEVEL_ALIASES = new Map([ + ['warning', 'warn'], + ['none', 'silent'], + ['off', 'silent'], +]); + +const DEFAULT_FLUSH_INTERVAL_MS = 2000; +const DEFAULT_MAX_BATCH_SIZE = 100; +const DEFAULT_BUFFER_CAPACITY = 2000; +const DEFAULT_TIMEOUT_MS = 5000; +const DEFAULT_WARN_INTERVAL_MS = 60_000; + +// OmniLogger rejects a whole batch when any entry breaks a limit, so each entry is clamped before +// it is buffered. It also caps a batch at 1000 entries and a request body under 2 MiB. +const MAX_MESSAGE_BYTES = 8 * 1024; +const MAX_CONTEXT_BYTES = 16 * 1024; +const MAX_BATCH_ENTRIES = 1000; +const MAX_BODY_BYTES = 1024 * 1024; // packing budget, well under OmniLogger's 2 MiB limit +const TRUNCATED_MARKER = ' [truncated]'; +const DROPPED_CONTEXT = '{"context_dropped":true}'; + +// The console methods that are mirrored, and the level each one ships at. console.log has no level +// of its own, so it ships at info. +const CONSOLE_LEVELS = [ + ['debug', 'debug'], + ['log', 'info'], + ['info', 'info'], + ['warn', 'warn'], + ['error', 'error'], +]; + +function canonicalLevel(name) { + const key = String(name ?? '') + .trim() + .toLowerCase(); + return LEVEL_ALIASES.get(key) ?? key; +} + +function positiveOr(value, fallback) { + return Number.isFinite(value) && value > 0 ? value : fallback; +} + +function clampMessage(message) { + if (Buffer.byteLength(message, 'utf8') <= MAX_MESSAGE_BYTES) return message; + const bytes = Buffer.from(message, 'utf8'); + let cut = MAX_MESSAGE_BYTES - Buffer.byteLength(TRUNCATED_MARKER); + // Cut on a UTF-8 character boundary: a continuation byte (10xxxxxx) starts no character. + while (cut > 0 && (bytes[cut] & 0xc0) === 0x80) cut -= 1; + return bytes.subarray(0, cut).toString('utf8') + TRUNCATED_MARKER; +} + +// serializeContext returns the context as JSON text, or undefined when there is none to send. +// A context that cannot be serialized is omitted; one that breaks a limit is replaced by a marker, +// so the entry itself still reaches OmniLogger. +function serializeContext(context) { + if (Object.prototype.toString.call(context) !== '[object Object]') return undefined; + let json; + try { + json = JSON.stringify(context); + } catch { + return undefined; + } + if (json === undefined) return undefined; + if (Buffer.byteLength(json, 'utf8') > MAX_CONTEXT_BYTES || json.includes('\\u0000')) return DROPPED_CONTEXT; + return json; +} + +// packBatches splits serialized entries into request bodies of at most maxEntries entries and +// MAX_BODY_BYTES bytes each. A flush can hold more than one batch's worth of entries when +// OmniLogger was slow, so the split keeps every request inside OmniLogger's limits. +function packBatches(entries, maxEntries) { + const batches = []; + let batch = []; + let bytes = 2; // the enclosing brackets + for (const entry of entries) { + const entryBytes = Buffer.byteLength(entry, 'utf8'); + const separator = batch.length === 0 ? 0 : 1; + if (batch.length > 0 && (batch.length >= maxEntries || bytes + separator + entryBytes > MAX_BODY_BYTES)) { + batches.push(batch); + batch = []; + bytes = 2; + } + bytes += (batch.length === 0 ? 0 : 1) + entryBytes; + batch.push(entry); + } + if (batch.length > 0) batches.push(batch); + return batches; +} + +function defaultWarning(text) { + process.stderr.write(`[${new Date().toISOString()}] ${text}\n`); +} + +// LogShipper batches entries in memory and sends them to OmniLogger in the background. Its methods +// never throw and never wait on the network, and it never prints anything itself except a +// rate-limited warning when OmniLogger cannot be reached. +export class LogShipper { + #service; + #url; + #token; + #threshold; + #flushIntervalMs; + #maxBatchSize; + #bufferCapacity; + #timeoutMs; + #warnIntervalMs; + #onWarning; + + #buffer = []; // serialized wire entries, oldest first + #timer; + #chain = Promise.resolve(); // sends run one at a time, in the order they were requested + #flushRequested = false; + #closed = false; + #lastWarnAt = null; + + constructor({ + baseUrl = '', + ingestToken = '', + service = '', + level = 'info', + flushIntervalMs = DEFAULT_FLUSH_INTERVAL_MS, + maxBatchSize = DEFAULT_MAX_BATCH_SIZE, + bufferCapacity = DEFAULT_BUFFER_CAPACITY, + timeoutMs = DEFAULT_TIMEOUT_MS, + warnIntervalMs = DEFAULT_WARN_INTERVAL_MS, + onWarning = defaultWarning, + } = {}) { + this.#service = String(service); + this.#url = `${String(baseUrl).replace(/\/+$/, '')}/api/logs`; + this.#token = String(ingestToken); + this.#threshold = LEVEL_RANK.get(canonicalLevel(level)) ?? LEVEL_RANK.get('info'); + this.#flushIntervalMs = positiveOr(flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS); + this.#maxBatchSize = Math.min( + MAX_BATCH_ENTRIES, + Math.max(1, Math.floor(positiveOr(maxBatchSize, DEFAULT_MAX_BATCH_SIZE))), + ); + this.#bufferCapacity = Math.max(1, Math.floor(positiveOr(bufferCapacity, DEFAULT_BUFFER_CAPACITY))); + this.#timeoutMs = positiveOr(timeoutMs, DEFAULT_TIMEOUT_MS); + this.#warnIntervalMs = positiveOr(warnIntervalMs, DEFAULT_WARN_INTERVAL_MS); + this.#onWarning = typeof onWarning === 'function' ? onWarning : defaultWarning; + + this.#timer = setInterval(() => this.#requestFlush(), this.#flushIntervalMs); + this.#timer.unref(); + } + + debug(...args) { + this.#emit('debug', args); + } + + info(...args) { + this.#emit('info', args); + } + + warn(...args) { + this.#emit('warn', args); + } + + error(...args) { + this.#emit('error', args); + } + + critical(...args) { + this.#emit('critical', args); + } + + // log queues one entry. An optional context object is sent as the entry's context. + log(level, message, context) { + try { + this.#record(level, String(message), context); + } catch { + // Shipping must never fail the caller. + } + } + + // flush sends everything buffered so far. It resolves once those sends have finished, and it + // never rejects. + flush() { + return this.#send(); + } + + // close drains the buffer and stops the periodic flush. Entries logged after close are dropped. + async close() { + this.#closed = true; + clearInterval(this.#timer); + await this.#send(); + } + + #emit(level, args) { + try { + this.#record(level, format(...args)); + } catch { + // Shipping must never fail the caller. + } + } + + #record(level, message, context) { + if (this.#closed) return; + const name = LOG_LEVELS.includes(canonicalLevel(level)) ? canonicalLevel(level) : 'info'; + if (LEVEL_RANK.get(name) < this.#threshold) return; + + if (this.#buffer.length >= this.#bufferCapacity) { + this.#warnOnce(`buffer full (cap=${this.#bufferCapacity}), dropping log entries for service "${this.#service}"`); + return; + } + + // Each field is serialized on its own so the context can be spliced in as raw JSON. + const fields = [ + `"service":${JSON.stringify(this.#service)}`, + `"level":${JSON.stringify(name)}`, + `"message":${JSON.stringify(clampMessage(message))}`, + ]; + const contextJson = serializeContext(context); + if (contextJson !== undefined) fields.push(`"context":${contextJson}`); + fields.push(`"occurred_at":${JSON.stringify(new Date().toISOString())}`); + this.#buffer.push(`{${fields.join(',')}}`); + + if (this.#buffer.length >= this.#maxBatchSize) this.#requestFlush(); + } + + // requestFlush asks for a flush without waiting for it. A request made while one is already + // pending is dropped, so a burst of log calls queues at most one extra send. + #requestFlush() { + if (this.#flushRequested) return; + this.#flushRequested = true; + void this.#send(); + } + + #send() { + this.#chain = this.#chain.then(() => this.#sendBuffered()).catch(() => {}); + return this.#chain; + } + + async #sendBuffered() { + this.#flushRequested = false; + if (this.#buffer.length === 0) return; + const entries = this.#buffer; + this.#buffer = []; + + let settled = 0; // entries of this flush that were sent or dropped + for (const batch of packBatches(entries, this.#maxBatchSize)) { + const retry = await this.#post(batch); + // A batch that may pass on a later attempt keeps itself and every later entry for the next + // flush. The rest of this flush is not sent now, so the entries still go out in order. + if (retry) { + this.#requeue(entries.slice(settled)); + return; + } + settled += batch.length; + } + } + + // requeue puts entries that failed to send back at the front of the buffer, so the next flush + // sends them before anything logged since. The buffer never grows past its capacity: when the + // waiting entries and the buffer do not all fit, the newest entries are dropped. + #requeue(entries) { + const combined = [...entries, ...this.#buffer]; + const dropped = Math.max(0, combined.length - this.#bufferCapacity); + this.#buffer = combined.slice(0, this.#bufferCapacity); + if (dropped > 0) { + this.#warnOnce(`buffer full while retrying, dropping ${dropped} log entries for service "${this.#service}"`); + } + } + + // post sends one batch and reports whether it must be sent again. That is true when no HTTP + // response came back, or the response was 429 or 5xx: those failures may pass. Any other non-2xx + // response is OmniLogger rejecting the batch, which a retry would not change, so it is warned + // about and dropped. + async #post(batch) { + const count = batch.length; + let response; + try { + response = await globalThis.fetch(this.#url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.#token}`, + }, + body: `[${batch.join(',')}]`, + signal: AbortSignal.timeout(this.#timeoutMs), + }); + } catch (err) { + const detail = err?.cause?.code ?? err?.message ?? String(err); + this.#warnOnce(`send ${count} entries to ${this.#url}, will retry: ${detail}`); + return true; + } + // Read the body so the connection can be reused. A failure here does not change the outcome. + await response.arrayBuffer().catch(() => {}); + const { status } = response; + if (status >= 200 && status < 300) return false; + if (status === 429 || status >= 500) { + this.#warnOnce(`OmniLogger answered HTTP ${status} for ${count} entries, will retry`); + return true; + } + this.#warnOnce(`OmniLogger rejected ${count} entries: HTTP ${status}`); + return false; + } + + #warnOnce(text) { + const now = Date.now(); + if (this.#lastWarnAt !== null && now - this.#lastWarnAt < this.#warnIntervalMs) return; + this.#lastWarnAt = now; + try { + this.#onWarning(`[logshipper] ${text}`); + } catch { + // A broken warning sink must not fail the caller either. + } + } +} + +// createLogShipperFromEnv returns a LogShipper for service when both OMNILOGGER_URL and +// OMNILOGGER_INGEST_TOKEN are set and non-empty, and null otherwise. A null result means shipping +// is disabled: no shipper, no network calls, and no extra output. Options other than env are passed +// to the LogShipper constructor. +export function createLogShipperFromEnv(service, { env = process.env, ...options } = {}) { + const baseUrl = String(env.OMNILOGGER_URL ?? '').trim(); + const ingestToken = String(env.OMNILOGGER_INGEST_TOKEN ?? '').trim(); + if (!baseUrl || !ingestToken) return null; + return new LogShipper({ ...options, baseUrl, ingestToken, service }); +} + +// mirrorConsole forwards each console.debug/log/info/warn/error call to the shipper at its level, +// after printing the line exactly as before. It returns a function that restores the original +// console methods. Call it once per shipper, or lines ship twice. +export function mirrorConsole(shipper, target = globalThis.console) { + const originals = new Map(); + for (const [method, level] of CONSOLE_LEVELS) { + const original = target[method]; + if (typeof original !== 'function') continue; + originals.set(method, original); + target[method] = function mirrored(...args) { + const result = original.apply(target, args); + shipper[level](...args); + return result; + }; + } + return function restoreConsole() { + for (const [method, original] of originals) target[method] = original; + }; +} diff --git a/shared/packages/node-backend/test/logshipper.test.js b/shared/packages/node-backend/test/logshipper.test.js new file mode 100644 index 0000000..5673772 --- /dev/null +++ b/shared/packages/node-backend/test/logshipper.test.js @@ -0,0 +1,544 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { createServer } from 'node:http'; +import { createLogShipperFromEnv, LogShipper, mirrorConsole } from '../src/logshipper.js'; + +// startSink runs a local stand-in for OmniLogger that records every request it receives. The first +// requests get the answers in `statuses`, in order: a status code, or null to drop the connection +// without answering. Later requests get `status`. When `gate` is given, each answer waits for it. +async function startSink({ status = 202, statuses = [], gate } = {}) { + const requests = []; + const server = createServer((req, res) => { + const chunks = []; + req.on('data', (chunk) => chunks.push(chunk)); + req.on('end', async () => { + const answer = statuses.length > 0 ? statuses.shift() : status; + requests.push({ + method: req.method, + path: req.url, + authorization: req.headers.authorization, + contentType: req.headers['content-type'], + status: answer, + accepted: answer >= 200 && answer < 300, + body: JSON.parse(Buffer.concat(chunks).toString('utf8')), + }); + await gate; + if (answer === null) { + req.socket.destroy(); + return; + } + res.writeHead(answer, { 'Content-Type': 'text/plain' }); + res.end('ok'); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + return { + url: `http://127.0.0.1:${server.address().port}`, + requests, + // entries returns what OmniLogger accepted, in the order it was sent. + entries: () => requests.filter((request) => request.accepted).flatMap((request) => request.body), + close: async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + }, + }; +} + +async function waitFor(check) { + const deadline = Date.now() + 5000; + while (!check()) { + if (Date.now() > deadline) assert.fail('condition not met within 5s'); + await new Promise((resolve) => setTimeout(resolve, 10)); + } +} + +function shipperFor(sink, options = {}) { + return new LogShipper({ + baseUrl: sink.url, + ingestToken: 'secret', + service: 'svc', + flushIntervalMs: 60_000, + onWarning: () => {}, + ...options, + }); +} + +test('shipping is disabled unless both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are non-empty', async (t) => { + const sink = await startSink(); + t.after(() => sink.close()); + const envs = [ + {}, + { OMNILOGGER_URL: sink.url }, + { OMNILOGGER_INGEST_TOKEN: 'secret' }, + { OMNILOGGER_URL: '', OMNILOGGER_INGEST_TOKEN: 'secret' }, + { OMNILOGGER_URL: sink.url, OMNILOGGER_INGEST_TOKEN: ' ' }, + ]; + for (const env of envs) { + assert.equal(createLogShipperFromEnv('svc', { env }), null, JSON.stringify(env)); + } +}); + +test('a disabled service makes no calls and prints nothing extra', async (t) => { + const sink = await startSink(); + t.after(() => sink.close()); + const local = []; + const target = { log: (...args) => local.push(args) }; + const shipper = createLogShipperFromEnv('svc', { env: { OMNILOGGER_URL: sink.url } }); + if (shipper) mirrorConsole(shipper, target); + target.log('still local'); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(shipper, null); + assert.deepEqual(local, [['still local']]); + assert.equal(sink.requests.length, 0); +}); + +test('createLogShipperFromEnv ships to the trimmed URL with the token and service name', async (t) => { + const sink = await startSink(); + const shipper = createLogShipperFromEnv('mediadesktop', { + env: { OMNILOGGER_URL: ` ${sink.url}/ `, OMNILOGGER_INGEST_TOKEN: ' secret-token ' }, + flushIntervalMs: 60_000, + onWarning: () => {}, + }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + assert.ok(shipper instanceof LogShipper); + shipper.info('from env'); + await shipper.flush(); + assert.equal(sink.requests.length, 1); + assert.equal(sink.requests[0].authorization, 'Bearer secret-token'); + assert.equal(sink.requests[0].body[0].service, 'mediadesktop'); +}); + +test('posts to /api/logs with the ingest token as a bearer credential', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink, { baseUrl: `${sink.url}///`, ingestToken: 'secret-token' }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + shipper.warn('hello'); + await shipper.flush(); + const [request] = sink.requests; + assert.equal(request.method, 'POST'); + assert.equal(request.path, '/api/logs'); + assert.equal(request.authorization, 'Bearer secret-token'); + assert.equal(request.contentType, 'application/json'); +}); + +test('every entry carries the service name, a level and an RFC 3339 UTC timestamp', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink, { service: 'mediadesktop', level: 'debug' }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + shipper.debug('d'); + shipper.critical('c'); + await shipper.flush(); + const entries = sink.entries(); + assert.deepEqual( + entries.map((e) => [e.service, e.level]), + [ + ['mediadesktop', 'debug'], + ['mediadesktop', 'critical'], + ], + ); + for (const entry of entries) { + assert.match(entry.occurred_at, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/); + } +}); + +test('flush sends everything buffered in one request, in order', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + shipper.info('one'); + shipper.info('two'); + shipper.info('three'); + await shipper.flush(); + await shipper.flush(); // nothing left, so no second request + assert.equal(sink.requests.length, 1); + assert.deepEqual( + sink.requests[0].body.map((e) => e.message), + ['one', 'two', 'three'], + ); +}); + +test('the periodic interval sends entries without an explicit flush', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink, { flushIntervalMs: 20 }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + shipper.info('tick'); + await waitFor(() => sink.entries().length === 1); + assert.equal(sink.entries()[0].message, 'tick'); +}); + +test('reaching the batch size flushes ahead of the interval', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink, { maxBatchSize: 3 }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + shipper.info('a'); + shipper.info('b'); + await new Promise((resolve) => setTimeout(resolve, 50)); + assert.equal(sink.requests.length, 0, 'two entries are below the batch size'); + shipper.info('c'); + await waitFor(() => sink.requests.length === 1); + assert.deepEqual( + sink.requests[0].body.map((e) => e.message), + ['a', 'b', 'c'], + ); +}); + +test('a backlog larger than one batch is split into requests of at most the batch size', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink, { maxBatchSize: 2 }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + for (let i = 0; i < 5; i += 1) shipper.info(`m${i}`); + await shipper.flush(); + assert.ok(sink.requests.every((request) => request.body.length <= 2)); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['m0', 'm1', 'm2', 'm3', 'm4'], + ); +}); + +test('the level threshold gates entries, and its aliases and unknown names resolve', async (t) => { + const sink = await startSink(); + t.after(() => sink.close()); + const cases = [ + { service: 'warning-alias', level: 'warning', kept: ['warn', 'error', 'critical'] }, + { service: 'silent-alias', level: 'off', kept: [] }, + { service: 'unknown-name', level: 'bogus', kept: ['info', 'warn', 'error', 'critical'] }, + ]; + for (const { service, level, kept } of cases) { + const shipper = shipperFor(sink, { service, level }); + shipper.debug('debug'); + shipper.info('info'); + shipper.warn('warn'); + shipper.error('error'); + shipper.critical('critical'); + await shipper.close(); + const messages = sink + .entries() + .filter((e) => e.service === service) + .map((e) => e.message); + assert.deepEqual(messages, kept, `level ${level}`); + } +}); + +test('console calls are mirrored at their levels and still printed locally', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink, { level: 'debug' }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + const local = []; + const target = {}; + for (const method of ['debug', 'log', 'info', 'warn', 'error']) { + target[method] = (...args) => local.push([method, ...args]); + } + const originals = { ...target }; + + const restore = mirrorConsole(shipper, target); + target.debug('d'); + target.log('l', 1); + target.info('i'); + target.warn('w'); + target.error('e', { a: 1 }); + restore(); + assert.deepEqual(target, originals, 'restore puts the original methods back'); + + await shipper.flush(); + assert.deepEqual(local, [ + ['debug', 'd'], + ['log', 'l', 1], + ['info', 'i'], + ['warn', 'w'], + ['error', 'e', { a: 1 }], + ]); + assert.deepEqual( + sink.entries().map((e) => [e.level, e.message]), + [ + ['debug', 'd'], + ['info', 'l 1'], + ['info', 'i'], + ['warn', 'w'], + ['error', 'e { a: 1 }'], + ], + ); +}); + +test('a message over 8192 bytes is cut on a character boundary and marked', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + // Four-byte characters after one ASCII byte: the cut position falls inside a character. + const long = `a${'\u{1F600}'.repeat(3000)}`; + shipper.info(long); + shipper.info('short'); + await shipper.flush(); + const [clamped, short] = sink.entries().map((e) => e.message); + assert.ok(Buffer.byteLength(clamped, 'utf8') <= 8192); + assert.ok(clamped.endsWith(' [truncated]')); + assert.ok(!clamped.includes('�'), 'the cut split a character'); + assert.ok(long.startsWith(clamped.slice(0, -' [truncated]'.length))); + assert.equal(short, 'short'); +}); + +test('an oversized context or one with a NUL escape is replaced by the dropped marker', async (t) => { + const sink = await startSink(); + const shipper = shipperFor(sink); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + const fits = { blob: 'x'.repeat(16 * 1024 - JSON.stringify({ blob: '' }).length) }; + shipper.log('info', 'fits', fits); + shipper.log('info', 'too big', { blob: 'x'.repeat(16 * 1024) }); + shipper.log('info', 'nul', { s: 'a\u0000b' }); + shipper.log('info', 'small', { ok: true, n: 1 }); + shipper.log('info', 'no context'); + await shipper.flush(); + const [a, b, c, d, e] = sink.entries(); + assert.deepEqual(a.context, fits); + assert.deepEqual(b.context, { context_dropped: true }); + assert.deepEqual(c.context, { context_dropped: true }); + assert.deepEqual(d.context, { ok: true, n: 1 }); + assert.equal('context' in e, false); + assert.equal(b.message, 'too big'); +}); + +test('a full buffer drops new entries with one warning instead of blocking', async (t) => { + const sink = await startSink(); + const warnings = []; + const shipper = shipperFor(sink, { bufferCapacity: 3, onWarning: (text) => warnings.push(text) }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + for (let i = 0; i < 10; i += 1) shipper.info(`m${i}`); + await shipper.flush(); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['m0', 'm1', 'm2'], + ); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /buffer full/); +}); + +test('a 503 on the first send is retried, and each entry arrives exactly once and in order', async (t) => { + const sink = await startSink({ statuses: [503] }); + const shipper = shipperFor(sink); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + shipper.info('a'); + shipper.info('b'); + await shipper.flush(); // refused with 503, so both entries stay buffered + await shipper.flush(); // accepted + await shipper.flush(); // nothing left to send + assert.deepEqual( + sink.requests.map((request) => request.status), + [503, 202], + ); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['a', 'b'], + ); +}); + +test('a dropped connection is retried like a server error', async (t) => { + const sink = await startSink({ statuses: [null] }); + const shipper = shipperFor(sink); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + shipper.info('a'); + await shipper.flush(); // no response at all, so the entry stays buffered + await shipper.flush(); + assert.deepEqual( + sink.requests.map((request) => request.status), + [null, 202], + ); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['a'], + ); +}); + +test('a 400 is dropped and not retried', async (t) => { + const sink = await startSink({ statuses: [400] }); + const warnings = []; + const shipper = shipperFor(sink, { onWarning: (text) => warnings.push(text) }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + shipper.info('rejected'); + await shipper.flush(); + await shipper.flush(); // nothing was kept, so nothing is sent again + shipper.info('next'); + await shipper.flush(); + assert.deepEqual( + sink.requests.map((request) => request.status), + [400, 202], + ); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['next'], + ); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /rejected 1 entries: HTTP 400/); +}); + +test('a failed batch holds back the rest of its flush, and they are sent again in order', async (t) => { + const sink = await startSink({ statuses: [202, 503] }); + const shipper = shipperFor(sink, { maxBatchSize: 2 }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + for (let i = 0; i < 5; i += 1) shipper.info(`m${i}`); + // Reaching the batch size starts a background flush of all five entries: [m0, m1] is accepted, + // [m2, m3] is refused, and [m4] must not be attempted. + await waitFor(() => sink.requests.length === 2); + await new Promise((resolve) => setTimeout(resolve, 50)); + assert.equal(sink.requests.length, 2, 'm4 waits for the next flush'); + await shipper.flush(); // [m2, m3], then [m4] + assert.deepEqual( + sink.requests.map((request) => request.status), + [202, 503, 202, 202], + ); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['m0', 'm1', 'm2', 'm3', 'm4'], + ); +}); + +test('during an outage the buffer holds at most its capacity, keeping the oldest entries', async (t) => { + const sink = await startSink({ statuses: [503, 503] }); + const shipper = shipperFor(sink, { bufferCapacity: 3 }); + t.after(async () => { + await shipper.close(); + await sink.close(); + }); + for (const m of ['a', 'b', 'c']) shipper.info(m); + await shipper.flush(); // refused, so a, b and c stay buffered + for (const m of ['d', 'e']) shipper.info(m); // the buffer is full, so these are dropped + await shipper.flush(); // still refused + await shipper.flush(); // the outage is over + assert.ok(sink.requests.every((request) => request.body.length <= 3)); + assert.deepEqual( + sink.requests.map((request) => request.status), + [503, 503, 202], + ); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['a', 'b', 'c'], + ); +}); + +test('a retry that does not fit beside new entries drops the newest ones', async (t) => { + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + const sink = await startSink({ statuses: [503], gate }); + const shipper = shipperFor(sink, { bufferCapacity: 3 }); + t.after(async () => { + release(); + await shipper.close(); + await sink.close(); + }); + shipper.info('a'); + shipper.info('b'); + const sending = shipper.flush(); + await waitFor(() => sink.requests.length === 1); + // While a and b are in flight, x, y and z fill the buffer. When the refusal arrives, a and b go back + // in front of them, so only a, b and x fit and y and z are dropped. + for (const m of ['x', 'y', 'z']) shipper.info(m); + release(); + await sending; + await shipper.flush(); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['a', 'b', 'x'], + ); +}); + +test('a rejecting or unreachable OmniLogger never throws, and warnings are rate-limited', async (t) => { + const rejecting = await startSink({ status: 400 }); + const warnings = []; + const shipper = shipperFor(rejecting, { onWarning: (text) => warnings.push(text) }); + t.after(async () => { + await shipper.close(); + await rejecting.close(); + }); + shipper.info('one'); + await shipper.flush(); + shipper.info('two'); + await shipper.flush(); + assert.equal(warnings.filter((text) => text.includes('rejected')).length, 1); + + const unreachable = shipperFor({ url: 'http://127.0.0.1:1' }, { onWarning: (text) => warnings.push(text) }); + unreachable.info('lost'); + await unreachable.flush(); + await unreachable.close(); + assert.ok(warnings.some((text) => text.includes('send 1 entries'))); + + const malformed = shipperFor({ url: 'not a url' }, { onWarning: (text) => warnings.push(text) }); + malformed.info('lost'); + await malformed.flush(); + await malformed.close(); +}); + +test('close sends what is left, and entries logged after it are dropped', async (t) => { + const sink = await startSink(); + t.after(() => sink.close()); + const shipper = shipperFor(sink); + shipper.info('last'); + await shipper.close(); + assert.deepEqual( + sink.entries().map((e) => e.message), + ['last'], + ); + shipper.info('after close'); + await shipper.flush(); + await shipper.close(); + assert.equal(sink.entries().length, 1); +}); + +test('the periodic flush timer does not keep the process alive', () => { + const moduleUrl = new URL('../src/logshipper.js', import.meta.url).href; + const script = ` + import { LogShipper } from ${JSON.stringify(moduleUrl)}; + new LogShipper({ baseUrl: 'http://127.0.0.1:1', ingestToken: 't', service: 's', flushIntervalMs: 3600000 }); + `; + const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { + encoding: 'utf8', + timeout: 10_000, + }); + assert.equal(result.signal, null, 'the process was kept alive by the timer'); + assert.equal(result.status, 0, result.stderr); +}); diff --git a/shared/packages/python-backend/README.md b/shared/packages/python-backend/README.md index 31454c6..ba5b092 100644 --- a/shared/packages/python-backend/README.md +++ b/shared/packages/python-backend/README.md @@ -110,7 +110,8 @@ give it, and updated live whenever ProjectConfigurator pushes a fresh `PUT /api/core-services/internal`. A service wires the actual route itself: ```python -from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, internal_secret_matches +from fastapi.responses import JSONResponse +from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, handle_core_services_push auth_client = AuthClient("") # pending: no URL yet, still safe to use core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url="")) @@ -118,17 +119,42 @@ core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url) # in your framework's route for PUT /api/core-services/internal: +@app.put("/api/core-services/internal") async def push_core_services(request): - if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET): - raise HTTPException(status_code=401) - body = await request.json() - try: - info = core_config.set(CoreConfigInfo.from_json(body)) - except ValueError as exc: - raise HTTPException(status_code=400, detail=str(exc)) - return {"ok": True, "info": info.to_json()} + status, body = handle_core_services_push( + core_config, SECRET, request.headers.get("X-Internal-Auth"), await request.body() + ) + return JSONResponse(body, status_code=status) ``` +`handle_core_services_push` is the framework-neutral body of the route. It returns +`(status, body)`, so any framework can send it, and it does the checks in this order: + +- `X-Internal-Auth` must equal SECRET, compared in constant time, or the response is + 401 `{"error": "internal service authentication required"}`. A SECRET that is not usable + (see below) gets 401 for every caller. +- A body over 4096 bytes, or one that is not a JSON object, gets 400 + `{"error": "invalid JSON body"}`. +- A non-empty `omniLoggerUrl`, `authGuardUrl` or `carrierNodeUrl(s)` that is not an http or + https URL with a host gets 400 `{"error": "core service URL must be an http or https URL with a host"}`. +- Otherwise it returns 200 `{"ok": true}`. The response never includes the ingest token. + Other fields are ignored. + +The store keeps the last non-empty value of each field, so a partial push never clears a stored +one. OmniLogger's URL and this service's ingest token (`CoreConfigInfo.omni_logger_url` and +`omni_logger_ingest_token`) are not used by the store's AuthGuard or CarrierNode logic. A +log shipper follows them through `follow_omnilogger`: + +```python +shipper = Shipper.from_env("myservice") or Shipper(base_url="", ingest_token="", service="myservice") +follow_omnilogger(core_config, shipper) # once, at startup; later pushes call shipper.set_credentials +``` + +`follow_omnilogger` calls `shipper.set_credentials(url, token)` after a push, but only once +both values are stored, so a token-only push never disables or re-points the shipper. +Don't seed the store with `OMNILOGGER_*` values from the environment. Those belong to the +shipper, and seeding them would make a token-only push re-point it. + `internal_secret_matches` also refuses a SECRET shorter than `MIN_INTERNAL_SECRET_LENGTH` (16 characters) or equal to an example placeholder (`EXAMPLE_INTERNAL_SECRETS`), so every internal route gated by it rejects all callers until the secret is set properly. Call @@ -191,3 +217,50 @@ This mounts `/status`, `/me` (GET/PUT), `/admin-needed`, `/setup`, `/login`, — the same URL paths and JSON response shapes as `shared/backend/auth` (Go)'s `Service`, so a project migrating onto this module gets the same standardized wire format that Go consumers of that engine already have. + +## `logshipper`: mirroring logs to OmniLogger + +`shared_backend.logshipper` is the Python counterpart of `shared/backend/logshipper` +(Go): it sends log entries to the workspace's central OmniLogger, and it is additive. +A service keeps its console logging as it is and adds an `OmniLoggerHandler` beside +its existing handlers, so each record also reaches OmniLogger: + +```python +import logging + +from shared_backend import OmniLoggerHandler, Shipper + +shipper = Shipper.from_env("myservice", level="info") # None unless both env vars are set +if shipper is not None: + logging.getLogger().addHandler(OmniLoggerHandler(shipper)) + +... + +if shipper is not None: + shipper.close() # on graceful shutdown; also runs at interpreter exit +``` + +`from_env` reads `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` and returns `None` when +either is unset or empty, so a disabled service makes no network calls and logs +exactly as before. The `level` argument is the threshold (`debug`, `info`, `warn`, +`error`, `critical`, or `silent`); it defaults to `info`. + +`set_credentials(base_url, token)` changes where entries are sent, and the ingest token +used, while the service runs. It is thread-safe and takes effect from the next flush, and +the background thread keeps running. An empty base URL or token disables shipping: entries +are no longer buffered, anything already buffered is dropped, and console output is +unchanged. `Shipper(base_url="", ingest_token="", service=...)` builds a disabled shipper +up front, so a push from ProjectConfigurator can enable it later (see `coreconfig` above). + +The handler maps `DEBUG`, `INFO`, `WARNING`, `ERROR` and `CRITICAL` to `debug`, `info`, +`warn`, `error` and `critical`. Entries are batched in a daemon thread and sent every 2 +seconds, or as soon as 100 are buffered, with a 5-second HTTP timeout and bearer auth. +The buffer holds 2000 entries and drops new ones when full. Failures and drops are +reported on stderr at most once a minute and never raise into the caller. + +Entries are clamped before buffering, because OmniLogger rejects a whole batch when +one entry breaks a limit. A message over 8192 bytes is cut on a character boundary +and given a ` [truncated]` suffix. A context over 16384 bytes, or one containing a NUL, +becomes `{"context_dropped":true}`. A NUL in a message is written as the text `\u0000`. +Batches are split to stay within 1000 entries and under 2 MiB per request. `Shipper` +never prints, so the service's own console output is unchanged. diff --git a/shared/packages/python-backend/src/shared_backend/__init__.py b/shared/packages/python-backend/src/shared_backend/__init__.py index 381a86e..bb91c7b 100644 --- a/shared/packages/python-backend/src/shared_backend/__init__.py +++ b/shared/packages/python-backend/src/shared_backend/__init__.py @@ -28,9 +28,16 @@ from .authclient import ( token_from_request, ) from .config import DatabaseConfig, database_url_from_env -from .coreconfig import MIN_INTERNAL_SECRET_LENGTH, internal_secret_matches, internal_secret_usable +from .coreconfig import ( + MIN_INTERNAL_SECRET_LENGTH, + follow_omnilogger, + handle_core_services_push, + internal_secret_matches, + internal_secret_usable, +) from .coreconfig import Info as CoreConfigInfo from .coreconfig import Store as CoreConfigStore +from .logshipper import OmniLoggerHandler, Shipper from .postgres import Database from .tokens import hash_token, new_session_token from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp, verify_totp_step @@ -46,6 +53,8 @@ __all__ = [ "token_from_request", "CoreConfigInfo", "CoreConfigStore", + "follow_omnilogger", + "handle_core_services_push", "internal_secret_matches", "internal_secret_usable", "MIN_INTERNAL_SECRET_LENGTH", @@ -65,6 +74,8 @@ __all__ = [ "hash_token", "new_session_token", "normalize_role", + "OmniLoggerHandler", + "Shipper", "password_hash_needs_upgrade", "totp_provisioning_uri", "verify_and_upgrade_password", diff --git a/shared/packages/python-backend/src/shared_backend/coreconfig.py b/shared/packages/python-backend/src/shared_backend/coreconfig.py index 89bba75..8e1fc1b 100644 --- a/shared/packages/python-backend/src/shared_backend/coreconfig.py +++ b/shared/packages/python-backend/src/shared_backend/coreconfig.py @@ -7,22 +7,28 @@ ProjectConfigurator/README.md's "Pushing core service info to other projects" section for the wire contract this module implements the receiving end of. +It also carries OmniLogger's URL and this service's ingest token (see `Info`). +`follow_omnilogger` keeps a log shipper's credentials in step with those pushes, +and `handle_core_services_push` is the framework-neutral body of the +PUT /api/core-services/internal route. + Framework-agnostic, like the rest of this package (see the top-level README's "HTTP framework adapters stay in each service" note): this module -has no HTTP server of its own. A service wires the actual +has no HTTP server of its own. A service mounts the actual PUT /api/core-services/internal route in its own framework (FastAPI, -aiohttp, ...), gated behind its own SECRET check the same -way its other internal-service routes already are, decodes the JSON body -into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment -for a minimal FastAPI example. +aiohttp, ...) and passes the raw body to `handle_core_services_push`, which +returns (status, body) for the service to send -- see that function's doc +comment for a minimal FastAPI example. """ from __future__ import annotations +import dataclasses import hmac +import json import threading from dataclasses import dataclass, field -from typing import Callable, Optional +from typing import Callable, Optional, Protocol from urllib.parse import urlsplit MIN_INTERNAL_SECRET_LENGTH = 16 @@ -76,6 +82,12 @@ class Info: # registered, in priority order (the first entry is the same as # carrier_node_url). carrier_node_urls: list = field(default_factory=list) + # omni_logger_url is OmniLogger's base URL, the instance that receives this + # service's log entries (Go: coreconfig.Info.OmniLoggerURL). + omni_logger_url: str = "" + # omni_logger_ingest_token is this service's OmniLogger ingest token. repr=False + # keeps it out of logs and reprs. to_json never includes it (see below). + omni_logger_ingest_token: str = field(default="", repr=False) @classmethod def from_json(cls, data: dict) -> "Info": @@ -88,13 +100,18 @@ class Info: auth_guard_url=str(data.get("authGuardUrl") or "").strip(), carrier_node_url=urls[0] if urls else "", carrier_node_urls=urls, + omni_logger_url=str(data.get("omniLoggerUrl") or "").strip(), + omni_logger_ingest_token=str(data.get("omniLoggerIngestToken") or "").strip(), ) def to_json(self) -> dict: + # omniLoggerIngestToken is deliberately left out: a to_json result may be sent back + # to a caller, and the token must never be echoed. return { "authGuardUrl": self.auth_guard_url, "carrierNodeUrl": self.carrier_node_url, "carrierNodeUrls": list(self.carrier_node_urls), + "omniLoggerUrl": self.omni_logger_url, } @@ -110,6 +127,7 @@ class Store: self._lock = threading.Lock() self._info = _normalize(fallback or Info()) self._on_update: Optional[Callable[[Info], None]] = None + self._subscribers: list[Callable[[Info], None]] = [] def get(self) -> Info: with self._lock: @@ -136,26 +154,25 @@ class Store: with self._lock: self._on_update = fn + def subscribe(self, fn: Callable[[Info], None]) -> None: + """Registers fn to be called (synchronously, so keep it fast) with the new Info after every + set(), in addition to on_update's single callback, which it does not replace. Use it when + more than one component follows the pushed values, such as an AuthClient and a log shipper + (see follow_omnilogger). Subscribers cannot be removed; they live as long as the Store.""" + with self._lock: + self._subscribers.append(fn) + def set(self, next_info: Info) -> Info: """Replaces the current Info, field by field, ignoring a blank/empty field so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers the other value. Returns the resulting - Info. Every URL must be an http or https URL with a host; otherwise - nothing is changed and ValueError is raised. Minimal FastAPI usage: - - @app.put("/api/core-services/internal") - async def push_core_services(request: Request): - if not internal_secret_matches(request.headers.get("X-Internal-Auth"), SECRET): - raise HTTPException(status_code=401) - body = await request.json() - try: - info = core_config_store.set(Info.from_json(body)) - except ValueError as exc: - raise HTTPException(status_code=400, detail=str(exc)) - return {"ok": True, "info": info.to_json()} - """ + Info (a copy). Every URL must be an http or https URL with a host; + otherwise nothing is changed and ValueError is raised. The receiving + route is normally handle_core_services_push, which calls this; see its + doc comment for the FastAPI wiring.""" next_info = _normalize(next_info) - for url in [next_info.auth_guard_url, *next_info.carrier_node_urls]: + urls = [next_info.auth_guard_url, next_info.omni_logger_url, *next_info.carrier_node_urls] + for url in urls: if url and not _is_service_url(url): raise ValueError( f"core service URL must be an http or https URL with a host: {url}" @@ -166,10 +183,19 @@ class Store: if next_info.carrier_node_urls: self._info.carrier_node_urls = next_info.carrier_node_urls self._info.carrier_node_url = next_info.carrier_node_urls[0] - current = self._info + if next_info.omni_logger_url: + self._info.omni_logger_url = next_info.omni_logger_url + if next_info.omni_logger_ingest_token: + self._info.omni_logger_ingest_token = next_info.omni_logger_ingest_token + current = dataclasses.replace( + self._info, carrier_node_urls=list(self._info.carrier_node_urls) + ) callback = self._on_update + subscribers = list(self._subscribers) if callback is not None: callback(current) + for fn in subscribers: + fn(current) return current @@ -181,4 +207,89 @@ def _normalize(info: Info) -> Info: auth_guard_url=info.auth_guard_url.strip(), carrier_node_url=cleaned[0] if cleaned else "", carrier_node_urls=cleaned, + omni_logger_url=info.omni_logger_url.strip().rstrip("/"), + omni_logger_ingest_token=info.omni_logger_ingest_token.strip(), ) + + +class SupportsSetCredentials(Protocol): + """What follow_omnilogger needs from a log shipper: logshipper.Shipper satisfies it.""" + + def set_credentials(self, base_url: str, token: str) -> None: ... + + +def follow_omnilogger(store: Store, shipper: SupportsSetCredentials) -> None: + """Keeps shipper's OmniLogger endpoint and ingest token in step with pushes, as Go's + logshipper.Shipper.Follow does. Whenever a set() leaves both omniLoggerUrl and + omniLoggerIngestToken non-empty in the store, shipper.set_credentials(url, token) is called. + Until both are stored, the shipper is left alone, so a push with a token but no URL never + disables or re-points an environment-configured shipper. + + Call it once at startup, after creating the shipper. The Store must not be seeded with + OmniLogger values from the environment: those belong to the shipper, and seeding them would + make a token-only push re-point it.""" + + def apply(info: Info) -> None: + if info.omni_logger_url and info.omni_logger_ingest_token: + shipper.set_credentials(info.omni_logger_url, info.omni_logger_ingest_token) + + apply(store.get()) + store.subscribe(apply) + + +MAX_PUSH_BODY_BYTES = 4096 +"""Largest PUT /api/core-services/internal body that handle_core_services_push reads.""" + +PUSH_AUTH_ERROR = "internal service authentication required" +PUSH_INVALID_JSON_ERROR = "invalid JSON body" +PUSH_INVALID_URL_ERROR = "core service URL must be an http or https URL with a host" + + +def handle_core_services_push( + store: Store, + secret: Optional[str], + provided_auth: Optional[str], + body: bytes, +) -> tuple[int, dict]: + """The framework-neutral body of PUT /api/core-services/internal, the route + ProjectConfigurator pushes to. It returns (status, json_body) for the service to send. + + - provided_auth is the X-Internal-Auth header (None when absent). A provided value that does + not equal secret, or any secret that is not usable (see internal_secret_usable), gets 401. + - body is the raw request body. Over MAX_PUSH_BODY_BYTES, or not a JSON object, gets 400. + - A non-empty omniLoggerUrl, authGuardUrl or carrierNodeUrl(s) value that is not an http or + https URL with a host gets 400 (Store.set validates them). Other fields are ignored. + - Success is 200 {"ok": True}. The response never includes the ingest token. + + Mount it at PUT /api/core-services/internal, for example in FastAPI: + + @app.put("/api/core-services/internal") + async def push_core_services(request: Request): + status, body = handle_core_services_push( + core_config_store, SECRET, request.headers.get("X-Internal-Auth"), + await request.body(), + ) + return JSONResponse(body, status_code=status) + """ + if not internal_secret_matches(provided_auth, secret): + return 401, {"error": PUSH_AUTH_ERROR} + if len(body) > MAX_PUSH_BODY_BYTES: + return 400, {"error": PUSH_INVALID_JSON_ERROR} + try: + data = json.loads(body) + except (ValueError, RecursionError): # JSONDecodeError and UnicodeDecodeError are ValueErrors + return 400, {"error": PUSH_INVALID_JSON_ERROR} + if not isinstance(data, dict): + return 400, {"error": PUSH_INVALID_JSON_ERROR} + # Info.from_json reads these fields; a wrong type gets 400 here instead of an error inside it. + for key in ("authGuardUrl", "carrierNodeUrl", "omniLoggerUrl", "omniLoggerIngestToken"): + if data.get(key) is not None and not isinstance(data[key], str): + return 400, {"error": PUSH_INVALID_JSON_ERROR} + urls = data.get("carrierNodeUrls") + if urls is not None and not isinstance(urls, list): + return 400, {"error": PUSH_INVALID_JSON_ERROR} + try: + store.set(Info.from_json(data)) + except ValueError: + return 400, {"error": PUSH_INVALID_URL_ERROR} + return 200, {"ok": True} diff --git a/shared/packages/python-backend/src/shared_backend/logshipper.py b/shared/packages/python-backend/src/shared_backend/logshipper.py new file mode 100644 index 0000000..46444d8 --- /dev/null +++ b/shared/packages/python-backend/src/shared_backend/logshipper.py @@ -0,0 +1,415 @@ +"""Client-side adapter for OmniLogger, the workspace's central log sink. Python counterpart of +shared/backend/logshipper (Go), and it follows the same wire contract. + +Shipping is additive. A service keeps its own console logging unchanged and adds an +`OmniLoggerHandler` next to its existing handlers, so each record also reaches OmniLogger. +`Shipper` never prints anything itself. + +Shipping is enabled only when both OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are set; see +`Shipper.from_env`, which returns None otherwise. + +Entries are clamped to OmniLogger's limits before they are buffered, because OmniLogger rejects +a whole batch when any one entry breaks a limit. A batch that fails with a network error, an HTTP +5xx or 429 is kept and sent again on a later flush, while any other rejection is dropped. Nothing +here raises into the caller or blocks it: failures and a full buffer are reported with a +rate-limited line on stderr. +""" + +from __future__ import annotations + +import atexit +import json +import logging +import os +import sys +import threading +import time +import urllib.error +import urllib.request +from collections.abc import Iterator, Mapping +from datetime import datetime, timezone +from typing import Any + +__all__ = ["OmniLoggerHandler", "Shipper", "to_omnilogger_level"] + +ENV_URL = "OMNILOGGER_URL" +ENV_TOKEN = "OMNILOGGER_INGEST_TOKEN" + +FLUSH_INTERVAL = 2.0 # seconds between background flushes +MAX_BATCH_SIZE = 100 # buffering this many entries flushes early +BUFFER_CAPACITY = 2000 # beyond this, new entries are dropped +HTTP_TIMEOUT = 5.0 +WARN_INTERVAL = 60.0 # at most one stderr warning per this many seconds + +# OmniLogger's limits (Central/OmniLogger/internal/httpapi/validate.go). +MAX_BATCH_ENTRIES = 1000 +MAX_BODY_BYTES = 2 * 1024 * 1024 +MAX_MESSAGE_BYTES = 8 * 1024 +MAX_CONTEXT_BYTES = 16 * 1024 +TRUNCATED_MARKER = " [truncated]" +DROPPED_CONTEXT = '{"context_dropped":true}' + +# Severity ranks, matching the Go shipper's scale (debug 10 ... critical 50). +_RANKS = {"debug": 10, "info": 20, "warn": 30, "error": 40, "critical": 50} +_SILENT = 100 +_LEVEL_NAMES = { + "debug": "debug", + "info": "info", + "warn": "warn", + "warning": "warn", + "error": "error", + "critical": "critical", +} +_THRESHOLD_RANKS = {**_RANKS, "silent": _SILENT, "none": _SILENT, "off": _SILENT} + + +def to_omnilogger_level(levelno: int) -> str: + """Maps a standard-library logging level number to OmniLogger's level name. + + DEBUG, INFO, WARNING, ERROR and CRITICAL map to debug, info, warn, error and critical. A level + between two of them takes the name of the lower one, and anything below INFO is debug. + """ + if levelno >= logging.CRITICAL: + return "critical" + if levelno >= logging.ERROR: + return "error" + if levelno >= logging.WARNING: + return "warn" + if levelno >= logging.INFO: + return "info" + return "debug" + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuses redirects, so the bearer token only ever goes to the configured URL.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001, ARG002 + return None + + +_OPENER = urllib.request.build_opener(_NoRedirect) + + +def _json_text(value: str) -> str: + return json.dumps(value, ensure_ascii=False) + + +def _clean_message(message: object) -> str: + # OmniLogger rejects a message with a NUL byte (PostgreSQL cannot store it) and then rejects the + # whole batch, so NUL is written as its escape text. Lone surrogates cannot be encoded as UTF-8. + text = message if isinstance(message, str) else str(message) + text = text.replace("\x00", "\\u0000") + return text.encode("utf-8", "replace").decode("utf-8") + + +def _clamp_message(text: str) -> str: + data = text.encode("utf-8") + if len(data) <= MAX_MESSAGE_BYTES: + return text + cut = MAX_MESSAGE_BYTES - len(TRUNCATED_MARKER.encode("utf-8")) + # Decoding with "ignore" drops a character that the cut split in half, so the cut lands on a + # character boundary. + return data[:cut].decode("utf-8", "ignore") + TRUNCATED_MARKER + + +def _clamp_context(context: Mapping[str, Any]) -> str: + try: + raw = json.dumps( + dict(context), ensure_ascii=False, separators=(",", ":"), default=str, allow_nan=False + ) + except (TypeError, ValueError, RecursionError): + return DROPPED_CONTEXT + # json.dumps writes a NUL as the escape \u0000, which OmniLogger refuses in context. + if "\\u0000" in raw or len(raw.encode("utf-8", "replace")) > MAX_CONTEXT_BYTES: + return DROPPED_CONTEXT + return raw + + +def _timestamp() -> str: + return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") + + +def _encode_entry( + service: str, level: str, message: object, context: Mapping[str, Any] | None +) -> bytes: + fields = [ + f'"service":{_json_text(service)}', + f'"level":"{level}"', + f'"message":{_json_text(_clamp_message(_clean_message(message)))}', + ] + if context is not None: + fields.append(f'"context":{_clamp_context(context)}') + fields.append(f'"occurred_at":"{_timestamp()}"') + return ("{" + ",".join(fields) + "}").encode("utf-8", "replace") + + +def _batch_bodies(entries: list[bytes]) -> Iterator[tuple[bytes, int]]: + """Groups encoded entries into request bodies of at most MAX_BATCH_ENTRIES entries and under + MAX_BODY_BYTES bytes each. Yields (body, entry count).""" + group: list[bytes] = [] + size = 2 # the enclosing brackets + for entry in entries: + extra = len(entry) + (1 if group else 0) # the comma before it, if any + if group and (len(group) >= MAX_BATCH_ENTRIES or size + extra >= MAX_BODY_BYTES): + yield b"[" + b",".join(group) + b"]", len(group) + group, size, extra = [], 2, len(entry) + group.append(entry) + size += extra + if group: + yield b"[" + b",".join(group) + b"]", len(group) + + +class Shipper: + """Buffers log entries and sends them to OmniLogger in batches from a background thread. + + Create one at startup with `Shipper.from_env(service)` and call `close()` on graceful shutdown. + `close()` also runs at interpreter exit (atexit), so a final flush happens even without it. + A Shipper is safe to use from many threads. + """ + + def __init__( + self, + *, + base_url: str, + ingest_token: str, + service: str, + level: str | None = None, + flush_interval: float = FLUSH_INTERVAL, + max_batch_size: int = MAX_BATCH_SIZE, + buffer_capacity: int = BUFFER_CAPACITY, + http_timeout: float = HTTP_TIMEOUT, + ) -> None: + """`level` is the threshold, using the same names as the services' LOG setting (debug, info, + warn, error, critical, silent). It defaults to info.""" + self._service = service + self._threshold = _THRESHOLD_RANKS.get((level or "info").strip().lower(), _RANKS["info"]) + self._flush_interval = flush_interval if flush_interval > 0 else FLUSH_INTERVAL + self._max_batch_size = max_batch_size + self._buffer_capacity = buffer_capacity + self._http_timeout = http_timeout + + self._buffer: list[bytes] = [] + self._buffer_lock = threading.Lock() + self._cred_lock = threading.Lock() + self._url: str | None = None # None while shipping is disabled + self._token = "" + self.set_credentials(base_url, ingest_token) + self._wake = threading.Event() + self._stop = threading.Event() + self._close_lock = threading.Lock() + self._closed = False + self._warn_lock = threading.Lock() + self._last_warn: float | None = None + + self._thread = threading.Thread(target=self._run, name=f"logshipper-{service}", daemon=True) + self._thread.start() + atexit.register(self.close) + + @classmethod + def from_env( + cls, + service: str, + *, + level: str | None = None, + environ: Mapping[str, str] | None = None, + ) -> Shipper | None: + """Returns a Shipper configured from OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN, or None + when either is unset or empty, which leaves the service with no shipping at all.""" + env = os.environ if environ is None else environ + url = (env.get(ENV_URL) or "").strip() + token = (env.get(ENV_TOKEN) or "").strip() + if not url or not token: + return None + return cls(base_url=url, ingest_token=token, service=service, level=level) + + def handler(self, level: int = logging.NOTSET) -> OmniLoggerHandler: + """Returns a logging handler that ships records to this Shipper.""" + return OmniLoggerHandler(self, level) + + def set_credentials(self, base_url: str, token: str) -> None: + """Sets where, and as which ingest token, entries are sent. It is thread-safe, takes effect + from the next flush, and does not restart the background thread. + + An empty base URL or token disables shipping: entries are no longer buffered, anything + already buffered is dropped, and the service's own console output carries on unchanged. + Otherwise entries go to `base_url` + "/api/logs" with `token` as the bearer token.""" + base = (base_url or "").strip().rstrip("/") + token = (token or "").strip() + url = base + "/api/logs" if base and token else None + with self._cred_lock: + self._url = url + self._token = token + if url is None: + with self._buffer_lock: + self._buffer = [] + + def _enabled(self) -> bool: + with self._cred_lock: + return self._url is not None + + def log(self, level: str, message: str, context: Mapping[str, Any] | None = None) -> None: + """Queues one entry. `level` is debug, info, warn (or warning), error or critical; any + other value is sent as info. `context` is an optional mapping sent as JSON.""" + name = _LEVEL_NAMES.get(str(level).strip().lower(), "info") + if _RANKS[name] < self._threshold or not self._enabled(): + return + try: + entry = _encode_entry(self._service, name, message, context) + except Exception: # noqa: BLE001 - a log sink must never fail its host + return + self._buffer_entry(entry) + + def debug(self, message: str, context: Mapping[str, Any] | None = None) -> None: + self.log("debug", message, context) + + def info(self, message: str, context: Mapping[str, Any] | None = None) -> None: + self.log("info", message, context) + + def warning(self, message: str, context: Mapping[str, Any] | None = None) -> None: + self.log("warn", message, context) + + def error(self, message: str, context: Mapping[str, Any] | None = None) -> None: + self.log("error", message, context) + + def critical(self, message: str, context: Mapping[str, Any] | None = None) -> None: + self.log("critical", message, context) + + def flush(self) -> None: + """Sends everything buffered now, in the calling thread. A batch that fails for a reason + that may pass (no connection, HTTP 5xx or 429) stays in the buffer with every later entry of + this flush, in order, and the rest of the flush waits for the next one. Other failures are + only reported on stderr, and at most once a minute.""" + with self._buffer_lock: + if not self._buffer: + return + pending, self._buffer = self._buffer, [] + sent = 0 + for body, count in _batch_bodies(pending): + if self._post(body, count): + self._requeue(pending[sent:]) + return + sent += count + + def _requeue(self, entries: list[bytes]) -> None: + """Puts entries that failed to send back at the front of the buffer, so the next flush + sends them before newer entries. The buffer stays within its capacity: when the waiting + entries and the buffer do not all fit, the newest entries are dropped, as _buffer_entry + drops them.""" + with self._buffer_lock: + if not self._enabled(): + return # shipping was disabled during the flush, so these go with the buffer + combined = entries + self._buffer + dropped = max(0, len(combined) - self._buffer_capacity) + self._buffer = combined[: self._buffer_capacity] + if dropped: + self._warn( + f"buffer full while retrying, dropping {dropped} log entries for service " + f"{self._service!r}" + ) + + def close(self) -> None: + """Stops the background thread after a final flush of whatever is buffered. Safe to call + more than once.""" + with self._close_lock: + if self._closed: + return + self._closed = True + self._stop.set() + self._wake.set() + if threading.current_thread() is not self._thread: + self._thread.join() + self.flush() + atexit.unregister(self.close) + + def _buffer_entry(self, entry: bytes) -> None: + if self._closed or not self._enabled(): + return + with self._buffer_lock: + full = len(self._buffer) >= self._buffer_capacity + if not full: + self._buffer.append(entry) + ready = len(self._buffer) >= self._max_batch_size + if full: + self._warn( + f"buffer full (cap={self._buffer_capacity}), dropping log entries for service " + f"{self._service!r}" + ) + elif ready: + self._wake.set() + + def _run(self) -> None: + while not self._stop.is_set(): + self._wake.wait(self._flush_interval) + # Cleared before the flush takes its snapshot, so an entry that arrives during the + # flush sets the event again and is not left waiting for the next interval. + self._wake.clear() + if self._stop.is_set(): + break + try: + self.flush() + except Exception: # noqa: BLE001 - keep the background thread alive + pass + + def _post(self, body: bytes, count: int) -> bool: + """Sends one request body. Returns True when it failed for a reason that may pass (no + connection, HTTP 5xx or 429), so the caller keeps its entries for a later flush. A request + OmniLogger rejects with any other status is reported and dropped, and returns False.""" + with self._cred_lock: + url, token = self._url, self._token + if url is None: + return False # shipping was disabled after these entries were taken for a flush + request = urllib.request.Request( + url, + data=body, + method="POST", + headers={ + "Content-Type": "application/json", + "Authorization": f"Bearer {token}", + }, + ) + try: + with _OPENER.open(request, timeout=self._http_timeout): + return False + except urllib.error.HTTPError as exc: + exc.close() + if exc.code == 429 or exc.code >= 500: + self._warn(f"OmniLogger answered HTTP {exc.code} for {count} entries, will retry") + return True + self._warn(f"OmniLogger rejected {count} entries: HTTP {exc.code}") + return False + except Exception as exc: # noqa: BLE001 - unreachable or misconfigured sink + self._warn(f"send {count} entries to {url}: {exc}") + return True + + def _warn(self, detail: str) -> None: + now = time.monotonic() + with self._warn_lock: + if self._last_warn is not None and now - self._last_warn < WARN_INTERVAL: + return + self._last_warn = now + try: + stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + sys.stderr.write(f"[{stamp}] [logshipper] logshipper: {detail}\n") + sys.stderr.flush() + except Exception: # noqa: BLE001 - stderr may be closed or missing + pass + + +class OmniLoggerHandler(logging.Handler): + """A logging handler that ships each record to a Shipper and writes nothing locally. + + Keep the service's own console handler and add this one beside it, so the console output is + unchanged. The shipped message is the record's formatted message, with any traceback appended. + The record's logger name goes in the entry's context. + """ + + def __init__(self, shipper: Shipper, level: int = logging.NOTSET) -> None: + super().__init__(level) + self._shipper = shipper + + def emit(self, record: logging.LogRecord) -> None: + try: + message = self.format(record) + self._shipper.log(to_omnilogger_level(record.levelno), message, {"logger": record.name}) + except Exception: # noqa: BLE001 - a log sink must never fail its host + pass diff --git a/shared/packages/python-backend/tests/test_coreconfig.py b/shared/packages/python-backend/tests/test_coreconfig.py index 43e4b7b..f363b42 100644 --- a/shared/packages/python-backend/tests/test_coreconfig.py +++ b/shared/packages/python-backend/tests/test_coreconfig.py @@ -1,9 +1,12 @@ +import json import unittest from shared_backend.coreconfig import ( MIN_INTERNAL_SECRET_LENGTH, Info, Store, + follow_omnilogger, + handle_core_services_push, internal_secret_matches, internal_secret_usable, ) @@ -117,5 +120,192 @@ class UrlValidationTests(unittest.TestCase): self.assertEqual(store.auth_guard_url, "http://auth.example.com") +class OmniLoggerStoreTests(unittest.TestCase): + def test_from_json_reads_omni_fields_and_to_json_never_carries_the_token(self): + info = Info.from_json( + {"omniLoggerUrl": "http://omni.example.com", "omniLoggerIngestToken": "tok-123"} + ) + self.assertEqual(info.omni_logger_url, "http://omni.example.com") + self.assertEqual(info.omni_logger_ingest_token, "tok-123") + self.assertEqual(info.to_json()["omniLoggerUrl"], "http://omni.example.com") + self.assertNotIn("omniLoggerIngestToken", info.to_json()) + self.assertNotIn("tok-123", json.dumps(info.to_json())) + self.assertNotIn("tok-123", repr(info)) + + def test_keeps_last_non_blank_values_and_strips_the_trailing_slash(self): + store = Store() + store.set( + Info(omni_logger_url="http://omni.example.com/", omni_logger_ingest_token="tok-1") + ) + store.set(Info(omni_logger_url=" ", omni_logger_ingest_token="")) + info = store.get() + self.assertEqual(info.omni_logger_url, "http://omni.example.com") + self.assertEqual(info.omni_logger_ingest_token, "tok-1") + + def test_a_bad_omni_url_is_refused_and_nothing_changes(self): + store = Store() + store.set(Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1")) + for bad in ["omni.example.com", "ftp://omni.example.com", "http://"]: + with self.subTest(url=bad), self.assertRaises(ValueError): + store.set(Info(omni_logger_url=bad, omni_logger_ingest_token="tok-2")) + self.assertEqual(store.get().omni_logger_url, "http://omni.example.com") + self.assertEqual(store.get().omni_logger_ingest_token, "tok-1") + + def test_subscribers_and_on_update_both_see_every_set(self): + store = Store() + from_on_update, from_subscriber = [], [] + store.on_update(from_on_update.append) + store.subscribe(from_subscriber.append) + store.set(Info(auth_guard_url="http://auth.example.com")) + self.assertEqual(len(from_on_update), 1) + self.assertEqual(len(from_subscriber), 1) + self.assertEqual(from_subscriber[0].auth_guard_url, "http://auth.example.com") + + +class _RecordingShipper: + def __init__(self): + self.calls = [] + + def set_credentials(self, base_url, token): + self.calls.append((base_url, token)) + + +class FollowOmniLoggerTests(unittest.TestCase): + def setUp(self): + self.store = Store() + self.shipper = _RecordingShipper() + follow_omnilogger(self.store, self.shipper) + + def test_a_push_with_both_values_sets_the_shipper(self): + self.store.set( + Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1") + ) + self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-1")]) + + def test_a_token_without_a_url_leaves_the_shipper_alone(self): + self.store.set(Info(omni_logger_ingest_token="tok-1")) + self.assertEqual(self.shipper.calls, []) + + def test_a_url_pushed_after_a_token_applies_both(self): + self.store.set(Info(omni_logger_ingest_token="tok-1")) + self.store.set(Info(omni_logger_url="http://omni.example.com")) + self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-1")]) + + def test_a_later_token_only_push_reuses_the_stored_url(self): + self.store.set( + Info(omni_logger_url="http://omni.example.com", omni_logger_ingest_token="tok-1") + ) + self.store.set(Info(omni_logger_ingest_token="tok-2")) + self.assertEqual( + self.shipper.calls, + [("http://omni.example.com", "tok-1"), ("http://omni.example.com", "tok-2")], + ) + + def test_pushes_without_omni_fields_do_not_touch_the_shipper(self): + self.store.set(Info(auth_guard_url="http://auth.example.com")) + self.assertEqual(self.shipper.calls, []) + + def test_a_store_without_omni_values_does_not_apply_at_startup(self): + follow_omnilogger(Store(), self.shipper) + self.assertEqual(self.shipper.calls, []) + + +INTERNAL_SECRET = "a-sufficiently-long-secret-value" +PUSH_BODY = {"omniLoggerUrl": "http://omni.example.com", "omniLoggerIngestToken": "tok-secret-1"} +AUTH_ERROR = {"error": "internal service authentication required"} +JSON_ERROR = {"error": "invalid JSON body"} +URL_ERROR = {"error": "core service URL must be an http or https URL with a host"} + + +class HandleCoreServicesPushTests(unittest.TestCase): + def setUp(self): + self.store = Store() + self.shipper = _RecordingShipper() + follow_omnilogger(self.store, self.shipper) + + def push(self, body, auth=INTERNAL_SECRET, secret=INTERNAL_SECRET): + raw = body if isinstance(body, bytes) else json.dumps(body).encode("utf-8") + return handle_core_services_push(self.store, secret, auth, raw) + + def test_a_missing_or_wrong_x_internal_auth_gets_401(self): + for auth in (None, "", "wrong-secret-value-here", INTERNAL_SECRET + "x"): + with self.subTest(auth=auth): + self.assertEqual(self.push(PUSH_BODY, auth=auth), (401, AUTH_ERROR)) + self.assertEqual(self.shipper.calls, []) + self.assertEqual(self.store.get().omni_logger_url, "") + + def test_an_unusable_secret_refuses_every_caller(self): + for secret in (None, "", "SECRET", "change-me-to-a-long-random-value", "short"): + with self.subTest(secret=secret): + status, _ = self.push(PUSH_BODY, auth=secret, secret=secret) + self.assertEqual(status, 401) + status, _ = self.push(PUSH_BODY, auth=INTERNAL_SECRET, secret=secret) + self.assertEqual(status, 401) + self.assertEqual(self.shipper.calls, []) + + def test_a_valid_push_sets_the_shipper_and_never_echoes_the_token(self): + status, body = self.push(PUSH_BODY) + self.assertEqual((status, body), (200, {"ok": True})) + self.assertEqual(self.shipper.calls, [("http://omni.example.com", "tok-secret-1")]) + self.assertNotIn("tok-secret-1", json.dumps(body)) + + def test_a_token_without_a_url_does_not_change_the_shipper(self): + status, body = self.push({"omniLoggerIngestToken": "tok-secret-1"}) + self.assertEqual((status, body), (200, {"ok": True})) + self.assertEqual(self.shipper.calls, []) + + def test_a_bad_omni_url_gets_400_and_changes_nothing(self): + for bad in ["omni.example.com", "ftp://omni.example.com", "javascript:alert(1)"]: + with self.subTest(url=bad): + body = {"omniLoggerUrl": bad, "omniLoggerIngestToken": "tok-secret-1"} + self.assertEqual(self.push(body), (400, URL_ERROR)) + self.assertEqual(self.shipper.calls, []) + + def test_a_bad_auth_guard_url_gets_400(self): + self.assertEqual(self.push({"authGuardUrl": "auth.example.com"}), (400, URL_ERROR)) + + def test_a_field_of_the_wrong_type_gets_400_not_a_server_error(self): + for body in ( + {"carrierNodeUrls": 5}, + {"carrierNodeUrls": True}, + {"carrierNodeUrls": "http://carrier.example.com"}, + {"carrierNodeUrl": ["http://carrier.example.com"]}, + {"authGuardUrl": 5}, + ): + with self.subTest(body=body): + self.assertEqual(self.push(body), (400, JSON_ERROR)) + self.assertEqual(self.shipper.calls, []) + + def test_an_oversized_body_or_a_body_that_is_not_a_json_object_gets_400(self): + cases = [ + json.dumps({"x": "a" * 4096}).encode("utf-8"), + b"not json", + b"[1, 2]", + b'"a string"', + b"\xff\xfe\x00", + json.dumps({"omniLoggerUrl": 5}).encode("utf-8"), + json.dumps({"omniLoggerIngestToken": ["tok"]}).encode("utf-8"), + ] + for raw in cases: + with self.subTest(raw=raw[:20]): + self.assertEqual(self.push(raw), (400, JSON_ERROR)) + + def test_a_body_of_exactly_4096_bytes_is_read(self): + raw = json.dumps({"x": "a" * 4087}).encode("utf-8") + self.assertEqual(len(raw), 4096) + self.assertEqual(self.push(raw), (200, {"ok": True})) + + def test_other_fields_and_null_values_are_ignored(self): + body = { + "contentScannerUrl": "not a url", + "comfyUiUrl": 7, + "carrierNodeSecret": "not-used-here", + "omniLoggerIngestToken": None, + "omniLoggerUrl": "http://omni.example.com", + } + self.assertEqual(self.push(body), (200, {"ok": True})) + self.assertEqual(self.shipper.calls, []) + + if __name__ == "__main__": unittest.main() diff --git a/shared/packages/python-backend/tests/test_logshipper.py b/shared/packages/python-backend/tests/test_logshipper.py new file mode 100644 index 0000000..d576096 --- /dev/null +++ b/shared/packages/python-backend/tests/test_logshipper.py @@ -0,0 +1,688 @@ +import contextlib +import io +import json +import logging +import socket +import threading +import time +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock + +from shared_backend.logshipper import ( + DROPPED_CONTEXT, + MAX_BATCH_ENTRIES, + MAX_BODY_BYTES, + MAX_CONTEXT_BYTES, + MAX_MESSAGE_BYTES, + TRUNCATED_MARKER, + OmniLoggerHandler, + Shipper, + to_omnilogger_level, +) + + +class _FakeOmniLogger: + """Local stand-in for OmniLogger's POST /api/logs. It records every request. Each request is + answered with the next status in `statuses`, and with `status` once that list is used up. + Only requests answered with a 2xx count as delivered, so `batches()` and `entries()` leave out + the refused ones.""" + + def __init__(self, status: int = 202) -> None: + self.status = status + self.statuses: list[int] = [] + self.requests: list[dict] = [] + self._lock = threading.Lock() + fake = self + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): # noqa: N802 - http.server's naming + length = int(self.headers.get("Content-Length", "0")) + raw = self.rfile.read(length) + with fake._lock: + status = fake.statuses.pop(0) if fake.statuses else fake.status + fake.requests.append( + { + "path": self.path, + "authorization": self.headers.get("Authorization"), + "content_type": self.headers.get("Content-Type"), + "body": raw, + "status": status, + } + ) + self.send_response(status) + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): # keep the test output quiet + pass + + self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self._server.server_port}" + self._thread = threading.Thread( + target=self._server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True + ) + self._thread.start() + + def stop(self) -> None: + self._server.shutdown() + self._server.server_close() + + def batches(self) -> list[list[dict]]: + with self._lock: + return [ + json.loads(request["body"]) + for request in self.requests + if 200 <= request["status"] < 300 + ] + + def entries(self) -> list[dict]: + return [entry for batch in self.batches() for entry in batch] + + +def _unused_url() -> str: + """A URL nothing listens on, so connecting to it is refused at once.""" + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + return f"http://127.0.0.1:{port}" + + +def _wait_for(predicate, timeout: float = 5.0) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return True + time.sleep(0.01) + return predicate() + + +class ShipperTestCase(unittest.TestCase): + def setUp(self) -> None: + self.omni = _FakeOmniLogger() + self.addCleanup(self.omni.stop) + + def make_shipper(self, **overrides) -> Shipper: + """A shipper that does not flush on its own, so each test decides when entries go out.""" + options = { + "base_url": self.omni.url, + "ingest_token": "secret-token", + "service": "svc", + "flush_interval": 3600, + } + options.update(overrides) + shipper = Shipper(**options) + self.addCleanup(shipper.close) + return shipper + + +class BatchingTests(ShipperTestCase): + def test_flush_sends_every_buffered_entry_in_one_request(self): + shipper = self.make_shipper() + shipper.info("one") + shipper.error("two") + shipper.flush() + shipper.flush() # nothing left, so no second request + + self.assertEqual(len(self.omni.requests), 1) + self.assertEqual([e["message"] for e in self.omni.entries()], ["one", "two"]) + + def test_reaching_the_batch_size_flushes_without_waiting_for_the_interval(self): + shipper = self.make_shipper(max_batch_size=2) + shipper.info("a") + shipper.info("b") + + self.assertTrue(_wait_for(lambda: len(self.omni.entries()) == 2)) + + def test_the_interval_flushes_a_partial_batch(self): + shipper = self.make_shipper(flush_interval=0.05) + shipper.info("lone entry") + + self.assertTrue(_wait_for(lambda: len(self.omni.entries()) == 1)) + + def test_a_batch_never_exceeds_1000_entries(self): + shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=5000) + for i in range(2500): + shipper.info(f"entry {i}") + shipper.flush() + + batches = self.omni.batches() + self.assertTrue(all(len(batch) <= MAX_BATCH_ENTRIES for batch in batches)) + self.assertEqual(sum(len(batch) for batch in batches), 2500) + self.assertEqual(self.omni.entries()[-1]["message"], "entry 2499") + + def test_a_batch_body_stays_under_2_mib(self): + shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=1000) + for _ in range(600): + shipper.info("x" * MAX_MESSAGE_BYTES) # about 8 KiB each, so 600 cannot fit in one body + shipper.flush() + + self.assertGreater(len(self.omni.requests), 1) + self.assertTrue(all(len(r["body"]) < MAX_BODY_BYTES for r in self.omni.requests)) + self.assertEqual(len(self.omni.entries()), 600) + + def test_close_sends_what_is_left_and_is_idempotent(self): + shipper = self.make_shipper() + shipper.info("last words") + shipper.close() + shipper.close() + + self.assertEqual([e["message"] for e in self.omni.entries()], ["last words"]) + + def test_logging_after_close_is_ignored(self): + shipper = self.make_shipper() + shipper.close() + shipper.info("too late") + shipper.flush() + + self.assertEqual(self.omni.requests, []) + + +class WireFormatTests(ShipperTestCase): + def test_request_uses_bearer_auth_json_and_the_api_logs_path(self): + shipper = self.make_shipper(base_url=self.omni.url + "/") + shipper.info("hello") + shipper.flush() + + request = self.omni.requests[0] + self.assertEqual(request["path"], "/api/logs") + self.assertEqual(request["authorization"], "Bearer secret-token") + self.assertEqual(request["content_type"], "application/json") + + def test_every_entry_carries_the_service_name(self): + shipper = self.make_shipper(service="heretic") + shipper.info("a") + shipper.critical("b") + shipper.flush() + + self.assertEqual({e["service"] for e in self.omni.entries()}, {"heretic"}) + + def test_entry_fields_and_occurred_at_format(self): + shipper = self.make_shipper() + shipper.warning("careful", {"path": "/x", "status": 503}) + shipper.info("plain") + shipper.flush() + + warned, plain = self.omni.entries() + self.assertEqual(warned["level"], "warn") + self.assertEqual(warned["context"], {"path": "/x", "status": 503}) + self.assertNotIn("context", plain) + for entry in (warned, plain): + self.assertRegex(entry["occurred_at"], r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$") + + def test_context_is_sent_unscrubbed(self): + shipper = self.make_shipper() + shipper.info("request", {"userId": 7}) + shipper.flush() + + self.assertEqual(self.omni.entries()[0]["context"], {"userId": 7}) + + +class ClampingTests(ShipperTestCase): + def test_a_long_message_is_cut_on_a_character_boundary_with_the_marker(self): + shipper = self.make_shipper() + shipper.info("é" * 5000) # 10000 bytes, and 8181 is an odd byte count to cut at + shipper.flush() + + message = self.omni.entries()[0]["message"] + self.assertLessEqual(len(message.encode("utf-8")), MAX_MESSAGE_BYTES) + self.assertTrue(message.endswith(TRUNCATED_MARKER)) + self.assertTrue(set(message[: -len(TRUNCATED_MARKER)]) <= {"é"}) + + def test_a_message_of_exactly_the_limit_is_untouched(self): + shipper = self.make_shipper() + exact = "y" * MAX_MESSAGE_BYTES + shipper.info(exact) + shipper.flush() + + self.assertEqual(self.omni.entries()[0]["message"], exact) + + def test_a_nul_byte_in_a_message_is_written_as_escape_text(self): + shipper = self.make_shipper() + shipper.info("before\x00after") + shipper.flush() + + self.assertEqual(self.omni.entries()[0]["message"], "before\\u0000after") + + def test_an_oversized_context_is_replaced_by_the_dropped_marker(self): + shipper = self.make_shipper() + shipper.info("big", {"blob": "x" * MAX_CONTEXT_BYTES}) + shipper.flush() + + entry = self.omni.entries()[0] + self.assertEqual(entry["context"], {"context_dropped": True}) + self.assertEqual(entry["message"], "big") + + def test_a_context_with_a_nul_is_replaced_but_an_ordinary_one_is_kept(self): + shipper = self.make_shipper() + shipper.info("nul", {"s": "a\x00b"}) + shipper.info("fine", {"ok": True}) + shipper.flush() + + nul, fine = self.omni.entries() + self.assertEqual(json.loads(DROPPED_CONTEXT), nul["context"]) + self.assertEqual(fine["context"], {"ok": True}) + + def test_an_unserialisable_context_is_replaced_not_lost(self): + shipper = self.make_shipper() + shipper.info("nan", {"value": float("nan")}) + shipper.flush() + + entry = self.omni.entries()[0] + self.assertEqual(entry["message"], "nan") + self.assertEqual(entry["context"], {"context_dropped": True}) + + +class DisabledModeTests(unittest.TestCase): + def test_from_env_returns_none_unless_both_variables_are_set(self): + cases = [ + {}, + {"OMNILOGGER_URL": "http://omni:8080"}, + {"OMNILOGGER_INGEST_TOKEN": "token"}, + {"OMNILOGGER_URL": "", "OMNILOGGER_INGEST_TOKEN": "token"}, + {"OMNILOGGER_URL": "http://omni:8080", "OMNILOGGER_INGEST_TOKEN": " "}, + ] + for environ in cases: + with self.subTest(environ=environ): + self.assertIsNone(Shipper.from_env("svc", environ=environ)) + + def test_from_env_builds_a_shipper_when_both_are_set(self): + omni = _FakeOmniLogger() + self.addCleanup(omni.stop) + shipper = Shipper.from_env( + "heretic", + environ={"OMNILOGGER_URL": omni.url, "OMNILOGGER_INGEST_TOKEN": "tok"}, + level="warn", + ) + self.addCleanup(shipper.close) + + self.assertIsNotNone(shipper) + shipper.info("below the warn threshold") + shipper.error("shipped") + shipper.flush() + self.assertEqual([e["message"] for e in omni.entries()], ["shipped"]) + self.assertEqual(omni.requests[0]["authorization"], "Bearer tok") + self.assertEqual(omni.entries()[0]["service"], "heretic") + + def test_from_env_reads_os_environ_by_default(self): + omni = _FakeOmniLogger() + self.addCleanup(omni.stop) + with mock.patch.dict( + "os.environ", + {"OMNILOGGER_URL": omni.url, "OMNILOGGER_INGEST_TOKEN": "env-token"}, + ): + shipper = Shipper.from_env("svc") + self.assertIsNotNone(shipper) + self.addCleanup(shipper.close) + + def test_disabled_logging_makes_no_network_calls_and_prints_nothing_extra(self): + omni = _FakeOmniLogger() + self.addCleanup(omni.stop) + stdout, stderr = io.StringIO(), io.StringIO() + logger = logging.getLogger("tests.logshipper.disabled") + logger.addHandler(logging.StreamHandler(stdout)) + logger.setLevel(logging.INFO) + self.addCleanup(logger.handlers.clear) + + with contextlib.redirect_stderr(stderr): + shipper = Shipper.from_env("svc", environ={}) + logger.info("local only") + self.assertIsNone(shipper) + + self.assertEqual(omni.requests, []) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(stdout.getvalue(), "local only\n") + + +class LevelMappingTests(ShipperTestCase): + def test_standard_levels_map_to_omnilogger_names(self): + self.assertEqual( + [ + to_omnilogger_level(logging.DEBUG), + to_omnilogger_level(logging.INFO), + to_omnilogger_level(logging.WARNING), + to_omnilogger_level(logging.ERROR), + to_omnilogger_level(logging.CRITICAL), + ], + ["debug", "info", "warn", "error", "critical"], + ) + + def test_levels_between_standard_ones_take_the_lower_name(self): + self.assertEqual(to_omnilogger_level(25), "info") + self.assertEqual(to_omnilogger_level(35), "warn") + self.assertEqual(to_omnilogger_level(55), "critical") + self.assertEqual(to_omnilogger_level(5), "debug") + + def test_handler_ships_each_record_at_its_mapped_level(self): + shipper = self.make_shipper(level="debug") + logger = logging.getLogger("tests.logshipper.levels") + logger.handlers.clear() + logger.addHandler(OmniLoggerHandler(shipper)) + logger.setLevel(logging.DEBUG) + logger.propagate = False + self.addCleanup(setattr, logger, "propagate", True) + self.addCleanup(logger.handlers.clear) + + logger.debug("d") + logger.info("i") + logger.warning("w") + logger.error("e") + logger.critical("c") + shipper.flush() + + entries = self.omni.entries() + self.assertEqual( + [(e["level"], e["message"]) for e in entries], + [("debug", "d"), ("info", "i"), ("warn", "w"), ("error", "e"), ("critical", "c")], + ) + self.assertEqual({e["context"]["logger"] for e in entries}, {"tests.logshipper.levels"}) + + def test_handler_writes_nothing_locally(self): + shipper = self.make_shipper() + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + OmniLoggerHandler(shipper).handle( + logging.LogRecord("n", logging.ERROR, __file__, 1, "quiet", None, None) + ) + self.assertEqual(stderr.getvalue(), "") + + def test_handler_appends_a_traceback_to_the_message(self): + shipper = self.make_shipper() + logger = logging.getLogger("tests.logshipper.traceback") + logger.handlers.clear() + logger.addHandler(OmniLoggerHandler(shipper)) + logger.propagate = False + self.addCleanup(setattr, logger, "propagate", True) + self.addCleanup(logger.handlers.clear) + + try: + raise ValueError("boom") + except ValueError: + logger.exception("failed") + shipper.flush() + + message = self.omni.entries()[0]["message"] + self.assertTrue(message.startswith("failed\nTraceback")) + self.assertIn("ValueError: boom", message) + + def test_threshold_filters_lower_levels_and_silent_ships_nothing(self): + warn_only = self.make_shipper(level="warn") + warn_only.info("skipped") + warn_only.warning("kept") + silent = self.make_shipper(level="silent") + silent.critical("never") + warn_only.flush() + silent.flush() + + self.assertEqual([e["message"] for e in self.omni.entries()], ["kept"]) + + +class FailureTests(ShipperTestCase): + def test_a_rejecting_sink_never_raises_and_warns_once(self): + omni = _FakeOmniLogger(status=400) + self.addCleanup(omni.stop) + shipper = self.make_shipper(base_url=omni.url) + + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + shipper.info("one") + shipper.flush() + shipper.info("two") + shipper.flush() + + self.assertEqual(len(omni.requests), 2) + self.assertEqual(stderr.getvalue().count("OmniLogger rejected"), 1) + + def test_an_unreachable_sink_never_raises(self): + shipper = self.make_shipper(base_url=_unused_url()) + shipper.info("nobody home") + + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + shipper.flush() + shipper.info("again") + shipper.flush() # inside the warning interval, so silent + + self.assertIn("send 1 entries", stderr.getvalue()) + self.assertEqual(stderr.getvalue().count("[logshipper]"), 1) + + def test_a_full_buffer_drops_the_newest_entries_and_warns_once(self): + shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6) + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + for i in range(10): + shipper.info(f"m{i}") + shipper.flush() + + self.assertEqual([e["message"] for e in self.omni.entries()], ["m0", "m1", "m2"]) + self.assertEqual(stderr.getvalue().count("buffer full"), 1) + + def test_a_redirect_is_not_followed_so_the_token_stays_with_the_configured_url(self): + class Redirect(BaseHTTPRequestHandler): + def do_POST(self): # noqa: N802 + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + self.send_response(307) + self.send_header("Location", "http://127.0.0.1:1/elsewhere") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Redirect) + threading.Thread( + target=server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True + ).start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + shipper = self.make_shipper(base_url=f"http://127.0.0.1:{server.server_port}") + shipper.info("x") + + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + shipper.flush() + self.assertIn("HTTP 307", stderr.getvalue()) + + +def _buffered_messages(shipper: Shipper) -> list[str]: + return [json.loads(entry)["message"] for entry in shipper._buffer] + + +class RetryTests(ShipperTestCase): + def test_a_503_is_retried_and_each_entry_arrives_once_in_order(self): + self.omni.statuses = [503] + shipper = self.make_shipper() + + with contextlib.redirect_stderr(io.StringIO()) as stderr: + shipper.info("a") + shipper.info("b") + shipper.flush() # refused with 503, so a and b wait for the next flush + shipper.info("c") + shipper.flush() # accepted: a, b and c, in order + shipper.flush() # nothing left, so no third request + + self.assertEqual([r["status"] for r in self.omni.requests], [503, 202]) + self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"]) + self.assertIn("will retry", stderr.getvalue()) + + def test_a_429_or_another_5xx_is_retried_as_well(self): + for status in (429, 500): + with self.subTest(status=status): + self.omni.statuses = [status] + shipper = self.make_shipper() + with contextlib.redirect_stderr(io.StringIO()): + shipper.info(f"after {status}") + shipper.flush() + shipper.flush() + + self.assertEqual(self.omni.requests[-1]["status"], 202) + messages = [e["message"] for e in self.omni.entries()] + self.assertEqual(messages.count(f"after {status}"), 1) + + def test_a_400_is_dropped_and_not_retried(self): + self.omni.statuses = [400] + shipper = self.make_shipper() + + with contextlib.redirect_stderr(io.StringIO()) as stderr: + shipper.info("rejected") + shipper.flush() + shipper.flush() # nothing was kept, so no second request + shipper.info("next") + shipper.flush() + + self.assertEqual([r["status"] for r in self.omni.requests], [400, 202]) + self.assertEqual([e["message"] for e in self.omni.entries()], ["next"]) + self.assertEqual(_buffered_messages(shipper), []) + self.assertIn("OmniLogger rejected 1 entries: HTTP 400", stderr.getvalue()) + + def test_a_failed_batch_stops_the_rest_of_the_flush(self): + self.omni.statuses = [202, 503] + shipper = self.make_shipper(max_batch_size=10**6, buffer_capacity=1000) + # Each entry is about 8 KiB, so these 600 need three request bodies. + messages = [f"{i:04d}".ljust(MAX_MESSAGE_BYTES, "x") for i in range(600)] + with contextlib.redirect_stderr(io.StringIO()): + for message in messages: + shipper.info(message) + shipper.flush() # the first body is accepted, the second refused, the third never sent + + self.assertEqual([r["status"] for r in self.omni.requests], [202, 503]) + delivered = [e["message"] for e in self.omni.entries()] + self.assertEqual(delivered, messages[: len(delivered)]) + + shipper.flush() + self.assertEqual([e["message"] for e in self.omni.entries()], messages) + + def test_during_an_outage_the_buffer_holds_at_most_its_capacity_oldest_first(self): + self.omni.status = 503 + shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6) + + with contextlib.redirect_stderr(io.StringIO()): + for message in ("a", "b", "c"): + shipper.info(message) + shipper.flush() # refused, so a, b and c wait for the next flush + for message in ("d", "e"): + shipper.info(message) # the buffer is full, so these are dropped + shipper.flush() # still refused + + self.assertEqual(_buffered_messages(shipper), ["a", "b", "c"]) + + self.omni.status = 202 + shipper.flush() + self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"]) + + def test_entries_logged_while_a_retry_waits_are_dropped_newest_first(self): + self.omni.status = 503 + shipper = self.make_shipper(buffer_capacity=3, max_batch_size=10**6) + for message in ("a", "b", "c"): + shipper.info(message) + + send = shipper._post + + def send_while_logging(body, count): + # d and e are logged while a, b and c are in flight, so the retried batch does not fit. + shipper.info("d") + shipper.info("e") + return send(body, count) + + shipper._post = send_while_logging + with mock.patch.object(shipper, "_warn") as warn: + shipper.flush() + del shipper._post + + self.assertEqual(_buffered_messages(shipper), ["a", "b", "c"]) + warn.assert_any_call("buffer full while retrying, dropping 2 log entries for service 'svc'") + + self.omni.status = 202 + shipper.flush() + self.assertEqual([e["message"] for e in self.omni.entries()], ["a", "b", "c"]) + + +class ConstructionTests(unittest.TestCase): + def test_the_package_exports_the_shipper_and_handler(self): + import shared_backend + + self.assertIs(shared_backend.Shipper, Shipper) + self.assertIs(shared_backend.OmniLoggerHandler, OmniLoggerHandler) + + def test_the_trailing_slash_is_optional_and_the_level_defaults_to_info(self): + omni = _FakeOmniLogger() + self.addCleanup(omni.stop) + shipper = Shipper(base_url=omni.url + "///", ingest_token="t", service="svc") + self.addCleanup(shipper.close) + self.assertEqual(shipper._url, omni.url + "/api/logs") + self.assertEqual(shipper._threshold, 20) + self.assertEqual(shipper._thread.name, "logshipper-svc") + + +class SetCredentialsTests(ShipperTestCase): + def test_a_rotated_token_is_sent_from_the_next_flush(self): + shipper = self.make_shipper() + shipper.set_credentials(self.omni.url, "rotated-token") + shipper.info("after rotation") + shipper.flush() + + request = self.omni.requests[0] + self.assertEqual(request["path"], "/api/logs") + self.assertEqual(request["authorization"], "Bearer rotated-token") + self.assertEqual(self.omni.entries()[0]["message"], "after rotation") + + def test_a_new_url_is_used_and_its_trailing_slashes_are_stripped(self): + other = _FakeOmniLogger() + self.addCleanup(other.stop) + shipper = self.make_shipper() + shipper.set_credentials(other.url + "///", "t2") + shipper.info("to the new endpoint") + shipper.flush() + + self.assertEqual(shipper._url, other.url + "/api/logs") + self.assertEqual(self.omni.requests, []) + self.assertEqual([e["message"] for e in other.entries()], ["to the new endpoint"]) + + def test_an_empty_url_or_token_disables_shipping_and_drops_the_buffer(self): + for base_url, token in ((self.omni.url, ""), ("", "secret-token"), (" ", "secret-token")): + with self.subTest(base_url=base_url, token=token): + shipper = self.make_shipper() + shipper.info("buffered before disabling") + shipper.set_credentials(base_url, token) + shipper.flush() + shipper.info("ignored while disabled") + shipper.flush() + self.assertEqual(self.omni.requests, []) + + def test_disabled_shipper_buffers_nothing(self): + shipper = Shipper(base_url="", ingest_token="", service="svc", flush_interval=3600) + self.addCleanup(shipper.close) + shipper.info("nothing to send to") + shipper.error("still nothing") + + self.assertEqual(shipper._buffer, []) + self.assertIsNone(shipper._url) + + def test_re_enabling_after_disabling_ships_again(self): + shipper = self.make_shipper() + shipper.set_credentials("", "") + shipper.set_credentials(self.omni.url, "secret-token") + shipper.info("back on") + shipper.flush() + + self.assertEqual([e["message"] for e in self.omni.entries()], ["back on"]) + + def test_an_in_flight_flush_is_dropped_once_shipping_is_disabled(self): + shipper = self.make_shipper() + shipper.set_credentials("", "") + shipper._post(b'[{"message":"late"}]', 1) + + self.assertEqual(self.omni.requests, []) + + def test_changing_credentials_does_not_restart_the_background_thread(self): + shipper = self.make_shipper() + thread = shipper._thread + shipper.set_credentials("", "") + shipper.set_credentials(self.omni.url, "t2") + + self.assertIs(shipper._thread, thread) + self.assertTrue(thread.is_alive()) + + +if __name__ == "__main__": + unittest.main()