|
| 1 | +use std::time::Duration; |
| 2 | + |
| 3 | +use async_trait::async_trait; |
| 4 | +use svc::policy::{Policy, Retry}; |
| 5 | +use svc::runservice::StandardService; |
| 6 | +use thiserror::Error; |
| 7 | + |
| 8 | +use svc::error::SvcResult; |
| 9 | +use svc::manager::ServiceManager; |
| 10 | +use svc::traits::{Service, ServiceState}; |
| 11 | + |
| 12 | +#[derive(Clone)] |
| 13 | +struct PolicyService { |
| 14 | + counter: u32, |
| 15 | +} |
| 16 | + |
| 17 | +#[derive(Error, Debug)] |
| 18 | +pub enum Error { |
| 19 | + #[error("Not done yet")] |
| 20 | + MoreToDo, |
| 21 | +} |
| 22 | + |
| 23 | +#[async_trait] |
| 24 | +impl Service for PolicyService { |
| 25 | + type Error = Error; |
| 26 | + |
| 27 | + async fn run(&mut self) -> Result<(), Error> { |
| 28 | + println!("Hello {}", self.counter); |
| 29 | + self.counter += 1; |
| 30 | + |
| 31 | + // returning an Err will invoke the policy for the Running state |
| 32 | + Err(Error::MoreToDo) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +#[tokio::main] |
| 37 | +async fn main() -> SvcResult<()> { |
| 38 | + const NAME: &str = "policy-service"; |
| 39 | + |
| 40 | + pretty_env_logger::formatted_builder() |
| 41 | + .filter_level(log::LevelFilter::Debug) |
| 42 | + .parse_default_env() |
| 43 | + .init(); |
| 44 | + |
| 45 | + let (mut client, future) = ServiceManager::spawn(); |
| 46 | + |
| 47 | + let svc = PolicyService { counter: 0 }; |
| 48 | + |
| 49 | + // Manually construct a ServiceRunner, and set a specific policy for |
| 50 | + // handling errors during .run() |
| 51 | + let svcr = StandardService::new(NAME, svc).with_run_policy( |
| 52 | + // Try up to 5 times, waiting 300ms between each attempt |
| 53 | + Policy::new() |
| 54 | + .with_retry(Retry::Limit(5)) |
| 55 | + .with_delay(Duration::from_millis(300)), |
| 56 | + ); |
| 57 | + |
| 58 | + let uuid = client.register(NAME, svcr).await?; |
| 59 | + client.start(uuid).await?; |
| 60 | + println!("main: service will attempt to run 5 times"); |
| 61 | + |
| 62 | + client.wait_for_start(uuid).await?; |
| 63 | + println!("main: service started"); |
| 64 | + |
| 65 | + client.wait_for_state(uuid, ServiceState::Failed).await?; |
| 66 | + client.shutdown().await?; |
| 67 | + future.await??; |
| 68 | + |
| 69 | + Ok(()) |
| 70 | +} |
0 commit comments