From 0f414a00d3629fe9bf89834c1e333815890099c4 Mon Sep 17 00:00:00 2001 From: Danny Kopping Date: Fri, 30 Aug 2024 13:03:25 +0200 Subject: [PATCH] fix: restore closing SMTP message on method exit (#14496) --- coderd/notifications/dispatch/smtp.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/coderd/notifications/dispatch/smtp.go b/coderd/notifications/dispatch/smtp.go index 7bbff3fcb8..107e9e2e8c 100644 --- a/coderd/notifications/dispatch/smtp.go +++ b/coderd/notifications/dispatch/smtp.go @@ -183,6 +183,15 @@ func (s *SMTPHandler) dispatch(subject, htmlBody, plainBody, to string) Delivery if err != nil { return true, xerrors.Errorf("message transmission: %w", err) } + closeOnce := sync.OnceValue(func() error { + return message.Close() + }) + // Close the message when this method exits in order to not leak resources. Even though we're calling this explicitly + // further down, the method may exit before then. + defer func() { + // If we try close an already-closed writer, it'll send a subsequent request to the server which is invalid. + _ = closeOnce() + }() // Create message headers. msg := &bytes.Buffer{} @@ -250,7 +259,7 @@ func (s *SMTPHandler) dispatch(subject, htmlBody, plainBody, to string) Delivery return false, xerrors.Errorf("write body buffer: %w", err) } - if err = message.Close(); err != nil { + if err = closeOnce(); err != nil { return true, xerrors.Errorf("delivery failure: %w", err) }