Repository navigation
Conversation
markmnl
left a comment
There was a problem hiding this comment.
One regression to fix before merging (the 2x request-body cap), three robustness concerns around shutdown and the post-commit budget, and some smaller notes. Most of this large diff is correct and an improvement.
Fix before merge
- Body cap rejects valid messages (inline on
messages.go). Reproduced against the test stack built from this branch with the fmsg-cli #20 build: an 8 MiB plain-text draft is accepted, an 8 MiB draft of<td>1</td>rows gets413 message data exceeds maximum size, with the limit at its 10 MiB default.
Worth addressing
Hub.Close()waits on pushes that can't be cancelled, so shutdown can outlast any supervisor's grace period (inline onhub.go).- The hub stops listening as soon as the signal arrives, before in-flight requests drain, so their notifications are lost (inline on
main.go). - The 15s post-commit budget is shared across all local recipients, and nothing retries the ones it doesn't reach (inline on
messages.go).
Smaller: classification cache pinning a transient failure, the sub-account rollback race, README for the new 413 on /thread, upload time now bounded by ReadTimeout, cache eviction cost. All inline.
What I verified
go vetandgo test -racepass; CI ran the PostgreSQL integration tests. The fmsg-docker suite with this branch together with fmsgid #10 and fmsg-cli #20 (fmsgd onmain): 16/16 pass.- Removing
validateParentis safe.resolveParentruns first in bothCreateandUpdateand already rejects a missing parent (400) and a draft or terminal one (409). beginOrReuseTxis safe. Every exit after it inUpload,Edit,ReactandAddRecipientsis either the commit or a response of 400 or above, which makesAtomicroll the outer transaction back, so the savepoint added nothing.- The
CountandresolveParentrewrites use indexes that exist in fmsgd'sdd.sql(msg_lower_idx,msg_to_lower_idx,msg_add_to_lower_idx,msg_add_to_batch_sha256_idx, and the unique constraint onmsg.sha256). - An oversized multipart upload does surface as
http.MaxBytesErrorthroughFormFile, so the new413path for attachments works. - The batched shared-file check in
removeUnheldselects the same files as the per-message version. *in the WebSocket origin check brings it in line with what the README already documents forFMSG_CORS_ORIGINS.- The new push query feeds
buildPushPayloadeverything it reads (FromandShortText).
Merge order
#68 and #69 touch the same handlers this PR restructures (Create/Update parent handling, React). Expect conflicts; landing the small ones first will be less work than rebasing them onto this.
🤖 Review by Claude Code
| identity := middleware.GetIdentity(c) | ||
|
|
||
| if h.MaxDataSize > 0 { | ||
| limitRequestBody(c, h.MaxDataSize*2+1<<20) |
There was a problem hiding this comment.
The 2x allowance rejects valid bodies (same expression in Update below and in Edit). data travels as a JSON string, and JSON escaping can expand a byte up to 6x, so 2*MaxDataSize + 1 MiB is not an upper bound on a legal request. Two cases that are easy to hit:
- Go clients, including fmsg-cli.
encoding/jsonescapes<,>and&as\u003cetc. by default, six bytes each. Markup-dense text such as<td>1</td>rows comes out about 3x. With the default 10 MiB limit the cap here is 21 MiB, so an 8 MiB HTML/XML body (24 MiB on the wire) now gets413 message data exceeds maximum sizewhile being under the limit. Onmainit is accepted. - ASCII-escaping encoders (Python's
json.dumpsdefault). Every 2-byte UTF-8 character (Cyrillic, Greek, Arabic, Hebrew) becomes a 6-byte\uXXXX, also 3x.
Measured expansion of data after encoding: Go json.Marshal 6.0x for <, 2.0x for newlines; ASCII-escaped Cyrillic 3.0x, CJK 2.0x.
The decoded-size check (len(msg.Data) > h.MaxDataSize) is still what enforces the limit, so this reader only has to stop unbounded bodies. h.MaxDataSize*6 + 1<<20 is the true worst case and still a hard bound. Worth a shared helper so the three call sites can't drift.
|
|
||
| // Close shuts down the bounded Web Push worker pool and waits for queued and | ||
| // in-flight pushes to finish. | ||
| func (h *Hub) Close() { |
There was a problem hiding this comment.
Close() can hold shutdown open for minutes. It waits for every queued job, and the jobs can't be cancelled: PushHandler.NotifyNewMsg discards the context it is given (_ context.Context) and builds its own from context.Background() with the 30s pushTimeout. So on SIGTERM with a slow or unreachable push service, up to 256 queued + 8 in-flight jobs each run to their timeout: worst case about 264 / 8 x 30s, roughly 16 minutes, after the HTTP server has already stopped. In practice the supervisor SIGKILLs first (Docker's default grace is 10s, systemd's 90s), which defeats the clean shutdown this PR adds, including the deferred database.Close().
Suggest bounding it: give Close a deadline (CloseContext(ctx) that stops waiting when the context ends), and derive the per-job context from the one passed to NotifyNewMsg via context.WithoutCancel plus a cancel the hub fires on close, so queued jobs are dropped rather than run.
Separately, on the full-queue drop a few lines down: that is a reasonable trade against unbounded goroutines, and since a job for an address with no subscriptions is one indexed query the queue should only back up when push endpoints stall. It would help to have the sizes configurable and the drop counted, since a log line is easy to miss.
| } | ||
| case <-ctx.Done(): | ||
| log.Println("fmsg-webapi shutting down...") | ||
| stop() |
There was a problem hiding this comment.
Ordering: the hub runs on this same signal context, so it stops LISTENing the moment the signal arrives, while srv.Shutdown then lets in-flight requests run for up to 15s. Any send / react / edit / add-to that commits during that drain fires NOTIFY new_msg with nobody listening, so its WebSocket events and Web Pushes are silently lost. (stop() here only restores default signal handling; the context is already cancelled.)
Giving the hub its own context.WithCancel(context.Background()) and cancelling it after srv.Shutdown returns closes the gap: stop accepting, drain requests, then stop the listener, then drain pushes.
Also note 15s is longer than Docker's default 10s stop grace, so under compose a slow drain is cut off by SIGKILL unless stop_grace_period is raised.
| // fmsgd's outbound sender skips the local domain entirely, so local | ||
| // recipients need their delivery status resolved here instead. | ||
| afterCommit(c, func() { | ||
| postCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) |
There was a problem hiding this comment.
Detaching from the request context is the right fix; a client hanging up after commit used to leave local recipients undelivered. One concern with the shape: the 15s is a single budget for the whole fan-out, not per recipient. resolveLocalDelivery does a fresh fmsgid GET (never the cached one), an UPDATE, and a usage POST for each local recipient, one after another, for to and then every add-to batch. With a couple of hundred local recipients and fmsgid a little slow, the budget runs out part-way, and every remaining recipient then fails instantly with context deadline exceeded, is logged, and is skipped.
Nothing retries those: fmsgd's sender skips the local domain, so they stay time_delivered IS NULL and never get their new_msg. Before this PR the only bound was fmsgid's 5s per call, so a slow fan-out finished late instead of partially.
Suggest keeping WithoutCancel but dropping the overall deadline in favour of the per-call timeouts (fmsgIDClient already has 5s; add one for the UPDATE), or scaling the budget by recipient count. Same pattern in Edit, React, AddRecipients and purge.
| cls = msgClassification{kind: msgClassEdit, subject: subject} | ||
| } | ||
| } | ||
| h.classCache.put(msgID, cls) |
There was a problem hiding this comment.
This caches the fallback as well as real answers. reactionSubject and editSubject log and return (0, false) on a DB error (and editSubject on a failed read of the edit document), which is indistinguishable here from "not a reaction/edit". One transient error on the first recipient of a reaction or edit pins it as msgClassNormal, so every remaining recipient gets a new_msg event and a Web Push for something that should have been a quiet reaction/edit event. Without the cache only that one recipient was affected.
Cheap fix: have the two classifiers return an error (or a third "unknown" result) and skip put when classification didn't complete.
| // untouched. | ||
| granted := false | ||
| if reinstated { | ||
| if created || reinstated { |
There was a problem hiding this comment.
Extending the rollback to created fixes a real leak (an address left accepting mail with no grant when store.Create fails). Two things to be aware of:
- It widens an existing race. Two concurrent creates for the same name: A registers (
created=true), B registers (created=false, already active), B's grant commits first, A'sstore.Createthen fails on the duplicate and A's deferred disable switches off the address B was just granted. It existed forreinstatedalready; it now covers first-time creates too. A double-submitted form is enough. Checking whether a grant forsubAddrexists before disabling (or only disabling when the failure isn't a duplicate-grant conflict) would close it. - The HTTP path drops
checkAcceptingFmsgIDas redundant, butapikey_cli.gokeepsrequireAcceptingCLIAddressafter the same registration call. Either both need it or neither does.
| if rerr != nil { | ||
| log.Printf("thread text: read %d: %v", e.ID, rerr) | ||
| continue | ||
| if err := populateThreadTextEntries(entries, paths, edits, h.DataDir, defaultThreadTextBytes); err != nil { |
There was a problem hiding this comment.
New response for this route: GET /fmsg/:id/thread now answers 413 with thread_too_large past 32 MiB, where it used to return the text however large. Sensible, but the README's error table for that route still lists only 404 and 403 (the /thread/messages table already has the 413 row), and AGENTS.md asks for the README to track response changes.
| srv := &http.Server{ | ||
| Handler: router, | ||
| ReadHeaderTimeout: 10 * time.Second, | ||
| ReadTimeout: 60 * time.Second, |
There was a problem hiding this comment.
For the record, since it now bounds uploads: ReadTimeout covers the whole request body, so an attachment at the default 10 MiB FMSG_API_MAX_ATTACH_SIZE needs about 1.4 Mbit/s sustained to make it in 60s. That is not a new ceiling in practice, because the 65s WriteTimeout deadline is set when the headers are read, so a slower upload was already stored and then failed to answer. Failing the read is the cleaner of the two. If larger limits are configured these two timeouts need to scale with them; a line in the README next to FMSG_API_MAX_ATTACH_SIZE would save someone the debugging.
| } | ||
| if len(c.entries) >= maxEntries { | ||
| // Evict the soonest-to-expire entries so the cache stays strictly bounded. | ||
| target := maxEntries - max(1, maxEntries/8) |
There was a problem hiding this comment.
Nit: when the cache is full of live entries this evicts 512 keys by doing 512 full scans of a 4096-entry map (about 2M iterations) while holding the write lock, which blocks every get on the auth path for the duration. It only happens once per 512 inserts above 4096 distinct addresses in 30s, so it is not urgent, but one pass that collects expiries and deletes everything at or below the 512th-smallest does the same job in O(n).
Summary
High-impact performance, reliability, and maintainability improvements from a Go code review (preserving all HTTP API contracts, WebSocket event payloads,
new_msgLISTEN/NOTIFY behavior, anddd.sql):Reliability, Bounds & Lifecycle
ReadTimeout, and graceful shutdown (cmd/fmsg-webapi/main.go,internal/db/db.go,internal/handlers/attachments.go,messages.go,edits.go): AddReadTimeout: 60sonhttp.Server, wrapUpload/Create/Update/Editbodies withhttp.MaxBytesReader, trapSIGINT/SIGTERMviasignal.NotifyContextto shut down HTTP/hub/push workers cleanly before closing the DB pool, and closepgxpoolif startupPingfails.internal/handlers/messages.go,edits.go,reactions.go,trash.go): Usecontext.WithTimeout(context.WithoutCancel(ctx), 15*time.Second)inafterCommitcallbacks so client disconnect after commit cannot abortresolveLocalDeliveryor quota release.attachments.go: Use case-insensitivesameAddrownership checks, exclude overwritten attachment's size fromcurrentTotaland clean up old filesafterCommit, use atomicO_CREATE|O_EXCLfile creation, and reusesafeDataPath.thread.go: EnforcedefaultThreadTextBytesinThreadText, handle emptydataPathinpopulateThreadBodieswithout 500s, use a typederrThreadTooLargesentinel, and load effective edits insideThreadMessages'sRepeatableReadtransaction before reading unedited bodies.ws.go: Adddefer c.close()inwritePumpso dead sockets disconnect immediately, and support"*"wildcard inCheckOrigin.apiauth/store.go&subaccounts.go: Guardmax_sub_accountscreation withpg_advisory_xact_lock, disable newly registeredfmsgidaddresses on failedstore.Create, and drop redundant post-registration GET.Performance
internal/handlers/hub.go,push.go): Replace unboundedgo h.notifyPush(...)with a fixed worker pool drained on shutdown, share a pooled*http.Clientwith 10s timeout + body draining inPushHandler, checkrows.Err(), and replace the 9-querymessageItemForcall inNotifyNewMsgwith a single targeted SQL query.internal/handlers/hub.go,indicators.go): Early-return onnew_msgwhen neither push nor WS listeners exist, cache immutablemsgIDclassifications across K-recipient fan-out, and skip the recursivethreadRootCTE for indicators when no participant has a connected WS.edits.go: Useos.Statinstead of reading up to 10 MiB bodies just forlen(subject)ineditSubject, and batchpopulateListEditswithANY($1).trash.go: BatchnotifyTrashand shared-filepath checks, runSET LOCAL fmsg.purge = 'on'once per purge, checkrows.Err(), and fail closed on DB errors inpurgedFor.count.go&references.go: RewritevisCTE and SHA-256resolveParentas indexedUNION/UNION ALLlookups.messages.go,transaction.go,indicators.go: CacheresolveIDingin.Context, avoid nested savepointBegininsideAtomic, batch recipient inserts viaunnest, remove duplicatevalidateParent, closerows& checkrows.Err()before list enrichment, consolidateenrichMessageListacrossList/Sent, consolidateIndicatequeries, and gateindicatorThrottleeviction sweeps.middleware/jwt.go&fmsgid_usage.go: PoolfmsgIDClient(MaxIdleConnsPerHost: 32), drain response bodies, normalize and boundfmsgIDCache, propagatectx, and fast-path first-party API tokens past JWKS verification.Testing
ws_test.go,thread_test.go,jwt_test.go,fmsgid_test.go,indicators_test.go,hub_test.go, andattachments_test.go.go vet ./...,go build ./..., andgo test -race -count=1 ./....