Debian Codegraph @

copy.go

raw
1 package desync
2
3 import (
4 "context"
5
6 "golang.org/x/sync/errgroup"
7 )
8
9 // Copy reads a list of chunks from the provided src store, and copies the ones
10 // not already present in the dst store. The goal is to load chunks from remote
11 // store to populate a cache. If progress is provided, it'll be called when a
12 // chunk has been processed. Used to draw a progress bar, can be nil.
13 func Copy(ctx context.Context, ids []ChunkID, src Store, dst WriteStore, n int, pb ProgressBar) error {
14 in := make(chan ChunkID)
15 g, ctx := errgroup.WithContext(ctx)
16
17 // Setup and start the progressbar if any
18 pb.SetTotal(len(ids))
19 pb.Start()
20 defer pb.Finish()
21
22 // Start the workers
23 for range n {
24 g.Go(func() error {
25 for id := range in {
26 pb.Increment()
27 hasChunk, err := dst.HasChunk(id)
28 if err != nil {
29 return err
30 }
31 if hasChunk {
32 continue
33 }
34 chunk, err := src.GetChunk(id)
35 if err != nil {
36 return err
37 }
38 if err := dst.StoreChunk(chunk); err != nil {
39 return err
40 }
41 }
42 return nil
43 })
44 }
45
46 // Feed the workers, the context is cancelled if any goroutine encounters an error
47 loop:
48 for _, c := range ids {
49 select {
50 case <-ctx.Done():
51 break loop
52 case in <- c:
53 }
54 }
55 close(in)
56
57 return g.Wait()
58 }