Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -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
Expand Down
66 changes: 64 additions & 2 deletions internal/cli/extras.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"
"unicode/utf8"

"github.com/secretli/cli/internal/share"
qrcode "github.com/skip2/go-qrcode"
"golang.org/x/term"
)
Expand All @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down
67 changes: 67 additions & 0 deletions internal/cli/progress_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package cli

import (
"strings"
"testing"
"time"

"github.com/secretli/cli/internal/share"
)

func TestFormatSpeed(t *testing.T) {
Expand Down Expand Up @@ -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))
}
}
4 changes: 2 additions & 2 deletions internal/cli/share.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
58 changes: 51 additions & 7 deletions internal/share/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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"},
Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Expand All @@ -321,14 +335,17 @@ 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
}
}
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)
Expand All @@ -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)
Expand Down Expand Up @@ -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
}
47 changes: 47 additions & 0 deletions internal/share/api/client_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api_test

import (
"bytes"
"context"
"errors"
"fmt"
Expand Down Expand Up @@ -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)
}
}
2 changes: 1 addition & 1 deletion internal/share/api/transfer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
Loading
Loading