constnow=Math.floor(Date.now()/1000);constrow=db.prepare("SELECT reset_at FROM rate_limits WHERE bucket=?").get(bucket)as{reset_at: number}|undefined;
if(row&&row.reset_at>now)returnfalse;
db.prepare("INSERT INTO rate_limits(bucket,count,reset_at) VALUES(?,1,?) ON CONFLICT(bucket) DO UPDATE SET count=count+1,reset_at=excluded.reset_at").run(bucket,now+seconds);returntrue;
constcandidate=db.prepare("SELECT id FROM alert_deliveries WHERE status='queued' AND run_after<=CURRENT_TIMESTAMP ORDER BY id LIMIT 1").get()as{id: number}|undefined;
if(!candidate)returnfalse;
constclaimed=db.prepare("UPDATE alert_deliveries SET status='running',attempts=attempts+1,started_at=CURRENT_TIMESTAMP WHERE id=? AND status='queued'").run(candidate.id);
if(!claimed.changes)returnfalse;
constalert=db.prepare("SELECT id,title,message,attempts FROM alert_deliveries WHERE id=?").get(candidate.id)asAlert;
consturl=process.env.ALERT_WEBHOOK_URL?.trim();
try{
if(!url)thrownewError("ALERT_WEBHOOK_URL is not configured");
consttarget=newURL(url);
if(target.protocol!=="https:")thrownewError("Alert webhook must use HTTPS");
db.prepare("UPDATE alert_deliveries SET status=?,last_error=?,finished_at=CASE WHEN ? THEN CURRENT_TIMESTAMP ELSE NULL END,run_after=CASE WHEN ? THEN run_after ELSE datetime('now', ?) END WHERE id=?").run(exhausted?"failed":"queued",message,exhausted?1 : 0,exhausted?1 : 0,`+${delayMinutes} minutes`,alert.id);