From 2f323bf243d2972c6be6875517bc7c6289fde616 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Thu, 29 Oct 2026 15:19:12 +0800 Subject: [PATCH] Trash: a delivery fmsgd has given up on no longer keeps a message fmsgd stops retrying a delivery once it is older than FMSG_RETRY_MAX_AGE (one day by default) but never marks it: a host that never answered leaves time_delivered null and response_code -1 for good. Delete for good treated every such row as pending with no age limit, and any add-to participant notification with time_notified null whatever its code, so a message sent to a dead or mistyped domain could never be removed from the host. The mirror was wrong too: fmsgd also retries codes 3, 5 and 101, which were treated as finished, so a message could be removed while fmsgd was still delivering it. Pending now means what it means to fmsgd: undelivered, last code null or one fmsgd retries (-1, 3, 5, 101), and younger than the retry window measured from the message's time_sent or the add-to batch's time_added. The rule is fmsg_api_delivery_pending in dd.sql, used by removeIfUnheld; the retryable codes are one list in trash.go that must match fmsgd's. FMSG_RETRY_MAX_AGE is read by the Web API as well (same default) and documented as a setting to keep equal on both. Co-Authored-By: Claude Fable 5.1 --- README.md | 9 ++- cmd/fmsg-webapi/main.go | 5 ++ dd.sql | 27 +++++++ internal/handlers/messages.go | 4 + internal/handlers/trash.go | 35 +++++++-- internal/handlers/trash_integration_test.go | 85 +++++++++++++++++++++ 6 files changed, 156 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 09f65bf..65c0ae8 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ HTTP API providing user/client message handling for an fmsg host. Exposes CRUD o | `FMSG_API_MAX_ATTACH_SIZE`| `10` | Maximum attachment file size in megabytes | | `FMSG_API_MAX_MSG_SIZE`| `20` | Maximum total message size (data + attachments) in megabytes | | `FMSG_API_SHORT_TEXT_SIZE`| `768` | Maximum bytes of message body returned inline as `short_text` for `text/*` UTF-8 messages | +| `FMSG_RETRY_MAX_AGE` | `86400` | Seconds fmsgd keeps retrying a delivery after the message was sent (its `FMSG_RETRY_MAX_AGE`; set both the same). A delivery older than this has been given up on and no longer keeps a deleted-for-good message on the host. | | `FMSG_CORS_ORIGINS` | *(optional)* | Comma-separated list of browser origins allowed via CORS, e.g. `https://example.com,https://www.example.com`. Use `*` to allow any origin. When unset, no CORS headers are emitted (server-to-server callers are unaffected). | | `FMSG_VAPID_PUBLIC_KEY` | *(optional)* | VAPID public key (URL-safe base64) for Web Push. Browsers also pass this as `applicationServerKey`. Generate the pair once with `npx web-push generate-vapid-keys`. | | `FMSG_VAPID_PRIVATE_KEY` | *(optional)* | VAPID private key (URL-safe base64) for Web Push. | @@ -820,8 +821,12 @@ Each identity has its own trash; nothing in it changes what anyone else sees. participant holds a message any more (none sent or accepted it without deleting it for good) and none of its deliveries is pending, it is removed from the host: its rows and files are deleted, and replies to it from - anywhere are then rejected by fmsgd as parent not found. This needs the - fmsgd schema that lets a transaction set `fmsg.purge`. + anywhere are then rejected by fmsgd as parent not found. A delivery (or + add-to participant notification) is pending while fmsgd may still make it: + undelivered, its last attempt (if any) got a code fmsgd retries, and it is + younger than `FMSG_RETRY_MAX_AGE`; one fmsgd has given up on doesn't keep + the message. This needs the fmsgd schema that lets a transaction set + `fmsg.purge`. ### Message hashes and references diff --git a/cmd/fmsg-webapi/main.go b/cmd/fmsg-webapi/main.go index 784771a..ab6b0a6 100644 --- a/cmd/fmsg-webapi/main.go +++ b/cmd/fmsg-webapi/main.go @@ -64,6 +64,10 @@ func main() { maxAttachSize := int64(envOrDefaultInt("FMSG_API_MAX_ATTACH_SIZE", 10)) * 1024 * 1024 maxMsgSize := int64(envOrDefaultInt("FMSG_API_MAX_MSG_SIZE", 20)) * 1024 * 1024 shortTextSize := envOrDefaultInt("FMSG_API_SHORT_TEXT_SIZE", 768) + retryMaxAge := envOrDefaultInt("FMSG_RETRY_MAX_AGE", handlers.DefaultRetryMaxAge) + if retryMaxAge <= 0 { + log.Fatal("environment variable FMSG_RETRY_MAX_AGE must be a positive number of seconds") + } // CORS: comma-separated list of allowed browser origins, e.g. // "https://app.example.com,https://www.example.com". Empty disables CORS. @@ -144,6 +148,7 @@ func main() { // Instantiate handlers. msgHandler := handlers.NewMessageHandler(database, dataDir, maxDataSize, maxMsgSize, shortTextSize, apiStore, idURL, localDomain) + msgHandler.RetryMaxAge = float64(retryMaxAge) attHandler := handlers.NewAttachmentHandler(database, dataDir, maxAttachSize, maxMsgSize) // Web Push handler: stores subscriptions and delivers VAPID pushes for diff --git a/dd.sql b/dd.sql index 73fd2b5..8a35de2 100644 --- a/dd.sql +++ b/dd.sql @@ -106,3 +106,30 @@ LANGUAGE sql STABLE AS $$ END FROM up JOIN fmsg_api_trash t ON t.addr = p_addr AND t.msg_id = up.id $$; + +-- fmsg_api_delivery_pending is whether fmsgd may still deliver some part of +-- message p_msg: a recipient (msg_to, msg_add_to) or an add-to participant +-- notification (msg_add_to_notify) that is not delivered, whose last attempt +-- (if any) got a code in p_retryable, and that at p_now is younger than +-- p_max_age seconds, measured from the message's time_sent or its add-to +-- batch's time_added as fmsgd's sender measures it. fmsgd gives up on older +-- rows without marking them, so they no longer keep a message on the host. +CREATE OR REPLACE FUNCTION fmsg_api_delivery_pending(p_msg bigint, p_now double precision, p_max_age double precision, p_retryable smallint[]) RETURNS boolean +LANGUAGE sql STABLE AS $$ + SELECT EXISTS ( + SELECT 1 FROM msg_to t JOIN msg m ON m.id = t.msg_id + WHERE t.msg_id = p_msg AND m.time_sent IS NOT NULL + AND t.time_delivered IS NULL + AND (t.response_code IS NULL OR t.response_code = ANY (p_retryable)) + AND p_now - m.time_sent < p_max_age) + OR EXISTS ( + SELECT 1 FROM msg_add_to a JOIN msg_add_to_batch b ON b.id = a.batch_id + WHERE a.msg_id = p_msg AND a.time_delivered IS NULL + AND (a.response_code IS NULL OR a.response_code = ANY (p_retryable)) + AND p_now - b.time_added < p_max_age) + OR EXISTS ( + SELECT 1 FROM msg_add_to_notify n JOIN msg_add_to_batch b ON b.id = n.batch_id + WHERE b.msg_id = p_msg AND n.time_notified IS NULL + AND (n.response_code IS NULL OR n.response_code = ANY (p_retryable)) + AND p_now - b.time_added < p_max_age) +$$; diff --git a/internal/handlers/messages.go b/internal/handlers/messages.go index 397fd0e..6ac264d 100644 --- a/internal/handlers/messages.go +++ b/internal/handlers/messages.go @@ -45,6 +45,10 @@ type MessageHandler struct { // has a different domain than this instance, but that has no bearing on // which recipients are local to it. See resolveLocalDelivery. LocalDomain string + // RetryMaxAge is fmsgd's FMSG_RETRY_MAX_AGE in seconds (0 means + // DefaultRetryMaxAge): deliveries older than this are ones fmsgd has given + // up on, so they no longer keep a deleted-for-good message on the host. + RetryMaxAge float64 } // NewMessageHandler creates a MessageHandler. diff --git a/internal/handlers/trash.go b/internal/handlers/trash.go index 85cf200..ac0ff76 100644 --- a/internal/handlers/trash.go +++ b/internal/handlers/trash.go @@ -455,12 +455,36 @@ func (h *MessageHandler) fileSize(path string, fallback int64) int64 { return fallback } +// retryableResponseCodes are the per-recipient response codes after which +// fmsgd retries a delivery: -1, its local code for an attempt that got no +// response, and the fmsg reject codes undisclosed (3), insufficient resources +// (5) and user full (101). Any other code is final. Must match fmsgd's +// retryableResponseCodes (cmd/fmsgd/sender.go). +var retryableResponseCodes = []int16{-1, 3, 5, 101} + +// DefaultRetryMaxAge is fmsgd's default FMSG_RETRY_MAX_AGE in seconds: how +// long after a message is sent (or recipients are added) fmsgd keeps retrying +// its deliveries. +const DefaultRetryMaxAge = 86400 + +// retryMaxAge is the configured retry window in seconds, or the default. +func (h *MessageHandler) retryMaxAge() float64 { + if h.RetryMaxAge > 0 { + return h.RetryMaxAge + } + return DefaultRetryMaxAge +} + // removeIfUnheld removes msgID from the host when no local participant holds // it any more (none sent or accepted it without deleting it for good) and no -// delivery or add-to notification of it is still pending. It returns whether -// it was removed and the stored files to delete once the transaction commits. +// delivery or add-to notification of it is still pending: undelivered, with a +// code fmsgd retries, and within the retry window (fmsg_api_delivery_pending +// in dd.sql). A delivery fmsgd has given up on doesn't keep the message. It +// returns whether it was removed and the stored files to delete once the +// transaction commits. func (h *MessageHandler) removeIfUnheld(ctx context.Context, msgID int64) (bool, []string, error) { var held, pending bool + now := float64(time.Now().UnixMicro()) / 1e6 err := h.q().QueryRow(ctx, `SELECT EXISTS ( SELECT 1 FROM ( @@ -471,11 +495,8 @@ func (h *MessageHandler) removeIfUnheld(ctx context.Context, msgID int64) (bool, WHERE split_part(lower(p.a), '@', 3) = ANY($2) AND NOT EXISTS (SELECT 1 FROM fmsg_api_trash t WHERE t.addr = lower(p.a) AND t.msg_id = $1 AND t.time_purged IS NOT NULL)), - EXISTS (SELECT 1 FROM msg_to WHERE msg_id = $1 AND time_delivered IS NULL AND (response_code IS NULL OR response_code = -1)) - OR EXISTS (SELECT 1 FROM msg_add_to WHERE msg_id = $1 AND time_delivered IS NULL AND (response_code IS NULL OR response_code = -1)) - OR EXISTS (SELECT 1 FROM msg_add_to_notify n JOIN msg_add_to_batch b ON b.id = n.batch_id - WHERE b.msg_id = $1 AND n.time_notified IS NULL)`, - msgID, h.localDomains()).Scan(&held, &pending) + fmsg_api_delivery_pending($1, $3, $4, $5)`, + msgID, h.localDomains(), now, h.retryMaxAge(), retryableResponseCodes).Scan(&held, &pending) if err != nil || held || pending { return false, nil, err } diff --git a/internal/handlers/trash_integration_test.go b/internal/handlers/trash_integration_test.go index 3399c80..24f8810 100644 --- a/internal/handlers/trash_integration_test.go +++ b/internal/handlers/trash_integration_test.go @@ -262,6 +262,91 @@ func TestPurge(t *testing.T) { } } +// A delivery fmsgd still retries keeps the message, whatever the code it +// retries after; one that ended with a final code does not. +func TestPurgeKeepsRetryableDelivery(t *testing.T) { + a := newFinalizationAPI(t) + ctx := context.Background() + full := a.sendAs(t, alice, []string{"@dave@remote.example"}, "user full", nil) + if _, err := a.pool.Exec(ctx, `UPDATE msg_to SET response_code = 101, attempt_count = 1, time_last_attempt = $2 WHERE msg_id = $1`, mustID(t, full), now()); err != nil { + t.Fatal(err) + } + if v := jsonResponse(t, a.request(alice, "DELETE", "/fmsg/"+full+"?permanent=true", nil), 200); v["removed"] != float64(0) { + t.Errorf("delivery fmsgd retries (user full) removed: %v", v) + } + unknown := a.sendAs(t, alice, []string{"@dave@remote.example"}, "user unknown", nil) + if _, err := a.pool.Exec(ctx, `UPDATE msg_to SET response_code = 100, attempt_count = 1, time_last_attempt = $2 WHERE msg_id = $1`, mustID(t, unknown), now()); err != nil { + t.Fatal(err) + } + if v := jsonResponse(t, a.request(alice, "DELETE", "/fmsg/"+unknown+"?permanent=true", nil), 200); v["removed"] != float64(1) { + t.Errorf("delivery that ended with a final code kept: %v", v) + } +} + +// A delivery fmsgd has given up on (older than the retry window, still +// undelivered) no longer keeps the message, nor does an add-to participant +// notification it has given up on. +func TestPurgeRemovesGivenUpDelivery(t *testing.T) { + a := newFinalizationAPI(t) + ctx := context.Background() + a.h.RetryMaxAge = 0.2 + + // Never answered: fmsgd records -1 and retries until the window closes. + id := a.sendAs(t, alice, []string{"@dave@remote.example"}, "out", nil) + if _, err := a.pool.Exec(ctx, `UPDATE msg_to SET response_code = -1, attempt_count = 5, time_last_attempt = $2 WHERE msg_id = $1`, mustID(t, id), now()); err != nil { + t.Fatal(err) + } + // Delivered to dave, then erin added: erin's delivery and the notification + // owed to dave's domain are pending until they age out. + added := a.sendAs(t, alice, []string{"@dave@remote.example"}, "added to", nil) + if _, err := a.pool.Exec(ctx, `UPDATE msg_to SET time_delivered = $2, response_code = 0 WHERE msg_id = $1`, mustID(t, added), now()); err != nil { + t.Fatal(err) + } + jsonResponse(t, a.request(alice, "POST", "/fmsg/"+added+"/add-to", map[string]any{"add_to": []string{"@erin@other.example"}}), 200) + var notifies int + if err := a.pool.QueryRow(ctx, `SELECT count(*) FROM msg_add_to_notify n JOIN msg_add_to_batch b ON b.id = n.batch_id WHERE b.msg_id = $1 AND n.time_notified IS NULL`, mustID(t, added)).Scan(¬ifies); err != nil || notifies != 1 { + t.Fatalf("pending notify rows = %d, %v; want 1", notifies, err) + } + for _, q := range []string{ + `UPDATE msg_add_to SET response_code = -1, attempt_count = 5, time_last_attempt = $2 WHERE msg_id = $1`, + `UPDATE msg_add_to_notify SET response_code = -1, attempt_count = 5, time_last_attempt = $2 WHERE batch_id IN (SELECT id FROM msg_add_to_batch WHERE msg_id = $1)`, + } { + if _, err := a.pool.Exec(ctx, q, mustID(t, added), now()); err != nil { + t.Fatal(err) + } + } + + // Inside the window both are kept (only hidden from alice). + if v := jsonResponse(t, a.request(alice, "DELETE", "/fmsg/"+id+"?permanent=true", nil), 200); v["removed"] != float64(0) { + t.Fatalf("delivery still in the retry window removed: %v", v) + } + time.Sleep(300 * time.Millisecond) + + // Past it, deleting for good removes the message from the host. + if v := jsonResponse(t, a.request(alice, "DELETE", "/fmsg/"+added+"?permanent=true", nil), 200); v["removed"] != float64(1) { + t.Errorf("given-up add-to delivery and notification kept the message: %v", v) + } + if a.exists(t, added) { + t.Error("message reported removed is still stored") + } + if !a.exists(t, id) { + t.Error("message deleted for good inside the window was removed without a purge") + } +} + +// exists reports whether message id is still stored on the host. +func (a *finalizationAPI) exists(t *testing.T, id string) bool { + t.Helper() + var ok bool + if err := a.pool.QueryRow(context.Background(), `SELECT EXISTS (SELECT 1 FROM msg WHERE id = $1)`, mustID(t, id)).Scan(&ok); err != nil { + t.Fatal(err) + } + return ok +} + +// now is the current time as fmsgd stores times: seconds since the epoch. +func now() float64 { return float64(time.Now().UnixMicro()) / 1e6 } + // A message still being delivered elsewhere is not removed. func TestPurgeKeepsPendingDelivery(t *testing.T) { a := newFinalizationAPI(t)