-
Notifications
You must be signed in to change notification settings - Fork 463
/
Copy pathcompress_and_encrypt.go
76 lines (63 loc) · 1.94 KB
/
compress_and_encrypt.go
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
package internal
import (
"fmt"
"io"
"github.com/pkg/errors"
"github.com/wal-g/tracelog"
"github.com/wal-g/wal-g/internal/compression"
"github.com/wal-g/wal-g/internal/crypto"
"github.com/wal-g/wal-g/utility"
)
// CompressAndEncryptError is used to catch specific errors from CompressAndEncrypt
// when uploading to Storage. Will not retry upload if this error occurs.
type CompressAndEncryptError struct {
error
}
func newCompressingPipeWriterError(reason string) CompressAndEncryptError {
return CompressAndEncryptError{errors.New(reason)}
}
func (err CompressAndEncryptError) Error() string {
return fmt.Sprintf(tracelog.GetErrorFormatter(), err.error)
}
// CompressAndEncrypt compresses input to a pipe reader. Output must be used or
// pipe will block.
func CompressAndEncrypt(source io.Reader, compressor compression.Compressor, crypter crypto.Crypter) io.Reader {
compressedReader, dstWriter := io.Pipe()
var writeCloser io.WriteCloser = dstWriter
if crypter != nil {
var err error
writeCloser, err = crypter.Encrypt(dstWriter)
if err != nil {
panic(err)
}
}
var compressedWriter io.WriteCloser
if compressor != nil {
writeIgnorer := &utility.EmptyWriteIgnorer{Writer: writeCloser}
compressedWriter = compressor.NewWriter(writeIgnorer)
} else {
compressedWriter = writeCloser
}
go func() {
_, err := utility.FastCopy(compressedWriter, source)
if err != nil {
e := newCompressingPipeWriterError("CompressAndEncrypt: compression failed")
_ = dstWriter.CloseWithError(e)
}
if err := compressedWriter.Close(); err != nil {
e := newCompressingPipeWriterError("CompressAndEncrypt: writer close failed")
_ = dstWriter.CloseWithError(e)
return
}
if crypter != nil {
err := writeCloser.Close()
if err != nil {
e := newCompressingPipeWriterError("CompressAndEncrypt: encryption failed")
_ = dstWriter.CloseWithError(e)
return
}
}
_ = dstWriter.Close()
}()
return compressedReader
}