@@ -2,96 +2,103 @@ import { defineAction, ActionError } from "astro:actions";
22import { z } from "astro:schema" ;
33import { getEmailService } from "../services/emailService.js" ;
44import { getRateLimitService } from "../services/rateLimitService.js" ;
5+ import type {
6+ RateLimitReservation ,
7+ RateLimitService ,
8+ } from "../services/rateLimitService.js" ;
59import type { EmailData } from "../utils/email.js" ;
610
7- // Define the success result type
11+ /** Result returned after a contact email has been sent successfully. */
812type SendMailResult = {
9- success : true ;
13+ success : true ;
1014} ;
1115
16+ /** Validates contact data, reserves a slot, and sends the contact email. */
1217export const sendMail = defineAction ( {
13- accept : "form" ,
14- input : z . object ( {
15- firstName : z . string ( ) . min ( 2 ) . max ( 50 ) . trim ( ) ,
16- lastName : z . string ( ) . min ( 2 ) . max ( 60 ) . trim ( ) ,
17- email : z . string ( ) . email ( ) . max ( 254 ) . toLowerCase ( ) ,
18- subject : z . string ( ) . min ( 1 ) . max ( 100 ) . trim ( ) ,
19- message : z . string ( ) . min ( 1 ) . max ( 3000 ) . trim ( ) ,
20- privacy : z . coerce . boolean ( ) . refine ( val => val === true ) ,
21- company : z . string ( ) . max ( 100 ) . trim ( ) . optional ( ) ,
22- phone : z . string ( ) . max ( 20 ) . trim ( ) . optional ( ) ,
23- website : z . union ( [ z . string ( ) , z . null ( ) , z . undefined ( ) ] )
24- . transform ( v => ( v ?? "" ) . trim ( ) )
25- . refine ( v => v === "" ) /* Honeypot */
26- } ) ,
27-
28- handler : async ( input ) : Promise < SendMailResult > => {
29- try {
30- const rateLimitService = getRateLimitService ( ) ;
31- const emailService = getEmailService ( ) ;
32-
33- // Get today's date in Swiss timezone
34- const today = rateLimitService . getSwissDate ( ) ;
35-
36- // 1. Check rate limit BEFORE sending email
37- const rateLimit = await rateLimitService . checkLimit ( today ) ;
38-
39- if ( ! rateLimit . allowed ) {
40- throw new ActionError ( {
41- code : "TOO_MANY_REQUESTS" ,
42- message : "Daily email limit reached. Please try again tomorrow."
43- } ) ;
44- }
18+ accept : "form" ,
19+ input : z . object ( {
20+ firstName : z . string ( ) . min ( 2 ) . max ( 50 ) . trim ( ) ,
21+ lastName : z . string ( ) . min ( 2 ) . max ( 60 ) . trim ( ) ,
22+ email : z . string ( ) . email ( ) . max ( 254 ) . toLowerCase ( ) ,
23+ subject : z . string ( ) . min ( 1 ) . max ( 100 ) . trim ( ) ,
24+ message : z . string ( ) . min ( 1 ) . max ( 3000 ) . trim ( ) ,
25+ privacy : z . coerce . boolean ( ) . refine ( ( val ) => val === true ) ,
26+ company : z . string ( ) . max ( 100 ) . trim ( ) . optional ( ) ,
27+ phone : z . string ( ) . max ( 20 ) . trim ( ) . optional ( ) ,
28+ website : z
29+ . union ( [ z . string ( ) , z . null ( ) , z . undefined ( ) ] )
30+ . transform ( ( v ) => ( v ?? "" ) . trim ( ) )
31+ . refine ( ( v ) => v === "" ) /* Honeypot */ ,
32+ } ) ,
4533
46- // 2. Send email
47- const emailData : EmailData = {
48- firstName : input . firstName ,
49- lastName : input . lastName ,
50- email : input . email ,
51- subject : input . subject ,
52- message : input . message ,
53- ...( input . company && { company : input . company } ) ,
54- ...( input . phone && { phone : input . phone } ) ,
55- } ;
34+ handler : async ( input ) : Promise < SendMailResult > => {
35+ let reservation : RateLimitReservation | null = null ;
36+ let rateLimitService : RateLimitService | null = null ;
5637
57- const result = await emailService . sendEmail ( emailData ) ;
38+ try {
39+ rateLimitService = getRateLimitService ( ) ;
40+ const emailService = getEmailService ( ) ;
5841
59- if ( ! result . success ) {
60- console . error ( "Email sending failed:" , result . error ) ;
61- throw new ActionError ( {
62- code : "BAD_REQUEST" ,
63- message : "Email service unavailable. Please try again later."
64- } ) ;
65- }
42+ // Reserve a slot before crossing the asynchronous email boundary.
43+ reservation = rateLimitService . tryAcquire ( ) ;
6644
67- console . log ( "Contact form processed successfully" , {
68- messageId : result . messageId ,
69- timestamp : new Date ( ) . toISOString ( ) ,
70- } ) ;
45+ if ( reservation === null ) {
46+ throw new ActionError ( {
47+ code : "TOO_MANY_REQUESTS" ,
48+ message : "Daily email limit reached. Please try again tomorrow." ,
49+ } ) ;
50+ }
7151
72- // 3. Increment rate limit counter after successful email
73- await rateLimitService . incrementCount ( today ) ;
52+ // Keep the reservation when the email succeeds; release it in catch on failure.
53+ const emailData : EmailData = {
54+ firstName : input . firstName ,
55+ lastName : input . lastName ,
56+ email : input . email ,
57+ subject : input . subject ,
58+ message : input . message ,
59+ ...( input . company && { company : input . company } ) ,
60+ ...( input . phone && { phone : input . phone } ) ,
61+ } ;
7462
75- return {
76- success : true ,
77- } as const ;
63+ const result = await emailService . sendEmail ( emailData ) ;
7864
79- } catch ( error ) {
80- console . error ( "Unexpected error during email sending:" , {
81- error : error instanceof Error ? error . message : "Unknown error" ,
82- timestamp : new Date ( ) . toISOString ( ) ,
83- } ) ;
65+ if ( ! result . success ) {
66+ console . error ( "Email sending failed:" , result . error ) ;
67+ throw new ActionError ( {
68+ code : "BAD_REQUEST" ,
69+ message : "Email service unavailable. Please try again later." ,
70+ } ) ;
71+ }
8472
85- /* Re-throw ActionErrors as-is */
86- if ( error instanceof ActionError ) {
87- throw error ;
88- }
73+ console . log ( "Contact form processed successfully" , {
74+ messageId : result . messageId ,
75+ timestamp : new Date ( ) . toISOString ( ) ,
76+ } ) ;
8977
90- /* Convert unexpected errors to ActionError */
91- throw new ActionError ( {
92- code : "INTERNAL_SERVER_ERROR" ,
93- message : "An unexpected error occurred. Please try again later."
94- } ) ;
95- }
78+ return {
79+ success : true ,
80+ } as const ;
81+ } catch ( error ) {
82+ console . error ( "Unexpected error during email sending:" , {
83+ error : error instanceof Error ? error . message : "Unknown error" ,
84+ timestamp : new Date ( ) . toISOString ( ) ,
85+ } ) ;
86+
87+ if ( reservation !== null ) {
88+ rateLimitService ?. release ( reservation ) ;
89+ reservation = null ;
90+ }
91+
92+ /* Re-throw ActionErrors as-is */
93+ if ( error instanceof ActionError ) {
94+ throw error ;
95+ }
96+
97+ /* Convert unexpected errors to ActionError */
98+ throw new ActionError ( {
99+ code : "INTERNAL_SERVER_ERROR" ,
100+ message : "An unexpected error occurred. Please try again later." ,
101+ } ) ;
96102 }
97- } ) ;
103+ } ,
104+ } ) ;
0 commit comments