Skip to content

Commit 3decd22

Browse files
committed
refactor: enhance rate limiting logic and implement email slot reservations
1 parent 8e4458d commit 3decd22

5 files changed

Lines changed: 341 additions & 199 deletions

File tree

‎src/actions/sendMail.ts‎

Lines changed: 84 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -2,96 +2,103 @@ import { defineAction, ActionError } from "astro:actions";
22
import { z } from "astro:schema";
33
import { getEmailService } from "../services/emailService.js";
44
import { getRateLimitService } from "../services/rateLimitService.js";
5+
import type {
6+
RateLimitReservation,
7+
RateLimitService,
8+
} from "../services/rateLimitService.js";
59
import type { EmailData } from "../utils/email.js";
610

7-
// Define the success result type
11+
/** Result returned after a contact email has been sent successfully. */
812
type SendMailResult = {
9-
success: true;
13+
success: true;
1014
};
1115

16+
/** Validates contact data, reserves a slot, and sends the contact email. */
1217
export 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+
});

‎src/components/ContactForm.astro‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,8 @@ export interface ContactFormProps {
1212
const { lang, t } = Astro.props as ContactFormProps;
1313
1414
const rateLimitService = getRateLimitService();
15-
const today = rateLimitService.getSwissDate();
16-
let rateLimitReached = false;
17-
18-
try {
19-
const rateLimit = await rateLimitService.checkLimit(today);
20-
rateLimitReached = !rateLimit.allowed;
21-
} catch (error) {
22-
console.error("Failed to check rate limit on page load:", error);
23-
rateLimitReached = false;
24-
}
15+
const rateLimit = rateLimitService.getStatus();
16+
const rateLimitReached = !rateLimit.allowed;
2517
2618
const result = Astro.getActionResult(actions.sendMail);
2719

‎src/services/rateLimitService.ts‎

Lines changed: 85 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,50 @@
1+
/** Result of a read-only daily rate-limit status check. */
12
export interface RateLimitResult {
23
allowed: boolean;
34
currentCount: number;
45
maxLimit: number;
56
resetDate: string;
67
}
78

9+
/** Token representing one reserved email slot. */
10+
export interface RateLimitReservation {
11+
readonly date: string;
12+
}
13+
14+
/** Public operations exposed by the in-memory rate-limit service. */
815
export interface RateLimitService {
9-
checkLimit(date: string): Promise<RateLimitResult>;
10-
incrementCount(date: string): Promise<void>;
16+
tryAcquire(): RateLimitReservation | null;
17+
release(reservation: RateLimitReservation): void;
18+
getStatus(): RateLimitResult;
1119
getSwissDate(): string;
1220
}
1321

14-
const productionCounts = new Map<string, number>();
22+
interface RateLimitState {
23+
date: string | null;
24+
count: number;
25+
}
26+
27+
const productionState: RateLimitState = {
28+
date: null,
29+
count: 0,
30+
};
31+
32+
const activeReservations = new WeakSet<object>();
1533

1634
/**
17-
* Rate Limiting Service
18-
* Handles contact form submission limits per day
35+
* Provides a process-wide limit of ten successfully sent emails per Swiss
36+
* calendar day using synchronous in-memory reservations.
1937
*/
2038
export class ContactRateLimitService implements RateLimitService {
2139
private readonly maxDailyEmails = 10;
2240

41+
constructor(private readonly now: () => Date = () => new Date()) {}
42+
2343
/**
24-
* Get current date in Swiss timezone (YYYY-MM-DD)
44+
* Returns the current date in the Europe/Zurich timezone as YYYY-MM-DD.
2545
*/
2646
getSwissDate(): string {
27-
return new Date()
47+
return this.now()
2848
.toLocaleDateString("de-CH", {
2949
year: "numeric",
3050
month: "2-digit",
@@ -36,30 +56,74 @@ export class ContactRateLimitService implements RateLimitService {
3656
.join("-");
3757
}
3858

59+
private resetForCurrentDay(): string {
60+
const date = this.getSwissDate();
61+
62+
if (productionState.date !== date) {
63+
productionState.date = date;
64+
productionState.count = 0;
65+
}
66+
67+
return date;
68+
}
69+
3970
/**
40-
* Check if rate limit is exceeded for given date
71+
* Atomically reserves one daily email slot, or returns null at the limit.
4172
*/
42-
async checkLimit(date: string): Promise<RateLimitResult> {
43-
const currentCount = productionCounts.get(date) ?? 0;
73+
tryAcquire(): RateLimitReservation | null {
74+
const date = this.resetForCurrentDay();
4475

45-
return {
46-
allowed: currentCount < this.maxDailyEmails,
47-
currentCount,
48-
maxLimit: this.maxDailyEmails,
49-
resetDate: date,
50-
};
76+
if (productionState.count >= this.maxDailyEmails) {
77+
return null;
78+
}
79+
80+
productionState.count += 1;
81+
const reservation = { date };
82+
activeReservations.add(reservation);
83+
return reservation;
84+
}
85+
86+
/**
87+
* Releases a previously acquired reservation on the same calendar day.
88+
*/
89+
release(reservation: RateLimitReservation): void {
90+
if (!activeReservations.has(reservation)) {
91+
return;
92+
}
93+
94+
activeReservations.delete(reservation);
95+
this.resetForCurrentDay();
96+
97+
if (
98+
reservation.date === productionState.date &&
99+
productionState.count > 0
100+
) {
101+
productionState.count -= 1;
102+
}
51103
}
52104

53105
/**
54-
* Increment rate limit counter for successful email
106+
* Reads the current limit status without reserving a slot.
55107
*/
56-
async incrementCount(date: string): Promise<void> {
57-
const currentCount = productionCounts.get(date) ?? 0;
58-
productionCounts.set(date, currentCount + 1);
108+
getStatus(): RateLimitResult {
109+
const date = this.resetForCurrentDay();
110+
111+
return {
112+
allowed: productionState.count < this.maxDailyEmails,
113+
currentCount: productionState.count,
114+
maxLimit: this.maxDailyEmails,
115+
resetDate: date,
116+
};
59117
}
60118
}
61119

62-
// Factory function
120+
/** Resets shared rate-limit state for isolated tests. */
121+
export const resetRateLimitStateForTests = (): void => {
122+
productionState.date = null;
123+
productionState.count = 0;
124+
};
125+
126+
/** Creates a rate-limit service backed by shared process-level state. */
63127
export const getRateLimitService = (): RateLimitService => {
64128
return new ContactRateLimitService();
65129
};

0 commit comments

Comments
 (0)