Skip to content

Modern Docker Management, Designed for Everyone

perf: improve websocket logs performance (#534)

Kyle Mendellbfd1064042a8
diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.go
index e239d66a1..b1b6e6dd8 100644
--- a/backend/internal/api/container_handler.go
+++ b/backend/internal/api/container_handler.go
@@ -2,10 +2,13 @@ package api
import (
"context"
+ "fmt"
"io"
"net/http"
"strings"
"sync"
+ "sync/atomic"
+ "time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
@@ -50,26 +53,66 @@ type containerLogStream struct {
hub *ws.Hub
once sync.Once
cancel context.CancelFunc
+ format string
+ seq atomic.Uint64
}
-func (h *ContainerHandler) getOrStartContainerLogHub(containerID string, follow bool, tail, since string, timestamps bool) *ws.Hub {
- v, _ := h.logStreams.LoadOrStore(containerID, &containerLogStream{
- hub: ws.NewHub(1024),
+func (h *ContainerHandler) getOrStartContainerLogHub(containerID, format string, batched bool, follow bool, tail, since string, timestamps bool) *ws.Hub {
+ key := fmt.Sprintf("%s::%s::batched=%t", containerID, format, batched)
+ v, _ := h.logStreams.LoadOrStore(key, &containerLogStream{
+ hub: ws.NewHub(1024),
+ format: format,
})
ls := v.(*containerLogStream)
ls.once.Do(func() {
ctx, cancel := context.WithCancel(context.Background())
ls.cancel = cancel
-
go ls.hub.Run(ctx)
+ // Always pull raw lines first
lines := make(chan string, 256)
go func() {
defer close(lines)
_ = h.containerService.StreamLogs(ctx, containerID, lines, follow, tail, since, timestamps)
}()
- go ws.ForwardLines(ctx, ls.hub, lines)
+
+ if format == "json" {
+ msgs := make(chan ws.LogMessage, 256)
+ go func() {
+ defer close(msgs)
+ for line := range lines {
+ level, msg, ts := ws.NormalizeContainerLine(line)
+ seq := ls.seq.Add(1)
+ timestamp := ts
+ if timestamp == "" {
+ timestamp = ws.NowRFC3339()
+ }
+ msgs <- ws.LogMessage{
+ Seq: seq,
+ Level: level,
+ Message: msg,
+ Timestamp: timestamp,
+ }
+ }
+ }()
+ if batched {
+ go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
+ } else {
+ go ws.ForwardLogJSON(ctx, ls.hub, msgs)
+ }
+ } else {
+ // Plain text mode still strips ANSI & timestamps for consistency
+ cleanChan := make(chan string, 256)
+ go func() {
+ defer close(cleanChan)
+ for line := range lines {
+ _, msg, _ := ws.NormalizeContainerLine(line)
+ cleanChan <- msg
+ }
+ }()
+ go ws.ForwardLines(ctx, ls.hub, cleanChan)
+ }
})
return ls.hub
@@ -91,12 +134,14 @@ func (h *ContainerHandler) GetLogsWS(c *gin.Context) {
tail := c.DefaultQuery("tail", "100")
since := c.Query("since")
timestamps := c.DefaultQuery("timestamps", "false") == "true"
+ format := c.DefaultQuery("format", "text")
+ batched := c.DefaultQuery("batched", "false") == "true"
conn, err := wsUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
- hub := h.getOrStartContainerLogHub(containerID, follow, tail, since, timestamps)
+ hub := h.getOrStartContainerLogHub(containerID, format, batched, follow, tail, since, timestamps)
ws.ServeClient(context.Background(), hub, conn)
}
diff --git a/backend/internal/api/project_handler.go b/backend/internal/api/project_handler.go
index d17e794f7..4812d59c8 100644
--- a/backend/internal/api/project_handler.go
+++ b/backend/internal/api/project_handler.go
@@ -7,6 +7,7 @@ import (
"net/http"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/gin-gonic/gin"
@@ -24,13 +25,18 @@ type ProjectHandler struct {
}
var wsUpgrader = websocket.Upgrader{
- CheckOrigin: func(r *http.Request) bool { return true },
+ CheckOrigin: func(r *http.Request) bool { return true },
+ ReadBufferSize: 32 * 1024,
+ WriteBufferSize: 32 * 1024,
+ EnableCompression: true,
}
type projectLogStream struct {
hub *ws.Hub
once sync.Once
cancel context.CancelFunc
+ format string
+ seq atomic.Uint64
}
func NewProjectHandler(group *gin.RouterGroup, projectService *services.ProjectService, authMiddleware *middleware.AuthMiddleware) {
@@ -307,16 +313,17 @@ func (h *ProjectHandler) RestartProject(c *gin.Context) {
})
}
-func (h *ProjectHandler) getOrStartProjectLogHub(projectID string, follow bool, tail, since string, timestamps bool) *ws.Hub {
- v, _ := h.logStreams.LoadOrStore(projectID, &projectLogStream{
- hub: ws.NewHub(1024),
+func (h *ProjectHandler) getOrStartProjectLogHub(projectID, format string, batched bool, follow bool, tail, since string, timestamps bool) *ws.Hub {
+ key := projectID + "::" + format
+ v, _ := h.logStreams.LoadOrStore(key, &projectLogStream{
+ hub: ws.NewHub(1024),
+ format: format,
})
ls := v.(*projectLogStream)
ls.once.Do(func() {
ctx, cancel := context.WithCancel(context.Background())
ls.cancel = cancel
-
go ls.hub.Run(ctx)
lines := make(chan string, 256)
@@ -324,7 +331,43 @@ func (h *ProjectHandler) getOrStartProjectLogHub(projectID string, follow bool,
defer close(lines)
_ = h.projectService.StreamProjectLogs(ctx, projectID, lines, follow, tail, since, timestamps)
}()
- go ws.ForwardLines(ctx, ls.hub, lines)
+
+ if format == "json" {
+ msgs := make(chan ws.LogMessage, 256)
+ go func() {
+ defer close(msgs)
+ for line := range lines {
+ level, service, msg, ts := ws.NormalizeProjectLine(line)
+ seq := ls.seq.Add(1)
+ timestamp := ts
+ if timestamp == "" {
+ timestamp = ws.NowRFC3339()
+ }
+ msgs <- ws.LogMessage{
+ Seq: seq,
+ Level: level,
+ Message: msg,
+ Service: service,
+ Timestamp: timestamp,
+ }
+ }
+ }()
+ if batched {
+ go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
+ } else {
+ go ws.ForwardLogJSON(ctx, ls.hub, msgs)
+ }
+ } else {
+ cleanChan := make(chan string, 256)
+ go func() {
+ defer close(cleanChan)
+ for line := range lines {
+ _, _, msg, _ := ws.NormalizeProjectLine(line)
+ cleanChan <- msg
+ }
+ }()
+ go ws.ForwardLines(ctx, ls.hub, cleanChan)
+ }
})
return ls.hub
@@ -341,14 +384,14 @@ func (h *ProjectHandler) GetProjectLogsWS(c *gin.Context) {
tail := c.DefaultQuery("tail", "100")
since := c.Query("since")
timestamps := c.DefaultQuery("timestamps", "false") == "true"
+ format := c.DefaultQuery("format", "text")
+ batched := c.DefaultQuery("batched", "false") == "true"
conn, err := wsUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
- hub := h.getOrStartProjectLogHub(projectID, follow, tail, since, timestamps)
-
- // don't use the request context; it is canceled when handler returns.
+ hub := h.getOrStartProjectLogHub(projectID, format, batched, follow, tail, since, timestamps)
ws.ServeClient(context.Background(), hub, conn)
}
diff --git a/backend/internal/utils/ws/ansi.go b/backend/internal/utils/ws/ansi.go
new file mode 100644
index 000000000..bc714c855
--- /dev/null
+++ b/backend/internal/utils/ws/ansi.go
@@ -0,0 +1,13 @@
+package ws
+
+import "regexp"
+
+var ansiRegexp = regexp.MustCompile(`\x1B\[[0-?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*(\x07|\x1B\\)|\x1B[@-_]`)
+
+// StripANSI removes ANSI color / control escape sequences.
+func StripANSI(s string) string {
+ if s == "" {
+ return s
+ }
+ return ansiRegexp.ReplaceAllString(s, "")
+}
diff --git a/backend/internal/utils/ws/bridge.go b/backend/internal/utils/ws/bridge.go
index 52e7b2e07..edc78a614 100644
--- a/backend/internal/utils/ws/bridge.go
+++ b/backend/internal/utils/ws/bridge.go
@@ -7,11 +7,12 @@ import (
)
type LogMessage struct {
- Level string `json:"level,omitempty"`
- Message string `json:"message"`
- Timestamp time.Time `json:"timestamp"`
- Service string `json:"service,omitempty"`
- ContainerID string `json:"containerId,omitempty"`
+ Seq uint64 `json:"seq"`
+ Level string `json:"level,omitempty"`
+ Message string `json:"message"`
+ Timestamp string `json:"timestamp"` // RFC3339(9) string
+ Service string `json:"service,omitempty"`
+ ContainerID string `json:"containerId,omitempty"`
}
// ForwardLines forwards plain text lines to the hub.
@@ -29,10 +30,8 @@ func ForwardLines(ctx context.Context, hub *Hub, lines <-chan string) {
}
}
-// ForwardLogJSON marshals LogMessage and forwards JSON to the hub.
+// ForwardLogJSON sends each LogMessage as its own JSON object frame.
func ForwardLogJSON(ctx context.Context, hub *Hub, logs <-chan LogMessage) {
- enc := json.NewEncoder(nil) // no reuse, just use json.Marshal below for simplicity
- _ = enc // avoid linter; using Marshal for perf/control
for {
select {
case <-ctx.Done():
@@ -41,8 +40,8 @@ func ForwardLogJSON(ctx context.Context, hub *Hub, logs <-chan LogMessage) {
if !ok {
return
}
- if m.Timestamp.IsZero() {
- m.Timestamp = time.Now()
+ if m.Timestamp == "" {
+ m.Timestamp = NowRFC3339()
}
if b, err := json.Marshal(m); err == nil {
hub.Broadcast(b)
@@ -50,3 +49,54 @@ func ForwardLogJSON(ctx context.Context, hub *Hub, logs <-chan LogMessage) {
}
}
}
+
+// ForwardLogJSONBatched batches log messages into a JSON array frame to reduce frame count.
+// Flushes when maxBatch reached or flushInterval elapsed.
+func ForwardLogJSONBatched(ctx context.Context, hub *Hub, logs <-chan LogMessage, maxBatch int, flushInterval time.Duration) {
+ if maxBatch <= 1 {
+ ForwardLogJSON(ctx, hub, logs)
+ return
+ }
+ t := time.NewTimer(flushInterval)
+ defer t.Stop()
+
+ buf := make([]LogMessage, 0, maxBatch)
+
+ flush := func() {
+ if len(buf) == 0 {
+ return
+ }
+ b, err := json.Marshal(buf)
+ if err == nil {
+ hub.Broadcast(b)
+ }
+ buf = buf[:0]
+ }
+
+ for {
+ select {
+ case <-ctx.Done():
+ flush()
+ return
+ case m, ok := <-logs:
+ if !ok {
+ flush()
+ return
+ }
+ if m.Timestamp == "" {
+ m.Timestamp = NowRFC3339()
+ }
+ buf = append(buf, m)
+ if len(buf) >= maxBatch {
+ flush()
+ if !t.Stop() {
+ <-t.C
+ }
+ t.Reset(flushInterval)
+ }
+ case <-t.C:
+ flush()
+ t.Reset(flushInterval)
+ }
+ }
+}
diff --git a/backend/internal/utils/ws/client.go b/backend/internal/utils/ws/client.go
index b86513b14..8725c9da5 100644
--- a/backend/internal/utils/ws/client.go
+++ b/backend/internal/utils/ws/client.go
@@ -3,6 +3,7 @@ package ws
import (
"context"
"log/slog"
+ "sync"
"time"
"github.com/gorilla/websocket"
@@ -13,16 +14,19 @@ const (
pongWait = 60 * time.Second
pingPeriod = pongWait * 9 / 10
- maxMessageSize = 1024
+ maxMessageSize = 64 * 1024
)
// Client represents a single WebSocket connection.
type Client struct {
conn *websocket.Conn
send chan []byte
+ once sync.Once
}
func NewClient(conn *websocket.Conn, sendBuffer int) *Client {
+ // Enable per-message deflate if negotiated (safe to ignore error)
+ _ = conn.SetCompressionLevel(1)
return &Client{
conn: conn,
send: make(chan []byte, sendBuffer),
@@ -39,10 +43,16 @@ func ServeClient(ctx context.Context, hub *Hub, conn *websocket.Conn) {
go c.readPump(ctx, hub)
}
+func (c *Client) safeRemove(hub *Hub) {
+ c.once.Do(func() {
+ hub.remove(c)
+ })
+}
+
func (c *Client) readPump(ctx context.Context, hub *Hub) {
// Ensure client is removed from hub without sending on a potentially
// unserviced channel. Use hub.remove which is safe when the hub has exited.
- defer hub.remove(c)
+ defer c.safeRemove(hub)
c.conn.SetReadLimit(maxMessageSize)
_ = c.conn.SetReadDeadline(time.Now().Add(pongWait))
@@ -70,7 +80,7 @@ func (c *Client) writePump(ctx context.Context, hub *Hub) {
// Stop ticker and ensure client is removed from hub without writing to hub.unregister.
defer func() {
ticker.Stop()
- hub.remove(c)
+ c.safeRemove(hub)
}()
for {
diff --git a/backend/internal/utils/ws/parse.go b/backend/internal/utils/ws/parse.go
new file mode 100644
index 000000000..df780cece
--- /dev/null
+++ b/backend/internal/utils/ws/parse.go
@@ -0,0 +1,74 @@
+package ws
+
+import (
+ "regexp"
+ "strings"
+ "time"
+)
+
+var (
+ isoDockerTs = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?\s+`)
+ slashDockerTs = regexp.MustCompile(`^\d{4}/\d{2}/\d{2}\s+\d{2}:\d{2}:\d{2}\s+`)
+)
+
+// NormalizeContainerLine parses a raw container log line into level + cleaned message.
+// It also attempts to extract a leading timestamp (returned as an RFC3339Nano string).
+func NormalizeContainerLine(raw string) (level string, msg string, timestamp string) {
+ line := StripANSI(strings.TrimRight(raw, "\r\n"))
+
+ level = "stdout"
+ switch {
+ case strings.HasPrefix(line, "[STDERR] "):
+ level = "stderr"
+ line = strings.TrimPrefix(line, "[STDERR] ")
+ case strings.HasPrefix(line, "stderr:"):
+ level = "stderr"
+ line = strings.TrimPrefix(line, "stderr:")
+ case strings.HasPrefix(line, "stdout:"):
+ level = "stdout"
+ line = strings.TrimPrefix(line, "stdout:")
+ }
+
+ // Strip and parse docker timestamps
+ if match := isoDockerTs.FindString(line); match != "" {
+ trimmed := strings.TrimSpace(match)
+ // try multiple ISO layouts
+ var parsed time.Time
+ var err error
+ parsed, err = time.Parse(time.RFC3339Nano, trimmed)
+ if err != nil {
+ parsed, err = time.Parse(time.RFC3339, trimmed)
+ }
+ if err == nil {
+ timestamp = parsed.UTC().Format(time.RFC3339Nano)
+ }
+ line = strings.TrimPrefix(line, match)
+ } else if match := slashDockerTs.FindString(line); match != "" {
+ trimmed := strings.TrimSpace(match)
+ parsed, err := time.Parse("2006/01/02 15:04:05", trimmed)
+ if err == nil {
+ timestamp = parsed.UTC().Format(time.RFC3339Nano)
+ }
+ line = strings.TrimPrefix(line, match)
+ }
+
+ return level, strings.TrimSpace(line), timestamp
+}
+
+// NormalizeProjectLine additionally extracts service (pattern: service | message).
+// Returns level, service, message, timestamp (RFC3339Nano) — timestamp may be empty.
+func NormalizeProjectLine(raw string) (level, service, msg, timestamp string) {
+ level, base, ts := NormalizeContainerLine(raw)
+ timestamp = ts
+
+ service = ""
+ if parts := strings.SplitN(base, " | ", 2); len(parts) == 2 {
+ service = strings.TrimSpace(parts[0])
+ base = parts[1]
+ }
+ return level, service, base, timestamp
+}
+
+func NowRFC3339() string {
+ return time.Now().UTC().Format(time.RFC3339Nano)
+}
diff --git a/backend/internal/utils/ws/proxy.go b/backend/internal/utils/ws/proxy.go
index a5566af18..018a23db4 100644
--- a/backend/internal/utils/ws/proxy.go
+++ b/backend/internal/utils/ws/proxy.go
@@ -9,7 +9,10 @@ import (
)
var upgrader = websocket.Upgrader{
- CheckOrigin: func(r *http.Request) bool { return true },
+ ReadBufferSize: 32 * 1024,
+ WriteBufferSize: 32 * 1024,
+ EnableCompression: true,
+ CheckOrigin: func(r *http.Request) bool { return true },
}
// ProxyHTTP upgrades the incoming client connection and bridges it to remoteWS.
diff --git a/frontend/src/lib/components/log-viewer.svelte b/frontend/src/lib/components/log-viewer.svelte
index 15d9397f9..c5c671845 100644
--- a/frontend/src/lib/components/log-viewer.svelte
+++ b/frontend/src/lib/components/log-viewer.svelte
@@ -1,11 +1,12 @@
<script lang="ts">
- import { browser, dev } from '$app/environment';
+ import { dev } from '$app/environment';
import { get } from 'svelte/store';
import { environmentStore } from '$lib/stores/environment.store';
import { m } from '$lib/paraglide/messages';
import { ReconnectingWebSocket } from '$lib/utils/ws';
interface LogEntry {
+ id: number;
timestamp: string;
level: 'stdout' | 'stderr' | 'info' | 'error';
message: string;
@@ -42,6 +43,81 @@
}: Props = $props();
let logs: LogEntry[] = $state([]);
+ let pending: LogEntry[] = [];
+ let flushScheduled = false;
+ let seq = 0;
+
+ let dropBefore = $state(0);
+
+ const COMPACT_FACTOR = 2;
+ let lastCompactSeq = 0;
+
+ let visibleLogs = $derived.by(() => {
+ if (dropBefore === 0) return logs;
+ return logs.filter((l) => l.id >= dropBefore);
+ });
+
+ function maybeCompact() {
+ const threshold = maxLines * COMPACT_FACTOR;
+ if (logs.length <= threshold) return;
+ if (seq - lastCompactSeq < maxLines) return;
+
+ // Keep the most recent maxLines entries, trim older ones
+ const keepCount = Math.max(1, maxLines);
+ if (logs.length > keepCount) {
+ const start = logs.length - keepCount;
+ logs = logs.slice(start);
+ }
+
+ // mark compaction point and clear dropBefore so future compactions don't rely on it
+ lastCompactSeq = seq;
+ dropBefore = 0;
+ }
+
+ function scheduleFlush() {
+ if (flushScheduled) return;
+ flushScheduled = true;
+ queueMicrotask(() => {
+ flushScheduled = false;
+ if (!pending.length) return;
+ logs = [...logs, ...pending];
+ pending = [];
+ if (logs.length > maxLines * COMPACT_FACTOR) {
+ maybeCompact();
+ }
+ if (autoScroll && logContainer) {
+ requestAnimationFrame(() => {
+ if (logContainer) logContainer.scrollTop = logContainer.scrollHeight;
+ });
+ }
+ });
+ }
+
+ export function clearLogs(opts?: { hard?: boolean; restart?: boolean }) {
+ const hard = opts?.hard === true;
+
+ if (hard) {
+ logs = [];
+ pending = [];
+ seq = 0;
+ dropBefore = 0;
+ lastCompactSeq = 0;
+ } else {
+ dropBefore = seq;
+ }
+
+ onClear?.();
+
+ if (opts?.restart) {
+ stopLogStream();
+ startLogStream();
+ }
+ }
+
+ export function hardClearLogs(restart = false) {
+ clearLogs({ hard: true, restart });
+ }
+
let logContainer: HTMLElement | undefined = $state();
let isStreaming = $state(false);
let error: string | null = $state(null);
@@ -54,9 +130,6 @@
const humanType = type === 'project' ? m.project() : m.container();
- const DOCKER_TS_ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z?\s*/;
- const DOCKER_TS_SLASH_RE = /^\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}\s*/;
-
function buildWebSocketEndpoint(path: string): string {
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
return `${protocol}://${window.location.host}${path}`;
@@ -69,7 +142,7 @@
type === 'project'
? `/api/environments/${envId}/projects/${projectId}/logs/ws`
: `/api/environments/${envId}/containers/${containerId}/logs/ws`;
- return buildWebSocketEndpoint(`${basePath}?follow=true&tail=100&timestamps=${showTimestamps}`);
+ return buildWebSocketEndpoint(`${basePath}?follow=true&tail=100&timestamps=${showTimestamps}&format=json&batched=true`);
}
export async function startLogStream() {
@@ -96,7 +169,12 @@
return await buildLogWsEndpoint();
},
parseMessage: (evt) => {
- return typeof evt.data === 'string' ? evt.data : '';
+ if (typeof evt.data !== 'string') return null;
+ try {
+ return JSON.parse(evt.data);
+ } catch {
+ return null;
+ }
},
onOpen: () => {
if (dev) console.log(m.log_viewer_connected({ type: humanType }));
@@ -105,9 +183,10 @@
},
onMessage: (payload) => {
if (!payload) return;
- for (const line of payload.split('\n')) {
- if (!line.trim()) continue;
- handleIncomingLine(line);
+ if (Array.isArray(payload)) {
+ for (const obj of payload) processLogObject(obj);
+ } else if (typeof payload === 'object') {
+ processLogObject(payload);
}
},
onError: (e) => {
@@ -126,25 +205,16 @@
await wsClient.connect();
}
- function handleIncomingLine(raw: string) {
- let level: LogEntry['level'] = raw.startsWith('[STDERR] ') ? 'stderr' : 'stdout';
- let line = raw.replace('[STDERR] ', '');
-
- // Try to extract "service | message" if present
- let service: string | undefined;
- if (line.includes(' | ')) {
- const parts = line.split(' | ', 2);
- if (parts.length === 2) {
- service = parts[0].trim();
- line = parts[1];
- }
- }
+ function processLogObject(obj: any) {
+ if (!obj || typeof obj !== 'object') return;
+ const { level = 'stdout', message = '', timestamp = new Date().toISOString(), service, containerId } = obj;
addLogEntry({
level,
- message: line,
- timestamp: new Date().toISOString(),
- service
+ message,
+ timestamp,
+ service,
+ containerId
});
}
@@ -164,9 +234,17 @@
onStop?.();
}
- export function clearLogs() {
- logs = [];
- onClear?.();
+ function addLogEntry(logData: { level: string; message: string; timestamp?: string; service?: string; containerId?: string }) {
+ const timestamp = logData.timestamp || new Date().toISOString();
+ pending.push({
+ id: seq++,
+ timestamp,
+ level: logData.level as LogEntry['level'],
+ message: logData.message,
+ service: logData.service,
+ containerId: logData.containerId
+ });
+ scheduleFlush();
}
export function toggleAutoScroll() {
@@ -182,36 +260,6 @@
return logs.length;
}
- function addLogEntry(logData: { level: string; message: string; timestamp?: string; service?: string; containerId?: string }) {
- let cleanMessage = logData.message;
- let timestamp = logData.timestamp || new Date().toISOString();
-
- if (DOCKER_TS_ISO_RE.test(cleanMessage)) {
- cleanMessage = cleanMessage.replace(DOCKER_TS_ISO_RE, '').trim();
- }
- if (DOCKER_TS_SLASH_RE.test(cleanMessage)) {
- cleanMessage = cleanMessage.replace(DOCKER_TS_SLASH_RE, '').trim();
- }
-
- const entry: LogEntry = {
- timestamp,
- level: logData.level as LogEntry['level'],
- message: cleanMessage,
- service: logData.service,
- containerId: logData.containerId
- };
-
- logs = [...logs.slice(-(maxLines - 1)), entry];
-
- if (autoScroll && logContainer) {
- requestAnimationFrame(() => {
- if (logContainer) {
- logContainer.scrollTop = logContainer.scrollHeight;
- }
- });
- }
- }
-
function formatTimestamp(timestamp: string): string {
const date = new Date(timestamp);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
@@ -231,7 +279,6 @@
}
$effect(() => {
- if (!browser) return;
const key = streamKey();
if (!key) return;
if (key === currentStreamKey && isStreaming) return;
@@ -272,24 +319,21 @@
{/if}
</div>
{:else}
- {#each logs as log (log.timestamp + log.message + (log.service || ''))}
+ {#each visibleLogs as log (log.id)}
<div class="flex border-l-2 border-transparent px-3 py-1 transition-colors hover:border-blue-500 hover:bg-gray-900/50">
{#if showTimestamps}
<span class="mr-3 min-w-fit shrink-0 text-xs text-gray-500">
{formatTimestamp(log.timestamp)}
</span>
{/if}
-
<span class="mr-2 shrink-0 text-xs {getLevelClass(log.level)} min-w-fit">
{log.level.toUpperCase()}
</span>
-
{#if type === 'project' && log.service}
<span class="mr-2 min-w-fit shrink-0 truncate text-xs text-blue-400" title={log.service}>
{log.service}
</span>
{/if}
-
<span class="flex-1 whitespace-pre-wrap break-words text-gray-300">
{log.message}
</span>
diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.ts
index 503780ce3..5871edef8 100644
--- a/frontend/src/lib/utils/ws.ts
+++ b/frontend/src/lib/utils/ws.ts
@@ -1,16 +1,13 @@
import type { SystemStats } from '$lib/types/system-stats.type';
export interface ReconnectWSOptions<T> {
- // builds the websocket URL (can be async)
buildUrl: () => string | Promise<string>;
- // parse an incoming MessageEvent into T (default: JSON.parse for string payloads)
parseMessage?: (evt: MessageEvent) => T;
onMessage?: (msg: T) => void;
onOpen?: () => void;
onClose?: () => void;
onError?: (err: Event | Error) => void;
maxBackoff?: number;
- // optional: whether to autoConnect immediately
autoConnect?: boolean;
}
@@ -91,12 +88,11 @@ export class ReconnectingWebSocket<T = unknown> {
private scheduleReconnect() {
this.attempt++;
- const backoff = Math.min(1000 * Math.pow(1.5, this.attempt), this.maxBackoff);
+ const exp = Math.min(1000 * Math.pow(1.5, this.attempt), this.maxBackoff);
+ const jitter = Math.random() * 0.3 * exp;
+ const backoff = exp - jitter;
setTimeout(() => {
- if (!this.closed) {
- // ignore connectOnce race if already connecting
- this.connectOnce();
- }
+ if (!this.closed) this.connectOnce();
}, backoff);
}