From bcc53182fb7d892708af7ac82fd473bf14cada4d Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Thu, 26 Nov 2026 10:12:01 +0800 Subject: [PATCH] Sender: configurable DB pool, honest concurrency, one probe for a down domain A delivery holds one connection from the sender's database pool for its whole exchange, so the pool, fixed at 32, was the real limit on outbound deliveries whatever FMSG_MAX_CONCURRENT_SEND said, and a backlog for an unreachable domain could hold every connection for a connect timeout at a time while deliveries to healthy domains waited. - FMSG_SENDER_DB_MAX_CONNS sets the pool size (default 32, minimum 2). - The delivery semaphore is sized to what can actually run: the smaller of FMSG_MAX_CONCURRENT_SEND and the pool minus one connection kept for the query that finds pending work. Deliveries no longer queue for a connection while holding a slot, and the start-up log states the number. - A domain the sender could not resolve or connect to gets one delivery at a time until a connection to it succeeds. The rest of its backlog waits for a later poll instead of occupying delivery slots. Part of #55; deliveries still hold a connection across network I/O. Co-Authored-By: Claude Fable 5.2 --- README.md | 3 +- cmd/fmsgd/sender.go | 79 ++++++++++++++++++++++--- cmd/fmsgd/sender_dispatch_test.go | 95 +++++++++++++++++++++++++++++++ cmd/fmsgd/store.go | 10 +++- cmd/fmsgd/store_test.go | 10 ++-- 5 files changed, 181 insertions(+), 16 deletions(-) create mode 100644 cmd/fmsgd/sender_dispatch_test.go diff --git a/README.md b/README.md index 491134f..fe31b90 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,8 @@ Requires Go 1.27 or newer. | FMSG_RETRY_INTERVAL | 20 | Seconds. Minimum time before retrying delivery to a recipient that previously failed. | | FMSG_RETRY_MAX_AGE | 86400 | Seconds. Maximum age of a message since creation before giving up on delivery retries (default 1 day). | | FMSG_POLL_INTERVAL | 10 | Seconds. How often the sender polls the database for pending messages. | -| FMSG_MAX_CONCURRENT_SEND | 1024 | Maximum number of outbound deliveries dispatched at once. Each delivery holds one connection from the sender's database pool (32) for the whole exchange, so at most 32 run concurrently; the rest wait for a connection. | +| FMSG_MAX_CONCURRENT_SEND | 1024 | Maximum number of outbound deliveries at once. The effective limit is the smaller of this and `FMSG_SENDER_DB_MAX_CONNS` - 1, because each delivery holds one database connection for its whole exchange. A domain that could not be connected to gets one delivery at a time until a connection to it succeeds. | +| FMSG_SENDER_DB_MAX_CONNS | 32 | Size of the sender's database connection pool (minimum 2). Inbound handling and indicators use a separate pool of 48, so fmsgd opens at most 48 + this many connections; keep PostgreSQL `max_connections` above that plus whatever else shares the server. | | FMSG_SKIP_DOMAIN_IP_CHECK | false | Set to "true" to skip verifying this host's external IP is in the fmsg DNS authorised IP set on startup. | | FMSG_SKIP_AUTHORISED_IPS | false | Set to "true" to skip verifying remote hosts IP is in the fmsg DNS authorised IP set during message exchange, and an indicator datagram's source address. WARNING setting this true effectively disables sender verification. | | FMSG_CHALLENGE_MODE | HAS_NOT_PARTICIPATED | When to issue an automatic CHALLENGE to the sending host. `HAS_NOT_PARTICIPATED` (default): challenge only when the message has no pid, or no message in the thread is from this host's domain. `ALWAYS`: always challenge. `NEVER`: never challenge. | diff --git a/cmd/fmsgd/sender.go b/cmd/fmsgd/sender.go index faf5e9f..2348956 100644 --- a/cmd/fmsgd/sender.go +++ b/cmd/fmsgd/sender.go @@ -50,6 +50,15 @@ func loadSenderEnvConfig() { RetryMaxAge = env.GetFloatDefault("FMSG_RETRY_MAX_AGE", 86400) PollInterval = env.GetIntDefault("FMSG_POLL_INTERVAL", 10) MaxConcurrentSend = env.GetIntDefault("FMSG_MAX_CONCURRENT_SEND", 1024) + SenderDBMaxConns = max(2, env.GetIntDefault("FMSG_SENDER_DB_MAX_CONNS", 32)) +} + +// deliverySlots is how many deliveries may run at once. A delivery holds one +// connection from the sender's database pool for its whole exchange, so the +// pool bounds it as well as FMSG_MAX_CONCURRENT_SEND; one connection is kept +// back for the query that finds pending work. +func deliverySlots(maxConcurrentSend, senderDBMaxConns int) int { + return max(1, min(maxConcurrentSend, senderDBMaxConns-1)) } // pendingTarget identifies a (message, domain) pair that needs delivery. @@ -633,6 +642,7 @@ func deliverUnit(db *sql.DB, target pendingTarget, prepared, expectedHash []byte targetIPs, err := lookupAuthorisedIPs(target.Domain) if err != nil { log.Printf("ERROR: sender: DNS lookup for fmsg.%s failed: %s", target.Domain, err) + outboundDomains.setReachable(target.Domain, false) return } @@ -640,9 +650,11 @@ func deliverUnit(db *sql.DB, target pendingTarget, prepared, expectedHash []byte conn := dialTargetIPs(targetIPs, RemotePort, tlsConf) if conn == nil { log.Printf("ERROR: sender: could not connect to any IP for fmsg.%s", target.Domain) + outboundDomains.setReachable(target.Domain, false) return } defer conn.Close() + outboundDomains.setReachable(target.Domain, true) // Register in outgoing map with Host B's IP before sending the header so // any incoming challenge can be matched by hash AND IP (ยง10.2 step 2). @@ -756,13 +768,55 @@ func deliverUnit(db *sql.DB, target pendingTarget, prepared, expectedHash []byte commitOrLog(tx, &committed, target.MsgID) } +// domainReachability remembers which domains the sender could not connect to +// on its last attempt. A domain is forgotten (reachable again) as soon as a +// connection to it succeeds, so the set stays as small as the number of peers +// that are down right now. +type domainReachability struct { + mu sync.Mutex + unreachable map[string]struct{} +} + +// outboundDomains is the sender's view of which peers it can currently reach. +var outboundDomains = &domainReachability{unreachable: make(map[string]struct{})} + +func (d *domainReachability) setReachable(domain string, reachable bool) { + k := strings.ToLower(domain) + d.mu.Lock() + defer d.mu.Unlock() + if reachable { + delete(d.unreachable, k) + } else { + d.unreachable[k] = struct{}{} + } +} + +func (d *domainReachability) isUnreachable(domain string) bool { + d.mu.Lock() + defer d.mu.Unlock() + _, down := d.unreachable[strings.ToLower(domain)] + return down +} + +// inFlightTracker deduplicates dispatch against deliveries already running, +// and holds a domain the sender could not connect to down to one delivery at +// a time. That one delivery is the probe: while it fails, the rest of the +// domain's backlog waits for a later poll instead of each taking a delivery +// slot for the length of a connect timeout, and when it connects the domain +// gets its full share again. type inFlightTracker struct { - mu sync.Mutex - active map[pendingTarget]struct{} + mu sync.Mutex + active map[pendingTarget]struct{} + perDomain map[string]int + domains *domainReachability } func newInFlightTracker() *inFlightTracker { - return &inFlightTracker{active: make(map[pendingTarget]struct{})} + return &inFlightTracker{ + active: make(map[pendingTarget]struct{}), + perDomain: make(map[string]int), + domains: outboundDomains, + } } func (f *inFlightTracker) acquire(t pendingTarget) bool { @@ -772,15 +826,25 @@ func (f *inFlightTracker) acquire(t pendingTarget) bool { if _, exists := f.active[k]; exists { return false } + if f.perDomain[k.Domain] > 0 && f.domains.isUnreachable(k.Domain) { + return false + } f.active[k] = struct{}{} + f.perDomain[k.Domain]++ return true } func (f *inFlightTracker) release(t pendingTarget) { k := pendingTarget{MsgID: t.MsgID, Domain: strings.ToLower(t.Domain)} f.mu.Lock() + defer f.mu.Unlock() + if _, exists := f.active[k]; !exists { + return + } delete(f.active, k) - f.mu.Unlock() + if f.perDomain[k.Domain]--; f.perDomain[k.Domain] <= 0 { + delete(f.perDomain, k.Domain) + } } // processPendingMessages finds messages needing delivery and dispatches a @@ -821,10 +885,11 @@ func processPendingMessages(ctx context.Context, sem chan struct{}, inFlight *in // listens for PostgreSQL notifications for immediate pickup of new messages. func startSender(ctx context.Context) { loadSenderEnvConfig() - log.Printf("INFO: sender: started (poll=%ds, retry=%.0fs, max_concurrent=%d)", - PollInterval, RetryInterval, MaxConcurrentSend) + slots := deliverySlots(MaxConcurrentSend, SenderDBMaxConns) + log.Printf("INFO: sender: started (poll=%ds, retry=%.0fs, max_concurrent=%d, db_max_conns=%d, deliveries_at_once=%d)", + PollInterval, RetryInterval, MaxConcurrentSend, SenderDBMaxConns, slots) - sem := make(chan struct{}, MaxConcurrentSend) + sem := make(chan struct{}, slots) inFlight := newInFlightTracker() // set up PostgreSQL LISTEN for immediate notification diff --git a/cmd/fmsgd/sender_dispatch_test.go b/cmd/fmsgd/sender_dispatch_test.go new file mode 100644 index 0000000..417ce47 --- /dev/null +++ b/cmd/fmsgd/sender_dispatch_test.go @@ -0,0 +1,95 @@ +package main + +import "testing" + +func TestDeliverySlots(t *testing.T) { + for _, tc := range []struct { + name string + maxConcurrentSend, poolSize int + want int + }{ + {"the pool bounds the default", 1024, 32, 31}, + {"FMSG_MAX_CONCURRENT_SEND bounds a large pool", 8, 32, 8}, + {"a larger pool raises the limit", 1024, 200, 199}, + {"never below one delivery", 1024, 1, 1}, + {"a non-positive limit still allows one", 0, 32, 1}, + } { + if got := deliverySlots(tc.maxConcurrentSend, tc.poolSize); got != tc.want { + t.Errorf("%s: deliverySlots(%d, %d) = %d, want %d", tc.name, tc.maxConcurrentSend, tc.poolSize, got, tc.want) + } + } +} + +func newTestInFlightTracker() *inFlightTracker { + f := newInFlightTracker() + f.domains = &domainReachability{unreachable: make(map[string]struct{})} + return f +} + +func TestInFlightTrackerDeduplicatesTargets(t *testing.T) { + f := newTestInFlightTracker() + target := pendingTarget{MsgID: 1, Domain: "Example.com"} + + if !f.acquire(target) { + t.Fatal("first acquire refused") + } + if f.acquire(pendingTarget{MsgID: 1, Domain: "example.COM"}) { + t.Fatal("the same target was acquired twice") + } + if !f.acquire(pendingTarget{MsgID: 2, Domain: "example.com"}) { + t.Fatal("a reachable domain must take more than one delivery at a time") + } + f.release(target) + if !f.acquire(target) { + t.Fatal("a released target could not be acquired again") + } +} + +// A domain the sender could not connect to gets one delivery at a time, so +// its backlog cannot occupy every delivery slot for the length of a connect +// timeout while other domains wait. +func TestInFlightTrackerHoldsUnreachableDomainToOneDelivery(t *testing.T) { + f := newTestInFlightTracker() + down, up := "down.example.com", "up.example.com" + + // Nothing is known about the domain yet: it gets its full share. + if !f.acquire(pendingTarget{MsgID: 1, Domain: down}) || !f.acquire(pendingTarget{MsgID: 2, Domain: down}) { + t.Fatal("deliveries to a domain not known to be down were refused") + } + f.domains.setReachable("DOWN.example.com", false) + + if f.acquire(pendingTarget{MsgID: 3, Domain: down}) { + t.Fatal("an unreachable domain with deliveries in flight took another slot") + } + if !f.acquire(pendingTarget{MsgID: 4, Domain: up}) { + t.Fatal("another domain was held back by the unreachable one") + } + + // Once nothing is in flight to it, one delivery goes out as the probe. + f.release(pendingTarget{MsgID: 1, Domain: down}) + if f.acquire(pendingTarget{MsgID: 3, Domain: down}) { + t.Fatal("a second delivery was allowed while one was still in flight") + } + f.release(pendingTarget{MsgID: 2, Domain: down}) + if !f.acquire(pendingTarget{MsgID: 3, Domain: down}) { + t.Fatal("the probe delivery to an unreachable domain was refused") + } + if f.acquire(pendingTarget{MsgID: 5, Domain: down}) { + t.Fatal("more than one probe delivery at a time") + } + + // The probe connects: the domain gets its full share again. + f.domains.setReachable(down, true) + if !f.acquire(pendingTarget{MsgID: 5, Domain: down}) { + t.Fatal("a domain that became reachable was still held back") + } +} + +func TestInFlightTrackerReleaseOfUnknownTargetIsHarmless(t *testing.T) { + f := newTestInFlightTracker() + f.release(pendingTarget{MsgID: 9, Domain: "example.com"}) + f.domains.setReachable("example.com", false) + if !f.acquire(pendingTarget{MsgID: 9, Domain: "example.com"}) { + t.Fatal("a stray release left the domain counted as busy") + } +} diff --git a/cmd/fmsgd/store.go b/cmd/fmsgd/store.go index 6eb5b14..48d673e 100644 --- a/cmd/fmsgd/store.go +++ b/cmd/fmsgd/store.go @@ -16,10 +16,14 @@ import ( const ( dbMaxOpenConns = 48 dbMaxIdleConns = 16 - senderDBMaxOpenConns = 32 senderDBMaxIdleConns = 8 ) +// SenderDBMaxConns is the size of the sender's database pool +// (FMSG_SENDER_DB_MAX_CONNS). A delivery holds one connection for its whole +// exchange, so the pool bounds how many deliveries run at once. +var SenderDBMaxConns = 32 + var ( dbMu sync.Mutex sharedDB *sql.DB @@ -76,8 +80,8 @@ func getSenderDB() (*sql.DB, error) { if err != nil { return nil, err } - db.SetMaxOpenConns(senderDBMaxOpenConns) - db.SetMaxIdleConns(senderDBMaxIdleConns) + db.SetMaxOpenConns(SenderDBMaxConns) + db.SetMaxIdleConns(min(senderDBMaxIdleConns, SenderDBMaxConns)) db.SetConnMaxLifetime(30 * time.Minute) db.SetConnMaxIdleTime(5 * time.Minute) senderDB = db diff --git a/cmd/fmsgd/store_test.go b/cmd/fmsgd/store_test.go index f44469a..98e7b2a 100644 --- a/cmd/fmsgd/store_test.go +++ b/cmd/fmsgd/store_test.go @@ -333,13 +333,13 @@ func TestSenderPoolSaturationDoesNotStarveInboundPool(t *testing.T) { } // Fill every single connection in the sender pool with open transactions. - heldTxs := make([]*sql.Tx, 0, senderDBMaxOpenConns) + heldTxs := make([]*sql.Tx, 0, SenderDBMaxConns) defer func() { for _, tx := range heldTxs { _ = tx.Rollback() } }() - for i := 0; i < senderDBMaxOpenConns; i++ { + for i := 0; i < SenderDBMaxConns; i++ { tx, err := sDB.Begin() if err != nil { t.Fatalf("sender Begin #%d: %v", i, err) @@ -347,7 +347,7 @@ func TestSenderPoolSaturationDoesNotStarveInboundPool(t *testing.T) { heldTxs = append(heldTxs, tx) } - // Queue additional Begin calls beyond senderDBMaxOpenConns to confirm the + // Queue additional Begin calls beyond SenderDBMaxConns to confirm the // sender pool is genuinely saturated and blocking. const extraWaiters = 4 extraDone := make(chan *sql.Tx, extraWaiters) @@ -370,8 +370,8 @@ func TestSenderPoolSaturationDoesNotStarveInboundPool(t *testing.T) { for sDB.Stats().WaitCount == 0 && time.Now().Before(deadline) { time.Sleep(time.Millisecond) } - if stats := sDB.Stats(); stats.InUse != senderDBMaxOpenConns || stats.WaitCount == 0 { - t.Fatalf("expected saturated sender pool (inUse=%d/%d, waitCount=%d)", stats.InUse, senderDBMaxOpenConns, stats.WaitCount) + if stats := sDB.Stats(); stats.InUse != SenderDBMaxConns || stats.WaitCount == 0 { + t.Fatalf("expected saturated sender pool (inUse=%d/%d, waitCount=%d)", stats.InUse, SenderDBMaxConns, stats.WaitCount) } // While the sender pool is completely saturated, an inbound getDB() query