diff --git a/README.md b/README.md index 2bd21e9..5954ded 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ The device-sync API token (generated from the dashboard's Settings page, used by | `PRODUCTION` | No | `false` | Set `true` to refuse plain HTTP: requests must arrive over TLS or through a `TRUSTED_PROXIES` proxy sending `X-Forwarded-Proto: https`. Requires `TRUSTED_PROXIES`. With `false`, the server logs a warning that TLS is off. | | `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup | | `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup | +| `OMNILOGGER_URL` | No | unset | Optional initial base URL of the OmniLogger log sink. Server log lines are also sent there when it and `OMNILOGGER_INGEST_TOKEN` are both set; console output is unchanged. ProjectConfigurator's push can supply or replace it at runtime. The `remap-users` command is not shipped. | +| `OMNILOGGER_INGEST_TOKEN` | No | unset | Optional initial ingest token for this service (`collabtable`). ProjectConfigurator normally supplies the token at runtime through its core-services push, which also starts shipping. Shipping stays off until both a URL and a token are known. | | `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops | | `NOTIF_RETENTION_MS` | No | `604800000` (7 days) | How long sync notifications are retained before cleanup | diff --git a/backend/.env.example b/backend/.env.example index 86d1711..621694c 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,80 +1,85 @@ -################################################################# -# Server -################################################################# -PORT=8080 -APP_VERSION=dev - -# Set to "true" once served over HTTPS - marks the admin session cookie Secure. -COOKIE_SECURE=false - -# Comma-separated IPs or CIDR ranges of reverse proxies whose X-Forwarded-For and -# X-Forwarded-Proto headers are believed. Empty (default) trusts no proxy, so the -# socket address is used for rate limits. Example: 10.0.0.1,172.18.0.0/16 -TRUSTED_PROXIES= - -# Set to "true" in production. Plain HTTP requests are refused unless they arrive -# over TLS or through a TRUSTED_PROXIES proxy that sends X-Forwarded-Proto: https. -# Requires TRUSTED_PROXIES. Default false: plain HTTP is allowed and logs a warning. -PRODUCTION=false - -################################################################# -# Authentication (AuthGuard) -################################################################# -# Base URL of the AuthGuard centralized identity service this app authenticates -# through instead of a local user table. AuthGuard integration has three states: -# - AUTHGUARD_URL set: used immediately. -# - AUTHGUARD_URL unset, AUTH_DISABLED unset/false (the default): "pending" -# -- auth stays fully enabled/gated, waiting for ProjectConfigurator to -# push a live URL (see below), and fails closed on auth calls until one -# arrives. -# - AUTH_DISABLED=true: authentication is fully off (no login screen, -# everything open). -# AUTHGUARD_URL=https://auth.example.com -# AUTH_DISABLED=true -# Only set AUTH_DISABLED=true for local development or a deployment you are -# certain does not need access control. Leaving AUTHGUARD_URL unset does NOT -# do this -- it just leaves the service "pending" until ProjectConfigurator's -# push arrives. - -# Base URL of a CarrierNode instance, for the generic per-project mount API -# (not used by any feature here yet). -# CARRIERNODE_URL=https://carrier.example.com - -# Shared secret CarrierNode and ProjectConfigurator were also configured with, -# sent/checked as X-Internal-Auth. AUTHGUARD_URL and CARRIERNODE_URL above are -# only the bootstrap fallback: once this project is registered in -# ProjectConfigurator's Projects workspace, it pushes both values here -# automatically (PUT /api/core-services/internal) and keeps them current -- -# see Core/ProjectConfigurator/README.md's "Pushing core service info to -# other projects". That push is itself authenticated with this secret, so it -# still needs to be set even though AUTHGUARD_URL/CARRIERNODE_URL don't. A -# push never overrides AUTH_DISABLED=true; it only ever retargets an -# already-enabled AuthGuard connection. - -################################################################# -# PostgreSQL configuration -################################################################# -# Postgres connection string (bring your own - this app does not run Postgres for you). -# Example: postgres://user:password@localhost:5432/collabtable -DATABASE_URL= - -################################################################# -# Startup resilience and sync tuning -################################################################# -# DB init retry interval in milliseconds (default: 5000) -DB_INIT_RETRY_INTERVAL_MS=5000 - -# Max DB init retry attempts. 0 means retry forever (default: 0) -DB_INIT_RETRY_MAX_ATTEMPTS=0 - -# Allow at most this much client clock skew into sync timestamps (default: 0) -# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops. -SYNC_MAX_FUTURE_SKEW_MS=0 - -# Notification retention period in milliseconds (default: 7 days) -NOTIF_RETENTION_MS=604800000 - -# Required shared-service authentication secret. -SECRET=change-me-to-a-long-random-value -# Set true only for local development or a standalone deployment. -AUTH_DISABLED=false +################################################################# +# Server +################################################################# +PORT=8080 +APP_VERSION=dev + +# Set to "true" once served over HTTPS - marks the admin session cookie Secure. +COOKIE_SECURE=false + +# Comma-separated IPs or CIDR ranges of reverse proxies whose X-Forwarded-For and +# X-Forwarded-Proto headers are believed. Empty (default) trusts no proxy, so the +# socket address is used for rate limits. Example: 10.0.0.1,172.18.0.0/16 +TRUSTED_PROXIES= + +# Set to "true" in production. Plain HTTP requests are refused unless they arrive +# over TLS or through a TRUSTED_PROXIES proxy that sends X-Forwarded-Proto: https. +# Requires TRUSTED_PROXIES. Default false: plain HTTP is allowed and logs a warning. +PRODUCTION=false + +################################################################# +# Authentication (AuthGuard) +################################################################# +# Base URL of the AuthGuard centralized identity service this app authenticates +# through instead of a local user table. AuthGuard integration has three states: +# - AUTHGUARD_URL set: used immediately. +# - AUTHGUARD_URL unset, AUTH_DISABLED unset/false (the default): "pending" +# -- auth stays fully enabled/gated, waiting for ProjectConfigurator to +# push a live URL (see below), and fails closed on auth calls until one +# arrives. +# - AUTH_DISABLED=true: authentication is fully off (no login screen, +# everything open). +# AUTHGUARD_URL=https://auth.example.com +# AUTH_DISABLED=true +# Only set AUTH_DISABLED=true for local development or a deployment you are +# certain does not need access control. Leaving AUTHGUARD_URL unset does NOT +# do this -- it just leaves the service "pending" until ProjectConfigurator's +# push arrives. + +# Base URL of a CarrierNode instance, for the generic per-project mount API +# (not used by any feature here yet). +# CARRIERNODE_URL=https://carrier.example.com + +# Shared secret CarrierNode and ProjectConfigurator were also configured with, +# sent/checked as X-Internal-Auth. AUTHGUARD_URL and CARRIERNODE_URL above are +# only the bootstrap fallback: once this project is registered in +# ProjectConfigurator's Projects workspace, it pushes both values here +# automatically (PUT /api/core-services/internal) and keeps them current -- +# see Core/ProjectConfigurator/README.md's "Pushing core service info to +# other projects". That push is itself authenticated with this secret, so it +# still needs to be set even though AUTHGUARD_URL/CARRIERNODE_URL don't. A +# push never overrides AUTH_DISABLED=true; it only ever retargets an +# already-enabled AuthGuard connection. + +################################################################# +# PostgreSQL configuration +################################################################# +# Postgres connection string (bring your own - this app does not run Postgres for you). +# Example: postgres://user:password@localhost:5432/collabtable +DATABASE_URL= + +################################################################# +# Startup resilience and sync tuning +################################################################# +# DB init retry interval in milliseconds (default: 5000) +DB_INIT_RETRY_INTERVAL_MS=5000 + +# Max DB init retry attempts. 0 means retry forever (default: 0) +DB_INIT_RETRY_MAX_ATTEMPTS=0 + +# Allow at most this much client clock skew into sync timestamps (default: 0) +# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops. +SYNC_MAX_FUTURE_SKEW_MS=0 + +# Notification retention period in milliseconds (default: 7 days) +NOTIF_RETENTION_MS=604800000 + +# Required shared-service authentication secret. +SECRET=change-me-to-a-long-random-value +# Set true only for local development or a standalone deployment. +AUTH_DISABLED=false + +# Optional initial values for shipping server log lines to OmniLogger. Shipping runs only when both are set. +# ProjectConfigurator normally supplies the ingest token at runtime, so these can stay empty. +OMNILOGGER_URL= +OMNILOGGER_INGEST_TOKEN= diff --git a/backend/db.go b/backend/db.go index 04e3e29..cead094 100644 --- a/backend/db.go +++ b/backend/db.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" + "repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper" sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres" ) @@ -314,7 +315,7 @@ func (d *DB) pruneExpiredSessions(ctx context.Context) { return case <-ticker.C: if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil { - fmt.Printf("[db] session prune failed: %v\n", err) + logPrintf(logshipper.LevelWarn, "[db] session prune failed: %v\n", err) } } } @@ -334,7 +335,7 @@ func (d *DB) cleanupNotifications(ctx context.Context) { case <-ticker.C: cutoff := time.Now().UnixMilli() - retention if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil { - fmt.Printf("[db] notification cleanup failed: %v\n", err) + logPrintf(logshipper.LevelWarn, "[db] notification cleanup failed: %v\n", err) } } } diff --git a/backend/notifications.go b/backend/notifications.go index 6f63be3..0a583e8 100644 --- a/backend/notifications.go +++ b/backend/notifications.go @@ -9,6 +9,8 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" + + "repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper" ) type queryExecutor interface { @@ -79,6 +81,6 @@ func ignoreNotificationError(err error) { if err != nil { // Notifications are an acceleration path for clients that poll. A failed // notification must never roll back the data mutation that produced it. - fmt.Printf("[notifications] enqueue failed: %v\n", err) + logPrintf(logshipper.LevelWarn, "[notifications] enqueue failed: %v\n", err) } } diff --git a/backend/omnilogger.go b/backend/omnilogger.go new file mode 100644 index 0000000..7246e52 --- /dev/null +++ b/backend/omnilogger.go @@ -0,0 +1,86 @@ +package main + +import ( + "fmt" + "io" + "log" + "os" + "strings" + + "repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper" +) + +// omniShipper mirrors the server's console lines to OmniLogger. It is always set: with no OMNILOGGER_URL or +// OMNILOGGER_INGEST_TOKEN it is disabled and ships nothing, until main hands it ProjectConfigurator's +// pushed token (see omniShipper.Follow in server.go). +var omniShipper = newOmniLoggerShipper() + +// newOmniLoggerShipper returns a shipper for OmniLogger. OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are +// optional initial values; ProjectConfigurator normally supplies the token at runtime. +func newOmniLoggerShipper() *logshipper.Shipper { + return logshipper.New(logshipper.Config{ + BaseURL: strings.TrimSpace(os.Getenv("OMNILOGGER_URL")), + IngestToken: strings.TrimSpace(os.Getenv("OMNILOGGER_INGEST_TOKEN")), + Service: "collabtable", + }) +} + +// stdoutLog and stderrLog are the Loggers behind the helpers below. Each writes its line to its console stream +// exactly as the fmt function it replaced did, and ships the line to OmniLogger at the severity the caller names. +var ( + stdoutLog = newConsoleLogger(os.Stdout, omniShipper) + stderrLog = newConsoleLogger(os.Stderr, omniShipper) +) + +// newConsoleLogger returns a Logger for console. NewLogger copies the standard logger's flags, and these helper +// lines have never carried a timestamp, so the flags are cleared only while the Logger is made. The standard +// logger keeps its own flags. +func newConsoleLogger(console io.Writer, shipper *logshipper.Shipper) *logshipper.Logger { + previous := log.Flags() + log.SetFlags(0) + defer log.SetFlags(previous) + return logshipper.NewLogger(console, shipper) +} + +// logPrintf, logPrintln, logErrorf and logErrorln write to stdout or stderr exactly as the fmt functions +// they wrap, and also ship the line to OmniLogger when shipping is enabled, at the severity the caller +// names. The console stream is the one the helper always used, whatever the severity. +func logPrintf(sev logshipper.Level, format string, args ...any) { + logLine(stdoutLog, sev, fmt.Sprintf(format, args...)) +} + +func logPrintln(sev logshipper.Level, args ...any) { + logLine(stdoutLog, sev, fmt.Sprintln(args...)) +} + +func logErrorf(sev logshipper.Level, format string, args ...any) { + logLine(stderrLog, sev, fmt.Sprintf(format, args...)) +} + +func logErrorln(sev logshipper.Level, args ...any) { + logLine(stderrLog, sev, fmt.Sprintln(args...)) +} + +// logLine writes msg to l's console and ships it at sev. msg keeps the newline its fmt call added, so the console +// line is the same bytes as before. Levels outside the five OmniLogger knows are reported as errors. +func logLine(l *logshipper.Logger, sev logshipper.Level, msg string) { + switch sev { + case logshipper.LevelDebug: + l.Debugf("%s", msg) + case logshipper.LevelInfo: + l.Infof("%s", msg) + case logshipper.LevelWarn: + l.Warnf("%s", msg) + case logshipper.LevelCritical: + l.Criticalf("%s", msg) + default: + l.Errorf("%s", msg) + } +} + +// exitAfterFlush sends the buffered log lines to OmniLogger and then exits. Use it instead of os.Exit after a +// line that must reach OmniLogger, such as a critical startup failure, which os.Exit would otherwise lose. +func exitAfterFlush(code int) { + omniShipper.Flush() + os.Exit(code) +} diff --git a/backend/omnilogger_test.go b/backend/omnilogger_test.go new file mode 100644 index 0000000..5f1ac6f --- /dev/null +++ b/backend/omnilogger_test.go @@ -0,0 +1,190 @@ +package main + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + + "repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig" + "repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper" +) + +// fakeOmniLogger is a stand-in OmniLogger that accepts only the bearer token it was started with and +// records every entry it receives. +type fakeOmniLogger struct { + *httptest.Server + mu sync.Mutex + requests int + entries []map[string]any +} + +func newFakeOmniLogger(t *testing.T, token string) *fakeOmniLogger { + t.Helper() + f := &fakeOmniLogger{} + f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + f.requests++ + f.mu.Unlock() + if r.Header.Get("Authorization") != "Bearer "+token { + w.WriteHeader(http.StatusUnauthorized) + return + } + var batch []map[string]any + if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + f.mu.Lock() + f.entries = append(f.entries, batch...) + f.mu.Unlock() + w.WriteHeader(http.StatusAccepted) + })) + t.Cleanup(f.Close) + return f +} + +// received reports how many requests arrived and the entries that were accepted. +func (f *fakeOmniLogger) received() (int, []map[string]any) { + f.mu.Lock() + defer f.mu.Unlock() + return f.requests, append([]map[string]any(nil), f.entries...) +} + +// hasMessage reports whether an entry for the collabtable service contains text. +func hasMessage(entries []map[string]any, text string) bool { + for _, entry := range entries { + message, _ := entry["message"].(string) + if entry["service"] == "collabtable" && strings.Contains(message, text) { + return true + } + } + return false +} + +// useOmniShipper makes shipper the package's omniShipper for the rest of the test. The helper Loggers are rebuilt +// on it with their consoles discarded, since they are made once at start-up and would otherwise keep the old shipper. +func useOmniShipper(t *testing.T, shipper *logshipper.Shipper) { + t.Helper() + previous, previousOut, previousErr := omniShipper, stdoutLog, stderrLog + omniShipper = shipper + stdoutLog = newConsoleLogger(io.Discard, shipper) + stderrLog = newConsoleLogger(io.Discard, shipper) + t.Cleanup(func() { + _ = shipper.Close() + omniShipper = previous + stdoutLog, stderrLog = previousOut, previousErr + }) +} + +func TestOmniLoggerShipperIsNeverNilAndDisabledWithoutConfig(t *testing.T) { + if omniShipper == nil { + t.Fatal("omniShipper must never be nil") + } + + t.Setenv("OMNILOGGER_URL", "") + t.Setenv("OMNILOGGER_INGEST_TOKEN", "") + shipper := newOmniLoggerShipper() + if shipper == nil { + t.Fatal("shipper must never be nil; with no configuration it is simply disabled") + } + useOmniShipper(t, shipper) + logPrintf(logshipper.LevelInfo, "no configuration, nothing should ship\n") + shipper.Flush() + + // A URL without a token is still disabled, so nothing reaches a reachable OmniLogger. + sink := newFakeOmniLogger(t, "test-token") + t.Setenv("OMNILOGGER_URL", sink.URL) + shipper = newOmniLoggerShipper() + useOmniShipper(t, shipper) + logPrintf(logshipper.LevelInfo, "no token, nothing should ship\n") + shipper.Flush() + if requests, _ := sink.received(); requests != 0 { + t.Fatalf("disabled shipper sent %d requests to OmniLogger", requests) + } +} + +func TestLogPrintfReachesOmniLogger(t *testing.T) { + sink := newFakeOmniLogger(t, "test-token") + t.Setenv("OMNILOGGER_URL", sink.URL) + t.Setenv("OMNILOGGER_INGEST_TOKEN", "test-token") + useOmniShipper(t, newOmniLoggerShipper()) + + logPrintf(logshipper.LevelInfo, "[test] hello from collabtable %d\n", 7) + _ = omniShipper.Close() + + if _, entries := sink.received(); !hasMessage(entries, "hello from collabtable 7") { + t.Fatalf("OmniLogger did not receive the line; entries: %v", entries) + } +} + +func TestOmniLoggerFollowsCoreConfigPush(t *testing.T) { + sink := newFakeOmniLogger(t, "pushed-token") + t.Setenv("OMNILOGGER_URL", "") + t.Setenv("OMNILOGGER_INGEST_TOKEN", "") + shipper := newOmniLoggerShipper() + useOmniShipper(t, shipper) + store := coreconfig.NewStore(coreconfig.Info{}) + shipper.Follow(store) + + logPrintf(logshipper.LevelInfo, "before the push\n") + shipper.Flush() + if requests, _ := sink.received(); requests != 0 { + t.Fatalf("shipper sent %d requests before ProjectConfigurator pushed a token", requests) + } + + store.Set(coreconfig.Info{OmniLoggerURL: sink.URL, OmniLoggerIngestToken: "pushed-token"}) + logPrintf(logshipper.LevelInfo, "after the push\n") + _ = shipper.Close() + + _, entries := sink.received() + if !hasMessage(entries, "after the push") { + t.Fatalf("OmniLogger did not receive the line after the push; entries: %v", entries) + } + if hasMessage(entries, "before the push") { + t.Fatal("a line logged before the push was shipped") + } +} + +// TestConvertedNotificationLineShipsOnceAtWarnAndKeepsConsoleLine runs a converted call site: a failed +// notification is printed on stdout as before, and reaches OmniLogger once, at warn. +func TestConvertedNotificationLineShipsOnceAtWarnAndKeepsConsoleLine(t *testing.T) { + sink := newFakeOmniLogger(t, "test-token") + t.Setenv("OMNILOGGER_URL", sink.URL) + t.Setenv("OMNILOGGER_INGEST_TOKEN", "test-token") + useOmniShipper(t, newOmniLoggerShipper()) + + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + previousStdout := stdoutLog + stdoutLog = newConsoleLogger(writer, omniShipper) + ignoreNotificationError(errors.New("disk full")) + stdoutLog = previousStdout + _ = writer.Close() + console, _ := io.ReadAll(reader) + _ = reader.Close() + if got, want := string(console), "[notifications] enqueue failed: disk full\n"; got != want { + t.Fatalf("console output = %q, want %q", got, want) + } + + _ = omniShipper.Close() + _, entries := sink.received() + var levels []string + for _, entry := range entries { + message, _ := entry["message"].(string) + if entry["service"] == "collabtable" && message == "[notifications] enqueue failed: disk full" { + level, _ := entry["level"].(string) + levels = append(levels, level) + } + } + if len(levels) != 1 || levels[0] != "warn" { + t.Fatalf("OmniLogger levels for the notification line = %v, want exactly one warn (entries %v)", levels, entries) + } +} diff --git a/backend/server.go b/backend/server.go index 53984ad..ab6c60e 100644 --- a/backend/server.go +++ b/backend/server.go @@ -6,8 +6,9 @@ import ( "embed" "encoding/json" "errors" - "fmt" + "io" "io/fs" + "log" "net" "net/http" "os" @@ -20,6 +21,7 @@ import ( sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" "repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig" + "repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper" sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres" ) @@ -53,25 +55,26 @@ func main() { if len(os.Args) > 1 && os.Args[1] == "remap-users" { os.Exit(runRemapUsers(os.Args[2:], os.Stdout)) } + log.SetOutput(io.MultiWriter(os.Stderr, omniShipper.Writer())) port := envOrDefault("PORT", "8080") connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL")) if connectionString == "" { - fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required") - os.Exit(1) + logErrorln(logshipper.LevelCritical, "DATABASE_URL environment variable is required") + exitAfterFlush(1) } internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET")) trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES")) if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) + logErrorln(logshipper.LevelCritical, err) + exitAfterFlush(1) } // PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so // the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES. production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true") if production && len(trustedProxies) == 0 { - fmt.Fprintln(os.Stderr, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there") - os.Exit(1) + logErrorln(logshipper.LevelCritical, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there") + exitAfterFlush(1) } ctx, cancel := context.WithCancel(context.Background()) @@ -79,8 +82,8 @@ func main() { database, err := connectWithRetry(ctx, connectionString) if err != nil { - fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err) - os.Exit(1) + logErrorf(logshipper.LevelCritical, "database initialization failed: %v\n", err) + exitAfterFlush(1) } defer database.close() go database.pruneExpiredSessions(ctx) @@ -98,11 +101,11 @@ func main() { authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true") switch { case authDisabled: - fmt.Println("auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated") + logPrintln(logshipper.LevelWarn, "auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated") case authGuardURL != "": - fmt.Printf("auth: AuthGuard at %s\n", authGuardURL) + logPrintf(logshipper.LevelInfo, "auth: AuthGuard at %s\n", authGuardURL) default: - fmt.Println("auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then") + logPrintln(logshipper.LevelWarn, "auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then") } auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled) @@ -115,6 +118,7 @@ func main() { // is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above). carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL")) coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL}) + omniShipper.Follow(coreConfig) coreConfig.OnUpdate(func(info coreconfig.Info) { if info.AuthGuardURL != "" { auth.SetAuthGuardBaseURL(info.AuthGuardURL) @@ -132,8 +136,8 @@ func main() { webRoot, err := fs.Sub(webFS, "web") if err != nil { - fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err) - os.Exit(1) + logErrorf(logshipper.LevelCritical, "embedded web assets missing: %v\n", err) + exitAfterFlush(1) } mux := http.NewServeMux() @@ -142,9 +146,9 @@ func main() { handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux))) if production { handler = withHTTPSRequired(trustedProxies, handler) - fmt.Println("PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https") + logPrintln(logshipper.LevelInfo, "PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https") } else { - fmt.Fprintln(os.Stderr, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.") + logErrorln(logshipper.LevelWarn, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.") } httpServer := &http.Server{ @@ -156,11 +160,11 @@ func main() { IdleTimeout: 120 * time.Second, } - fmt.Printf("CollabTable Go server listening on :%s\n", port) - fmt.Printf("Database: PostgreSQL (pgx)\n") + logPrintf(logshipper.LevelInfo, "CollabTable Go server listening on :%s\n", port) + logPrintf(logshipper.LevelInfo, "Database: PostgreSQL (pgx)\n") if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { - fmt.Fprintf(os.Stderr, "server error: %v\n", err) - os.Exit(1) + logErrorf(logshipper.LevelCritical, "server error: %v\n", err) + exitAfterFlush(1) } } @@ -172,7 +176,7 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) if err == nil { if schemaErr := database.initSchema(ctx); schemaErr == nil { if attempt > 1 { - fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt) + logPrintf(logshipper.LevelInfo, "[DB] Connected after %d attempt(s)\n", attempt) } return database, nil } else { @@ -181,11 +185,11 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) } } - fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err) + logErrorf(logshipper.LevelWarn, "[DB] Initialization attempt %d failed: %v\n", attempt, err) if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts { return nil, err } - fmt.Printf("[DB] Retrying in %s...\n", retryOptions.Interval) + logPrintf(logshipper.LevelWarn, "[DB] Retrying in %s...\n", retryOptions.Interval) select { case <-ctx.Done(): return nil, ctx.Err() diff --git a/backend/sync.go b/backend/sync.go index 54c157f..ab70ba7 100644 --- a/backend/sync.go +++ b/backend/sync.go @@ -3,12 +3,13 @@ package main import ( "context" "errors" - "fmt" "net/http" "sort" "time" "github.com/jackc/pgx/v5" + + "repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper" ) // maxConcurrentSyncs caps sync requests in flight. It stays below the pool size @@ -431,7 +432,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { orphans := make([]OrphanValue, 0) incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues) if incoming > 0 { - fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues)) + logPrintf(logshipper.LevelInfo, "[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues)) } err := s.db.withTx(r.Context(), func(tx pgx.Tx) error { @@ -447,7 +448,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) { writeJSONError(w, http.StatusNotFound, "List not found") return } - fmt.Printf("[SYNC] Failed: %v\n", err) + logPrintf(logshipper.LevelError, "[SYNC] Failed: %v\n", err) writeJSONError(w, http.StatusInternalServerError, "Sync failed") return }