Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01b18be1e4 | ||
|
|
ed3544acfe |
No files matched your search
@@ -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 |
|
||||
|
||||
|
||||
@@ -78,3 +78,8 @@ NOTIF_RETENTION_MS=604800000
|
||||
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=
|
||||
+3
-2
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+27
-23
@@ -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()
|
||||
|
||||
+4
-3
@@ -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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@gabriel20xx/web-ui": patch
|
||||
---
|
||||
|
||||
Fix `MediaPlayer` controls not fading away during playback when the pointer stays still. Pointer movement now counts as activity anywhere over the player, including over a picture drawn on a canvas stacked above the frame, so the controls fade after a few seconds and come back when the pointer moves over the player again. The `autoHideControls` doc comment now describes its real behavior: `true` (the default) fades the controls, `false` keeps them visible.
|
||||
@@ -128,7 +128,10 @@
|
||||
controls?: boolean
|
||||
/** Renders the controls over the media surface or as a toolbar below it. */
|
||||
controlsPlacement?: 'overlay' | 'toolbar'
|
||||
/** Keep controls visible during playback. */
|
||||
/**
|
||||
* Fade the controls out after a few seconds of playback with no pointer or key activity over
|
||||
* the player. False keeps them visible while playing.
|
||||
*/
|
||||
autoHideControls?: boolean
|
||||
/** Whether clicks and key presses on the media surface control playback. */
|
||||
surfaceControls?: boolean
|
||||
@@ -192,6 +195,19 @@
|
||||
scheduleControlsHide()
|
||||
}
|
||||
|
||||
// The picture can sit on a canvas stacked above the frame, where the pointer never reaches the
|
||||
// frame's own elements. Pointer activity therefore counts anywhere inside the player's box.
|
||||
function handlePointerActivity(event: PointerEvent) {
|
||||
if (!controls || !playerFrame) return
|
||||
const bounds = playerFrame.getBoundingClientRect()
|
||||
const inside =
|
||||
event.clientX >= bounds.left &&
|
||||
event.clientX <= bounds.right &&
|
||||
event.clientY >= bounds.top &&
|
||||
event.clientY <= bounds.bottom
|
||||
if (inside) handlePlayerActivity()
|
||||
}
|
||||
|
||||
function togglePlayback() {
|
||||
if (controlsDisabled) return
|
||||
if (onTogglePlayback) {
|
||||
@@ -506,6 +522,8 @@
|
||||
<svelte:window
|
||||
onfullscreenchange={handleFullscreenChange}
|
||||
onkeydown={globalKeyboardControls ? handleKeydown : undefined}
|
||||
onpointermove={controls ? handlePointerActivity : undefined}
|
||||
onpointerdown={controls ? handlePointerActivity : undefined}
|
||||
/>
|
||||
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { cleanup, fireEvent, render } from '@testing-library/svelte';
|
||||
import { tick } from 'svelte';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import MediaPlayer from '../src/lib/components/MediaPlayer.svelte';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
const SOURCE = 'https://media.example/clip.mp4';
|
||||
const HIDDEN_CLASS = 'media-player-controls-hidden';
|
||||
|
||||
const videoElement = (): HTMLVideoElement => {
|
||||
const element = document.querySelector<HTMLVideoElement>('video');
|
||||
if (!element) throw new Error('no video element');
|
||||
return element;
|
||||
};
|
||||
|
||||
const frameElement = (): HTMLElement => {
|
||||
const element = document.querySelector<HTMLElement>('.media-player');
|
||||
if (!element) throw new Error('no player frame');
|
||||
return element;
|
||||
};
|
||||
|
||||
const controlsRoot = (): HTMLElement => {
|
||||
const element = document.querySelector<HTMLElement>('.media-player-controls');
|
||||
if (!element) throw new Error('no controls');
|
||||
return element;
|
||||
};
|
||||
|
||||
// jsdom has no layout, so the player's box on the page is given by hand.
|
||||
function placeFrame(left: number, top: number, right: number, bottom: number) {
|
||||
frameElement().getBoundingClientRect = () =>
|
||||
({ left, top, right, bottom, width: right - left, height: bottom - top, x: left, y: top, toJSON: () => ({}) }) as DOMRect;
|
||||
}
|
||||
|
||||
// jsdom does not load or play media, so position, length and rate are set by hand.
|
||||
function setMedia(element: HTMLVideoElement, media: { currentTime: number; duration: number }) {
|
||||
Object.defineProperty(element, 'currentTime', { configurable: true, writable: true, value: media.currentTime });
|
||||
Object.defineProperty(element, 'duration', { configurable: true, value: media.duration });
|
||||
Object.defineProperty(element, 'playbackRate', { configurable: true, writable: true, value: 1 });
|
||||
}
|
||||
|
||||
describe('MediaPlayer controls auto-hide', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('fades the controls after a playing video has been idle, with no pointer movement', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
|
||||
await fireEvent.play(element);
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(false);
|
||||
|
||||
vi.advanceTimersByTime(2600);
|
||||
await tick();
|
||||
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(true);
|
||||
});
|
||||
|
||||
it('fades the controls when playback is driven from outside (controlled playing prop)', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip', playing: true } });
|
||||
await tick();
|
||||
|
||||
vi.advanceTimersByTime(2600);
|
||||
await tick();
|
||||
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the controls visible while the pointer keeps moving over the player', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
await fireEvent.play(element);
|
||||
|
||||
vi.advanceTimersByTime(2000);
|
||||
await fireEvent.mouseMove(frameElement());
|
||||
vi.advanceTimersByTime(2000);
|
||||
await tick();
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(false);
|
||||
|
||||
vi.advanceTimersByTime(600);
|
||||
await tick();
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(true);
|
||||
});
|
||||
|
||||
it('shows the controls again on pause and does not hide them while paused', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
await fireEvent.play(element);
|
||||
vi.advanceTimersByTime(2600);
|
||||
await tick();
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(true);
|
||||
|
||||
await fireEvent.pause(element);
|
||||
vi.advanceTimersByTime(5000);
|
||||
await tick();
|
||||
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(false);
|
||||
});
|
||||
|
||||
it('never fades the controls when autoHideControls is off', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip', autoHideControls: false } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
await fireEvent.play(element);
|
||||
|
||||
vi.advanceTimersByTime(10000);
|
||||
await tick();
|
||||
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(false);
|
||||
});
|
||||
|
||||
it('counts pointer movement over the player area as activity when an element above the frame takes the events', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip', controlsPlacement: 'toolbar' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
placeFrame(0, 0, 640, 360);
|
||||
await fireEvent.play(element);
|
||||
vi.advanceTimersByTime(2600);
|
||||
await tick();
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(true);
|
||||
|
||||
// MediaViewer draws the picture on a canvas beside the frame, so the pointer never reaches the frame itself.
|
||||
document.body.dispatchEvent(new MouseEvent('pointermove', { bubbles: true, clientX: 320, clientY: 180 }));
|
||||
await tick();
|
||||
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores pointer movement outside the player area', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
placeFrame(0, 0, 640, 360);
|
||||
await fireEvent.play(element);
|
||||
vi.advanceTimersByTime(2600);
|
||||
await tick();
|
||||
|
||||
document.body.dispatchEvent(new MouseEvent('pointermove', { bubbles: true, clientX: 900, clientY: 180 }));
|
||||
await tick();
|
||||
|
||||
expect(controlsRoot().classList.contains(HIDDEN_CLASS)).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user