| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"context" |
| 6 |
"crypto" |
| 7 |
"fmt" |
| 8 |
"math" |
| 9 |
"slices" |
| 10 |
"sync" |
| 11 |
|
| 12 |
"golang.org/x/sync/errgroup" |
| 13 |
|
| 14 |
"github.com/pkg/errors" |
| 15 |
|
| 16 |
"io" |
| 17 |
) |
| 18 |
|
| 19 |
// Index represents the content of an index file |
| 20 |
type Index struct { |
| 21 |
Index FormatIndex |
| 22 |
Chunks []IndexChunk |
| 23 |
} |
| 24 |
|
| 25 |
// IndexChunk is a table entry in an index file containing the chunk ID (SHA256) |
| 26 |
// Similar to an FormatTableItem but with Start and Size instead of just offset to |
| 27 |
// make it easier to use throughout the application. |
| 28 |
type IndexChunk struct { |
| 29 |
ID ChunkID |
| 30 |
Start uint64 |
| 31 |
Size uint64 |
| 32 |
} |
| 33 |
|
| 34 |
// IndexFromReader parses a caibx structure (from a reader) and returns a populated Caibx |
| 35 |
// object |
| 36 |
func IndexFromReader(r io.Reader) (c Index, err error) { |
| 37 |
d := NewFormatDecoder(bufio.NewReader(r)) |
| 38 |
var ok bool |
| 39 |
// Read the index |
| 40 |
e, err := d.Next() |
| 41 |
if err != nil { |
| 42 |
return c, errors.Wrap(err, "reading index") |
| 43 |
} |
| 44 |
|
| 45 |
c.Index, ok = e.(FormatIndex) |
| 46 |
if !ok { |
| 47 |
return c, errors.New("input is not an index file") |
| 48 |
} |
| 49 |
|
| 50 |
// Ensure the algorithm the library uses matches that of the index file |
| 51 |
switch Digest.Algorithm() { |
| 52 |
case crypto.SHA512_256: |
| 53 |
if c.Index.FeatureFlags&CaFormatSHA512256 == 0 { |
| 54 |
return c, errors.New("index file uses SHA256") |
| 55 |
} |
| 56 |
case crypto.SHA256: |
| 57 |
if c.Index.FeatureFlags&CaFormatSHA512256 != 0 { |
| 58 |
return c, errors.New("index file uses SHA512-256") |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
// Read the table |
| 63 |
e, err = d.Next() |
| 64 |
if err != nil { |
| 65 |
return c, errors.Wrap(err, "reading chunk table") |
| 66 |
} |
| 67 |
table, ok := e.(FormatTable) |
| 68 |
if !ok { |
| 69 |
return c, errors.New("index table not found in input") |
| 70 |
} |
| 71 |
|
| 72 |
// Convert the chunk table into a different format for easier use |
| 73 |
c.Chunks = make([]IndexChunk, len(table.Items)) |
| 74 |
var lastOffset uint64 |
| 75 |
for i, r := range table.Items { |
| 76 |
c.Chunks[i].ID = r.Chunk |
| 77 |
c.Chunks[i].Start = lastOffset |
| 78 |
c.Chunks[i].Size = r.Offset - lastOffset |
| 79 |
lastOffset = r.Offset |
| 80 |
// Check the max size of the chunk only. The min apparently doesn't apply |
| 81 |
// to the last chunk. |
| 82 |
if c.Chunks[i].Size > c.Index.ChunkSizeMax { |
| 83 |
return c, fmt.Errorf("chunk size %d is larger than maximum %d", c.Chunks[i].Size, c.Index.ChunkSizeMax) |
| 84 |
} |
| 85 |
} |
| 86 |
return |
| 87 |
} |
| 88 |
|
| 89 |
// WriteTo writes the index and chunk table into a stream |
| 90 |
func (i *Index) WriteTo(w io.Writer) (int64, error) { |
| 91 |
index := FormatIndex{ |
| 92 |
FormatHeader: FormatHeader{Size: 48, Type: CaFormatIndex}, |
| 93 |
FeatureFlags: i.Index.FeatureFlags, |
| 94 |
ChunkSizeMin: i.Index.ChunkSizeMin, |
| 95 |
ChunkSizeAvg: i.Index.ChunkSizeAvg, |
| 96 |
ChunkSizeMax: i.Index.ChunkSizeMax, |
| 97 |
} |
| 98 |
|
| 99 |
bw := bufio.NewWriter(w) |
| 100 |
d := NewFormatEncoder(bw) |
| 101 |
n, err := d.Encode(index) |
| 102 |
if err != nil { |
| 103 |
return n, err |
| 104 |
} |
| 105 |
|
| 106 |
// Convert the chunk list back into the format used in index files (with offset |
| 107 |
// instead of start+size) |
| 108 |
var offset uint64 |
| 109 |
fChunks := make([]FormatTableItem, len(i.Chunks)) |
| 110 |
for p, c := range i.Chunks { |
| 111 |
offset += c.Size |
| 112 |
fChunks[p] = FormatTableItem{Chunk: c.ID, Offset: offset} |
| 113 |
} |
| 114 |
table := FormatTable{ |
| 115 |
FormatHeader: FormatHeader{Size: math.MaxUint64, Type: CaFormatTable}, |
| 116 |
Items: fChunks, |
| 117 |
} |
| 118 |
n1, err := d.Encode(table) |
| 119 |
|
| 120 |
if err := bw.Flush(); err != nil { |
| 121 |
return n + n1, err |
| 122 |
} |
| 123 |
return n + n1, err |
| 124 |
} |
| 125 |
|
| 126 |
// Length returns the total (uncompressed) size of the indexed stream |
| 127 |
func (i *Index) Length() int64 { |
| 128 |
if len(i.Chunks) < 1 { |
| 129 |
return 0 |
| 130 |
} |
| 131 |
lastChunk := i.Chunks[len(i.Chunks)-1] |
| 132 |
return int64(lastChunk.Start + lastChunk.Size) |
| 133 |
} |
| 134 |
|
| 135 |
// ChunkStream splits up a blob into chunks using the provided chunker (single stream), |
| 136 |
// populates a store with the chunks and returns an index. Hashing and compression |
| 137 |
// is performed in n goroutines while the hashing algorithm is performed serially. |
| 138 |
func ChunkStream(ctx context.Context, c Chunker, ws WriteStore, n int) (Index, error) { |
| 139 |
type chunkJob struct { |
| 140 |
num int |
| 141 |
start uint64 |
| 142 |
b []byte |
| 143 |
} |
| 144 |
var ( |
| 145 |
mu sync.Mutex |
| 146 |
in = make(chan chunkJob) |
| 147 |
results = make(map[int]IndexChunk) |
| 148 |
) |
| 149 |
|
| 150 |
g, ctx := errgroup.WithContext(ctx) |
| 151 |
s := NewChunkStorage(ws) |
| 152 |
|
| 153 |
// All the chunks are processed in parallel, but we need to preserve the |
| 154 |
// order for later. So add the chunking results to a map, indexed by |
| 155 |
// the chunk number so we can rebuild it in the right order when done |
| 156 |
recordResult := func(num int, r IndexChunk) { |
| 157 |
mu.Lock() |
| 158 |
defer mu.Unlock() |
| 159 |
results[num] = r |
| 160 |
} |
| 161 |
|
| 162 |
// Start the workers responsible for checksum calculation, compression and |
| 163 |
// storage (if required). Each job comes with a chunk number for sorting later |
| 164 |
for range n { |
| 165 |
g.Go(func() error { |
| 166 |
for c := range in { |
| 167 |
// Create a chunk object, needed to calculate the checksum |
| 168 |
chunk := NewChunk(c.b) |
| 169 |
|
| 170 |
// Record the index row |
| 171 |
idxChunk := IndexChunk{Start: c.start, Size: uint64(len(c.b)), ID: chunk.ID()} |
| 172 |
recordResult(c.num, idxChunk) |
| 173 |
|
| 174 |
if err := s.StoreChunk(chunk); err != nil { |
| 175 |
return err |
| 176 |
} |
| 177 |
} |
| 178 |
return nil |
| 179 |
}) |
| 180 |
} |
| 181 |
|
| 182 |
// Feed the workers, stop if there are any errors. To keep the index list in |
| 183 |
// order, we calculate the checksum here before handing them over to the |
| 184 |
// workers for compression and storage. That could probably be optimized further |
| 185 |
var num int // chunk #, so we can re-assemble the index in the right order later |
| 186 |
loop: |
| 187 |
for { |
| 188 |
start, b, err := c.Next() |
| 189 |
if err != nil { |
| 190 |
return Index{}, err |
| 191 |
} |
| 192 |
if len(b) == 0 { |
| 193 |
break |
| 194 |
} |
| 195 |
|
| 196 |
// Copy the buffer before sending it to workers. The chunker |
| 197 |
// reuses its internal backing buffer across fillBuffer() calls, |
| 198 |
// so the slice returned by Next() may be overwritten by the |
| 199 |
// next call. |
| 200 |
b = slices.Clone(b) |
| 201 |
|
| 202 |
// Send it off for compression and storage |
| 203 |
select { |
| 204 |
case <-ctx.Done(): |
| 205 |
break loop |
| 206 |
case in <- chunkJob{num: num, start: start, b: b}: |
| 207 |
} |
| 208 |
num++ |
| 209 |
} |
| 210 |
close(in) |
| 211 |
|
| 212 |
if err := g.Wait(); err != nil { |
| 213 |
return Index{}, err |
| 214 |
} |
| 215 |
|
| 216 |
// All the chunks have been processed and are stored in a map. Now build a |
| 217 |
// list in the correct order to be used in the index below |
| 218 |
chunks := make([]IndexChunk, len(results)) |
| 219 |
for i := 0; i < len(results); i++ { |
| 220 |
chunks[i] = results[i] |
| 221 |
} |
| 222 |
|
| 223 |
// Build and return the index |
| 224 |
index := Index{ |
| 225 |
Index: FormatIndex{ |
| 226 |
FeatureFlags: CaFormatExcludeNoDump | CaFormatSHA512256, |
| 227 |
ChunkSizeMin: c.Min(), |
| 228 |
ChunkSizeAvg: c.Avg(), |
| 229 |
ChunkSizeMax: c.Max(), |
| 230 |
}, |
| 231 |
Chunks: chunks, |
| 232 |
} |
| 233 |
return index, nil |
| 234 |
} |