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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
|
package streamcache
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/config"
"gitlab.com/gitlab-org/gitaly/v14/internal/log"
"gitlab.com/gitlab-org/gitaly/v14/internal/testhelper"
)
func newCache(dir string) Cache {
return New(config.StreamCacheConfig{
Enabled: true,
Dir: dir,
MaxAge: config.Duration(time.Hour),
}, log.Default())
}
func TestCache_writeOneReadMultiple(t *testing.T) {
tmp := testhelper.TempDir(t)
c := newCache(tmp)
defer c.Stop()
const (
key = "test key"
N = 10
)
content := func(i int) string { return fmt.Sprintf("content %d", i) }
for i := 0; i < N; i++ {
t.Run(fmt.Sprintf("read %d", i), func(t *testing.T) {
r, created, err := c.FindOrCreate(key, writeString(content(i)))
require.NoError(t, err)
defer r.Close()
require.Equal(t, i == 0, created, "all calls except the first one should be cache hits")
out, err := io.ReadAll(r)
require.NoError(t, err)
require.NoError(t, r.Wait(context.Background()))
require.Equal(t, content(0), string(out), "expect cache hits for all i > 0")
})
}
requireCacheFiles(t, tmp, 1)
}
func TestCache_manyConcurrentWrites(t *testing.T) {
tmp := testhelper.TempDir(t)
c := newCache(tmp)
defer c.Stop()
const (
key = "test key"
N = 1000
)
content := make([]string, N)
errors := make(chan error, N)
output := make([]string, N)
start := make(chan struct{})
buf := make([]byte, 4096)
for i := 0; i < N; i++ {
_, _ = rand.Read(buf) // math/rand.Read always returns len(buf), nil
content[i] = string(buf)
go func(i int) {
errors <- func() error {
<-start
r, _, err := c.FindOrCreate(key, writeString(content[i]))
if err != nil {
return err
}
defer r.Close()
out, err := io.ReadAll(r)
if err != nil {
return err
}
output[i] = string(out)
return r.Wait(context.Background())
}()
}(i)
}
close(start) // Start all goroutines at once
// Wait for all goroutines to finish
for i := 0; i < N; i++ {
require.NoError(t, <-errors)
}
for i := 0; i < N; i++ {
require.Equal(t, output[0], output[i], "all calls to FindOrCreate returned the same bytes")
}
require.Contains(t, content, output[0], "data returned by FindOrCreate is not mangled")
requireCacheFiles(t, tmp, 1)
}
func writeString(s string) func(io.Writer) error {
return func(w io.Writer) error {
_, err := io.WriteString(w, s)
return err
}
}
func requireCacheFiles(t *testing.T, dir string, n int) {
t.Helper()
find := string(testhelper.MustRunCommand(t, nil, "find", dir, "-type", "f"))
require.Equal(t, n, strings.Count(find, "\n"), "unexpected find output %q", find)
}
func requireCacheEntries(t *testing.T, _c Cache, n int) {
t.Helper()
c := _c.(*cache)
c.m.Lock()
defer c.m.Unlock()
require.Len(t, c.index, n)
}
func TestCache_deletedFile(t *testing.T) {
tmp := testhelper.TempDir(t)
c := newCache(tmp)
defer c.Stop()
const (
key = "test key"
)
content := func(i int) string { return fmt.Sprintf("content %d", i) }
r1, created, err := c.FindOrCreate(key, writeString(content(1)))
require.NoError(t, err)
defer r1.Close()
require.True(t, created)
require.NoError(t, os.RemoveAll(tmp), "wipe out underlying files of cache")
require.NoError(t, os.MkdirAll(tmp, 0o755))
// File is gone from filesystem but not from cache
requireCacheFiles(t, tmp, 0)
requireCacheEntries(t, c, 1)
r2, created, err := c.FindOrCreate(key, writeString(content(2)))
require.NoError(t, err)
defer r2.Close()
require.True(t, created, "because the first file is gone, cache is forced to create a new entry")
out1, err := io.ReadAll(r1)
require.NoError(t, err)
require.Equal(t, content(1), string(out1), "r1 should still see its original pre-wipe contents")
out2, err := io.ReadAll(r2)
require.NoError(t, err)
require.Equal(t, content(2), string(out2), "r2 should see the new post-wipe contents")
}
func TestCache_scope(t *testing.T) {
tmp := testhelper.TempDir(t)
const (
N = 100
key = "test key"
)
// Intentionally create multiple cache instances sharing one directory,
// to test that they do not trample on each others files.
cache := make([]Cache, N)
input := make([]string, N)
reader := make([]*Stream, N)
var err error
for i := 0; i < N; i++ {
input[i] = fmt.Sprintf("test content %d", i)
cache[i] = newCache(tmp)
defer func(i int) { cache[i].Stop() }(i)
var created bool
reader[i], created, err = cache[i].FindOrCreate(key, writeString(input[i]))
require.NoError(t, err)
defer func(i int) { require.NoError(t, reader[i].Close()) }(i)
require.True(t, created)
}
// If different cache instances overwrite their entries, the effect may
// be order dependent, e.g. "last write wins". We could reverse the order
// now to catch that possible bug, but then we only test for one kind of
// bug. Let's shuffle instead, which can catch more hypothetical bugs.
rand.Shuffle(N, func(i, j int) {
reader[i], reader[j] = reader[j], reader[i]
input[i], input[j] = input[j], input[i]
})
for i := 0; i < N; i++ {
r, content := reader[i], input[i]
out, err := io.ReadAll(r)
require.NoError(t, err)
require.NoError(t, r.Wait(context.Background()))
require.Equal(t, content, string(out))
}
}
type clock struct {
n int
sync.Mutex
*sync.Cond
}
func newClock() *clock {
cl := &clock{}
cl.Cond = sync.NewCond(cl)
return cl
}
func (cl *clock) wait() {
cl.Lock()
defer cl.Unlock()
for old := cl.n; old == cl.n; {
cl.Cond.Wait()
}
}
func (cl *clock) advance() {
cl.Lock()
defer cl.Unlock()
cl.n++
cl.Cond.Broadcast()
}
func TestCache_diskCleanup(t *testing.T) {
tmp := testhelper.TempDir(t)
const (
key = "test key"
)
cl := newClock()
c := newCacheWithSleep(tmp, 0, func(time.Duration) { cl.wait() }, log.Default())
defer c.Stop()
content := func(i int) string { return fmt.Sprintf("content %d", i) }
r1, created, err := c.FindOrCreate(key, writeString(content(1)))
require.NoError(t, err)
defer r1.Close()
require.True(t, created)
out1, err := io.ReadAll(r1)
require.NoError(t, err)
require.Equal(t, content(1), string(out1))
require.NoError(t, r1.Wait(context.Background()))
// File and index entry should still exist because cleanup goroutines are blocked.
requireCacheFiles(t, tmp, 1)
requireCacheEntries(t, c, 1)
// Unblock cleanup goroutines so they run exactly once
cl.advance()
// Give them time to do their work
time.Sleep(10 * time.Millisecond)
// File and index entry should have been removed by cleanup goroutines.
requireCacheFiles(t, tmp, 0)
requireCacheEntries(t, c, 0)
r2, created, err := c.FindOrCreate(key, writeString(content(2)))
require.NoError(t, err)
defer r2.Close()
require.True(t, created)
out2, err := io.ReadAll(r2)
require.NoError(t, err)
require.NoError(t, r2.Wait(context.Background()))
// Sanity check: no stale value returned by the cache
require.Equal(t, content(2), string(out2))
}
func TestCache_failedWrite(t *testing.T) {
tmp := testhelper.TempDir(t)
c := newCache(tmp)
defer c.Stop()
testCases := []struct {
desc string
create func(io.Writer) error
}{
{
desc: "create returns error",
create: func(io.Writer) error { return errors.New("something went wrong") },
},
{
desc: "create panics",
create: func(io.Writer) error { panic("oh no") },
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
r1, created, err := c.FindOrCreate(tc.desc, tc.create)
require.NoError(t, err)
require.True(t, created)
_, err = io.Copy(io.Discard, r1)
require.NoError(t, err, "errors on the write end are not propagated via Read()")
require.NoError(t, r1.Close(), "errors on the write end are not propagated via Close()")
require.Error(t, r1.Wait(context.Background()), "error propagation happens via Wait()")
time.Sleep(10 * time.Millisecond)
const happy = "all is good"
r2, created, err := c.FindOrCreate(tc.desc, writeString(happy))
require.NoError(t, err)
defer r2.Close()
require.True(t, created, "because the previous entry failed, a new one should have been created")
out, err := io.ReadAll(r2)
require.NoError(t, err)
require.NoError(t, r2.Wait(context.Background()))
require.Equal(t, happy, string(out))
})
}
}
func TestCache_failCreateFile(t *testing.T) {
tmp := testhelper.TempDir(t)
c := newCache(tmp)
defer c.Stop()
createError := errors.New("cannot create file")
c.(*cache).createFile = func() (namedWriteCloser, error) { return nil, createError }
_, _, err := c.FindOrCreate("key", func(io.Writer) error { return nil })
require.Equal(t, createError, err)
}
func TestCache_unWriteableFile(t *testing.T) {
tmp := testhelper.TempDir(t)
c := newCache(tmp)
defer c.Stop()
c.(*cache).createFile = func() (namedWriteCloser, error) {
return os.OpenFile(filepath.Join(tmp, "unwriteable"), os.O_RDONLY|os.O_CREATE|os.O_EXCL, 0o644)
}
r, created, err := c.FindOrCreate("key", func(w io.Writer) error {
_, err := io.WriteString(w, "hello")
return err
})
require.NoError(t, err)
require.True(t, created)
_, err = io.ReadAll(r)
require.NoError(t, err)
err = r.Wait(context.Background())
require.IsType(t, &os.PathError{}, err)
require.Equal(t, "write", err.(*os.PathError).Op)
}
func TestCache_unCloseableFile(t *testing.T) {
tmp := testhelper.TempDir(t)
c := newCache(tmp)
defer c.Stop()
c.(*cache).createFile = func() (namedWriteCloser, error) {
f, err := os.OpenFile(filepath.Join(tmp, "uncloseable"), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err != nil {
return nil, err
}
return f, f.Close() // Already closed so cannot be closed again
}
r, created, err := c.FindOrCreate("key", func(w io.Writer) error { return nil })
require.NoError(t, err)
require.True(t, created)
_, err = io.ReadAll(r)
require.NoError(t, err)
err = r.Wait(context.Background())
require.IsType(t, &os.PathError{}, err)
require.Equal(t, "close", err.(*os.PathError).Op)
}
func TestCache_cannotOpenFileForReading(t *testing.T) {
tmp := testhelper.TempDir(t)
c := newCache(tmp)
defer c.Stop()
c.(*cache).createFile = func() (namedWriteCloser, error) {
f, err := os.OpenFile(filepath.Join(tmp, "unopenable"), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err != nil {
return nil, err
}
return f, os.Remove(f.Name()) // Removed so cannot be opened
}
_, _, err := c.FindOrCreate("key", func(w io.Writer) error { return nil })
err = errors.Unwrap(err)
require.IsType(t, &os.PathError{}, err)
require.Equal(t, "open", err.(*os.PathError).Op)
}
func TestWaiter(t *testing.T) {
w := newWaiter()
err := errors.New("test error")
w.SetError(err)
require.Equal(t, err, w.Wait(context.Background()))
}
func TestWaiter_cancel(t *testing.T) {
w := newWaiter()
errc := make(chan error, 1)
ctx, cancel := context.WithCancel(context.Background())
go func() { errc <- w.Wait(ctx) }()
cancel()
require.Equal(t, context.Canceled, <-errc)
}
func TestNullCache(t *testing.T) {
const (
N = 1000
inputSize = 4096
key = "key"
)
c := NullCache{}
start := make(chan struct{})
results := make(chan error, N)
for i := 0; i < N; i++ {
go func() {
results <- func() error {
input := make([]byte, inputSize)
n, err := rand.Read(input)
if err != nil {
return err
}
if n != inputSize {
return io.ErrShortWrite
}
<-start
s, created, err := c.FindOrCreate(key, func(w io.Writer) error {
for j := 0; j < len(input); j++ {
n, err := w.Write(input[j : j+1])
if err != nil {
return err
}
if n != 1 {
return io.ErrShortWrite
}
}
return nil
})
if err != nil {
return err
}
defer s.Close()
if !created {
return errors.New("created should be true")
}
output, err := io.ReadAll(s)
if err != nil {
return err
}
if !bytes.Equal(output, input) {
return errors.New("output does not match input")
}
return s.Wait(context.Background())
}()
}()
}
close(start)
for i := 0; i < N; i++ {
require.NoError(t, <-results)
}
}
|