Debian Codegraph @

streaming.go

raw
1 /**
2 * Reed-Solomon Coding over 8-bit values.
3 *
4 * Copyright 2015, Klaus Post
5 * Copyright 2015, Backblaze, Inc.
6 */
7
8 package reedsolomon
9
10 import (
11 "errors"
12 "fmt"
13 "io"
14 "sync"
15 )
16
17 // StreamEncoder is an interface to encode Reed-Salomon parity sets for your data.
18 // It provides a fully streaming interface, and processes data in blocks of up to 4MB.
19 //
20 // For small shard sizes, 10MB and below, it is recommended to use the in-memory interface,
21 // since the streaming interface has a start up overhead.
22 //
23 // For all operations, no readers and writers should not assume any order/size of
24 // individual reads/writes.
25 //
26 // For usage examples, see "stream-encoder.go" and "streamdecoder.go" in the examples
27 // folder.
28 type StreamEncoder interface {
29 // Encode parity shards for a set of data shards.
30 //
31 // Input is 'shards' containing readers for data shards followed by parity shards
32 // io.Writer.
33 //
34 // The number of shards must match the number given to NewStream().
35 //
36 // Each reader must supply the same number of bytes.
37 //
38 // The parity shards will be written to the writer.
39 // The number of bytes written will match the input size.
40 //
41 // If a data stream returns an error, a StreamReadError type error
42 // will be returned. If a parity writer returns an error, a
43 // StreamWriteError will be returned.
44 Encode(data []io.Reader, parity []io.Writer) error
45
46 // Verify returns true if the parity shards contain correct data.
47 //
48 // The number of shards must match the number total data+parity shards
49 // given to NewStream().
50 //
51 // Each reader must supply the same number of bytes.
52 // If a shard stream returns an error, a StreamReadError type error
53 // will be returned.
54 Verify(shards []io.Reader) (bool, error)
55
56 // Reconstruct will recreate the missing shards if possible.
57 //
58 // Given a list of valid shards (to read) and invalid shards (to write)
59 //
60 // You indicate that a shard is missing by setting it to nil in the 'valid'
61 // slice and at the same time setting a non-nil writer in "fill".
62 // An index cannot contain both non-nil 'valid' and 'fill' entry.
63 // If both are provided 'ErrReconstructMismatch' is returned.
64 //
65 // If there are too few shards to reconstruct the missing
66 // ones, ErrTooFewShards will be returned.
67 //
68 // The reconstructed shard set is complete, but integrity is not verified.
69 // Use the Verify function to check if data set is ok.
70 Reconstruct(valid []io.Reader, fill []io.Writer) error
71
72 // Split a an input stream into the number of shards given to the encoder.
73 //
74 // The data will be split into equally sized shards.
75 // If the data size isn't dividable by the number of shards,
76 // the last shard will contain extra zeros.
77 //
78 // You must supply the total size of your input.
79 // 'ErrShortData' will be returned if it is unable to retrieve the
80 // number of bytes indicated.
81 Split(data io.Reader, dst []io.Writer, size int64) (err error)
82
83 // Join the shards and write the data segment to dst.
84 //
85 // Only the data shards are considered.
86 //
87 // You must supply the exact output size you want.
88 // If there are to few shards given, ErrTooFewShards will be returned.
89 // If the total data size is less than outSize, ErrShortData will be returned.
90 Join(dst io.Writer, shards []io.Reader, outSize int64) error
91 }
92
93 // StreamReadError is returned when a read error is encountered
94 // that relates to a supplied stream.
95 // This will allow you to find out which reader has failed.
96 type StreamReadError struct {
97 Err error // The error
98 Stream int // The stream number on which the error occurred
99 }
100
101 // Error returns the error as a string
102 func (s StreamReadError) Error() string {
103 return fmt.Sprintf("error reading stream %d: %s", s.Stream, s.Err)
104 }
105
106 // String returns the error as a string
107 func (s StreamReadError) String() string {
108 return s.Error()
109 }
110
111 // StreamWriteError is returned when a write error is encountered
112 // that relates to a supplied stream. This will allow you to
113 // find out which reader has failed.
114 type StreamWriteError struct {
115 Err error // The error
116 Stream int // The stream number on which the error occurred
117 }
118
119 // Error returns the error as a string
120 func (s StreamWriteError) Error() string {
121 return fmt.Sprintf("error writing stream %d: %s", s.Stream, s.Err)
122 }
123
124 // String returns the error as a string
125 func (s StreamWriteError) String() string {
126 return s.Error()
127 }
128
129 // rsStream contains a matrix for a specific
130 // distribution of datashards and parity shards.
131 // Construct if using NewStream()
132 type rsStream struct {
133 r *reedSolomon
134 o options
135
136 // Shard reader
137 readShards func(dst [][]byte, in []io.Reader) error
138 // Shard writer
139 writeShards func(out []io.Writer, in [][]byte) error
140
141 blockPool sync.Pool
142 }
143
144 // NewStream creates a new encoder and initializes it to
145 // the number of data shards and parity shards that
146 // you want to use. You can reuse this encoder.
147 // Note that the maximum number of data shards is 256.
148 func NewStream(dataShards, parityShards int, o ...Option) (StreamEncoder, error) {
149 if dataShards+parityShards > 256 {
150 return nil, ErrMaxShardNum
151 }
152
153 r := rsStream{o: defaultOptions}
154 for _, opt := range o {
155 opt(&r.o)
156 }
157 // Override block size if shard size is set.
158 if r.o.streamBS == 0 && r.o.shardSize > 0 {
159 r.o.streamBS = r.o.shardSize
160 }
161 if r.o.streamBS <= 0 {
162 r.o.streamBS = 4 << 20
163 }
164 if r.o.shardSize == 0 && r.o.maxGoroutines == defaultOptions.maxGoroutines {
165 o = append(o, WithAutoGoroutines(r.o.streamBS))
166 }
167
168 enc, err := New(dataShards, parityShards, o...)
169 if err != nil {
170 return nil, err
171 }
172 r.r = enc.(*reedSolomon)
173
174 r.blockPool.New = func() any {
175 return AllocAligned(dataShards+parityShards, r.o.streamBS)
176 }
177 r.readShards = readShards
178 r.writeShards = writeShards
179 if r.o.concReads {
180 r.readShards = cReadShards
181 }
182 if r.o.concWrites {
183 r.writeShards = cWriteShards
184 }
185
186 return &r, err
187 }
188
189 // NewStreamC creates a new encoder and initializes it to
190 // the number of data shards and parity shards given.
191 //
192 // This functions as 'NewStream', but allows you to enable CONCURRENT reads and writes.
193 func NewStreamC(dataShards, parityShards int, conReads, conWrites bool, o ...Option) (StreamEncoder, error) {
194 return NewStream(dataShards, parityShards, append(o, WithConcurrentStreamReads(conReads), WithConcurrentStreamWrites(conWrites))...)
195 }
196
197 func (r *rsStream) createSlice() [][]byte {
198 out := r.blockPool.Get().([][]byte)
199 for i := range out {
200 out[i] = out[i][:r.o.streamBS]
201 }
202 return out
203 }
204
205 // Encodes parity shards for a set of data shards.
206 //
207 // Input is 'shards' containing readers for data shards followed by parity shards
208 // io.Writer.
209 //
210 // The number of shards must match the number given to NewStream().
211 //
212 // Each reader must supply the same number of bytes.
213 //
214 // The parity shards will be written to the writer.
215 // The number of bytes written will match the input size.
216 //
217 // If a data stream returns an error, a StreamReadError type error
218 // will be returned. If a parity writer returns an error, a
219 // StreamWriteError will be returned.
220 func (r *rsStream) Encode(data []io.Reader, parity []io.Writer) error {
221 if len(data) != r.r.dataShards {
222 return ErrTooFewShards
223 }
224
225 if len(parity) != r.r.parityShards {
226 return ErrTooFewShards
227 }
228
229 all := r.createSlice()
230 defer r.blockPool.Put(all)
231 in := all[:r.r.dataShards]
232 out := all[r.r.dataShards:]
233 read := 0
234
235 for {
236 err := r.readShards(in, data)
237 switch err {
238 case nil:
239 case io.EOF:
240 if read == 0 {
241 return ErrShardNoData
242 }
243 return nil
244 default:
245 return err
246 }
247 out = trimShards(out, shardSize(in))
248 read += shardSize(in)
249 err = r.r.Encode(all)
250 if err != nil {
251 return err
252 }
253 err = r.writeShards(parity, out)
254 if err != nil {
255 return err
256 }
257 }
258 }
259
260 // Trim the shards so they are all the same size
261 func trimShards(in [][]byte, size int) [][]byte {
262 for i := range in {
263 if len(in[i]) != 0 {
264 in[i] = in[i][0:size]
265 }
266 if len(in[i]) < size {
267 in[i] = in[i][:0]
268 }
269 }
270 return in
271 }
272
273 func readShards(dst [][]byte, in []io.Reader) error {
274 if len(in) != len(dst) {
275 panic("internal error: in and dst size do not match")
276 }
277 size := -1
278 for i := range in {
279 if in[i] == nil {
280 dst[i] = dst[i][:0]
281 continue
282 }
283 n, err := io.ReadFull(in[i], dst[i])
284 // The error is EOF only if no bytes were read.
285 // If an EOF happens after reading some but not all the bytes,
286 // ReadFull returns ErrUnexpectedEOF.
287 switch err {
288 case io.ErrUnexpectedEOF, io.EOF:
289 if size < 0 {
290 size = n
291 } else if n != size {
292 // Shard sizes must match.
293 return ErrShardSize
294 }
295 dst[i] = dst[i][0:n]
296 case nil:
297 continue
298 default:
299 return StreamReadError{Err: err, Stream: i}
300 }
301 }
302 if size == 0 {
303 return io.EOF
304 }
305 return nil
306 }
307
308 func writeShards(out []io.Writer, in [][]byte) error {
309 if len(out) != len(in) {
310 panic("internal error: in and out size do not match")
311 }
312 for i := range in {
313 if out[i] == nil {
314 continue
315 }
316 n, err := out[i].Write(in[i])
317 if err != nil {
318 return StreamWriteError{Err: err, Stream: i}
319 }
320 //
321 if n != len(in[i]) {
322 return StreamWriteError{Err: io.ErrShortWrite, Stream: i}
323 }
324 }
325 return nil
326 }
327
328 type readResult struct {
329 n int
330 size int
331 err error
332 }
333
334 // cReadShards reads shards concurrently
335 func cReadShards(dst [][]byte, in []io.Reader) error {
336 if len(in) != len(dst) {
337 panic("internal error: in and dst size do not match")
338 }
339 var wg sync.WaitGroup
340 wg.Add(len(in))
341 res := make(chan readResult, len(in))
342 for i := range in {
343 if in[i] == nil {
344 dst[i] = dst[i][:0]
345 wg.Done()
346 continue
347 }
348 go func(i int) {
349 defer wg.Done()
350 n, err := io.ReadFull(in[i], dst[i])
351 // The error is EOF only if no bytes were read.
352 // If an EOF happens after reading some but not all the bytes,
353 // ReadFull returns ErrUnexpectedEOF.
354 res <- readResult{size: n, err: err, n: i}
355
356 }(i)
357 }
358 wg.Wait()
359 close(res)
360 size := -1
361 for r := range res {
362 switch r.err {
363 case io.ErrUnexpectedEOF, io.EOF:
364 if size < 0 {
365 size = r.size
366 } else if r.size != size {
367 // Shard sizes must match.
368 return ErrShardSize
369 }
370 dst[r.n] = dst[r.n][0:r.size]
371 case nil:
372 default:
373 return StreamReadError{Err: r.err, Stream: r.n}
374 }
375 }
376 if size == 0 {
377 return io.EOF
378 }
379 return nil
380 }
381
382 // cWriteShards writes shards concurrently
383 func cWriteShards(out []io.Writer, in [][]byte) error {
384 if len(out) != len(in) {
385 panic("internal error: in and out size do not match")
386 }
387 var errs = make(chan error, len(out))
388 var wg sync.WaitGroup
389 wg.Add(len(out))
390 for i := range in {
391 go func(i int) {
392 defer wg.Done()
393 if out[i] == nil {
394 errs <- nil
395 return
396 }
397 n, err := out[i].Write(in[i])
398 if err != nil {
399 errs <- StreamWriteError{Err: err, Stream: i}
400 return
401 }
402 if n != len(in[i]) {
403 errs <- StreamWriteError{Err: io.ErrShortWrite, Stream: i}
404 }
405 }(i)
406 }
407 wg.Wait()
408 close(errs)
409 for err := range errs {
410 if err != nil {
411 return err
412 }
413 }
414
415 return nil
416 }
417
418 // Verify returns true if the parity shards contain correct data.
419 //
420 // The number of shards must match the number total data+parity shards
421 // given to NewStream().
422 //
423 // Each reader must supply the same number of bytes.
424 // If a shard stream returns an error, a StreamReadError type error
425 // will be returned.
426 func (r *rsStream) Verify(shards []io.Reader) (bool, error) {
427 if len(shards) != r.r.totalShards {
428 return false, ErrTooFewShards
429 }
430
431 read := 0
432 all := r.createSlice()
433 defer r.blockPool.Put(all)
434 for {
435 err := r.readShards(all, shards)
436 if err == io.EOF {
437 if read == 0 {
438 return false, ErrShardNoData
439 }
440 return true, nil
441 }
442 if err != nil {
443 return false, err
444 }
445 read += shardSize(all)
446 ok, err := r.r.Verify(all)
447 if !ok || err != nil {
448 return ok, err
449 }
450 }
451 }
452
453 // ErrReconstructMismatch is returned by the StreamEncoder, if you supply
454 // "valid" and "fill" streams on the same index.
455 // Therefore it is impossible to see if you consider the shard valid
456 // or would like to have it reconstructed.
457 var ErrReconstructMismatch = errors.New("valid shards and fill shards are mutually exclusive")
458
459 // Reconstruct will recreate the missing shards if possible.
460 //
461 // Given a list of valid shards (to read) and invalid shards (to write)
462 //
463 // You indicate that a shard is missing by setting it to nil in the 'valid'
464 // slice and at the same time setting a non-nil writer in "fill".
465 // An index cannot contain both non-nil 'valid' and 'fill' entry.
466 //
467 // If there are too few shards to reconstruct the missing
468 // ones, ErrTooFewShards will be returned.
469 //
470 // The reconstructed shard set is complete when explicitly asked for all missing shards.
471 // However its integrity is not automatically verified.
472 // Use the Verify function to check in case the data set is complete.
473 func (r *rsStream) Reconstruct(valid []io.Reader, fill []io.Writer) error {
474 if len(valid) != r.r.totalShards {
475 return ErrTooFewShards
476 }
477 if len(fill) != r.r.totalShards {
478 return ErrTooFewShards
479 }
480
481 all := r.createSlice()
482 defer r.blockPool.Put(all)
483 reconDataOnly := true
484 for i := range valid {
485 if valid[i] != nil && fill[i] != nil {
486 return ErrReconstructMismatch
487 }
488 if i >= r.r.dataShards && fill[i] != nil {
489 reconDataOnly = false
490 }
491 }
492
493 read := 0
494 for {
495 err := r.readShards(all, valid)
496 if err == io.EOF {
497 if read == 0 {
498 return ErrShardNoData
499 }
500 return nil
501 }
502 if err != nil {
503 return err
504 }
505 read += shardSize(all)
506 all = trimShards(all, shardSize(all))
507
508 if reconDataOnly {
509 err = r.r.ReconstructData(all) // just reconstruct missing data shards
510 } else {
511 err = r.r.Reconstruct(all) // reconstruct all missing shards
512 }
513 if err != nil {
514 return err
515 }
516 err = r.writeShards(fill, all)
517 if err != nil {
518 return err
519 }
520 }
521 }
522
523 // Join the shards and write the data segment to dst.
524 //
525 // Only the data shards are considered.
526 //
527 // You must supply the exact output size you want.
528 // If there are to few shards given, ErrTooFewShards will be returned.
529 // If the total data size is less than outSize, ErrShortData will be returned.
530 func (r *rsStream) Join(dst io.Writer, shards []io.Reader, outSize int64) error {
531 // Do we have enough shards?
532 if len(shards) < r.r.dataShards {
533 return ErrTooFewShards
534 }
535
536 // Trim off parity shards if any
537 shards = shards[:r.r.dataShards]
538 for i := range shards {
539 if shards[i] == nil {
540 return StreamReadError{Err: ErrShardNoData, Stream: i}
541 }
542 }
543 // Join all shards
544 src := io.MultiReader(shards...)
545
546 // Copy data to dst
547 n, err := io.CopyN(dst, src, outSize)
548 if err == io.EOF {
549 return ErrShortData
550 }
551 if err != nil {
552 return err
553 }
554 if n != outSize {
555 return ErrShortData
556 }
557 return nil
558 }
559
560 // Split a an input stream into the number of shards given to the encoder.
561 //
562 // The data will be split into equally sized shards.
563 // If the data size isn't dividable by the number of shards,
564 // the last shard will contain extra zeros.
565 //
566 // You must supply the total size of your input.
567 // 'ErrShortData' will be returned if it is unable to retrieve the
568 // number of bytes indicated.
569 func (r *rsStream) Split(data io.Reader, dst []io.Writer, size int64) error {
570 if size == 0 {
571 return ErrShortData
572 }
573 if len(dst) != r.r.dataShards {
574 return ErrInvShardNum
575 }
576
577 for i := range dst {
578 if dst[i] == nil {
579 return StreamWriteError{Err: ErrShardNoData, Stream: i}
580 }
581 }
582
583 // Calculate number of bytes per shard.
584 perShard := (size + int64(r.r.dataShards) - 1) / int64(r.r.dataShards)
585
586 // Pad data to r.Shards*perShard.
587 paddingSize := (int64(r.r.totalShards) * perShard) - size
588 data = io.MultiReader(data, io.LimitReader(zeroPaddingReader{}, paddingSize))
589
590 // Split into equal-length shards and copy.
591 for i := range dst {
592 n, err := io.CopyN(dst[i], data, perShard)
593 if err != io.EOF && err != nil {
594 return err
595 }
596 if n != perShard {
597 return ErrShortData
598 }
599 }
600
601 return nil
602 }
603
604 type zeroPaddingReader struct{}
605
606 var _ io.Reader = &zeroPaddingReader{}
607
608 func (t zeroPaddingReader) Read(p []byte) (n int, err error) {
609 n = len(p)
610 for i := 0; i < n; i++ {
611 p[i] = 0
612 }
613 return n, nil
614 }