Files
playlistd/src/daemon/create_playlists.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

102 lines
3.0 KiB
Rust

use crate::models::CreateTrackedPlaylist;
use crate::subsonic::Subsonic;
use crate::CONFIG;
use chrono::Local;
use sqlx::postgres::PgPool;
use std::time::Duration;
use tokio::time::{interval, MissedTickBehavior};
use uuid::Uuid;
pub async fn create_playlists_daemon(
media_client: impl AsRef<Subsonic> + Clone,
) -> Result<(), Box<dyn std::error::Error>> {
log::info!("Playlist rule daemon starting");
let database = PgPool::connect(
CONFIG
.get()
.unwrap()
.get::<String>("database.url")?
.as_str(),
)
.await
.unwrap();
let mut ticker = interval(Duration::from_secs(
CONFIG.get().unwrap().get::<u64>("daemon.interval")?,
));
ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut failures = super::Failures::default();
loop {
// the first tick completes straight away
ticker.tick().await;
let records_res = sqlx::query_as!(
CreateTrackedPlaylist,
r#"SELECT * FROM "create_tracked_playlist""#
)
.fetch_all(&database)
.await;
match records_res {
Ok(records) => {
for record in records {
let key = record.id.to_string();
let about = format!("playlist rule {:?}", record.name_template);
match create_playlist(media_client.clone(), record, database.clone()).await {
Ok(()) => failures.succeeded(&key, &about),
Err(e) => failures.failed(&key, format!("Could not run {}: {}", about, e)),
}
}
}
Err(e) => {
log::error!("Could not fetch playlist rules: {}", e);
}
}
}
}
async fn create_playlist(
media_client: impl AsRef<Subsonic>,
playlist_rule: CreateTrackedPlaylist,
database: PgPool,
) -> Result<(), Box<dyn std::error::Error>> {
let now = Local::now();
let new_name = now.format(&playlist_rule.name_template).to_string();
if Some(&new_name) != playlist_rule.last_name.as_ref() {
log::info!("Creating playlist {:?}", new_name);
// Create playlist
let playlist = media_client.as_ref().create_playlist(&new_name).await?;
let uuid = Uuid::new_v4();
sqlx::query!(
r#"
INSERT INTO "tracked_playlist" (id, playlist_id, playlist_size, tracking_user, tracking_type)
VALUES ($1, $2, $3, $4, $5)
"#,
uuid,
playlist.id,
playlist_rule.playlist_size,
playlist_rule.tracking_user,
playlist_rule.tracking_type,
)
.execute(&database)
.await?;
sqlx::query!(
r#"
UPDATE "create_tracked_playlist" SET last_name = $1 WHERE id = $2
"#,
new_name,
playlist_rule.id,
)
.execute(&database)
.await?;
}
Ok(())
}