⏲ Situwaition is a Rust utility library that waits for conditions

Overview

situwaition

situwaition runs a closure continuously, until an Ok(..) is received, or a timeout period elapses.

Install

cargo add situwaition                      # only sync waiting is enabled by default
cargo add situwaition --features async-std # use async-std
cargo add situwaition --features tokio     # use tokio

If you're editing Cargo.toml by hand:

[dependencies]
situwaition = "0.3"
#situwaition = { version = "0.3", features = [ "async-std" ] }
#situwaition = { version = "0.3", features = [ "tokio" ] }

Quickstart

Sync

To use situwaition in synchronous contexts:

use situwaition::wait_for;

// ...

    // Do some waiting
    let result = wait_for(|| {
        // Get the current value from the mutex
        if some_condition { Ok(value) } else { Err(SomeError) ]
    });

    // Act on the result
    match result {
        Ok(v) => { ... }
        Err(SituwaitionError::TimeoutError(e)) => { ... }
    }

// ...

situwaition will run the function continuously, ignoring Error(..) responses until:

  • The function resolves to an Ok(..) variant
  • The configured timeout (3s by default, checking every 250ms) is reached.

See a full example in examples/sync.rs. To run the sync example:

cargo run --example sync

Tokio

If you're using tokio, then your code looks like this:

use situwaition::runtime::tokio::wait_for;

// ...

    // Do some waiting
    let result = wait_for(|| async {
        // Get the current value from the mutex
        if some_condition { Ok(value) } else { Err(SomeError) ]
    });

    // Act on the result
    match result {
        Ok(v) => { ... }
        Err(SituwaitionError::TimeoutError(e)) => { ... }
    }

// ...

Note here that you are passing a Future factory to the function -- a function/closure (|| { ... }) that outputs a Future (async { .. }).

The usual async usage rules apply -- use move, Arcs, Mutexes, and other ownership/synchronization primitives where appropriate.

See a full example in examples/tokio.rs. To run the tokio example:

cargo run --example tokio --features=tokio

async-std

If you're using async-std, then your code looks like this:

use situwaition::runtime::tokio::wait_for;

// ...

    // Do some waiting
    let result = wait_for(|| async {
        // Get the current value from the mutex
        if some_condition { Ok(value) } else { Err(SomeError) ]
    });

    // Act on the result
    match result {
        Ok(v) => { ... }
        Err(SituwaitionError::TimeoutError(e)) => { ... }
    }

// ...

See a full example in examples/async_std.rs. To run the async-std example:

cargo run --example async-std --features=async-std

Verbose configuration

If you'd like to control more finely the intervals and how many times a check will occur, you can create the Waiter object(s) yourself:

use situwaition::runtime::AsyncWaiter;
use situwaition::runtime::SyncWaiter;

// Synchronous code
SyncWaiter::with_timeout(|| { ... }, Duration::from_millis(500))?;

// Asynchronous code (either tokio or async-std)
AsyncWaiter::with_timeout(|| async { ... }, Duration::from_millis(500))?
    .exec()
    .await;

See the methods on SyncWaiter and AsyncWaiter for more options.

Supported environments

situwaition works with the following environments:

Name Supported?
Synchronous
Async w/ tokio
Async w/ async-std

Development

To get started working on developing situwatiion, run the following just targets:

just setup build

To check that your changes are fine, you'll probably want to run:

just test

If you want to see the full list of targets available that you can run just without any arguments.

just

There are a few useful targets like just build-watch which will continuously build the project thanks to cargo watch.

Contributing

Contributions are welcome! If you find a bug or an impovement that should be included in situwaition, create an issue or open a pull request.

You might also like...
A small utility for tracking the change in opening and closing of issues in a GitHub repo

A small utility for tracking the change in opening and closing of issues in a GitHub repo. This tool can be used to build visualizations for issue triage over time with the hope of motivating closing more issues than are opened.

mdTranslation is a utility to prepare multi-lingual Markdown documents.

mdTranslation is a utility to prepare multi-lingual Markdown documents. There's also a mdBook preprocessor called mdbook-translation for

Devmode is a project management utility for developers.
Devmode is a project management utility for developers.

Dev(mode) Dev(mode) is a project management utility for developers.

Provides utility functions to perform a graceful shutdown on an tokio-rs based service

tokio-graceful-shutdown IMPORTANT: This crate is in an early stage and not ready for production. This crate provides utility functions to perform a gr

Progmem utility for the AVR architecture

avr-progmem Progmem utilities for the AVR architectures. This crate provides unsafe utilities for working with data stored in the program memory of an

Emoji-printer - Utility to convert strings with emoji shortcodes to strings with the emoji unicode

Emoji Printer Intro Utility to convert strings with emoji shortcodes (:sushi:) to strings with the emoji unicode ( 🍣 ) Install cargo add emoji-printe

Rs.aws-login - A command line utility to simplify logging into AWS services.

aws-login A command line utility to simplify logging into AWS accounts and services. $ aws-login use ? Please select a profile to use: › ❯ dev-read

Lupus is a utility to administer backups with future integration with rsync

Lupus is a utility to administer backups with future integration with rsync. Many other features are either included or planned such as chat bridges using rcon and or parsing the pipe output from programs/games.

Auto Fan Management Utility in Linux Systems for Monster Laptops
Auto Fan Management Utility in Linux Systems for Monster Laptops

Auto Fan Management Utility in Linux Systems for Monster Laptops Monster Laptoplar için Linux Sistemlerde Oto Fan Yönetimi TR Monster laptoplar gömülü

Comments
  • fix: honor timeouts for long sync check

    fix: honor timeouts for long sync check

    Resolves #4

    As of PR creation, the new check passes and none of the others do:

    cargo nextest run -E 'test(test_unit_sync_executor_with_long_check)'
    

    A couple things left:

    • [x] Investigate using RwLock instead of Mutex
    • [x] Finish implementing the cases in the check loop
    opened by t3hmrman 1
  • Timeouts may not be upheld with long sync check function

    Timeouts may not be upheld with long sync check function

    If given a sync function that resolves after a long interval (ex. 10 minutes), the SyncWaiter will blow past it's timeout.

    Thanks to TroyDota on Reddit for gesturing towards the easiest mitigation -- spawning a thread and checking for completion.

    It's a bit of an edge case (most checks will be short) but timeouts not being honored is a bug.

    bug impl/sync 
    opened by t3hmrman 0
  • fix: add doc_cfg to improve docs.rs experience

    fix: add doc_cfg to improve docs.rs experience

    See comment in users.rust-lang.org -- on docs.rs it's very hard to tell where the tokio package comes from (the feature is required) -- so it's a good idea to use the recommended doc_cfg flag.

    Thanks SkiFire13 for the recommendation

    documentation enhancement 
    opened by t3hmrman 1
  • Improve documentation with timelines, examples

    Improve documentation with timelines, examples

    Thanks to rnottaken on Reddit for noting the lack of clarity in the documentation around the API, for example differences/distinction between check_interval and cooldown.

    Conversation reproduced below:

    Hey first of, nice crate!

    I get what you're doing, but I think that the docs would be easier understandable with more examples of usage.

    https://docs.rs/situwaition/0.2.1/situwaition/struct.SituwaitionOpts.html# for instance, it was hard for me to decipher what the timeline would be if I specify both the interval and the cooldown. When will the checks happen? When is the first going to happen and when will the next one happen? Is the first check going to happen after interval and every other after cooldown? Is interval the right choice of word then?

    I responded with:

    Hey thanks for the comment -- I appreciate you taking a look!

    Yeah, it is a bit confusing, let me try and lay it out.

    So interval actually has to do with checking for completion, where as cooldown happens after doing the actual action (it's a throttle, really, maybe I should rename it!)... Maybe it should be called backoff.

    This was a result of realizing that how often you check and how often you run the function are separate "timelines" so to speak.

    If I try and think of an example:

    • check takes 100ms
    • check interval is 500ms
    • timeout is 1000ms

    In this scenario, the check will run 10 times, and you'll check once (the second check will likely be past 1000ms in the future)

    Maybe the check is something we don't want to run 10 times a second -- maybe it should only be run every half a second at most -- this means that we need to stop the check from running, but we might want to keep checking so we can exit early as fast as possible.

    In that case you would want:

    • check takes 100ms (the operation hasn't changed)
    • cooldown is 400ms
    • check interval is 100ms (we want to find out as fast as possible that it's done, around)
    • timeout is 1000ms

    In this scenario, we've slowed down the checks (so we're not doing them as fast as possible), but the interval at which we check whether

    This 100% needs some more thinking on my part -- a diagram and examples, so I'm going to file an issue -- thanks again for bringing this up.

    To improve the documentation the following should be done:

    • [ ] Think about and write a FAQ section on the distinction between cooldown and check_interval
    • [ ] Consider renaming cooldown to backoff (BackoffStrategy might be a good enum to create)
    • [ ] Add example timeline visualizations
    • [ ] Add non-trivial usage examples (ex. using reqwest) early in the documentation.
    • [ ] Make the per-runtime/implementation sections more succinct if possible.
    documentation enhancement 
    opened by t3hmrman 1
Releases(v0.3.3)
  • v0.3.3(Jul 30, 2023)

    [0.3.3] - 2023-07-30

    Bug Fixes

    • Nightly usage & feature flag specification
    • Superfluous build.rs

    Documentation

    • Add more cfg annotations for docs

    Miscellaneous Tasks

    • Automate release tagging & publish to crates.io
    Source code(tar.gz)
    Source code(zip)
  • v0.3.2(Jul 29, 2023)

  • v0.3.1(Jul 28, 2023)

  • v0.3.0(Jul 28, 2023)

  • v0.2.1(Jul 12, 2023)

  • v0.2.0(Jul 12, 2023)

    [0.2.0] - 2023-07-12

    Bug Fixes

    • [breaking] Honor timeouts for long sync check

    Documentation

    • 'situation' -> 'situwaition'

    Miscellaneous Tasks

    • Fix categories
    • Add repository to Cargo.toml
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jul 11, 2023)

    What's Changed

    • ci: update CI YAML by @t3hmrman in https://github.com/t3hmrman/situwaition/pull/1
    • feat: add tokio support by @t3hmrman in https://github.com/t3hmrman/situwaition/pull/2
    • feat: add async-std support by @t3hmrman in https://github.com/t3hmrman/situwaition/pull/3

    New Contributors

    • @t3hmrman made their first contribution in https://github.com/t3hmrman/situwaition/pull/1

    Full Changelog: https://github.com/t3hmrman/situwaition/commits/v0.1.0

    Source code(tar.gz)
    Source code(zip)
Owner
Victor Adossi ("vados")
Most of my stuff is on GitLab :) https://gitlab.com/mrman
Victor Adossi (
A simple string parsing utility library for Rust, supporting no_std contexts.

strp Utility library for parsing data from an input string, or stdin if built with the std feature. Supports no_std contexts when built without the st

iqon 5 Nov 3, 2022
A Rust utility library, making easier by taking the hassle out of working. :octocat:

reddish A Rust utility library, making easier by taking the hassle out of working. Usage Add this to your Cargo.toml: [dependencies] reddish = "0.2.0"

Rogério Araújo 12 Jan 21, 2023
Utility library to work with tuples.

Utility library to work with tuples.

René Kijewski 9 Nov 30, 2022
ᎩᎦᎨᎢ (IPA: [gigagei]) is a random quote fetching console utility. Written in Rust.

gigagei ᎩᎦᎨᎢ (IPA: [gigagei]) is a random quote fetching console utility. Written in Rust. Installing Use latest pre-built binary from releases Buildi

veleth 10 Jun 17, 2022
A fast, multi-threaded line counting utility written in Rust.

xloc A fast, multi-threaded line counting utility written in Rust. What is xloc A drop in replacement for bash's wc -l. Your project has x lines of co

null 1 Nov 15, 2021
A cli utility written in Rust that allows fetching all the labels of a project, save those as a YAML file

A cli utility written in Rust that allows fetching all the labels of a project, save those as a YAML file that you can easily edit or save as backup and apply a saved preset to new repositories.

Chevdor 4 May 5, 2022
A rust-based version of the popular dnsgen python utility

ripgen A rust-based version of the popular dnsgen python utility. ripgen is split into two main parts: ripgen: A CLI utility that calls into ripgen_li

resync 198 Jan 2, 2023
Tons of extension utility functions for Rust

LazyExt Tons of extension utility functions for Rust. English | 简体中文 Status Name Status Crate Documents Introduction lazyext-slice Alpha Thousands of

Al Liu 2 Dec 5, 2022
Verbump - A simple utility written in rust to bump and manage git semantic version tags.

Verbump - A simple utility written in rust to bump and manage git semantic version tags.

Sarat Chandra 6 May 6, 2022
Batch rename utility for developers

nomino Batch rename utility for developers How to install Pre-Compiled You can download a pre-compiled executable for Linux, MacOS and Windows operati

Navid 458 Dec 27, 2022