Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions app/database/migrations/2026_12_03_000300_create_emails_table.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use laravel::db::AnyTransaction;

/// The emails outbox (ported as today's), and each person's email choices and sign-up notice.
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(
"CREATE TABLE emails (
id BIGSERIAL PRIMARY KEY,
kind TEXT NOT NULL,
dedupe_key TEXT NOT NULL UNIQUE,
organization_id BIGINT REFERENCES organizations(id) ON DELETE CASCADE,
user_id BIGINT REFERENCES users(id) ON DELETE CASCADE,
recipient TEXT NOT NULL,
data JSONB NOT NULL,
subject TEXT,
text_body TEXT,
html_body TEXT,
state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'sent', 'failed')),
attempts INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
claimed_at TIMESTAMPTZ,
sent_at TIMESTAMPTZ,
dismissed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX emails_pending ON emails (created_at) WHERE state = 'pending';
CREATE INDEX emails_organization ON emails (organization_id, created_at);
CREATE INDEX emails_failed ON emails (id) WHERE state = 'failed' AND dismissed_at IS NULL;
ALTER TABLE users
ADD COLUMN email_low_credits BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN email_receipts BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN signup_notified_at TIMESTAMPTZ;",
)
.unprepared()
.await?;
Ok(())
}
12 changes: 11 additions & 1 deletion app/src/auth/memberships.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ pub struct MembershipChanged {
pub organization_id: i64,
pub user_id: i64,
pub role: Option<Role>,
/// When the membership changed (milliseconds), fixed at dispatch: the notice's dedupe key, so a retried listener
/// doesn't send it twice.
pub changed_at: i64,
}

impl MembershipChanged {
#[must_use]
pub fn now(organization_id: i64, user_id: i64, role: Option<Role>) -> Self {
Self { organization_id, user_id, role, changed_at: laravel::now().timestamp().as_millisecond() }
}
}

#[derive(Debug)]
Expand Down Expand Up @@ -151,7 +161,7 @@ pub async fn apply(
})
.await?;
for (org, role) in &notices {
MembershipChanged { organization_id: *org, user_id, role: *role }.dispatch().await?;
MembershipChanged::now(*org, user_id, *role).dispatch().await?;
}
Ok(notices.len())
}
Expand Down
14 changes: 14 additions & 0 deletions app/src/billing/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//! Billing (sc-8900, the billing side; ported from today's server as it moves over). For now, the credit pack the
//! emails quote.

/// A pack of credits bought on top of a plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CreditPack {
pub credits: i64,
pub price_cents: i64,
/// Automatic packs buy one when the balance falls below this.
pub reload_below: i64,
}

/// One pack: 500,000 credits for $15, as today.
pub const CREDIT_PACK: CreditPack = CreditPack { credits: 500_000, price_cents: 1_500, reload_below: 100_000 };
24 changes: 24 additions & 0 deletions app/src/heartbeat.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//! Scheduled work pushes its result to a Gatus external endpoint when one is configured (`<PREFIX>_URL` and
//! `<PREFIX>_TOKEN`, such as `VISUALCI_EMAILS_HEARTBEAT_URL`), so a run that failed, or no run at all, alerts. Ported
//! from today's server.

use laravel::http::client;

/// Push a run's result. A failed push only logs: Gatus alerts on the missing heartbeat instead.
pub async fn push(prefix: &str, result: Result<(), String>) {
let Ok(url) = std::env::var(format!("{prefix}_URL")) else { return };
if url.is_empty() {
return;
}
let token = std::env::var(format!("{prefix}_TOKEN")).unwrap_or_default();
let (success, error) = match result {
Ok(()) => ("true", String::new()),
Err(e) => ("false", e),
};
let sent = client::post(url).token(token).query([("success", success), ("error", error.as_str())]).await;
match sent {
Ok(response) if response.successful() => {}
Ok(response) => tracing::warn!(prefix, status = %response.status(), "heartbeat refused"),
Err(e) => tracing::warn!(prefix, error = %e, "heartbeat failed"),
}
}
3 changes: 3 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
//! VisualCI's server on Laravel Rust. Who owns which module, and the seams between them, are in sc-8900.

pub mod auth;
pub mod billing;
pub mod config;
pub mod domain;
pub mod forge;
pub mod heartbeat;
pub mod http;
pub mod listeners;
pub mod models;
pub mod notify;
#[path = "../database/seeders/mod.rs"]
pub mod seeders;
pub mod storage;
Expand Down
30 changes: 30 additions & 0 deletions app/src/notify/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! Transactional emails (sc-8900, the emails side), ported from today's server. Each email is rendered from a
//! [`Kind`], recorded in the `emails` outbox under a `dedupe_key` that names the event and its period (so a threshold
//! emails once a month, an invoice once), and sent through Postmark by [`DeliverEmails`]: queued right after an email
//! is, and scheduled every five minutes for anything left over. A failed send stays pending and is retried; after five
//! attempts it's marked failed for staff to retry or dismiss. Billing emails go to an organization's billing email, or
//! else its admins; security emails go to the person concerned. People can turn off low-credit warnings and
//! receipt-style emails; security, billing problems and running out can't be.

pub mod outbox;
pub mod postmark;
pub mod render;

pub use outbox::{DeliverEmails, To, queue};
pub use render::{About, Kind, Paused, Preference, Rendered, render};

use laravel::event::{Event, listener};

use crate::auth::memberships::MembershipChanged;

/// Someone joined an organization or left it: tell them.
#[listener]
pub async fn membership_changed(event: Event<MembershipChanged>) -> laravel::Result<()> {
let kind = match event.role {
Some(role) => Kind::AddedToOrg { role: role.as_str().to_string() },
None => Kind::RemovedFromOrg,
};
let key = format!("{}:{}:{}:{}", kind.name(), event.organization_id, event.user_id, event.changed_at);
queue(&kind, To::User(event.user_id), Some(event.organization_id), &key).await?;
Ok(())
}
Loading
Loading