File: sharedtemp_test.go

package info (click to toggle)
docker.io 28.5.2%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 69,048 kB
  • sloc: sh: 5,867; makefile: 863; ansic: 184; python: 162; asm: 159
file content (253 lines) | stat: -rw-r--r-- 6,553 bytes parent folder | download | duplicates (2)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package loggerutils

import (
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/pkg/errors"
	"gotest.tools/v3/assert"
	is "gotest.tools/v3/assert/cmp"
)

func TestSharedTempFileConverter(t *testing.T) {
	t.Parallel()

	t.Run("OneReaderAtATime", func(t *testing.T) {
		t.Parallel()
		dir := t.TempDir()
		name := filepath.Join(dir, "test.txt")
		createFile(t, name, "hello, world!")

		uut := newSharedTempFileConverter(copyTransform(strings.ToUpper))
		uut.TempDir = dir

		for i := 0; i < 3; i++ {
			t.Logf("Iteration %v", i)

			rdr := convertPath(t, uut, name)
			assert.Check(t, is.Equal("HELLO, WORLD!", readAll(t, rdr)))
			assert.Check(t, rdr.Close())
			assert.Check(t, is.Equal(fs.ErrClosed, rdr.Close()), "closing an already-closed reader should return an error")
		}

		assert.NilError(t, os.Remove(name))
		checkDirEmpty(t, dir)
	})

	t.Run("RobustToRenames", func(t *testing.T) {
		t.Parallel()
		dir := t.TempDir()
		apath := filepath.Join(dir, "test.txt")
		createFile(t, apath, "file a")

		var conversions int
		uut := newSharedTempFileConverter(
			func(dst io.WriteSeeker, src io.ReadSeeker) error {
				conversions++
				return copyTransform(strings.ToUpper)(dst, src)
			},
		)
		uut.TempDir = dir

		ra1 := convertPath(t, uut, apath)

		// Rotate the file to a new name and write a new file in its place.
		bpath := apath
		apath = filepath.Join(dir, "test2.txt")
		assert.NilError(t, os.Rename(bpath, apath))
		createFile(t, bpath, "file b")

		rb1 := convertPath(t, uut, bpath) // Same path, different file.
		ra2 := convertPath(t, uut, apath) // New path, old file.
		assert.Check(t, is.Equal(2, conversions), "expected only one conversion per unique file")

		// Interleave reading and closing to shake out ref-counting bugs:
		// closing one reader shouldn't affect any other open readers.
		assert.Check(t, is.Equal("FILE A", readAll(t, ra1)))
		assert.NilError(t, ra1.Close())
		assert.Check(t, is.Equal("FILE A", readAll(t, ra2)))
		assert.NilError(t, ra2.Close())
		assert.Check(t, is.Equal("FILE B", readAll(t, rb1)))
		assert.NilError(t, rb1.Close())

		assert.NilError(t, os.Remove(apath))
		assert.NilError(t, os.Remove(bpath))
		checkDirEmpty(t, dir)
	})

	t.Run("ConcurrentRequests", func(t *testing.T) {
		t.Parallel()
		dir := t.TempDir()
		name := filepath.Join(dir, "test.txt")
		createFile(t, name, "hi there")

		var conversions atomic.Uint32
		notify := make(chan chan struct{}, 1)
		firstConversionStarted := make(chan struct{})
		notify <- firstConversionStarted
		unblock := make(chan struct{})
		uut := newSharedTempFileConverter(
			func(dst io.WriteSeeker, src io.ReadSeeker) error {
				t.Log("Convert: enter")
				defer t.Log("Convert: exit")
				select {
				case c := <-notify:
					close(c)
				default:
				}
				<-unblock
				conversions.Add(1)
				return copyTransform(strings.ToUpper)(dst, src)
			},
		)
		uut.TempDir = dir

		closers := make(chan io.Closer, 4)
		var wg sync.WaitGroup
		wg.Add(3)
		for i := 0; i < 3; i++ {
			go func() {
				defer wg.Done()
				t.Logf("goroutine %v: enter", i)
				defer t.Logf("goroutine %v: exit", i)
				f := convertPath(t, uut, name)
				assert.Check(t, is.Equal("HI THERE", readAll(t, f)), "in goroutine %v", i)
				closers <- f
			}()
		}

		select {
		case <-firstConversionStarted:
		case <-time.After(2 * time.Second):
			t.Fatal("the first conversion should have started by now")
		}
		close(unblock)
		t.Log("starting wait")
		wg.Wait()
		t.Log("wait done")

		f := convertPath(t, uut, name)
		closers <- f
		close(closers)
		assert.Check(t, is.Equal("HI THERE", readAll(t, f)), "after all goroutines returned")
		for c := range closers {
			assert.Check(t, c.Close())
		}

		assert.Check(t, is.Equal(uint32(1), conversions.Load()))

		assert.NilError(t, os.Remove(name))
		checkDirEmpty(t, dir)
	})

	t.Run("ConvertError", func(t *testing.T) {
		t.Parallel()
		dir := t.TempDir()
		name := filepath.Join(dir, "test.txt")
		createFile(t, name, "hi there")
		src, err := open(name)
		assert.NilError(t, err)
		defer src.Close()

		fakeErr := errors.New("fake error")
		var start sync.WaitGroup
		start.Add(3)
		uut := newSharedTempFileConverter(
			func(dst io.WriteSeeker, src io.ReadSeeker) error {
				start.Wait()
				runtime.Gosched()
				if fakeErr != nil {
					return fakeErr
				}
				return copyTransform(strings.ToUpper)(dst, src)
			},
		)
		uut.TempDir = dir

		var done sync.WaitGroup
		done.Add(3)
		for i := 0; i < 3; i++ {
			go func() {
				defer done.Done()
				t.Logf("goroutine %v: enter", i)
				defer t.Logf("goroutine %v: exit", i)
				start.Done()
				_, err := uut.Do(src)
				assert.Check(t, is.ErrorIs(err, fakeErr), "in goroutine %v", i)
			}()
		}
		done.Wait()

		// Conversion errors should not be "sticky". A subsequent
		// request should retry from scratch.
		fakeErr = errors.New("another fake error")
		_, err = uut.Do(src)
		assert.Check(t, is.ErrorIs(err, fakeErr))

		fakeErr = nil
		f, err := uut.Do(src)
		assert.Check(t, err)
		assert.Check(t, is.Equal("HI THERE", readAll(t, f)))
		assert.Check(t, f.Close())

		// Files pending delete continue to show up in directory
		// listings on Windows RS5. Close the remaining handle before
		// deleting the file to prevent spurious failures with
		// checkDirEmpty.
		assert.Check(t, src.Close())
		assert.NilError(t, os.Remove(name))
		checkDirEmpty(t, dir)
	})
}

func createFile(t *testing.T, path string, content string) {
	t.Helper()
	f, err := openFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o644)
	assert.NilError(t, err)
	_, err = io.WriteString(f, content)
	assert.NilError(t, err)
	assert.NilError(t, f.Close())
}

func convertPath(t *testing.T, uut *sharedTempFileConverter, path string) *sharedFileReader {
	t.Helper()
	f, err := open(path)
	assert.NilError(t, err)
	defer func() { assert.NilError(t, f.Close()) }()
	r, err := uut.Do(f)
	assert.NilError(t, err)
	return r
}

func readAll(t *testing.T, r io.Reader) string {
	t.Helper()
	v, err := io.ReadAll(r)
	assert.NilError(t, err)
	return string(v)
}

func checkDirEmpty(t *testing.T, path string) {
	t.Helper()
	ls, err := os.ReadDir(path)
	assert.NilError(t, err)
	assert.Check(t, is.Len(ls, 0), "directory should be free of temp files")
}

func copyTransform(f func(string) string) func(dst io.WriteSeeker, src io.ReadSeeker) error {
	return func(dst io.WriteSeeker, src io.ReadSeeker) error {
		s, err := io.ReadAll(src)
		if err != nil {
			return err
		}
		_, err = io.WriteString(dst, f(string(s)))
		return err
	}
}