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
19 changes: 19 additions & 0 deletions examples/leaderboard.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use anyhow::{Result, bail};
use jiff::Zoned;
use job_watcher::axum::{Router, extract::State, routing::get};
use job_watcher::{
AppBuilder, Heartbeat, TaskLabel, WatchedTask, WatchedTaskOutput, WatcherAppContext,
config::{Delay, TaskConfig, WatcherConfig},
Expand Down Expand Up @@ -83,6 +84,24 @@ impl WatcherAppContext for DummyApp {
fn title(&self) -> String {
"Example application Status".to_owned()
}

fn extend_router<S>(&self, router: Router<S>) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
let custom_router = Router::new()
.route("/", get(hello_handler))
.with_state(HelloState(self.0.clone()));

router.nest_service("/hello", custom_router)
}
}

#[derive(Clone)]
struct HelloState(Zoned);

async fn hello_handler(State(state): State<HelloState>) -> String {
format!("Hello from custom route! App live since {}", state.0)
}

impl WatchedTask<DummyApp> for LeaderBoard {
Expand Down
29 changes: 16 additions & 13 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::defaults;
use std::collections::HashMap;

#[derive(serde::Deserialize, serde::Serialize, Clone, Copy, Debug)]
Expand All @@ -13,38 +12,42 @@ pub enum Delay {
#[derive(serde::Deserialize, serde::Serialize, Clone, Copy, Debug)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct TaskConfig {
/// Delay between runs
/// Delay between successful task executions.
pub delay: Delay,
/// How many seconds before we should consider the result out of date
/// Number of seconds a task can run before it is considered "out of date".
///
/// This does not include the delay time
/// If a task's execution time exceeds this value, its status will be flagged
/// accordingly. This is useful for monitoring tasks that might be stuck.
///
/// Setting this also enables a hard timeout on task execution. If a task
/// runs for longer than `MAX_TASK_SECONDS` (180 seconds), it will be
/// cancelled.
pub out_of_date: Option<u32>,
/// How many times to retry before giving up, overriding the general watcher
/// config
/// Number of times to retry a failing task before giving up.
///
/// This overrides the global `retries` setting in `WatcherConfig`.
pub retries: Option<usize>,
/// How many seconds to delay between retries, overriding the general
/// watcher config
/// Delay in seconds between retries of a failing task.
///
/// This overrides the global `delay_between_retries` setting in `WatcherConfig`.
pub delay_between_retries: Option<u32>,
}

#[derive(serde::Deserialize, serde::Serialize, Clone, Debug)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct WatcherConfig {
/// How many times to retry before giving up
#[serde(default = "defaults::retries")]
pub retries: usize,
/// How many seconds to delay between retries
#[serde(default = "defaults::delay_between_retries")]
pub delay_between_retries: u32,
#[serde(default)]
pub tasks: HashMap<String, TaskConfig>,
}

impl Default for WatcherConfig {
fn default() -> Self {
Self {
retries: defaults::retries(),
delay_between_retries: defaults::delay_between_retries(),
retries: 6,
delay_between_retries: 20,
tasks: Default::default(),
}
}
Expand Down
7 changes: 0 additions & 7 deletions src/defaults.rs

This file was deleted.

8 changes: 7 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
mod rest_api;

pub mod config;
mod defaults;

use anyhow::{Context, Result};
pub use axum;
use axum::{
Json,
http::{self, HeaderValue},
Expand All @@ -45,6 +45,12 @@ pub trait WatcherAppContext {
fn watcher_config(&self) -> WatcherConfig;
fn triggers_alert(&self, label: &TaskLabel, selected_label: Option<&TaskLabel>) -> bool;
fn show_output(&self, label: &TaskLabel) -> bool;
fn extend_router<S>(&self, router: axum::Router<S>) -> axum::Router<S>
where
S: Clone + Send + Sync + 'static,
{
router
}
}

#[derive(
Expand Down
23 changes: 15 additions & 8 deletions src/rest_api.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::{convert::Infallible, sync::Arc};
use std::{convert::Infallible, sync::Arc, time::Duration};

use anyhow::Result;
use axum::{
extract::{Path, State},
http::{self, HeaderMap, header},
http::{self, HeaderMap, StatusCode, header},
response::IntoResponse,
routing::get,
};
Expand All @@ -12,6 +12,7 @@ use tower::ServiceBuilder;
use tower_http::{
cors::CorsLayer,
limit::RequestBodyLimitLayer,
timeout::TimeoutLayer,
trace::{self, TraceLayer},
};
use tracing::Level;
Expand Down Expand Up @@ -40,9 +41,10 @@ pub(crate) async fn start_rest_api<C: WatcherAppContext + Send + Sync + Clone +
.on_response(trace::DefaultOnResponse::new().level(Level::INFO)),
)
.layer(RequestBodyLimitLayer::new(1_024_000))
// .layer(TimeoutLayer::new(std::time::Duration::from_secs(
// 5
// )))
.layer(TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(3),
))
.layer(
CorsLayer::new()
.allow_origin(tower_http::cors::Any)
Expand All @@ -54,9 +56,14 @@ pub(crate) async fn start_rest_api<C: WatcherAppContext + Send + Sync + Clone +
.route("/", get(homepage))
.route("/healthz", get(healthz))
.route("/status/{*label}", get(status::single))
.route("/status", get(status::all))
.layer(service_builder)
.with_state(RestApp { app, statuses });
.route("/status", get(status::all));

let router = app.extend_router(router);

let router = router.layer(service_builder).with_state(RestApp {
app: app.clone(),
statuses,
});

tracing::info!("Launching server");

Expand Down