258 lines
7.7 KiB
Go
258 lines
7.7 KiB
Go
// 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
|
|
// RetryAfter is copied to the response header for a rate-limit fixture.
|
|
RetryAfter string
|
|
// DropAfterAccept stores the message and closes the connection without an
|
|
// HTTP answer, like a provider accepting the request before the response
|
|
// is lost.
|
|
DropAfterAccept bool
|
|
}
|
|
|
|
// 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
|
|
accepted int
|
|
scripted []Reply
|
|
clock func() time.Time
|
|
}
|
|
|
|
type message struct {
|
|
id string
|
|
body string
|
|
acceptedAt time.Time
|
|
}
|
|
|
|
const providerIdempotencyWindow = 24 * time.Hour
|
|
|
|
// New starts the fixture on a loopback address.
|
|
func New() *Server {
|
|
server := &Server{messages: make(map[string]message), clock: time.Now}
|
|
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)) }
|
|
|
|
// SetClock replaces the provider clock so tests can expire idempotency keys
|
|
// without waiting in real time.
|
|
func (server *Server) SetClock(clock func() time.Time) {
|
|
server.mu.Lock()
|
|
defer server.mu.Unlock()
|
|
if clock == nil {
|
|
server.clock = time.Now
|
|
return
|
|
}
|
|
server.clock = clock
|
|
}
|
|
|
|
// 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 server.accepted
|
|
}
|
|
|
|
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)
|
|
}
|
|
payload, record, ok := readRequest(response, request)
|
|
if !ok {
|
|
return
|
|
}
|
|
server.handleEmail(response, payload, record)
|
|
}
|
|
|
|
func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, Request, bool) {
|
|
if request.Method != http.MethodPost || request.URL.Path != "/emails" {
|
|
writeError(response, http.StatusNotFound, "not_found")
|
|
return nil, Request{}, false
|
|
}
|
|
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 {
|
|
writeError(response, http.StatusUnauthorized, "invalid_api_key")
|
|
return nil, Request{}, false
|
|
}
|
|
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes))
|
|
if err != nil {
|
|
writeError(response, http.StatusBadRequest, "invalid_parameter")
|
|
return nil, Request{}, false
|
|
}
|
|
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 nil, Request{}, false
|
|
}
|
|
return payload, Request{
|
|
IdempotencyKey: request.Header.Get("Idempotency-Key"),
|
|
To: body.To,
|
|
Subject: body.Subject,
|
|
Text: body.Text,
|
|
HTML: body.HTML,
|
|
}, true
|
|
}
|
|
|
|
func (server *Server) handleEmail(response http.ResponseWriter, payload []byte, record Request) {
|
|
server.mu.Lock()
|
|
reply := Reply{}
|
|
if len(server.scripted) > 0 {
|
|
reply = server.scripted[0]
|
|
server.scripted = server.scripted[1:]
|
|
}
|
|
now := server.clock()
|
|
known, seen := server.messages[record.IdempotencyKey]
|
|
if seen && now.Sub(known.acceptedAt) >= providerIdempotencyWindow {
|
|
delete(server.messages, record.IdempotencyKey)
|
|
seen = false
|
|
}
|
|
if reply.Status != 0 {
|
|
server.requests = append(server.requests, record)
|
|
server.mu.Unlock()
|
|
if reply.RetryAfter != "" {
|
|
response.Header().Set("Retry-After", reply.RetryAfter)
|
|
}
|
|
writeError(response, reply.Status, reply.Name)
|
|
return
|
|
}
|
|
messageID, replayed, conflict := server.recordAcceptanceLocked(record.IdempotencyKey, string(payload), now, known, seen)
|
|
record.Replayed = replayed
|
|
server.requests = append(server.requests, record)
|
|
server.mu.Unlock()
|
|
if conflict {
|
|
writeError(response, http.StatusConflict, "invalid_idempotent_request")
|
|
return
|
|
}
|
|
if reply.DropAfterAccept {
|
|
dropConnection(response)
|
|
return
|
|
}
|
|
writeAccepted(response, messageID)
|
|
}
|
|
|
|
func (server *Server) recordAcceptanceLocked(key, body string, now time.Time, known message, seen bool) (string, bool, bool) {
|
|
if seen {
|
|
if known.body != body {
|
|
return "", false, true
|
|
}
|
|
return known.id, true, false
|
|
}
|
|
accepted := message{id: uuid.NewString(), body: body, acceptedAt: now}
|
|
if key != "" {
|
|
server.messages[key] = accepted
|
|
} else {
|
|
server.messages[accepted.id] = accepted
|
|
}
|
|
server.accepted++
|
|
return accepted.id, false, false
|
|
}
|
|
|
|
func dropConnection(response http.ResponseWriter) {
|
|
if hijacker, ok := response.(http.Hijacker); ok {
|
|
connection, _, err := hijacker.Hijack()
|
|
if err == nil {
|
|
_ = connection.Close()
|
|
}
|
|
}
|
|
}
|
|
|
|
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)})
|
|
}
|