const DAILY_LIMIT = 1000 ; import { pii_retention_to_future } from "@cocalc/database/postgres/pii" ; import getPool from "@cocalc/database/pool" ; import { getServerSettings } from "@cocalc/server/settings" ; export default async function sendEmailThrottle ( id ? ) { if ( ! id ) return ; const day = startOfToday ( ) ; const pool = getPool ( "short" ) ; const { rows } = await pool . query ( "SELECT count FROM email_counter WHERE time=$1 AND id=$2" , [ day , id ] ) ; if ( rows . length > 0 && rows [ 0 ] . count > DAILY_LIMIT ) { throw Error ( `You may send at most ${ DAILY_LIMIT } emails per day, and you have reached that limit.` ) ; } if ( rows . length > 0 ) { await pool . query ( "UPDATE email_counter SET count = count + 1 WHERE id=$1 AND time=$2" , [ id , day ] ) ; } else { const settings = await getServerSettings ( ) ; const expire = pii_retention_to_future ( settings . pii_retention ?? false ) ; await pool . query ( "INSERT INTO email_counter (id,time,count,expire) VALUES($1,$2,1,$3) ON CONFLICT (id, time) DO UPDATE SET count = excluded.count + 1" , [ id , day , expire ] ) ; } } function startOfToday ( ) { const now = new Date ( ) ; return new Date ( now . getFullYear ( ) , now . getMonth ( ) , now . getDate ( ) ) ; }