diff --git a/go.mod b/go.mod index bae3443..3e73e69 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/secretli/cli -go 1.27.3 +go 1.27.4 require ( github.com/creack/pty v1.1.24 diff --git a/internal/cli/extras.go b/internal/cli/extras.go index d90cc8d..0aea1ac 100644 --- a/internal/cli/extras.go +++ b/internal/cli/extras.go @@ -9,6 +9,7 @@ import ( "time" "unicode/utf8" + "github.com/secretli/cli/internal/share" qrcode "github.com/skip2/go-qrcode" "golang.org/x/term" ) @@ -34,8 +35,9 @@ type progressBar struct { // and a wrapped line can't be redrawn in place. width int - last time.Time - shown bool + last time.Time + shown bool + retrying bool // samples are how far the transfer was at times at least // sampleInterval apart, over the last rateWindow and one from before. @@ -101,9 +103,69 @@ func (p *progressBar) update(done, total int64) { _, _ = fmt.Fprintf(p.w, "\r\033[K%s", line) } +// stageCells is how wide the upload's bar is. +const stageCells = 20 + +// stages draws an upload: a bar in three parts that always add up to the +// bundle, sent (█), encrypted and ready to send (▓), still to read (░), +// then how far along, and the speed and time left, or what it waits for. +// On a narrow terminal the speed goes first, then the bar. +func (p *progressBar) stages(u share.UploadProgress) { + if p == nil || u.Total < progressThreshold { + return + } + now := time.Now() + p.sample(u.Sent, now) + // Starting or ending a retry shows at once; the rest of the time, the + // line redraws at most ten times a second. + if u.Uploaded < u.Total && u.Retrying == p.retrying && now.Sub(p.last) < 100*time.Millisecond { + return + } + p.last, p.shown, p.retrying = now, true, u.Retrying + + percent := u.Sent * 100 / u.Total + amounts := fmt.Sprintf("%d%% · %s of %s", percent, formatSize(u.Sent), formatSize(u.Total)) + var tail string + switch { + case u.Retrying: + tail = "a part didn't go through, trying it again…" + case u.Sent >= u.Total: + tail = "waiting for the server to confirm…" + default: + if rate, over, moved := p.rate(); over >= rateAfter || moved >= rateAfterBytes { + tail = formatSpeed(rate, u.Total-u.Sent) + } + } + withBar := p.label + " " + stageBar(u, stageCells) + " " + amounts + lines := []string{withBar, p.label + " " + amounts} + if tail != "" { + lines = []string{withBar + " · " + tail, withBar, p.label + " " + amounts} + } + line := lines[len(lines)-1] + for _, candidate := range lines { + if p.width <= 0 || utf8.RuneCountInString(candidate) < p.width { + line = candidate + break + } + } + _, _ = fmt.Fprintf(p.w, "\r\033[K%s", line) +} + +// stageBar is the upload as cells: sent, then encrypted and ready to send, +// then still to read. A part only counts as full once all of it is there. +func stageBar(u share.UploadProgress, cells int) string { + sent := int(u.Sent * int64(cells) / u.Total) + encrypted := max(int(u.Encrypted*int64(cells)/u.Total), sent) + return strings.Repeat("█", sent) + strings.Repeat("▓", encrypted-sent) + strings.Repeat("░", cells-encrypted) +} + // sample notes how far the transfer is, and forgets what is too old to // count. func (p *progressBar) sample(done int64, now time.Time) { + if n := len(p.samples); n > 0 && done < p.samples[n-1].done { + // The count went back, as when a part is sent again: start over. + p.samples = p.samples[:0] + } if n := len(p.samples); n > 0 && now.Sub(p.samples[n-1].at) < sampleInterval { return } diff --git a/internal/cli/progress_test.go b/internal/cli/progress_test.go index df716de..9b792de 100644 --- a/internal/cli/progress_test.go +++ b/internal/cli/progress_test.go @@ -1,8 +1,11 @@ package cli import ( + "strings" "testing" "time" + + "github.com/secretli/cli/internal/share" ) func TestFormatSpeed(t *testing.T) { @@ -95,3 +98,67 @@ func (l *lineRecorder) Write(b []byte) (int, error) { l.last = string(b) return len(b), nil } + +func TestStageBar(t *testing.T) { + cases := []struct { + sent, encrypted int64 + want string + }{ + {0, 0, "░░░░░░░░░░"}, + {0, 50, "▓▓▓▓▓░░░░░"}, + {20, 50, "██▓▓▓░░░░░"}, + // A cell is sent only once all of it is. + {99, 100, "█████████▓"}, + {100, 100, "██████████"}, + } + for _, tc := range cases { + got := stageBar(share.UploadProgress{Total: 100, Encrypted: tc.encrypted, Sent: tc.sent}, 10) + if got != tc.want { + t.Errorf("sent %d, encrypted %d: %q, want %q", tc.sent, tc.encrypted, got, tc.want) + } + } +} + +func TestUploadLine(t *testing.T) { + const mb = 1 << 20 + var line lineRecorder + p := &progressBar{w: &line, label: "Uploading"} + // Two seconds in, 64 MiB sent: 32 MiB a second. + p.samples = []progressSample{{at: time.Now().Add(-2 * time.Second)}} + u := share.UploadProgress{Total: 256 * mb, Encrypted: 128 * mb, Sent: 64 * mb, Uploaded: 32 * mb} + p.stages(u) + if want := "\r\033[KUploading █████▓▓▓▓▓░░░░░░░░░░ 25% · 64.0 MB of 256.0 MB · 32.0 MB/s · 6 s left"; line.last != want { + t.Errorf("line %q,\nwant %q", line.last, want) + } + // A retry shows at once, in place of the speed. + u.Retrying = true + p.stages(u) + if !strings.HasSuffix(line.last, "· a part didn't go through, trying it again…") { + t.Errorf("retry line %q", line.last) + } + // A narrow terminal loses the speed first, then the bar. + u.Retrying = false + p.width, p.last = 60, time.Time{} + p.stages(u) + if want := "\r\033[KUploading █████▓▓▓▓▓░░░░░░░░░░ 25% · 64.0 MB of 256.0 MB"; line.last != want { + t.Errorf("narrow line %q,\nwant %q", line.last, want) + } + p.width, p.last = 40, time.Time{} + p.stages(u) + if want := "\r\033[KUploading 25% · 64.0 MB of 256.0 MB"; line.last != want { + t.Errorf("narrower line %q,\nwant %q", line.last, want) + } +} + +// A part sent again makes the count go back; the speed starts over then, +// rather than going negative. +func TestProgressRateStartsOverWhenTheCountGoesBack(t *testing.T) { + start := time.Now() + p := &progressBar{} + p.sample(0, start) + p.sample(10<<20, start.Add(time.Second)) + p.sample(2<<20, start.Add(2*time.Second)) + if len(p.samples) != 1 { + t.Errorf("%d samples after going back, want 1", len(p.samples)) + } +} diff --git a/internal/cli/share.go b/internal/cli/share.go index 71ad5c4..7e2b48d 100644 --- a/internal/cli/share.go +++ b/internal/cli/share.go @@ -169,8 +169,8 @@ func (e *env) share(ctx context.Context, o shareOptions, args []string) error { } params.Password = password - bar := e.progress("Encrypting and uploading…") - params.Progress = bar.update + bar := e.progress("Uploading") + params.Progress = bar.stages result, err := share.Share(ctx, e.client(server), params) bar.finish() if err != nil { diff --git a/internal/share/api/client.go b/internal/share/api/client.go index 5fabb6e..1fc56f2 100644 --- a/internal/share/api/client.go +++ b/internal/share/api/client.go @@ -179,7 +179,7 @@ func (c *Client) ReadRange(ctx context.Context, publicID, sessionToken string, s "Authorization": {"Bearer " + sessionToken}, "Range": {fmt.Sprintf("bytes=%d-%d", start, end)}, } - resp, err := c.do(ctx, http.MethodGet, "/api/v1/secrets/"+publicID+"/blob", headers, nil, 0) + resp, err := c.do(ctx, http.MethodGet, "/api/v1/secrets/"+publicID+"/blob", headers, nil, 0, nil) if err != nil { return nil, err } @@ -252,7 +252,16 @@ func (c *Client) StartUpload(ctx context.Context, req UploadRequest) (*UploadSes // UploadPart sends one part of the bundle. Parts are numbered from 1 and // every part but the last must be at least 5 MiB. -func (c *Client) UploadPart(ctx context.Context, sessionID, token string, partNumber int, offset int64, data []byte, sha256Hex string) error { +// PartProgress hears how a part upload goes, if set. Sent is told how many +// bytes of the current attempt have gone out; Retrying, that an attempt +// failed and another will follow, whose bytes count from zero again. +type PartProgress struct { + Sent func(n int64) + Retrying func() +} + +// UploadPart sends one part of an upload, retrying transient failures. +func (c *Client) UploadPart(ctx context.Context, sessionID, token string, partNumber int, offset int64, data []byte, sha256Hex string, progress *PartProgress) error { headers := http.Header{ "Authorization": {"Bearer " + token}, "Content-Type": {"application/octet-stream"}, @@ -261,7 +270,12 @@ func (c *Client) UploadPart(ctx context.Context, sessionID, token string, partNu headerPartSHA256: {sha256Hex}, } path := fmt.Sprintf("/api/v1/secrets/uploads/%s/parts/%d", sessionID, partNumber) - return c.doJSON(ctx, http.MethodPut, path, headers, data, nil) + resp, err := c.do(ctx, http.MethodPut, path, headers, data, int64(len(data)), progress) + if err != nil { + return err + } + _, _ = io.Copy(io.Discard, resp.Body) + return resp.Body.Close() } // CompleteUpload turns the uploaded parts into the secret and returns its @@ -289,7 +303,7 @@ func (c *Client) AbortUpload(ctx context.Context, sessionID, token string) error // doJSON performs a request and decodes a JSON answer into out, if out is set. func (c *Client) doJSON(ctx context.Context, method, path string, headers http.Header, body []byte, out any) error { - resp, err := c.do(ctx, method, path, headers, body, int64(len(body))) + resp, err := c.do(ctx, method, path, headers, body, int64(len(body)), nil) if err != nil { return err } @@ -306,13 +320,13 @@ func (c *Client) doJSON(ctx context.Context, method, path string, headers http.H // do sends the request, retrying transient failures, and returns a response // with a 2xx status; anything else becomes an *Error. -func (c *Client) do(ctx context.Context, method, path string, headers http.Header, body []byte, contentLength int64) (*http.Response, error) { +func (c *Client) do(ctx context.Context, method, path string, headers http.Header, body []byte, contentLength int64, progress *PartProgress) (*http.Response, error) { var lastErr error for attempt := 1; attempt <= MaxTransientAttempts; attempt++ { if err := ctx.Err(); err != nil { return nil, err } - resp, err := c.once(ctx, method, path, headers, body, contentLength) + resp, err := c.once(ctx, method, path, headers, body, contentLength, progress) if err == nil { return resp, nil } @@ -321,6 +335,9 @@ func (c *Client) do(ctx context.Context, method, path string, headers http.Heade if !errors.As(err, &apiErr) || !transient(apiErr) || attempt == MaxTransientAttempts { return nil, err } + if progress != nil && progress.Retrying != nil { + progress.Retrying() + } if err := sleep(ctx, retryDelay(attempt, apiErr.RetryAfter)); err != nil { return nil, err } @@ -328,7 +345,7 @@ func (c *Client) do(ctx context.Context, method, path string, headers http.Heade return nil, lastErr } -func (c *Client) once(ctx context.Context, method, path string, headers http.Header, body []byte, contentLength int64) (*http.Response, error) { +func (c *Client) once(ctx context.Context, method, path string, headers http.Header, body []byte, contentLength int64, progress *PartProgress) (*http.Response, error) { var reader io.Reader if body != nil { reader = bytes.NewReader(body) @@ -343,6 +360,16 @@ func (c *Client) once(ctx context.Context, method, path string, headers http.Hea return nil, fmt.Errorf("build request: %w", err) } req.ContentLength = contentLength + if body != nil && progress != nil && progress.Sent != nil { + // Counted from zero on every attempt, and on the transport's own + // resend over a fresh connection too, which GetBody serves. + counted := func() io.ReadCloser { + progress.Sent(0) + return io.NopCloser(&countingReader{r: bytes.NewReader(body), counted: progress.Sent}) + } + req.Body = counted() + req.GetBody = func() (io.ReadCloser, error) { return counted(), nil } + } for name, values := range headers { for _, v := range values { req.Header.Add(name, v) @@ -439,3 +466,20 @@ func newRequestID() string { h := hex.EncodeToString(b[:]) return h[:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:] } + +// countingReader tells how much of a request body the transport has taken, +// which is about what has gone out: it reads the body as it writes it. +type countingReader struct { + r io.Reader + n int64 + counted func(n int64) +} + +func (c *countingReader) Read(p []byte) (int, error) { + n, err := c.r.Read(p) + if n > 0 { + c.n += int64(n) + c.counted(c.n) + } + return n, err +} diff --git a/internal/share/api/client_test.go b/internal/share/api/client_test.go index 19aa6df..fbcc4d2 100644 --- a/internal/share/api/client_test.go +++ b/internal/share/api/client_test.go @@ -1,6 +1,7 @@ package api_test import ( + "bytes" "context" "errors" "fmt" @@ -258,3 +259,49 @@ func TestTransferValuesMustBeCanonicalBase64URL(t *testing.T) { } } } + +// A part upload tells how much of its body has gone out, and when it is +// sent again after a failure, it counts from zero once more. +func TestUploadPartReportsWhatItSent(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + if requests.Add(1) == 1 { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"part_number":1}`) + })) + defer srv.Close() + + data := bytes.Repeat([]byte{7}, 256*1024) + var sent []int64 + retries := 0 + progress := &api.PartProgress{ + Sent: func(n int64) { sent = append(sent, n) }, + Retrying: func() { retries++ }, + } + if err := api.New(srv.URL).UploadPart(context.Background(), "s", "t", 1, 0, data, "hash", progress); err != nil { + t.Fatal(err) + } + if retries != 1 { + t.Errorf("%d retries reported, want 1", retries) + } + // Two attempts: each starts at zero and ends with the whole body. + var starts, ends int + for i, n := range sent { + if n == 0 { + starts++ + } + if n == int64(len(data)) { + ends++ + } + if i > 0 && n != 0 && n < sent[i-1] { + t.Errorf("went back from %d to %d within an attempt", sent[i-1], n) + } + } + if starts != 2 || ends != 2 { + t.Errorf("sent %v: %d starts and %d ends, want 2 of each", sent, starts, ends) + } +} diff --git a/internal/share/api/transfer.go b/internal/share/api/transfer.go index ec00f2e..f6cdb9c 100644 --- a/internal/share/api/transfer.go +++ b/internal/share/api/transfer.go @@ -151,7 +151,7 @@ func (c *Client) CloseTransfer(ctx context.Context, transferID, token, reason st // longPoll is one GET that the server holds until the leg exists or its // window passes; 204 is the window passing, and ok is false then. func (c *Client) longPoll(ctx context.Context, path, token string, out any) (bool, error) { - resp, err := c.do(ctx, http.MethodGet, path, jsonHeaders(token), nil, 0) + resp, err := c.do(ctx, http.MethodGet, path, jsonHeaders(token), nil, 0, nil) if err != nil { return false, err } diff --git a/internal/share/share.go b/internal/share/share.go index f7cd2b2..4c9c897 100644 --- a/internal/share/share.go +++ b/internal/share/share.go @@ -151,9 +151,25 @@ type Params struct { // Reusable keeps the link working until it expires; the default is once. Reusable bool Password string - // Progress, if set, is told about uploaded bytes. It is never called + // Progress, if set, is told how far the upload is. It is never called // from two goroutines at once. - Progress func(uploaded, total int64) + Progress func(UploadProgress) +} + +// UploadProgress is how far an upload is, in bytes of the encrypted bundle. +// They nest: Uploaded <= Sent <= Encrypted <= Total. +type UploadProgress struct { + // Total is the whole encrypted bundle, padding included. + Total int64 + // Encrypted is what has been read and encrypted; Total minus it is + // still to read. + Encrypted int64 + // Sent is what has gone out, parts still on their way included. + Sent int64 + // Uploaded is what the server has confirmed: parts it has stored. + Uploaded int64 + // Retrying is whether a part failed for a moment and waits to go again. + Retrying bool } // Result is a shared secret: its links and what the server confirmed. @@ -261,29 +277,16 @@ func Share(ctx context.Context, c *api.Client, p Params) (*Result, error) { // the server's part size, the last one shorter, a few at a time. Parts are // cut wherever chunks begin and end, so their sizes say nothing about the // files (FORMAT.md section 9). Only a handful of parts are ever in memory. -func upload(ctx context.Context, c *api.Client, session *api.UploadSession, plan *bundle.StreamPlan, sources []bundle.Source, blobKeys *keys.KeySet, progress func(uploaded, total int64)) (time.Time, error) { - stream, err := bundle.NewEncrypter(plan, sources, blobKeys) +func upload(ctx context.Context, c *api.Client, session *api.UploadSession, plan *bundle.StreamPlan, sources []bundle.Source, blobKeys *keys.KeySet, progress func(UploadProgress)) (time.Time, error) { + encrypter, err := bundle.NewEncrypter(plan, sources, blobKeys) if err != nil { return time.Time{}, err } g, gctx := errgroup.WithContext(ctx) g.SetLimit(UploadConcurrency) - var ( - mu sync.Mutex - uploaded int64 - ) - // Parts finish on their own goroutines; the lock is held through the - // callback, so a caller's progress code never runs twice at once. - report := func(n int64) { - if progress == nil { - return - } - mu.Lock() - defer mu.Unlock() - uploaded += n - progress(uploaded, plan.TotalSize) - } - report(0) + t := &uploadTracker{progress: progress, total: plan.TotalSize, sending: map[int]int64{}, retrying: map[int]bool{}} + t.update(func() {}) + stream := &encryptedCounter{r: encrypter, t: t} var offset int64 for number := 1; offset < plan.TotalSize; number++ { @@ -302,10 +305,23 @@ func upload(ctx context.Context, c *api.Client, session *api.UploadSession, plan } partOffset, sum := offset, bundle.SHA256Hex(data) g.Go(func() error { - if err := c.UploadPart(gctx, session.ID, session.Token, number, partOffset, data, sum); err != nil { + defer t.update(func() { delete(t.sending, number); delete(t.retrying, number) }) + hooks := &api.PartProgress{ + Sent: func(n int64) { + // An attempt starting over ends the wait to retry. + t.update(func() { t.sending[number] = n; delete(t.retrying, number) }) + }, + Retrying: func() { t.update(func() { t.sending[number] = 0; t.retrying[number] = true }) }, + } + if err := c.UploadPart(gctx, session.ID, session.Token, number, partOffset, data, sum, hooks); err != nil { return describeUploadError(err) } - report(int64(len(data))) + // Stored and no longer on its way, in one step, so it never + // counts twice. + t.update(func() { + delete(t.sending, number) + t.uploaded += int64(len(data)) + }) return nil }) offset += int64(len(data)) @@ -547,3 +563,53 @@ func describeUploadError(err error) error { } return err } + +// uploadTracker adds up how far an upload is. Parts move on their own +// goroutines; the lock is held through the callback, so a caller's progress +// code never runs twice at once. +type uploadTracker struct { + mu sync.Mutex + progress func(UploadProgress) + total int64 + encrypted int64 + uploaded int64 + // sending is what each part on its way has sent of its current attempt. + sending map[int]int64 + retrying map[int]bool +} + +// update changes the counts under the lock and reports them. +func (t *uploadTracker) update(change func()) { + t.mu.Lock() + defer t.mu.Unlock() + change() + if t.progress == nil { + return + } + sent := t.uploaded + for _, n := range t.sending { + sent += n + } + t.progress(UploadProgress{ + Total: t.total, + Encrypted: t.encrypted, + Sent: sent, + Uploaded: t.uploaded, + Retrying: len(t.retrying) > 0, + }) +} + +// encryptedCounter counts the bundle's bytes as they come out of the +// encrypter. +type encryptedCounter struct { + r io.Reader + t *uploadTracker +} + +func (e *encryptedCounter) Read(p []byte) (int, error) { + n, err := e.r.Read(p) + if n > 0 { + e.t.update(func() { e.t.encrypted += int64(n) }) + } + return n, err +} diff --git a/internal/share/share_test.go b/internal/share/share_test.go index 447beb6..3e9f867 100644 --- a/internal/share/share_test.go +++ b/internal/share/share_test.go @@ -107,9 +107,18 @@ func TestShareFilesWithPasswordInSeveralParts(t *testing.T) { } var progressCalls int var lastUploaded, lastTotal int64 + var sentAhead bool result, err := share.Share(ctx, c, share.Params{ Files: files, Password: "hunter2", Reusable: true, Expiration: "1h", - Progress: func(uploaded, total int64) { progressCalls++; lastUploaded, lastTotal = uploaded, total }, + Progress: func(p share.UploadProgress) { + progressCalls++ + lastUploaded, lastTotal = p.Uploaded, p.Total + if p.Uploaded > p.Sent || p.Sent > p.Encrypted || p.Encrypted > p.Total { + t.Errorf("progress does not nest: %+v", p) + } + // Sending shows before the server confirms a part. + sentAhead = sentAhead || p.Sent > p.Uploaded + }, }) if err != nil { t.Fatal(err) @@ -117,8 +126,8 @@ func TestShareFilesWithPasswordInSeveralParts(t *testing.T) { if result.Kind != share.KindFiles || !result.Reusable || !result.PasswordProtected || len(result.Names) != 2 { t.Errorf("result = %+v", result) } - if progressCalls < 2 || lastUploaded != lastTotal { - t.Errorf("progress: %d calls, ended at %d of %d", progressCalls, lastUploaded, lastTotal) + if progressCalls < 2 || lastUploaded != lastTotal || !sentAhead { + t.Errorf("progress: %d calls, ended at %d of %d, sent ahead of stored: %v", progressCalls, lastUploaded, lastTotal, sentAhead) } if fake := srv.Fake(); fake != nil { if sizes := fake.PartSizes(); len(sizes) != 3 || sizes[0] != 9*1024*1024 || sizes[1] != 9*1024*1024 || sizes[2]+18*1024*1024 != lastTotal { diff --git a/internal/share/sharetest/stream.go b/internal/share/sharetest/stream.go index 5eb9dfe..29fcdeb 100644 --- a/internal/share/sharetest/stream.go +++ b/internal/share/sharetest/stream.go @@ -56,7 +56,7 @@ func shareBlob(t testing.TB, origin, kind string, reusable bool, base *keys.KeyS if int64(len(blob)) > session.PartSize { t.Fatalf("a bundle of %d bytes needs more than one part", len(blob)) } - if err := c.UploadPart(ctx, session.ID, session.Token, 1, 0, blob, bundle.SHA256Hex(blob)); err != nil { + if err := c.UploadPart(ctx, session.ID, session.Token, 1, 0, blob, bundle.SHA256Hex(blob), nil); err != nil { t.Fatal(err) } if _, err := c.CompleteUpload(ctx, session.ID, session.Token); err != nil {