aboutsummaryrefslogtreecommitdiffstats
path: root/feedsd/src/main.rs
blob: 1bb3c5060da2a4afa74471f73a9f76735e3299a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// -*- coding: utf-8 -*-
//
// Copyright (C) 2024 Michael Büsch <m@bues.ch>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-2.0-or-later

#![forbid(unsafe_code)]

mod refresh;
mod systemd;

use crate::{refresh::refresh_feeds, systemd::systemd_notify_ready};
use anyhow::{self as ah, format_err as err, Context as _};
use clap::Parser;
use feedsdb::{Db, DEBUG};
use std::{fs::OpenOptions, io::Write as _, num::NonZeroUsize, sync::Arc, time::Duration};
use tokio::{
    runtime,
    signal::unix::{signal, SignalKind},
    sync, task,
};

/// Create the PID-file in the /run subdirectory.
fn make_pidfile() -> ah::Result<()> {
    OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open("/run/feedsd/feedsd.pid")
        .context("Open PID-file")?
        .write_all(format!("{}\n", std::process::id()).as_bytes())
        .context("Write to PID-file")
}

#[derive(Parser, Debug, Clone)]
struct Opts {
    /// The name of the database to use.
    #[arg(long, default_value = "feeds")]
    db: String,

    /// Set the number async worker threads.
    #[arg(long, default_value = "4")]
    worker_threads: NonZeroUsize,

    /// Feed refresh interval, in seconds.
    #[arg(long, default_value = "600")]
    refresh_interval: u64,

    /// Do not create `/run/feedsd/feedsd.pid`.
    #[arg(long)]
    no_pidfile: bool,
}

impl Opts {
    pub fn refresh_interval(&self) -> Duration {
        Duration::from_secs(self.refresh_interval)
    }
}

#[must_use]
async fn do_refresh(db: Arc<Db>, opts: &Opts) -> (bool, Duration) {
    if DEBUG {
        eprintln!("Refreshing...");
    }
    match refresh_feeds(db, opts.refresh_interval()).await {
        Err(e) => {
            eprintln!("ERROR: {e:?}");
            (false, Duration::from_secs(60))
        }
        Ok(sleep_dur) => {
            if DEBUG {
                eprintln!("Refreshed. Sleeping {sleep_dur:?}.");
            }
            (true, sleep_dur)
        }
    }
}

async fn async_main(opts: Opts) -> ah::Result<()> {
    let opts = Arc::new(opts);

    // Create pid-file in /run.
    if !opts.no_pidfile {
        make_pidfile()?;
    }

    // Register unix signal handlers.
    let mut sigterm = signal(SignalKind::terminate()).unwrap();
    let mut sigint = signal(SignalKind::interrupt()).unwrap();
    let mut sighup = signal(SignalKind::hangup()).unwrap();

    // Create async IPC channels.
    let (exit_sock_tx, mut exit_sock_rx) = sync::mpsc::channel(1);

    // Create the database access object.
    let db = Arc::new(Db::new(&opts.db).await.context("Database")?);

    // Initialize the database, if not already done.
    db.open()
        .await
        .context("Open database")?
        .init()
        .await
        .context("Initialize database")?;

    // Ready-signal to systemd.
    systemd_notify_ready().context("Notify systemd")?;

    // Vacuum the database.
    db.open()
        .await
        .context("Open database")?
        .vacuum()
        .await
        .context("Vacuum database")?;

    // Task: DB refresher.
    task::spawn({
        let db = Arc::clone(&db);
        let opts = Arc::clone(&opts);

        async move {
            let mut err_count = 0_u32;
            loop {
                let (ok, sleep_dur) = do_refresh(Arc::clone(&db), &opts).await;
                if ok {
                    err_count = err_count.saturating_sub(1);
                } else {
                    err_count = err_count.saturating_add(3);
                    if err_count >= 9 {
                        let e = Err(err!("Too many errors. Bailing to systemd."));
                        let _ = exit_sock_tx.send(e).await;
                        break;
                    }
                }
                tokio::time::sleep(sleep_dur).await;
            }
        }
    });

    // Task: Main loop.
    let exitcode;
    loop {
        tokio::select! {
            _ = sigterm.recv() => {
                eprintln!("SIGTERM: Terminating.");
                exitcode = Ok(());
                break;
            }
            _ = sigint.recv() => {
                exitcode = Err(err!("Interrupted by SIGINT."));
                break;
            }
            _ = sighup.recv() => {
                println!("SIGHUP: Triggering database refresh.");
                let _ = do_refresh(Arc::clone(&db), &opts).await;
            }
            code = exit_sock_rx.recv() => {
                exitcode = code.unwrap_or_else(|| Err(err!("Unknown error code.")));
                break;
            }
        }
    }
    exitcode
}

fn main() -> ah::Result<()> {
    let opts = Opts::parse();

    runtime::Builder::new_multi_thread()
        .worker_threads(opts.worker_threads.into())
        .max_blocking_threads(opts.worker_threads.into()) // one blocking per worker.
        .thread_keep_alive(Duration::from_secs(10))
        .enable_all()
        .build()
        .context("Tokio runtime builder")?
        .block_on(async_main(opts))
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface