summaryrefslogtreecommitdiff
path: root/internal/server/handlers/readcommand_cancellation_test.go
blob: 4b77224d54ddf5f1a60e4c93d4f74ddc3cf627c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package handlers

import (
	"context"
	"testing"
	"time"

	"github.com/mimecast/dtail/internal/io/fs"
	"github.com/mimecast/dtail/internal/io/line"
	"github.com/mimecast/dtail/internal/lcontext"
	"github.com/mimecast/dtail/internal/omode"
	"github.com/mimecast/dtail/internal/regex"
)

type retryOnlyFileReader struct{}

func (retryOnlyFileReader) Start(context.Context, lcontext.LContext, chan<- *line.Line, regex.Regex) error {
	return nil
}

func (retryOnlyFileReader) StartWithProcessor(context.Context, lcontext.LContext, line.Processor, regex.Regex) error {
	return nil
}

func (retryOnlyFileReader) StartWithProcessorOptimized(context.Context, lcontext.LContext, line.Processor, regex.Regex) error {
	return nil
}

func (retryOnlyFileReader) FilePath() string {
	return ""
}

func (retryOnlyFileReader) Retry() bool {
	return true
}

var _ fs.FileReader = retryOnlyFileReader{}

func TestExecuteReadLoopStopsPromptlyWhenContextCanceledDuringRetrySleep(t *testing.T) {
	handler := newSessionTestHandler("readcommand-cancel-user")
	handler.serverCfg.ReadRetryIntervalMs = 1000

	command := newReadCommand(handler, omode.TailClient)
	reader := retryOnlyFileReader{}

	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan struct{})
	strategyCalls := 0

	go func() {
		command.executeReadLoop(ctx, lcontext.LContext{}, "/var/log/app.log", "app.log", regex.NewNoop(), reader,
			func(context.Context, lcontext.LContext, fs.FileReader, regex.Regex) error {
				strategyCalls++
				cancel()
				return nil
			})
		close(done)
	}()

	select {
	case <-done:
	case <-time.After(150 * time.Millisecond):
		t.Fatal("executeReadLoop did not stop promptly after cancellation")
	}

	if strategyCalls != 1 {
		t.Fatalf("expected one read attempt before cancellation, got %d", strategyCalls)
	}
}