|
| 1 | +// Copyright 2025 Emmanuel Madehin |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package logs |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "os" |
| 10 | + "path/filepath" |
| 11 | + "strings" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/dployr-io/dployr/pkg/core/logs" |
| 16 | + "github.com/dployr-io/dployr/pkg/shared" |
| 17 | +) |
| 18 | + |
| 19 | +func newTestHandler(t *testing.T, dataDir string) *Handler { |
| 20 | + t.Helper() |
| 21 | + h := &Handler{ |
| 22 | + logger: shared.NewLogger(), |
| 23 | + dataDir: dataDir, |
| 24 | + config: &shared.Config{ |
| 25 | + LogMaxChunkBytes: 8 * 1024 * 1024, |
| 26 | + LogBatchSize: 50, |
| 27 | + LogBatchTimeout: 250 * time.Millisecond, |
| 28 | + LogMaxBatchTimeout: 2 * time.Second, |
| 29 | + LogPollInterval: 20 * time.Millisecond, |
| 30 | + LogMaxFileReadBytes: 100 * 1024 * 1024, |
| 31 | + LogMaxStreams: 100, |
| 32 | + }, |
| 33 | + } |
| 34 | + streamSemOnce.Do(func() { |
| 35 | + streamSemaphore = shared.NewSemaphore(h.config.LogMaxStreams) |
| 36 | + }) |
| 37 | + return h |
| 38 | +} |
| 39 | + |
| 40 | +// writeLogFile creates the .dployr/logs directory under dataDir and writes lines to <name>.log |
| 41 | +func writeLogFile(t *testing.T, dataDir, name string, lines []string) string { |
| 42 | + t.Helper() |
| 43 | + dir := filepath.Join(dataDir, ".dployr", "logs") |
| 44 | + if err := os.MkdirAll(dir, 0o755); err != nil { |
| 45 | + t.Fatalf("mkdir: %v", err) |
| 46 | + } |
| 47 | + path := filepath.Join(dir, name+".log") |
| 48 | + content := strings.Join(lines, "\n") + "\n" |
| 49 | + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { |
| 50 | + t.Fatalf("writeLogFile: %v", err) |
| 51 | + } |
| 52 | + return path |
| 53 | +} |
| 54 | + |
| 55 | +func allEntries(chunks []logs.LogChunk) []logs.LogEntry { |
| 56 | + var out []logs.LogEntry |
| 57 | + for _, c := range chunks { |
| 58 | + out = append(out, c.Entries...) |
| 59 | + } |
| 60 | + return out |
| 61 | +} |
| 62 | + |
| 63 | +// --------------------------------------------------------------------------- |
| 64 | + |
| 65 | +func TestStreamLogs_EmptyDuration_ReadsFromBeginning(t *testing.T) { |
| 66 | + dir := t.TempDir() |
| 67 | + writeLogFile(t, dir, "my-svc", []string{ |
| 68 | + `{"time":"2025-01-01T00:00:01Z","level":"INFO","msg":"line-1"}`, |
| 69 | + `{"time":"2025-01-01T00:00:02Z","level":"INFO","msg":"line-2"}`, |
| 70 | + `{"time":"2025-01-01T00:00:03Z","level":"INFO","msg":"line-3"}`, |
| 71 | + }) |
| 72 | + |
| 73 | + h := newTestHandler(t, dir) |
| 74 | + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 75 | + defer cancel() |
| 76 | + |
| 77 | + var chunks []logs.LogChunk |
| 78 | + _ = h.StreamLogs(ctx, logs.StreamOptions{StreamID: "s1", Path: "my-svc", Duration: ""}, func(c logs.LogChunk) error { |
| 79 | + chunks = append(chunks, c) |
| 80 | + cancel() // stop after first flush |
| 81 | + return nil |
| 82 | + }) |
| 83 | + |
| 84 | + entries := allEntries(chunks) |
| 85 | + if len(entries) < 3 { |
| 86 | + t.Fatalf("expected at least 3 entries from beginning, got %d", len(entries)) |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +func TestStreamLogs_LiveDuration_DoesNotReplayOldEntries(t *testing.T) { |
| 91 | + dir := t.TempDir() |
| 92 | + oldTime := time.Now().Add(-10 * time.Minute) |
| 93 | + var oldLines []string |
| 94 | + for i := range 5 { |
| 95 | + oldLines = append(oldLines, fmt.Sprintf(`{"time":%q,"level":"INFO","msg":"old-%d"}`, oldTime.Format(time.RFC3339), i)) |
| 96 | + } |
| 97 | + writeLogFile(t, dir, "my-svc", oldLines) |
| 98 | + |
| 99 | + h := newTestHandler(t, dir) |
| 100 | + ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond) |
| 101 | + defer cancel() |
| 102 | + |
| 103 | + var chunks []logs.LogChunk |
| 104 | + _ = h.StreamLogs(ctx, logs.StreamOptions{StreamID: "s-live", Path: "my-svc", Duration: "live"}, func(c logs.LogChunk) error { |
| 105 | + chunks = append(chunks, c) |
| 106 | + return nil |
| 107 | + }) |
| 108 | + |
| 109 | + for _, e := range allEntries(chunks) { |
| 110 | + if strings.Contains(e.RawLine, "old-") { |
| 111 | + t.Errorf("live mode must not replay entries older than 5 minutes, got: %s", e.RawLine) |
| 112 | + } |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +func TestStreamLogs_ContextCancellation_StopsStream(t *testing.T) { |
| 117 | + dir := t.TempDir() |
| 118 | + writeLogFile(t, dir, "my-svc", []string{`{"time":"2025-01-01T00:00:01Z","level":"INFO","msg":"ping"}`}) |
| 119 | + |
| 120 | + h := newTestHandler(t, dir) |
| 121 | + ctx, cancel := context.WithCancel(context.Background()) |
| 122 | + |
| 123 | + done := make(chan struct{}) |
| 124 | + go func() { |
| 125 | + defer close(done) |
| 126 | + _ = h.StreamLogs(ctx, logs.StreamOptions{StreamID: "s1", Path: "my-svc", Duration: "live"}, func(logs.LogChunk) error { |
| 127 | + return nil |
| 128 | + }) |
| 129 | + }() |
| 130 | + |
| 131 | + cancel() |
| 132 | + select { |
| 133 | + case <-done: |
| 134 | + case <-time.After(2 * time.Second): |
| 135 | + t.Fatal("StreamLogs did not stop within 2s after context cancellation") |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +func TestStreamLogs_FileNotExistInitially_WaitsAndOpens(t *testing.T) { |
| 140 | + dir := t.TempDir() |
| 141 | + logDir := filepath.Join(dir, ".dployr", "logs") |
| 142 | + if err := os.MkdirAll(logDir, 0o755); err != nil { |
| 143 | + t.Fatalf("mkdir: %v", err) |
| 144 | + } |
| 145 | + |
| 146 | + h := newTestHandler(t, dir) |
| 147 | + |
| 148 | + go func() { |
| 149 | + time.Sleep(150 * time.Millisecond) |
| 150 | + path := filepath.Join(logDir, "late-svc.log") |
| 151 | + _ = os.WriteFile(path, []byte("{\"time\":\"2025-01-01T00:00:01Z\",\"level\":\"INFO\",\"msg\":\"appeared\"}\n"), 0o644) |
| 152 | + }() |
| 153 | + |
| 154 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 155 | + defer cancel() |
| 156 | + |
| 157 | + var got []logs.LogEntry |
| 158 | + _ = h.StreamLogs(ctx, logs.StreamOptions{StreamID: "s2", Path: "late-svc", Duration: ""}, func(c logs.LogChunk) error { |
| 159 | + got = append(got, c.Entries...) |
| 160 | + cancel() |
| 161 | + return nil |
| 162 | + }) |
| 163 | + |
| 164 | + if len(got) == 0 { |
| 165 | + t.Fatal("expected at least one entry after file appeared, got none") |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +func TestStreamLogs_BatchesMultipleLines(t *testing.T) { |
| 170 | + dir := t.TempDir() |
| 171 | + var lines []string |
| 172 | + for i := range 20 { |
| 173 | + lines = append(lines, fmt.Sprintf(`{"time":"2025-01-01T00:00:%02dZ","level":"INFO","msg":"entry-%d"}`, i%60, i)) |
| 174 | + } |
| 175 | + writeLogFile(t, dir, "batchy-svc", lines) |
| 176 | + |
| 177 | + h := newTestHandler(t, dir) |
| 178 | + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 179 | + defer cancel() |
| 180 | + |
| 181 | + var chunks []logs.LogChunk |
| 182 | + _ = h.StreamLogs(ctx, logs.StreamOptions{StreamID: "s3", Path: "batchy-svc", Duration: ""}, func(c logs.LogChunk) error { |
| 183 | + chunks = append(chunks, c) |
| 184 | + cancel() |
| 185 | + return nil |
| 186 | + }) |
| 187 | + |
| 188 | + entries := allEntries(chunks) |
| 189 | + if len(entries) == 0 { |
| 190 | + t.Fatal("expected batched entries, got none") |
| 191 | + } |
| 192 | + if len(chunks) >= 20 { |
| 193 | + t.Errorf("expected batched chunks (< 20), got %d separate chunks", len(chunks)) |
| 194 | + } |
| 195 | +} |
0 commit comments