App Instance Detector
A lightweight, lockfile-free Rust library for detecting and communicating with other running instances of an application on the same machine.
It uses a TCP-based handshake mechanism, allowing applications to discover each other, find available ports, and exchange basic information.
This library is used in conjunction with the Autonomo CLI Platform.
GitHub: https://github.com/AutonomoDev/app-instance-detector
Features
- Instance Detection: Scan a range of ports to find all running instances of your application.
- Port Discovery: Find the next available TCP port for a new application instance to bind to.
- Lockfile-Free: Avoids the complexities and cleanup issues associated with using filesystem lockfiles for singleton patterns.
- Customizable Handshakes: Send custom messages to identify instances and receive custom responses (e.g., process ID, version, or application state).
Installation
To include app-instance-detector in your Rust application, add the following line to your Cargo.toml file:
[]
= "0.9.0"
Getting Started & Usage
The primary use case is for an application to check for existing instances upon startup. If none are found, it starts its own "handshake server" to become discoverable by future instances.
Here is a complete example demonstrating how to use the library in a typical application.
Example main.rs
use ;
use Duration;
use ;
How to Run the Example
- Save the code above as
src/main.rsin your project. - Ensure your
Cargo.tomlincludes the dependency. - Run the application from your terminal:
- While the first instance is running, open a new terminal and run
cargo runagain. The second instance will detect the first one and exit.
Compiling
To compile the library or any application using it, run the build script:
API Overview
The library exposes a few key functions:
find_all_instances(base_port, max_search, timeout, request_message) -> Vec<(u16, String)>: Scans a port range, sends a handshake request, and returns a list of ports and responses from discovered instances.find_next_available_port(base_port, max_search) -> u16: Finds the first TCP port that is not in use within a given range.start_handshake_server<F>(port, response_generator: F): Spawns a background thread that listens on the specified port and responds to any incoming connection using the providedresponse_generatorclosure.is_port_in_use(port) -> bool: A simple utility to check if a specific port is currently in use.send_handshake_request(port, timeout, request_message) -> anyhow::Result<String>: The low-level function for sending a request to a single port and getting a response.
License
This project is licensed under the MIT License.