Files
sorsfonalak/services/worker/src/config.rs
T
fecoandClaude Opus 5.5 2a0830fda0
CI / test (push) Successful in 1m29s
CI / build (push) Successful in 9m7s
CI / deploy (push) Skipped
Invoices: issued in Billingo by the worker, downloadable on Számláim
A paid checkout queues an invoice row with every invoice detail (buyer,
tax type and number, item, net, VAT, gross). The worker's new 'invoices'
task creates the Billingo partner and the paid card invoice and e-mails
it (API v3), saving each step so a retry never issues a second invoice,
and keeps Billingo's whole answer; the PDF is fetched from Billingo when
the user downloads it from the new Számláim page (in the menu once there
is an invoice). Payments and invoices outlive a deleted account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-20 07:52:34 +00:00

129 lines
5.6 KiB
Rust

//! Configuration from environment variables.
use std::time::Duration;
use anyhow::Context;
use lettre::message::Mailbox;
/// The jobs a worker process runs (`WORKER_TASKS`, comma-separated).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tasks {
/// Sending the e-mails of `email_outbox`.
pub email: bool,
/// The hourly removal of expired data.
pub cleanup: bool,
/// Writing the analyses and answers with the LLM (both lanes).
pub analyses: bool,
/// Issuing the invoices of the payments in Billingo.
pub invoices: bool,
}
impl Tasks {
pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true, invoices: true };
const NONE: Tasks = Tasks { email: false, cleanup: false, analyses: false, invoices: false };
pub fn parse(raw: &str) -> anyhow::Result<Self> {
let mut tasks = Self::NONE;
for name in raw.split(',').map(str::trim).filter(|n| !n.is_empty()) {
match name {
"email" => tasks.email = true,
"cleanup" => tasks.cleanup = true,
"analyses" => tasks.analyses = true,
"invoices" => tasks.invoices = true,
other => anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices)"),
}
}
anyhow::ensure!(tasks != Self::NONE, "WORKER_TASKS names no task");
Ok(tasks)
}
}
pub struct Config {
/// What this process does; all of it by default.
pub tasks: Tasks,
pub database_url: String,
/// `smtp://host:port` (plain, e.g. Mailpit), `smtp://user:pass@host:587?tls=required`
/// (STARTTLS) or `smtps://...` (TLS). Without it, Amazon SES from the AWS
/// variables (see `ses.rs`). Neither: e-mails stay in the outbox.
pub smtp_url: Option<String>,
/// For the log: where the SMTP address came from (no secrets).
pub smtp_about: Option<String>,
/// Sender, e.g. `Sorsfonalak <noreply@sorsfonalak.hu>`.
pub mail_from: Mailbox,
/// Fallback polling interval; new e-mails are picked up at once via LISTEN/NOTIFY.
pub poll_interval: Duration,
/// After this many failed attempts an e-mail is marked as failed.
pub max_email_attempts: i32,
/// Unset: analyses stay pending.
pub openrouter_api_key: Option<String>,
pub openrouter_base_url: String,
/// Frontend address, sent to OpenRouter as `HTTP-Referer`.
pub public_base_url: Option<String>,
/// Detailed analyses and forecasts written at the same time (0: none).
pub analysis_concurrency: usize,
/// Summaries and answers written at the same time (0: none).
pub quick_concurrency: usize,
/// After this many failed attempts an analysis fails and is refunded.
pub max_analysis_attempts: i32,
/// `BILLINGO_API_KEY`; unset: invoices stay pending.
pub billingo_api_key: Option<String>,
/// `BILLINGO_API_URL` (default `https://api.billingo.hu/v3`).
pub billingo_api_url: String,
/// `BILLINGO_BLOCK_ID`: the invoice pad (default: the account's first one).
pub billingo_block_id: Option<i64>,
/// `MAX_INVOICE_ATTEMPTS` (default 10, about a day with the backoff):
/// then the invoice is marked failed for an admin.
pub max_invoice_attempts: i32,
}
fn var(name: &str) -> Option<String> {
std::env::var(name).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())
}
fn parsed<T: std::str::FromStr>(name: &str, default: T) -> anyhow::Result<T>
where
T::Err: std::fmt::Display,
{
match var(name) {
Some(raw) => raw.parse().map_err(|e| anyhow::anyhow!("invalid {name} '{raw}': {e}")),
None => Ok(default),
}
}
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
let mail_from = var("MAIL_FROM").unwrap_or_else(|| "Sorsfonalak <noreply@sorsfonalak.local>".into());
let (smtp_url, smtp_about) = match var("SMTP_URL") {
Some(url) => (Some(url), None),
None => match crate::ses::smtp_url(|name| std::env::var(name).ok())? {
Some((url, about)) => (Some(url), Some(about)),
None => (None, None),
},
};
Ok(Self {
tasks: var("WORKER_TASKS").map(|raw| Tasks::parse(&raw)).transpose()?.unwrap_or(Tasks::ALL),
database_url: var("DATABASE_URL").context("DATABASE_URL is required")?,
smtp_url,
smtp_about,
mail_from: mail_from.parse().with_context(|| format!("invalid MAIL_FROM '{mail_from}'"))?,
poll_interval: Duration::from_secs(parsed("POLL_INTERVAL_SECS", 30)?),
max_email_attempts: parsed("MAX_EMAIL_ATTEMPTS", 8)?,
// The lower-case name is accepted too (as written in some secrets files).
openrouter_api_key: var("OPENROUTER_API_KEY").or_else(|| var("openrouter_api_key")),
openrouter_base_url: var("OPENROUTER_BASE_URL")
.unwrap_or_else(|| crate::analysis::openrouter::DEFAULT_BASE_URL.into()),
public_base_url: var("PUBLIC_BASE_URL"),
analysis_concurrency: parsed("ANALYSIS_CONCURRENCY", 4)?,
quick_concurrency: parsed("QUICK_CONCURRENCY", 2)?,
max_analysis_attempts: parsed("MAX_ANALYSIS_ATTEMPTS", 3)?,
billingo_api_key: var("BILLINGO_API_KEY"),
billingo_api_url: var("BILLINGO_API_URL").unwrap_or_else(|| crate::invoices::DEFAULT_BASE_URL.into()),
billingo_block_id: var("BILLINGO_BLOCK_ID")
.map(|v| v.parse())
.transpose()
.context("invalid BILLINGO_BLOCK_ID")?,
max_invoice_attempts: parsed("MAX_INVOICE_ATTEMPTS", 10)?,
})
}
}