145 lines
4.8 KiB
TypeScript
145 lines
4.8 KiB
TypeScript
|
|
import { randomUUID } from "node:crypto";
|
|
|
|
import type { ApiKey } from "./api-key";
|
|
import { addressesOf } from "./address";
|
|
import { config } from "./config";
|
|
import { query, transaction } from "./db";
|
|
import type { NormalizedMail } from "./schema";
|
|
|
|
export class QuotaExceededError extends Error {
|
|
constructor(message = "Tageslimit erreicht") {
|
|
super(message);
|
|
this.name = "QuotaExceededError";
|
|
}
|
|
}
|
|
|
|
export class SuppressedError extends Error {
|
|
recipients: string[];
|
|
|
|
constructor(recipients: string[]) {
|
|
super(`Empfänger gesperrt: ${recipients.join(", ")}`);
|
|
this.name = "SuppressedError";
|
|
this.recipients = recipients;
|
|
}
|
|
}
|
|
|
|
export type StoredPayload = {
|
|
from: ReturnType<typeof payloadFrom>;
|
|
to: ReturnType<typeof payloadFrom>[];
|
|
cc: ReturnType<typeof payloadFrom>[];
|
|
bcc: ReturnType<typeof payloadFrom>[];
|
|
reply_to: ReturnType<typeof payloadFrom>[];
|
|
subject: string;
|
|
html?: string;
|
|
text?: string;
|
|
headers: Record<string, string>;
|
|
attachments: { filename: string; content: string; content_type?: string }[];
|
|
tags: { name: string; value: string }[];
|
|
};
|
|
|
|
function payloadFrom(mailbox: { address: string; name?: string }) {
|
|
return mailbox.name ? { address: mailbox.address, name: mailbox.name } : { address: mailbox.address };
|
|
}
|
|
|
|
export function storedPayload(mail: NormalizedMail): StoredPayload {
|
|
return {
|
|
from: payloadFrom(mail.from),
|
|
to: mail.to.map(payloadFrom),
|
|
cc: mail.cc.map(payloadFrom),
|
|
bcc: mail.bcc.map(payloadFrom),
|
|
reply_to: mail.replyTo.map(payloadFrom),
|
|
subject: mail.subject,
|
|
html: mail.html,
|
|
text: mail.text,
|
|
headers: mail.headers,
|
|
attachments: mail.attachments.map((item) => ({
|
|
filename: item.filename,
|
|
content: item.content.toString("base64"),
|
|
content_type: item.contentType,
|
|
})),
|
|
tags: mail.tags,
|
|
};
|
|
}
|
|
|
|
export async function enqueue(
|
|
apiKey: ApiKey,
|
|
mail: NormalizedMail,
|
|
idempotencyKey?: string | null,
|
|
): Promise<{ id: string; duplicate: boolean }> {
|
|
const recipients = addressesOf([...mail.to, ...mail.cc, ...mail.bcc]);
|
|
const { rows: suppressed } = await query<{ email: string }>(
|
|
`select email from suppressions where email = any($1::text[])`,
|
|
[recipients],
|
|
);
|
|
if (suppressed.length) throw new SuppressedError(suppressed.map((row) => row.email));
|
|
|
|
const payload = storedPayload(mail);
|
|
|
|
return transaction(async (client) => {
|
|
await client.query(`select pg_advisory_xact_lock(hashtext($1))`, [apiKey.id]);
|
|
|
|
if (idempotencyKey) {
|
|
const existing = await client.query<{ id: string }>(
|
|
`select id from messages where api_key_id = $1 and idempotency_key = $2`,
|
|
[apiKey.id, idempotencyKey],
|
|
);
|
|
if (existing.rows[0]) return { id: existing.rows[0].id, duplicate: true };
|
|
}
|
|
|
|
const usage = await client.query<{ key_daily: string; key_monthly: string; global_daily: string }>(
|
|
`select
|
|
count(*) filter (where api_key_id = $1 and created_at >= date_trunc('day', now())) as key_daily,
|
|
count(*) filter (where api_key_id = $1 and created_at >= date_trunc('month', now())) as key_monthly,
|
|
count(*) filter (where created_at >= date_trunc('day', now())) as global_daily
|
|
from messages`,
|
|
[apiKey.id],
|
|
);
|
|
const row = usage.rows[0];
|
|
if (Number(row?.key_daily ?? 0) >= apiKey.dailyLimit) {
|
|
throw new QuotaExceededError(`Tageslimit für ${apiKey.app} erreicht`);
|
|
}
|
|
if (Number(row?.key_monthly ?? 0) >= apiKey.monthlyLimit) {
|
|
throw new QuotaExceededError(`Monatslimit für ${apiKey.app} erreicht`);
|
|
}
|
|
if (Number(row?.global_daily ?? 0) >= config.globalDailyLimit) {
|
|
throw new QuotaExceededError("Globales Tageslimit erreicht");
|
|
}
|
|
|
|
const id = randomUUID();
|
|
const inserted = await client.query<{ id: string }>(
|
|
`insert into messages (
|
|
id, api_key_id, app, from_email, from_name, to_emails, cc_emails, bcc_emails,
|
|
reply_to, subject, status, payload, idempotency_key
|
|
) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'queued',$11,$12)
|
|
on conflict (api_key_id, idempotency_key) do nothing
|
|
returning id`,
|
|
[
|
|
id,
|
|
apiKey.id,
|
|
apiKey.app,
|
|
mail.from.address,
|
|
mail.from.name ?? null,
|
|
addressesOf(mail.to),
|
|
addressesOf(mail.cc),
|
|
addressesOf(mail.bcc),
|
|
addressesOf(mail.replyTo),
|
|
mail.subject,
|
|
payload,
|
|
idempotencyKey || null,
|
|
],
|
|
);
|
|
|
|
if (!inserted.rows[0] && idempotencyKey) {
|
|
const existing = await client.query<{ id: string }>(
|
|
`select id from messages where api_key_id = $1 and idempotency_key = $2`,
|
|
[apiKey.id, idempotencyKey],
|
|
);
|
|
return { id: existing.rows[0]?.id ?? id, duplicate: true };
|
|
}
|
|
|
|
await client.query(`select pg_notify('courier_queue', $1)`, [id]);
|
|
return { id: inserted.rows[0]?.id ?? id, duplicate: false };
|
|
});
|
|
}
|