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
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions cmd/fmsg-webapi/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions dd.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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)
$$;
4 changes: 4 additions & 0 deletions internal/handlers/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
35 changes: 28 additions & 7 deletions internal/handlers/trash.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
}
Expand Down
85 changes: 85 additions & 0 deletions internal/handlers/trash_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(&notifies); 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)
Expand Down
Loading