-
Notifications
You must be signed in to change notification settings - Fork 343
/
diag_writer.go
67 lines (53 loc) · 1.67 KB
/
diag_writer.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
package repodiag
import (
"context"
"sync"
"github.com/kopia/kopia/internal/blobcrypto"
"github.com/kopia/kopia/internal/gather"
"github.com/kopia/kopia/repo/blob"
"github.com/kopia/kopia/repo/logging"
)
var log = logging.Module("repodiag")
// Writer manages encryption and asynchronous writing of diagnostic blobs to the repository.
type Writer struct {
st blob.Storage
bc blobcrypto.Crypter
wg sync.WaitGroup
}
// EncryptAndWriteBlobAsync encrypts given content and writes it to the repository asynchronously,
// folllowed by calling the provided closeFunc.
func (w *Writer) EncryptAndWriteBlobAsync(ctx context.Context, prefix blob.ID, data gather.Bytes, closeFunc func()) {
encrypted := gather.NewWriteBuffer()
// Close happens in a goroutine
blobID, err := blobcrypto.Encrypt(w.bc, data, prefix, "", encrypted)
if err != nil {
encrypted.Close()
// this should not happen, also nothing can be done about this, we're not in a place where we can return error, log it.
log(ctx).Warnf("unable to encrypt diagnostics blob: %v", err)
return
}
b := encrypted.Bytes()
w.wg.Add(1)
go func() {
defer w.wg.Done()
defer encrypted.Close()
defer closeFunc()
if err := w.st.PutBlob(ctx, blobID, b, blob.PutOptions{}); err != nil {
// nothing can be done about this, we're not in a place where we can return error, log it.
log(ctx).Warnf("unable to write diagnostics blob: %v", err)
return
}
}()
}
// Wait waits for all the writes to complete.
func (w *Writer) Wait(ctx context.Context) error {
w.wg.Wait()
return nil
}
// NewWriter creates a new writer.
func NewWriter(
st blob.Storage,
bc blobcrypto.Crypter,
) *Writer {
return &Writer{st: st, bc: bc}
}