feat(mail): send service identity mail through a leased worker

This commit is contained in:
shira committed 2026-10-06 21:08:11 +03:00
1 parent 204c6bae62
commit d21fd49a42
58 files changed
+7577 -164

No files matched your search

@@ -0,0 +1,189 @@
// Package resendfixture is a local stand-in for the Resend HTTP API, for
// tests of the delivery layer. It speaks the part of the API that the
// resend transport uses: POST /emails with a bearer key and an
// Idempotency-Key, answered with {"id": ...} or a Resend error object. It
// keeps what it receives so a test can check the recipient, the key, and the
// number of provider calls, and it deduplicates a repeated key the way
// Resend does, so a test can tell a second call from a second message.
//
// It is a test fixture only; production keeps the real Resend transport and
// never imports this package.
package resendfixture
import (
"crypto/subtle"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
)
// APIKey is the key the fixture accepts.
const APIKey = "re_fixture_key" //nolint:gosec // A key of the local fixture, not a credential.
const maxRequestBytes = 1 << 20
// Request is one call that reached the fixture.
type Request struct {
IdempotencyKey string
To []string
Subject string
Text string
HTML string
// Replayed is set when the key was already used with the same body: the
// fixture answered with the original message and created no new one.
Replayed bool
}
// Reply is a scripted answer.
type Reply struct {
Status int
// Name is the Resend error name for a non-2xx answer, for example
// "daily_quota_exceeded".
Name string
}
// Server is the fixture. Create it with New.
type Server struct {
http *httptest.Server
// arrivals counts calls from the moment they are received, before the
// delay, so a test can tell that a call is in flight.
arrivals atomic.Int64
delay atomic.Int64 // nanoseconds
mu sync.Mutex
requests []Request
messages map[string]message // by idempotency key
scripted []Reply
}
type message struct {
id string
body string
}
// New starts the fixture on a loopback address.
func New() *Server {
server := &Server{messages: make(map[string]message)}
server.http = httptest.NewServer(http.HandlerFunc(server.serve))
return server
}
// URL is the endpoint to give the loopback transport.
func (server *Server) URL() string { return server.http.URL + "/emails" }
// Close stops the fixture.
func (server *Server) Close() { server.http.Close() }
// Script queues answers for the next calls, in order; calls after them are
// accepted as usual.
func (server *Server) Script(replies ...Reply) {
server.mu.Lock()
defer server.mu.Unlock()
server.scripted = append(server.scripted, replies...)
}
// SetDelay makes the fixture wait before it answers every later call, so a
// test can act while a send is in flight.
func (server *Server) SetDelay(delay time.Duration) { server.delay.Store(int64(delay)) }
// Arrivals returns how many calls the fixture has received, answered or
// not yet.
func (server *Server) Arrivals() int { return int(server.arrivals.Load()) }
// Requests returns every call received, in order.
func (server *Server) Requests() []Request {
server.mu.Lock()
defer server.mu.Unlock()
return append([]Request(nil), server.requests...)
}
// Messages returns the number of distinct messages the fixture accepted: a
// replayed key does not add one.
func (server *Server) Messages() int {
server.mu.Lock()
defer server.mu.Unlock()
return len(server.messages)
}
func (server *Server) serve(response http.ResponseWriter, request *http.Request) {
server.arrivals.Add(1)
if delay := time.Duration(server.delay.Load()); delay > 0 {
time.Sleep(delay)
}
if request.Method != http.MethodPost || request.URL.Path != "/emails" {
writeError(response, http.StatusNotFound, "not_found")
return
}
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 {
writeError(response, http.StatusUnauthorized, "invalid_api_key")
return
}
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes))
if err != nil {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return
}
var body struct {
To []string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text"`
HTML string `json:"html"`
}
if err := json.Unmarshal(payload, &body); err != nil {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return
}
key := request.Header.Get("Idempotency-Key")
record := Request{IdempotencyKey: key, To: body.To, Subject: body.Subject, Text: body.Text, HTML: body.HTML}
server.mu.Lock()
defer server.mu.Unlock()
if len(server.scripted) > 0 {
reply := server.scripted[0]
server.scripted = server.scripted[1:]
server.requests = append(server.requests, record)
writeError(response, reply.Status, reply.Name)
return
}
known, seen := server.messages[key]
switch {
case seen && known.body != string(payload):
// The key was used with another body: Resend refuses it.
server.requests = append(server.requests, record)
writeError(response, http.StatusConflict, "invalid_idempotent_request")
return
case seen:
record.Replayed = true
server.requests = append(server.requests, record)
writeAccepted(response, known.id)
return
}
accepted := message{id: uuid.NewString(), body: string(payload)}
if key != "" {
server.messages[key] = accepted
} else {
server.messages[accepted.id] = accepted
}
server.requests = append(server.requests, record)
writeAccepted(response, accepted.id)
}
func writeAccepted(response http.ResponseWriter, id string) {
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)
_ = json.NewEncoder(response).Encode(map[string]string{"id": id})
}
func writeError(response http.ResponseWriter, status int, name string) {
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(status)
_ = json.NewEncoder(response).Encode(map[string]any{"statusCode": status, "name": name, "message": "fixture " + strconv.Itoa(status)})
}
@@ -0,0 +1,67 @@
package resendfixture_test
import (
"testing"
"time"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func newMail(t *testing.T, subject, key string) outbound.OutgoingMail {
t.Helper()
to, err := domain.NewEmailAddress("fixture.user@example.com")
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
return outbound.OutgoingMail{To: to, Subject: subject, TextBody: "text\n", IdempotencyKey: key}
}
func TestFixtureAnswersLikeResendForTheLoopbackTransport(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "Lincodex <no-reply@example.com>", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
first, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/1"))
if err != nil || first.Outcome != outbound.MailOutcomeAccepted || first.ProviderMessageID == "" {
t.Fatalf("first Send() = %+v, %v; want accepted with a message ID", first, err)
}
// The same key and body gets the original answer and creates no message.
again, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/1"))
if err != nil || again.ProviderMessageID != first.ProviderMessageID {
t.Fatalf("repeated Send() = %+v, %v; want the original message ID %q", again, err, first.ProviderMessageID)
}
if fixture.Messages() != 1 || len(fixture.Requests()) != 2 || !fixture.Requests()[1].Replayed {
t.Fatalf("messages = %d, requests = %+v; want one message and a replayed second call", fixture.Messages(), fixture.Requests())
}
// The same key with another body is the documented conflict.
conflict, err := sender.Send(t.Context(), newMail(t, "Other subject", "delivery/1"))
if err != nil || conflict.Outcome != outbound.MailOutcomeUnknown || conflict.ProviderCode != "invalid_idempotent_request" {
t.Fatalf("conflicting Send() = %+v, %v; want unknown invalid_idempotent_request", conflict, err)
}
fixture.Script(resendfixture.Reply{Status: 429, Name: "daily_quota_exceeded"})
quota, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/2"))
if err != nil || quota.Outcome != outbound.MailOutcomeRejected || quota.Rejection != outbound.MailRejectionQuotaExhausted {
t.Fatalf("scripted Send() = %+v, %v; want a quota refusal", quota, err)
}
}
func TestLoopbackSenderRefusesAnyOtherHost(t *testing.T) {
for _, endpoint := range []string{
"https://api.resend.com/emails",
"http://api.resend.com/emails",
"http://192.0.2.10:8080/emails",
"https://127.0.0.1:8080/emails",
"not a url",
} {
if _, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", time.Second, endpoint, time.Now); err == nil {
t.Fatalf("NewLoopbackSender(%q) accepted a non-loopback endpoint", endpoint)
}
}
}