Files
playlistd/src/main.rs
T
Claude a594c56abc Set up logging properly
Rocket's logger was the only one, so messages from the daemons depended on
it having launched, and most messages bypassed logging with println!.

- Install env_logger at startup: level from log.level (LOG_LEVEL), with
  RUST_LOG overriding it. Rocket's per-request logs and sqlx's Postgres
  notices are kept to warnings.
- Under systemd, prefix lines with their syslog priority so journald
  records levels (journalctl -p warning works).
- Replace every println! with a log macro at a fitting level.
- Recurring failures are a warning when they start or change, debug while
  they repeat, and an info message when they recover.
- Listenbrainz errors are readable: an unknown user is "Listenbrainz user
  "x" doesn't exist" rather than a JSON decode error, and a period without
  stats yet (204) leaves the playlist alone instead of failing to decode.
  The UI's Refresh shows the same messages.
- Warnings name the playlist or rule they're about.
- Songs missing from the library are debug output, not errors every tick.
- Daemons no longer run twice at startup (interval's first tick is
  immediate), and a failing playlist rule or daemon is logged instead of
  panicking the task.
- Subsonic errors display as messages rather than Debug output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p
2026-11-13 21:48:54 +00:00

290 lines
8.6 KiB
Rust

mod cluster;
mod daemon;
mod discover;
mod listenbrainz;
mod mix;
mod models;
mod playlist;
mod subsonic;
mod track;
mod tracked;
mod web;
mod youtube;
use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon};
use crate::models::{
ClusterMixRule, CreateTrackedPlaylist, PartialClusterMixRule, PartialCreateTrackedPlaylist,
PartialTrackedPlaylist, TrackedPlaylist,
};
use crate::subsonic::{Subsonic, SubsonicBuilder};
use config::Config;
use rocket::serde::json::{json, Json};
use rocket::{get, post, routes, serde::json::Value as JsonValue, State};
use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPool;
use std::sync::{Arc, OnceLock};
pub static CONFIG: OnceLock<Config> = OnceLock::new();
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
CONFIG
.set(
Config::builder()
.add_source(config::File::with_name("playlistd").required(false))
.add_source(config::Environment::default().separator("_"))
.build()
.unwrap(),
)
.unwrap();
init_logging(CONFIG.get().unwrap());
let database = PgPool::connect(
CONFIG
.get()
.unwrap()
.get::<String>("database.url")?
.as_str(),
)
.await?;
sqlx::migrate!().run(&database).await?;
let media_client = Arc::new(
SubsonicBuilder::new()
.base(CONFIG.get().unwrap().get::<String>("subsonic.base")?)
.username(CONFIG.get().unwrap().get::<String>("subsonic.username")?)
.password(CONFIG.get().unwrap().get::<String>("subsonic.password")?)
.build()?,
);
{
let _media_client = media_client.clone();
tokio::spawn(async move {
if let Err(e) = update_playlists_daemon(_media_client).await {
log::error!("Tracked playlist daemon stopped: {}", e);
}
});
}
{
let _media_client = media_client.clone();
tokio::spawn(async move {
if let Err(e) = create_playlists_daemon(_media_client).await {
log::error!("Playlist rule daemon stopped: {}", e);
}
});
}
{
let _media_client = media_client.clone();
tokio::spawn(async move {
if let Err(e) = cluster_mixes_daemon(_media_client).await {
log::error!("Cluster mix daemon stopped: {}", e);
}
});
}
let youtube = youtube::YouTube::new(
CONFIG
.get()
.unwrap()
.get::<String>("discover.ytdlp")
.unwrap_or_else(|_| "yt-dlp".to_string()),
);
let mut server = rocket::build()
.manage(media_client)
.manage(database)
.manage(youtube)
.mount("/api/discover", web::routes())
.mount("/api/tracked", tracked::routes())
.mount(
"/api/playlist",
routes![
create_tracking_playlist,
add_tracking_playlist,
all_playlists,
create_tracking_playlist_rule,
create_cluster_mix_rule,
all_cluster_mix_rules,
],
);
// the discover UI's built files (discover/dist)
if let Ok(ui) = CONFIG.get().unwrap().get::<String>("discover.ui") {
server = server.mount("/", rocket::fs::FileServer::from(ui));
}
server.launch().await?;
Ok(())
}
/// Log to stdout at `log.level` (default "info"). RUST_LOG overrides it, e.g.
/// `RUST_LOG=playlistd=debug,sqlx=info`.
fn init_logging(config: &Config) {
use log::LevelFilter;
use std::io::Write;
let configured = config.get::<String>("log.level").ok();
let level = configured
.as_deref()
.and_then(|l| l.parse::<LevelFilter>().ok())
.unwrap_or(LevelFilter::Info);
let mut builder = env_logger::Builder::new();
builder.filter_level(level);
// Rocket logs every request at info; keep its warnings and launch messages
builder.filter_module("rocket", level.min(LevelFilter::Warn));
// sqlx logs Postgres notices (e.g. from migrations) at info
builder.filter_module("sqlx", level.min(LevelFilter::Warn));
// libraries that are very chatty at debug
for module in ["hyper", "hyper_util", "reqwest", "rustls", "h2"] {
builder.filter_module(module, level.min(LevelFilter::Info));
}
builder.parse_env("RUST_LOG");
// Under systemd, tag lines with their priority so `journalctl -p warning` works.
// journald adds its own timestamps.
if std::env::var_os("JOURNAL_STREAM").is_some() {
builder.format(|buf, record| {
let priority = match record.level() {
log::Level::Error => 3,
log::Level::Warn => 4,
log::Level::Info => 6,
log::Level::Debug | log::Level::Trace => 7,
};
writeln!(buf, "<{}>{}: {}", priority, record.target(), record.args())
});
}
builder.init();
if let Some(configured) = configured {
if configured.parse::<LevelFilter>().is_err() {
log::warn!(
"Unknown log.level {:?}; use error, warn, info, debug or trace",
configured
);
}
}
}
#[derive(Serialize)]
struct JsonError {
error: String,
}
impl From<sqlx::Error> for JsonError {
fn from(value: sqlx::Error) -> Self {
Self {
error: value.to_string(),
}
}
}
impl From<uuid::Error> for JsonError {
fn from(value: uuid::Error) -> Self {
Self {
error: value.to_string(),
}
}
}
#[derive(Serialize)]
enum Response<T> {
Success(T),
Error(JsonError),
}
#[derive(Deserialize)]
pub struct CreatePlaylist {
pub playlist_name: String,
pub playlist_size: i32,
pub tracking_user: Option<String>,
pub tracking_type: Option<String>,
}
/// Create a new playlist and attach a tracker
#[post("/rule", data = "<create_playlist_rule>")]
async fn create_tracking_playlist_rule(
pool: &State<PgPool>,
create_playlist_rule: Json<PartialCreateTrackedPlaylist>,
) -> Json<Response<CreateTrackedPlaylist>> {
match create_playlist_rule.record(pool.inner()).await {
Ok(playlist) => Json(Response::Success(playlist)),
Err(e) => Json(Response::Error(e.into())),
}
}
/// Create a new playlist and attach a tracker
#[post("/create", data = "<create_playlist>")]
async fn create_tracking_playlist(
media_client: &State<Arc<Subsonic>>,
pool: &State<PgPool>,
create_playlist: Json<CreatePlaylist>,
) -> Json<Response<TrackedPlaylist>> {
match media_client
.create_playlist(create_playlist.playlist_name.clone())
.await
{
Ok(created_playlist) => {
let partial = PartialTrackedPlaylist {
playlist_id: created_playlist.id,
playlist_size: create_playlist.playlist_size,
tracking_user: create_playlist.tracking_user.clone(),
tracking_type: create_playlist.tracking_type.clone(),
};
match partial.record(pool.inner()).await {
Ok(playlist) => Json(Response::Success(playlist)),
Err(e) => Json(Response::Error(e.into())),
}
}
Err(_) => Json(Response::Error(JsonError {
error: "Couldn't create Subsonic playlist".to_string(),
})),
}
}
/// Add tracking to an existing playlist
#[post("/track", data = "<playlist>")]
async fn add_tracking_playlist(
pool: &State<PgPool>,
playlist: Json<PartialTrackedPlaylist>,
) -> Json<Response<TrackedPlaylist>> {
match playlist.record(pool.inner()).await {
Ok(playlist) => Json(Response::Success(playlist)),
Err(e) => Json(Response::Error(e.into())),
}
}
/// Get all tracked playlists
#[get("/")]
async fn all_playlists(pool: &State<PgPool>) -> JsonValue {
match TrackedPlaylist::all(pool.inner()).await {
Ok(playlists) => json!(playlists),
Err(_) => json!([]),
}
}
/// Create a rule that maintains genre mixes built from clustering a user's recent listens
#[post("/mix", data = "<rule>")]
async fn create_cluster_mix_rule(
pool: &State<PgPool>,
rule: Json<PartialClusterMixRule>,
) -> Json<Response<ClusterMixRule>> {
match rule.record(pool.inner()).await {
Ok(rule) => Json(Response::Success(rule)),
Err(e) => Json(Response::Error(e.into())),
}
}
/// Get all cluster mix rules
#[get("/mix")]
async fn all_cluster_mix_rules(pool: &State<PgPool>) -> JsonValue {
match ClusterMixRule::all(pool.inner()).await {
Ok(rules) => json!(rules),
Err(_) => json!([]),
}
}