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
6 changes: 6 additions & 0 deletions app/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,12 @@ VISUALCI_STRIPE_WEBHOOK_SECRET=
# Secret. The groups check's token.
# VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN=

# The daily reminder to organizations whose credit override ends within a week.
# VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_URL=

# Secret. The credit override reminder's token.
# VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_TOKEN=

######################################################################################################################
# Laravel Rust
######################################################################################################################
Expand Down
50 changes: 50 additions & 0 deletions app/database/migrations/2026_12_04_100000_credit_overrides.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//! Per-organization credit overrides (sc-8900): staff raise an organization's monthly credits for a while, such as a
//! big open source project that needs more than the standard pool (`domain::credit_overrides`).
//!
//! `credit_overrides` holds at most one override per organization. It applies through `until` (a UTC date, inclusive)
//! and is read at the time it's needed, so once that day is over the organization is back on its plan's allowance
//! with nothing to run. `label` is what the organization's billing page shows ("Open source sponsorship"); `reason` is
//! staff's own note and isn't shown to customers. Clearing one deletes the row.
//!
//! `credit_override_audit` is every change, for staff: who made it (a user, or `console`), the monthly allowance
//! before and after, the override set (none when it was cleared) and the reason.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(SCHEMA).unprepared().await?;
Ok(())
}

const SCHEMA: &str = r#"
CREATE TABLE credit_overrides (
organization_id BIGINT PRIMARY KEY REFERENCES organizations(id) ON DELETE CASCADE,
-- The monthly allowance while it applies, in place of the plan's.
credits BIGINT NOT NULL CHECK (credits > 0),
-- The last day it applies (UTC).
until DATE NOT NULL,
label TEXT NOT NULL,
reason TEXT NOT NULL,
set_by BIGINT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX credit_overrides_until ON credit_overrides (until);

CREATE TABLE credit_override_audit (
id BIGSERIAL PRIMARY KEY,
organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
-- Who: a staff member's email, or `console`.
actor TEXT NOT NULL,
old_allowance BIGINT NOT NULL,
new_allowance BIGINT NOT NULL,
-- The override set; all NULL when it was cleared.
credits BIGINT,
until DATE,
label TEXT,
reason TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX credit_override_audit_organization ON credit_override_audit (organization_id, created_at);
"#;
6 changes: 6 additions & 0 deletions app/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,12 @@ pub struct Heartbeats {
/// The groups check's token.
#[env("VISUALCI_GROUPS_CHECK_HEARTBEAT_TOKEN", secret)]
pub groups_check_token: Option<String>,
/// The daily reminder to organizations whose credit override ends within a week.
#[env("VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_URL")]
pub credit_overrides_url: Option<String>,
/// The credit override reminder's token.
#[env("VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_TOKEN", secret)]
pub credit_overrides_token: Option<String>,
}

/// The variables Laravel Rust reads itself. VisualCI keeps the framework's names for them.
Expand Down
92 changes: 92 additions & 0 deletions app/src/console/credits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
//! Credit overrides from the console (`domain::credit_overrides`): `org:set-credits` for staff, and the daily
//! reminder the schedule runs.

use laravel::console::{Console, clap, command};
use laravel::time::civil::Date;

use super::heartbeat;
use crate::domain::credit_overrides::{self, Actor, Change};

/// `org:set-credits`: raise an organization's monthly credits until a date, or end that now (`--clear`). Recorded in
/// `credit_override_audit` as `console`, with the reason. Setting the same values again records it again and changes
/// nothing else.
///
/// `visualci-app org:set-credits --org acme --credits 3000000 --until 2027-06-01 --label "Open source sponsorship"
/// --reason "big open source project, agreed with marketing"`
#[derive(clap::Parser)]
#[command(name = "org:set-credits")]
pub struct OrgSetCredits {
/// The organization's slug.
#[arg(long)]
org: String,
/// Credits a month while it applies, in place of the plan's (more than the plan's).
#[arg(long, required_unless_present = "clear", conflicts_with = "clear")]
credits: Option<i64>,
/// The last day it applies (UTC), YYYY-MM-DD; after today.
#[arg(long, required_unless_present = "clear", conflicts_with = "clear")]
until: Option<Date>,
/// What the organization's billing page shows, such as "Open source sponsorship".
#[arg(long, conflicts_with = "clear")]
label: Option<String>,
/// Why, for the audit log (not shown to the customer).
#[arg(long)]
reason: String,
/// End the override now: back to the plan's allowance.
#[arg(long)]
clear: bool,
}

#[command]
impl OrgSetCredits {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let outcome = match (self.clear, self.credits, self.until) {
(true, _, _) => credit_overrides::clear(&self.org, &self.reason, Actor::Console).await?,
(false, Some(credits), Some(until)) => {
let change =
Change { org: &self.org, credits, until, label: self.label.as_deref(), reason: &self.reason };
credit_overrides::set(change, Actor::Console).await?
}
_ => Err("give --credits and --until, or --clear".to_string()),
};
let answer = outcome.map_err(laravel::Error::msg)?;
let line = match answer["override"].as_object() {
Some(o) => format!(
"{}: {} credits a month until {} ({}), was {}",
answer["org"].as_str().unwrap_or_default(),
o["credits"],
o["until"].as_str().unwrap_or_default(),
o["label"].as_str().unwrap_or_default(),
answer["was"]["allowance"]
),
None => format!(
"{}: back to the plan's {} credits a month, was {}",
answer["org"].as_str().unwrap_or_default(),
answer["allowance"],
answer["was"]["allowance"]
),
};
console.line(line);
Ok(())
}
}

/// `credits:override-reminders`, daily: email the admins of organizations whose credit override ends within a week,
/// once per end date ([`credit_overrides::remind`]). Pushes its result to `VISUALCI_CREDIT_OVERRIDES_HEARTBEAT_URL`
/// (and `_TOKEN`): Gatus alerts on a failed run and on a day with no run.
#[derive(clap::Parser)]
#[command(name = "credits:override-reminders")]
pub struct OverrideReminders;

#[command]
impl OverrideReminders {
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
let outcome = credit_overrides::remind().await;
heartbeat::push(
heartbeat::Heartbeat::CreditOverrides,
outcome.as_ref().map(|_| ()).map_err(ToString::to_string),
)
.await;
console.line(format!("credits:override-reminders: queued {} emails", outcome?));
Ok(())
}
}
6 changes: 4 additions & 2 deletions app/src/console/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
//! The schedule (`laravel schedule:run` every minute, in production a CronJob): the builds sweep every five minutes;
//! retention, the groups check and the demo reset daily. Each run pushes its result to a heartbeat, so a task that
//! failed or stopped running alerts.
//! retention, the groups check, the demo reset and the credit override reminders daily. Each run pushes its result to
//! a heartbeat, so a task that failed or stopped running alerts.

use laravel::schedule::{self, Schedule};

// The heartbeat every scheduled task pushes to (`crate::heartbeat`).
pub use crate::heartbeat;
pub mod credits;
pub mod demo;
pub mod retention;
pub mod staff;
Expand All @@ -16,6 +17,7 @@ fn schedule(schedule: &mut Schedule) {
schedule.command("retention:prune").daily_at("03:00").without_overlapping().on_one_runner();
schedule.command("groups:check").daily_at("04:00").without_overlapping().on_one_runner();
schedule.command("demo:reset").name("demo-reset").daily_at("05:00").without_overlapping().on_one_runner();
schedule.command("credits:override-reminders").daily_at("06:00").without_overlapping().on_one_runner();
}

/// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL` and `_TOKEN`).
Expand Down
Loading
Loading