Skip to content

Stream uploads, harden watch/downloads/auth storage, and share HTTP transport - #20

Open
markmnl wants to merge 3 commits into
mainfrom
review/perf-and-reliability
Open

markmnl wants to merge 3 commits into
mainfrom
review/perf-and-reliability

Conversation

@markmnl

@markmnl markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Summary

High-impact performance, reliability, and maintainability improvements from a Go code review:

Performance & Resource Efficiency

  • Stream attachment uploads with O(1) memory (internal/api/client.go): Stream regular files directly from disk via io.MultiReader with exact Content-Length and replayable req.GetBody (preserving 401 token-refresh retries), instead of buffering entire files in a bytes.Buffer.
  • Shared HTTP transport, timeouts, and keep-alive reuse (internal/api/client.go, internal/auth/manager.go, cmd/client.go): Share a cloned http.Transport with ResponseHeaderTimeout: 30s between auth.Manager and api.Client, apply 30s request timeouts for JSON/token calls, propagate cmd.Context() via http.NewRequestWithContext, drain closed response bodies for TCP/TLS keep-alive reuse, and cap error body reads at 64 KiB.
  • Adaptive page sizing for negative message indexes (cmd/msgid.go): Avoid fetching 100 full messages when resolving -1 (and guard against math.MinInt64 negation overflow panic).

Reliability & Bug Fixes

  • Fix Watch() reconnect and backoff behavior (internal/api/watch.go): Only reset exponential backoff after a healthy connection (eventsRead > 0 or uptime >= 30s), retry transient dial failures (network errors and 5xx) when Reconnect is enabled while failing fast on 4xx/auth errors, stop mislabeling auth errors as "network error", read bounded handshake error bodies, and cap WS frame reads (SetReadLimit(4 MiB)).
  • Escape attachment filenames and message IDs in URL paths (internal/api/client.go): Use url.PathEscape in DownloadAttachment, DeleteAttachment, and messagePath.
  • Atomic file downloads (internal/api/client.go): Validate checkStatus(resp) before touching disk (preventing DownloadData from truncating existing files on HTTP errors), stream to a temp file in the destination directory, verify Close(), and rename atomically on success.
  • Atomic auth.Save & preserved Load() errors (internal/auth/store.go, internal/auth/tokencache.go, internal/auth/manager.go): Share atomic temp+chmod+sync+rename persistence across auth.Save and token cache, avoid creating config dirs on read-only Load(), and only report "missing credentials" on os.ErrNotExist.
  • Piped stdin login without trailing newline (cmd/login.go): Accept io.EOF when non-empty input was read.

Maintainability

  • Consolidate doJSON / listMessages / downloadToFile in internal/api/client.go and readMessageContent / buildDraftPayload in cmd/message.go.
  • Move direct dependency github.com/gorilla/websocket out of // indirect in go.mod.

Testing

  • Added unit tests covering streaming uploads + 401 replay, path escaping, atomic download failure preservation, watch backoff/reconnect/auth handling, atomic auth storage, resolveMessageID MinInt64/paging, readMessageContent, and piped login.
  • Verified with go vet ./..., go build ./..., and go test -race -count=1 ./....

@markmnl markmnl left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three behaviour regressions I'd fix before merging, plus one lesser one. All four are reproduced by running this branch; details and suggested fixes are inline.

Where What changed for the user
1 downloadToFile Downloaded files become 0600, symlinks are replaced, and /dev/stdout / /dev/null / pipes stop working as destinations
2 Watch fmsg watch hangs silently when the server is unreachable; with --timeout it exits 2 ("nothing arrived") instead of 1
3 readMessageContent A named pipe or <(cmd) as the content argument is sent as its path, not its contents
4 doJSON A 30s total deadline now covers uploading inline message data, with no way to raise it

For 2, with a cached token and the API stopped, fmsg --json watch --timeout 5s gives exit 1 after 0s on main and exit 2 after 5s on this branch.

The rest holds up

  • Streaming upload: exact Content-Length, and GetBody replays correctly through the 401 refresh; the tests cover both.
  • Checking the status before opening the output file fixes the truncate-on-error bug on its own (see 1 for why the rename on top needs narrowing).
  • The backoff fix is real: on main the backoff is reset on every successful handshake, so a server that accepts and then drops is redialled every second for ever.
  • auth.json written atomically, Load() no longer creating the config directory, and a corrupt file no longer reported as "missing credentials".
  • Path escaping for message ids and attachment names.

What I ran
go vet, go test -race: pass. The fmsg-docker integration suite with this branch together with fmsgid #10 and fmsg-webapi #71 (fmsgd on main): 16/16 pass. None of those tests exercise the four cases above, which is why they got through.

Docs
AGENTS.md asks for README updates when command behaviour changes. Whatever is decided for watch on an unreachable server, and for download destinations, should be reflected there.

🤖 Review by Claude Code

Comment thread internal/api/client.go Outdated
}

out, err := os.Create(outputPath)
out, err := os.CreateTemp(filepath.Dir(outputPath), ".fmsg-download-*")

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regression: temp-file + rename changes what get-data <id> <file> and get-attach do to the destination. Checking the status before touching disk is the real fix for the truncate-on-404 bug; the rename on top of it has side effects. I ran each of these against this branch:

case main this PR
new file, umask 022 rw-r--r-- rw------- (CreateTemp is always 0600)
overwrite an existing rw-rw-r-- file mode kept becomes rw-------
destination is a symlink writes through it symlink replaced by a regular file, target left stale
/dev/stdout, /dev/null works creating output file: open /dev/.fmsg-download-…: permission denied
named pipe / writable file in a read-only dir works fails (needs to create a sibling)

/dev/stdout matters because get-attach takes exactly three args and has no stdout mode, so that is the only way to pipe an attachment. Run as root (common in containers) it is worse than a failure: the rename would replace the /dev/stdout node itself.

Suggested shape: Lstat the destination; use temp + rename only when it doesn't exist or is a regular file, and otherwise write straight to it (the status check has already happened). For the temp path, Chmod to the existing file's mode, or 0666 &^ umask for a new one.

Related: the deferred os.Remove(tmpPath) never runs on Ctrl-C, because cmd.Context() isn't signal-aware (cmd/root.go calls rootCmd.Execute(), so every command gets context.Background()). An interrupted download now leaves a hidden .fmsg-download-* file behind each time, where it used to leave a visible partial file under the name asked for. signal.NotifyContext + rootCmd.ExecuteContext(ctx) in Execute() would fix that and make the new ctx plumbing in this PR actually cancel things.

Comment thread internal/api/watch.go Outdated
if ctx.Err() != nil {
return ctx.Err()
}
if !opts.Reconnect || !isTransientDialError(err) {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regression: fmsg watch now hangs silently when the server can't be reached. cmd/watch.go always passes Reconnect: true, so with this change a dial failure on the very first attempt (connection refused, DNS typo in FMSG_API_URL, TLS/x509 error, 5xx) is retried forever, and nothing is printed because OnConnect is the only callback.

Same call against a closed port, Reconnect: true, 4s deadline:

  • main: returns immediately, network error: dial tcp 127.0.0.1:1: connect: connection refused
  • this PR: returns after 4s with context deadline exceeded

That also breaks the documented exit codes. fmsg --json watch --timeout 30s now waits the full 30s and exits 2 ("nothing arrived") for a server that is down, where it used to exit 1 straight away. Scripts and agents polling with --once --timeout can no longer tell an outage from a quiet inbox. (It only bites when a token is already in hand, i.e. a cached token or a stored JWT; a failed key exchange still fails fast.)

Retrying transient failures on reconnect is the right call. Two options for the initial dial:

  1. Fail fast until the first successful handshake (track everConnected), retry only after that; or
  2. Add an OnRetry(err error, wait time.Duration) hook to WatchOptions and have cmd/watch.go print reconnecting in 4s: <err> to stderr, and treat an expired --timeout with zero successful connects as an error rather than errNoEvent.

I'd do 1, plus the stderr line from 2 for reconnects.

Comment thread cmd/message.go Outdated
}
return data, nil
}
if info, err := os.Stat(arg); err == nil && info.Mode().IsRegular() {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regression: non-regular files are now sent as their own path. IsRegular() is false for named pipes, /dev/stdin and bash process substitution (/dev/fd/63), so fmsg send addr <(some-command) now sends the literal text /dev/fd/63. main used os.ReadFile, which reads those fine. Checked with a FIFO on this branch: readMessageContent(fifo) returns the pipe's path, os.ReadFile(fifo) returns its contents.

err == nil && !info.IsDir() keeps the improvement here (an unreadable file is an error, not silently sent as text) without dropping pipes. Worth a test case alongside the directory one.

Comment thread internal/api/client.go
// (either raw []byte or a value to marshal), checks status, and decodes the
// JSON response into out when non-nil.
func (c *Client) doJSON(ctx context.Context, method, rawURL string, body any, out any) (int, error) {
ctx, cancel := c.withRequestTimeout(ctx)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This deadline covers the whole exchange, including writing the request body, and CreateMessage/UpdateMessage/EditMessage carry the message data inline. With the server default of 10 MiB for FMSG_API_MAX_DATA_SIZE that needs roughly 2.8 Mbit/s of sustained uplink to finish in 30s, more once JSON escaping is counted (encoding/json writes <, >, & as six bytes each). Slower links used to succeed, just slowly; now fmsg send addr big.txt fails with a context deadline and there's no flag or env var to raise it.

The new transport already sets ResponseHeaderTimeout, which handles the stalled-server case this is aimed at without limiting upload time. Suggest applying the 30s only to calls without a caller-supplied body (GET/DELETE and the small fixed payloads), or making it overridable (FMSG_TIMEOUT), or both.

Comment thread internal/api/watch_test.go Outdated
if gap2 < 30*time.Millisecond || gap3 < 65*time.Millisecond {
t.Fatalf("expected exponential backoff growth on unhealthy drops: gaps=%v, %v, %v", gap1, gap2, gap3)
}
if gap4 >= gap3 {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: flake risk. The lower-bound asserts above are safe (a timer never fires early), but this one compares two wall-clock gaps and fails if the ~20ms reconnect is delayed past ~80ms, which a loaded -race CI runner can do. Asserting against a fixed generous ceiling (say gap4 < 60ms given a 20ms initial and 80ms max) keeps the intent with more headroom, or drive it with an injected clock/sleep func.

Comment thread internal/auth/manager.go Outdated

// NewManager returns a Manager for the configured fmsg-webapi base URL.
func NewManager(apiURL string) *Manager {
t := http.DefaultTransport.(*http.Transport).Clone()

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this transport (and the duplicated defaultRequestTimeout / maxErrorBodyBytes constants) is built and then thrown away on the only production path, since newAuthenticatedClient immediately overwrites manager.HTTP with the shared one. A NewManager(apiURL, httpClient) parameter, or leaving HTTP nil here and defaulting lazily, would remove the duplication.

…ast on initial watch dial, support FIFOs, and uncap inline body timeouts
@markmnl

markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Addressed all review comments in caff9e0:

  1. downloadToFile & signal cancellation (internal/api/client.go, cmd/root.go): Lstat destination after checkStatus(resp); use atomic sibling temp-file + rename only for new files (created via O_EXCL mode 0666 so the kernel applies the process umask) and existing regular files (preserving mode via Chmod, falling back to direct open if the parent dir is read-only). Stream directly for symlinks, /dev/stdout, /dev/null, and FIFOs. Wired signal.NotifyContext into rootCmd.ExecuteContext so Ctrl-C triggers deferred cleanup.
  2. Watch initial dial & reconnect logging (internal/api/watch.go, cmd/watch.go): Track everConnected so initial dial failures fail fast even with Reconnect: true (preserving exit code 1 on unreachable server / --timeout), while post-connect transient failures retry with backoff and log via OnRetry to stderr.
  3. readMessageContent (cmd/message.go): Changed info.Mode().IsRegular() to !info.IsDir() so named pipes / process substitution (<(cmd)) are read instead of sent as literal paths (covered by TestReadMessageContentFromFIFO).
  4. Inline body upload timeout (internal/api/client.go): Added doJSONUnbounded for CreateMessage, UpdateMessage, and EditMessage so slow uplinks aren't bounded by the 30s request deadline while ResponseHeaderTimeout still guards against stalled servers.
  5. Nits: Replaced wall-clock backoff ratio assertion in watch_test.go with a deterministic watchSleep hook, and lazily initialize auth.Manager's default HTTP client so newAuthenticatedClient doesn't allocate a throwaway transport.

@markmnl markmnl left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked at caff9e0. The four regressions and the nits from the first review are fixed. The fix for temp-file cleanup introduced one new regression (inline, cmd/root.go), which I'd fix before merging.

Verified:

  • Downloads: new files honour the umask, existing files keep their mode, and symlinks, /dev/stdout, /dev/null and FIFOs are written through. Covered by TestDownloadToFilePermissionsAndSpecialTargets.
  • watch: an initial dial failure fails fast again; drops after a successful connect retry with backoff and say so on stderr.
  • Content argument: FIFOs and <(cmd) are read.
  • Inline body uploads: CreateMessage, UpdateMessage and EditMessage no longer carry the 30s total deadline. ResponseHeaderTimeout starts only after the body is written, so a slow uplink is fine and a silent server is still bounded.
  • go vet and go test -race ./... pass, and the fmsg-docker suite passes 16/16 with this build of the CLI.

Comment thread cmd/root.go
func Execute() {
injectDashDash()
if err := rootCmd.Execute(); err != nil {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New regression: a command blocked on stdin can no longer be interrupted. NotifyContext takes over SIGINT/SIGTERM for the whole process, but the stdin reads don't watch the context: readCredential (fmsg login), and readMessageContent("-") behind send, draft, update and edit. The signal cancels ctx and nothing notices, and because stop() only runs after ExecuteContext returns, a second signal is swallowed too.

Reproduced with fmsg login < fifo (writer held open) and SIGTERM, which goes through the same registration as SIGINT:

build result
main exits 143 immediately
this branch still running after two signals; needed SIGKILL

On a terminal that means Ctrl-C at the fmsg API key or user JWT: prompt does nothing, and fmsg send @a@example.com - can only be abandoned with Ctrl-D.

Smallest fix: restore default handling once the first signal has cancelled the context, so the second one terminates.

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
context.AfterFunc(ctx, stop)

That still leaves the first Ctrl-C ignored during a stdin read. To keep single-Ctrl-C behaviour, make those two reads return on ctx.Done() (read in a goroutine and select), or only install the handler for the commands that have something to clean up (get-data, get-attach). A test that cancels the context while readMessageContent("-") is blocked would pin it.

Comment thread internal/api/client.go
}
if len(body) > 0 {
req.Header.Set("Content-Type", "application/json")
existingRegular := err == nil && info.Mode().IsRegular()

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two leftovers of replace-by-rename for an existing regular file. Both are minor and neither is a blocker:

  • A read-only destination is now overwritten. With keep.txt at mode 0444, main fails with permission denied; this branch replaces the content (the mode stays 0444), because rename only needs write permission on the directory. Checked with a throwaway test. If refusing is the intended behaviour, check info.Mode().Perm()&0200 (or try opening the file for writing) before taking the temp-file path.
  • Hard links are split. The other name keeps the old content, where main updated both.

Falling back to a direct write when info.Sys().(*syscall.Stat_t).Nlink > 1 would cover the second; I'd leave it unless someone hits it.

Routing SIGINT/SIGTERM into the command context (so an interrupted
download removes its temp file) left commands that block on a read deaf
to the signal: the login prompt and content read from stdin or a named
pipe never looked at the context, and a second signal was swallowed too.

- Abandon those reads when the context is cancelled.
- Restore default signal handling after the first signal, so a second
  one always terminates.
- Put the terminal's echo back when the credential prompt is abandoned.
- Exit 130 without printing an error or usage after an interrupt, as a
  process killed by the signal would.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@markmnl

markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Pushed 0edbaf6 for the Ctrl-C regression from the last review.

  • Blocking reads follow the context. The login prompt and content read from -, a file or a named pipe are abandoned when the command context is cancelled.
  • A second signal always terminates. Default signal handling is restored as soon as the first signal has cancelled the context.
  • The terminal is put back. Abandoning the credential prompt restores echo. main leaves echo off after Ctrl-C at that prompt, so this is slightly better than before the PR.
  • Interrupts exit quietly with 130, as a process killed by SIGINT would, instead of printing context canceled and the usage text. Ordinary errors are reported as before.

Checked with the built binaries (login prompt on a pty, and stdin from a pipe):

build Ctrl-C at the tty prompt SIGINT / SIGTERM with piped stdin
main killed by SIGINT, echo left off killed by the signal
caff9e0 keeps running ignores two signals
0edbaf6 exit 130, echo restored exit 130, nothing printed

Tests added: TestReadMessageContentReturnsWhenContextCancelled (a named pipe with no writer) and two for the quiet-exit wrapper. go vet and go test -race ./... pass.

Not changed: the read-only destination and hard-link notes on downloadToFile.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant