197 lines
6.5 KiB
Go
197 lines
6.5 KiB
Go
// Package mailretry implements the local operator command for inspecting and
|
|
// authorizing a retry of an unknown mail delivery.
|
|
package mailretry
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/config"
|
|
"lincodex/backend/internal/adapter/secondary/mail/resend"
|
|
"lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/notification"
|
|
)
|
|
|
|
const usage = "usage: mail-retry inspect --delivery <uuid> | mail-retry retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk"
|
|
|
|
type action uint8
|
|
|
|
const (
|
|
inspectAction action = iota + 1
|
|
retryAction
|
|
)
|
|
|
|
// Command is a parsed, validated local mail retry command.
|
|
type Command struct {
|
|
Action action
|
|
DeliveryID uuid.UUID
|
|
Actor string
|
|
AcknowledgeDuplicateRisk bool
|
|
}
|
|
|
|
// Operator is the metadata-only and audit-backed retry usecase.
|
|
type Operator interface {
|
|
Inspect(ctx context.Context, deliveryID uuid.UUID) (notification.DeliveryRetryInspection, error)
|
|
RetryUnknown(ctx context.Context, deliveryID uuid.UUID, actor string, acknowledgeDuplicateRisk bool) (string, error)
|
|
}
|
|
|
|
// Parse validates every argument before Run reads configuration or connects
|
|
// to PostgreSQL.
|
|
func Parse(args []string) (Command, error) {
|
|
if len(args) == 0 {
|
|
return Command{}, errors.New(usage)
|
|
}
|
|
|
|
var command Command
|
|
var actor *string
|
|
var acknowledge *bool
|
|
switch args[0] {
|
|
case "inspect":
|
|
command.Action = inspectAction
|
|
case "retry":
|
|
command.Action = retryAction
|
|
default:
|
|
return Command{}, errors.New(usage)
|
|
}
|
|
|
|
flags := flag.NewFlagSet("mail-retry "+args[0], flag.ContinueOnError)
|
|
flags.SetOutput(io.Discard)
|
|
deliveryID := flags.String("delivery", "", "delivery UUID")
|
|
if command.Action == retryAction {
|
|
actor = flags.String("actor", "", "operator handle")
|
|
acknowledge = flags.Bool("acknowledge-duplicate-risk", false, "acknowledge that a duplicate may be sent")
|
|
}
|
|
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
|
return Command{}, errors.New(usage)
|
|
}
|
|
parsedID, err := uuid.Parse(strings.TrimSpace(*deliveryID))
|
|
if err != nil || parsedID == uuid.Nil {
|
|
return Command{}, errors.New("delivery must be a non-zero UUID")
|
|
}
|
|
command.DeliveryID = parsedID
|
|
if command.Action == retryAction {
|
|
if _, err := domain.ParseMailRetryActor(strings.TrimSpace(*actor)); err != nil {
|
|
return Command{}, errors.New("actor must be operator:<handle>")
|
|
}
|
|
if !*acknowledge {
|
|
return Command{}, errors.New("--acknowledge-duplicate-risk is required")
|
|
}
|
|
command.Actor = strings.TrimSpace(*actor)
|
|
command.AcknowledgeDuplicateRisk = true
|
|
}
|
|
return command, nil
|
|
}
|
|
|
|
// Run parses the command, loads only its database and mail-account settings
|
|
// from the supplied environment, then executes the operator usecase. It does
|
|
// not load dotenv files or read transport credentials.
|
|
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
|
|
command, err := Parse(args)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if lookup == nil || output == nil {
|
|
return errors.New("mail retry command dependencies are required")
|
|
}
|
|
databaseURL := config.DatabaseURLFromEnv(lookup)
|
|
if databaseURL == "" {
|
|
return errors.New("DATABASE_URL is not set")
|
|
}
|
|
provider := strings.ToLower(strings.TrimSpace(envValue(lookup, "EMAIL_PROVIDER", "")))
|
|
if provider != string(config.EmailProviderResend) {
|
|
return errors.New("mail retry is available only with EMAIL_PROVIDER=resend in this build")
|
|
}
|
|
accountLabel := strings.TrimSpace(envValue(lookup, "EMAIL_ACCOUNT", "default"))
|
|
account, err := domain.NewMailProviderAccount(provider, accountLabel)
|
|
if err != nil {
|
|
return errors.New("mail provider account configuration is invalid")
|
|
}
|
|
|
|
pool, err := postgres.NewPool(ctx, databaseURL)
|
|
if err != nil {
|
|
return errors.New("database configuration is invalid")
|
|
}
|
|
defer pool.Close()
|
|
if err := pool.Ping(ctx); err != nil {
|
|
return errors.New("database is unavailable")
|
|
}
|
|
deliveries := postgres.NewDeliveryStore(pool).Deliveries()
|
|
operator, err := notification.NewDeliveryRetryOperator(
|
|
postgres.NewTransactor(pool),
|
|
deliveries,
|
|
account,
|
|
resend.IdempotencyWindow,
|
|
time.Now,
|
|
)
|
|
if err != nil {
|
|
return errors.New("mail retry is unavailable")
|
|
}
|
|
return Execute(ctx, command, operator, output)
|
|
}
|
|
|
|
// Execute prints the duplicate-risk warning before retry authorization can
|
|
// mutate the delivery or append an audit decision.
|
|
func Execute(ctx context.Context, command Command, operator Operator, output io.Writer) error {
|
|
if operator == nil || output == nil {
|
|
return errors.New("mail retry command dependencies are required")
|
|
}
|
|
snapshot, err := operator.Inspect(ctx, command.DeliveryID)
|
|
if err != nil {
|
|
return safeOperationError(err)
|
|
}
|
|
if command.Action == inspectAction {
|
|
if _, err := fmt.Fprintf(output,
|
|
"delivery: %s\nprovider: %s\nstatus: %s\nattempts: %d\n%s\n",
|
|
snapshot.DeliveryID, snapshot.Provider, snapshot.Status, snapshot.AttemptCount, notification.DuplicateRiskWarning,
|
|
); err != nil {
|
|
return errors.New("could not write mail retry inspection")
|
|
}
|
|
return nil
|
|
}
|
|
if command.Action != retryAction || !command.AcknowledgeDuplicateRisk {
|
|
return errors.New(usage)
|
|
}
|
|
if _, err := fmt.Fprintln(output, notification.DuplicateRiskWarning); err != nil {
|
|
return errors.New("could not write duplicate-risk warning")
|
|
}
|
|
if _, err := operator.RetryUnknown(ctx, command.DeliveryID, command.Actor, command.AcknowledgeDuplicateRisk); err != nil {
|
|
return safeOperationError(err)
|
|
}
|
|
if _, err := fmt.Fprintln(output, "retry scheduled; audit decision recorded"); err != nil {
|
|
return errors.New("retry was scheduled, but the result could not be written")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func envValue(lookup config.LookupEnv, name, fallback string) string {
|
|
value, ok := lookup(name)
|
|
if !ok || strings.TrimSpace(value) == "" {
|
|
return fallback
|
|
}
|
|
return value
|
|
}
|
|
|
|
func safeOperationError(err error) error {
|
|
switch {
|
|
case errors.Is(err, outbound.ErrDeliveryNotFound):
|
|
return errors.New("delivery not found")
|
|
case errors.Is(err, outbound.ErrDeliveryRetryNotAllowed):
|
|
return errors.New("delivery is not eligible for manual retry")
|
|
case errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired):
|
|
return errors.New("duplicate-risk acknowledgement is required")
|
|
case errors.Is(err, domain.ErrInvalidDelivery):
|
|
return errors.New("delivery or actor is invalid")
|
|
default:
|
|
return errors.New("mail retry operation failed")
|
|
}
|
|
}
|