fix(servicediscovery/nats): validate config after defaults

Root-cause fix: Connect validated the raw config before withDefaults, so
the Heartbeat<TTL guard was skipped whenever Heartbeat was unset and a
custom TTL below DefaultHeartbeat passed as a silently expiring registry.
Apply defaults first so the documented invariant is enforced. No
WIRE/DELETE decision applies: this is a producer-ordering bug, not
unreachable code.
This commit is contained in:
sam committed 2026-09-15 12:51:17 +10:00
1 parent 0c5ea7b2a0
commit 0a73394c23
2 files changed
+12 -1

No files matched your search

@@ -45,10 +45,10 @@ type Client struct {
// On any failure the partially-built connection is closed before returning, so
// a failed Connect leaks nothing.
func Connect(ctx context.Context, cfg Config, log *slog.Logger) (*Client, error) {
cfg = cfg.withDefaults()
if err := cfg.Validate(); err != nil {
return nil, err
}
cfg = cfg.withDefaults()
if log == nil {
log = slog.New(slog.DiscardHandler)
}
@@ -23,6 +23,17 @@ func testConfig() Config {
return Config{TTL: time.Second, Heartbeat: 200 * time.Millisecond}
}
// TestConnectRejectsTTLBelowDefaultHeartbeat pins the Connect ordering: a
// caller that sets TTL below DefaultHeartbeat and leaves Heartbeat unset must
// be refused as ErrInvalidConfig, not silently given a registry whose live
// entries expire between refreshes (DefaultHeartbeat >= TTL).
func TestConnectRejectsTTLBelowDefaultHeartbeat(t *testing.T) {
_, err := Connect(context.Background(), Config{URL: "nats://127.0.0.1:1", TTL: 2 * time.Second}, discardLogger())
if !errors.Is(err, ErrInvalidConfig) {
t.Fatalf("Connect() = %v, want ErrInvalidConfig", err)
}
}
// newServer starts a real in-process NATS server with JetStream enabled. This
// is the established test technique for the NATS infrastructure (see the
// sibling eventbus/nats retention test): a real server, not a mocked client.