Repository navigation
Conversation
markmnl
left a comment
There was a problem hiding this comment.
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, andGetBodyreplays 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
mainthe backoff is reset on every successful handshake, so a server that accepts and then drops is redialled every second for ever. auth.jsonwritten 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
| } | ||
|
|
||
| out, err := os.Create(outputPath) | ||
| out, err := os.CreateTemp(filepath.Dir(outputPath), ".fmsg-download-*") |
There was a problem hiding this comment.
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.
| if ctx.Err() != nil { | ||
| return ctx.Err() | ||
| } | ||
| if !opts.Reconnect || !isTransientDialError(err) { |
There was a problem hiding this comment.
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:
- Fail fast until the first successful handshake (track
everConnected), retry only after that; or - Add an
OnRetry(err error, wait time.Duration)hook toWatchOptionsand havecmd/watch.goprintreconnecting in 4s: <err>to stderr, and treat an expired--timeoutwith zero successful connects as an error rather thanerrNoEvent.
I'd do 1, plus the stderr line from 2 for reconnects.
| } | ||
| return data, nil | ||
| } | ||
| if info, err := os.Stat(arg); err == nil && info.Mode().IsRegular() { |
There was a problem hiding this comment.
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.
| // (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) |
There was a problem hiding this comment.
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.
| 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 { |
There was a problem hiding this comment.
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.
|
|
||
| // NewManager returns a Manager for the configured fmsg-webapi base URL. | ||
| func NewManager(apiURL string) *Manager { | ||
| t := http.DefaultTransport.(*http.Transport).Clone() |
There was a problem hiding this comment.
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
|
Addressed all review comments in
|
markmnl
left a comment
There was a problem hiding this comment.
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/nulland FIFOs are written through. Covered byTestDownloadToFilePermissionsAndSpecialTargets. 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,UpdateMessageandEditMessageno longer carry the 30s total deadline.ResponseHeaderTimeoutstarts only after the body is written, so a slow uplink is fine and a silent server is still bounded. go vetandgo test -race ./...pass, and the fmsg-docker suite passes 16/16 with this build of the CLI.
| func Execute() { | ||
| injectDashDash() | ||
| if err := rootCmd.Execute(); err != nil { | ||
| ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
There was a problem hiding this comment.
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.
| } | ||
| if len(body) > 0 { | ||
| req.Header.Set("Content-Type", "application/json") | ||
| existingRegular := err == nil && info.Mode().IsRegular() |
There was a problem hiding this comment.
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.txtat mode0444,mainfails with permission denied; this branch replaces the content (the mode stays0444), because rename only needs write permission on the directory. Checked with a throwaway test. If refusing is the intended behaviour, checkinfo.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
mainupdated 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>
|
Pushed
Checked with the built binaries (login prompt on a pty, and stdin from a pipe):
Tests added: Not changed: the read-only destination and hard-link notes on |
Summary
High-impact performance, reliability, and maintainability improvements from a Go code review:
Performance & Resource Efficiency
internal/api/client.go): Stream regular files directly from disk viaio.MultiReaderwith exactContent-Lengthand replayablereq.GetBody(preserving 401 token-refresh retries), instead of buffering entire files in abytes.Buffer.internal/api/client.go,internal/auth/manager.go,cmd/client.go): Share a clonedhttp.TransportwithResponseHeaderTimeout: 30sbetweenauth.Managerandapi.Client, apply 30s request timeouts for JSON/token calls, propagatecmd.Context()viahttp.NewRequestWithContext, drain closed response bodies for TCP/TLS keep-alive reuse, and cap error body reads at 64 KiB.cmd/msgid.go): Avoid fetching 100 full messages when resolving-1(and guard againstmath.MinInt64negation overflow panic).Reliability & Bug Fixes
Watch()reconnect and backoff behavior (internal/api/watch.go): Only reset exponential backoff after a healthy connection (eventsRead > 0or uptime>= 30s), retry transient dial failures (network errors and 5xx) whenReconnectis 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)).internal/api/client.go): Useurl.PathEscapeinDownloadAttachment,DeleteAttachment, andmessagePath.internal/api/client.go): ValidatecheckStatus(resp)before touching disk (preventingDownloadDatafrom truncating existing files on HTTP errors), stream to a temp file in the destination directory, verifyClose(), and rename atomically on success.auth.Save& preservedLoad()errors (internal/auth/store.go,internal/auth/tokencache.go,internal/auth/manager.go): Share atomic temp+chmod+sync+rename persistence acrossauth.Saveand token cache, avoid creating config dirs on read-onlyLoad(), and only report"missing credentials"onos.ErrNotExist.cmd/login.go): Acceptio.EOFwhen non-empty input was read.Maintainability
doJSON/listMessages/downloadToFileininternal/api/client.goandreadMessageContent/buildDraftPayloadincmd/message.go.github.com/gorilla/websocketout of// indirectingo.mod.Testing
resolveMessageIDMinInt64/paging,readMessageContent, and piped login.go vet ./...,go build ./..., andgo test -race -count=1 ./....